Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/rejected.json +1 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/client/lffbench_client/__init__.py +139 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/cost.py +37 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/DRIVER.md +144 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/fake_driver.py +152 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/protocol.py +364 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/session.py +346 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/tasks.py +123 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/__init__.py +0 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l2_knock.py +457 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l2_restore_layout.py +502 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l3_card_edge.py +364 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l3_wide.py +435 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l4_diagonal.py +524 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_count.py +562 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_swap.py +466 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py +398 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_drawer_cabinet.py +1273 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py +468 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_viewer/README.md +150 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_viewer/export.py +219 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_viewer/live.py +406 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_viewer/viewer.html +111 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/claude_batch.py +309 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/lerobot_sft_dataset.py +473 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/outcomes.py +141 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/qwen_vl_server.sh +17 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/replay_la.py +85 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/tool_gateway.py +331 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/trace_html.py +148 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/validate_parts_cart.py +52 -0
- leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/vla_acceptance.py +228 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/agent/backends/chat_completions.py +150 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json +23 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json +36 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/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_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json +18 -0
- leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/agent_viewer/export.py +219 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/batches.json +9 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/workspace_isolation_patch.json +41 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/workspace_isolation_regression.json +46 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/rejected.json +1 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/release/image_stats.json +703 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/context.py +377 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/cost.py +37 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l3_card_edge.py +364 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_slide.py +577 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l7_offcenter_push.py +613 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/audit_subagent.py +130 -0
- leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/full_report.py +89 -0
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/rejected.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[]
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/client/lffbench_client/__init__.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""LFF-Bench Python client: the three agent tools of one episode, for any robot harness framework (docs/18 §6.3).
|
| 2 |
+
|
| 3 |
+
Only the standard library; it never imports the simulator. It talks to the episode's tool gateway
|
| 4 |
+
(scripts/tool_gateway.py), which runs next to the robot server and owns the per-attempt tool-call budget, the jailed
|
| 5 |
+
shell and the workspace images. A framework registers the three tools with the schemas from tool_specs() and calls
|
| 6 |
+
them through a Session:
|
| 7 |
+
|
| 8 |
+
from lffbench_client import Session
|
| 9 |
+
s = Session.from_env() # LFF_GATEWAY_URL, LFF_GATEWAY_TOKEN (set by the launcher)
|
| 10 |
+
first = s.first_message() # README + first status, as every harness gets it
|
| 11 |
+
tools = s.tool_specs("openai_responses") # or raw / mcp / anthropic / openai_chat
|
| 12 |
+
r = s.robot("move_eef x=0.5 y=0.0 z=0.2") # -> ToolResult
|
| 13 |
+
r.json() # the robot server's reply as a dict
|
| 14 |
+
s.view_images(["obs/s001_agentview.jpg"]).images # [(mime, bytes)]
|
| 15 |
+
|
| 16 |
+
A ToolResult's content is the list a model should see, in MCP form (text items and base64 image items); finished
|
| 17 |
+
says that the episode is over (stop calling tools). Nothing here can reset the scene or read the verdict: the only
|
| 18 |
+
feedback is what the robot server writes into the tool results.
|
| 19 |
+
"""
|
| 20 |
+
import base64
|
| 21 |
+
import dataclasses
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import urllib.error
|
| 25 |
+
import urllib.parse
|
| 26 |
+
import urllib.request
|
| 27 |
+
|
| 28 |
+
__all__ = ["Session", "ToolResult", "GatewayError", "STYLES"]
|
| 29 |
+
__version__ = "0.1.0"
|
| 30 |
+
|
| 31 |
+
STYLES = ("raw", "mcp", "anthropic", "openai_responses", "openai_chat")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class GatewayError(RuntimeError):
|
| 35 |
+
pass
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
@dataclasses.dataclass
|
| 39 |
+
class ToolResult:
|
| 40 |
+
content: list # [{"type": "text", "text"} | {"type": "image", "mimeType", "data" (base64)}]
|
| 41 |
+
is_error: bool
|
| 42 |
+
finished: bool # the episode is over: stop calling tools and report
|
| 43 |
+
calls_in_attempt: int # tool calls used in the current attempt (after an automatic finish: 0)
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def text(self):
|
| 47 |
+
"""All text items, joined by newlines."""
|
| 48 |
+
return "\n".join(c["text"] for c in self.content if c.get("type") == "text")
|
| 49 |
+
|
| 50 |
+
def json(self):
|
| 51 |
+
"""The first text item parsed as JSON (robot / shell / view_images replies are JSON objects)."""
|
| 52 |
+
for c in self.content:
|
| 53 |
+
if c.get("type") == "text":
|
| 54 |
+
return json.loads(c["text"])
|
| 55 |
+
raise ValueError("no text item")
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def images(self):
|
| 59 |
+
"""[(mime type, bytes)] of the image items."""
|
| 60 |
+
return [(c["mimeType"], base64.b64decode(c["data"])) for c in self.content if c.get("type") == "image"]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class Session:
|
| 64 |
+
"""One episode's tools through its gateway. face labels this access path in the gateway transcript."""
|
| 65 |
+
|
| 66 |
+
def __init__(self, url, token, face="sdk", timeout_s=900.0):
|
| 67 |
+
self.url, self.token, self.face, self.timeout_s = url.rstrip("/"), token, face, timeout_s
|
| 68 |
+
self._opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # loopback: never via a proxy
|
| 69 |
+
|
| 70 |
+
@classmethod
|
| 71 |
+
def from_env(cls, face="sdk", **kw):
|
| 72 |
+
url, token = os.environ.get("LFF_GATEWAY_URL"), os.environ.get("LFF_GATEWAY_TOKEN")
|
| 73 |
+
if not url or not token:
|
| 74 |
+
raise GatewayError("LFF_GATEWAY_URL / LFF_GATEWAY_TOKEN are not set")
|
| 75 |
+
return cls(url, token, face=face, **kw)
|
| 76 |
+
|
| 77 |
+
@classmethod
|
| 78 |
+
def from_gateway_file(cls, path, face="sdk", **kw):
|
| 79 |
+
"""gateway.json written by the gateway in the run's log dir (launchers only; harness processes get env vars)."""
|
| 80 |
+
d = json.load(open(path))
|
| 81 |
+
return cls(d["url"], d["token"], face=face, **kw)
|
| 82 |
+
|
| 83 |
+
# ------------------------------------------------------------------------------------------------ http
|
| 84 |
+
def _request(self, method, path, body=None):
|
| 85 |
+
req = urllib.request.Request(self.url + path, method=method,
|
| 86 |
+
data=None if body is None else json.dumps(body).encode(),
|
| 87 |
+
headers={"Authorization": f"Bearer {self.token}", "X-LFF-Face": self.face,
|
| 88 |
+
"Content-Type": "application/json"})
|
| 89 |
+
try:
|
| 90 |
+
with self._opener.open(req, timeout=self.timeout_s) as r:
|
| 91 |
+
return r.read(), r.headers.get("Content-Type", "")
|
| 92 |
+
except urllib.error.HTTPError as e:
|
| 93 |
+
raise GatewayError(f"{method} {path}: HTTP {e.code}: {e.read()[:500].decode('utf-8', 'replace')}") from None
|
| 94 |
+
except urllib.error.URLError as e:
|
| 95 |
+
raise GatewayError(f"{method} {path}: {e.reason}") from None
|
| 96 |
+
|
| 97 |
+
def _get_json(self, path):
|
| 98 |
+
return json.loads(self._request("GET", path)[0])
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------------------------------------------ tools
|
| 101 |
+
def call(self, name, arguments=None):
|
| 102 |
+
raw, _ = self._request("POST", "/tool", dict(name=name, arguments=arguments or {}))
|
| 103 |
+
d = json.loads(raw)
|
| 104 |
+
return ToolResult(content=d["content"], is_error=bool(d["is_error"]), finished=bool(d["finished"]),
|
| 105 |
+
calls_in_attempt=d.get("calls_in_attempt"))
|
| 106 |
+
|
| 107 |
+
def robot(self, command):
|
| 108 |
+
"""One robot command, exactly as in the instructions (e.g. 'status', 'move_eef x=0.5 z=0.2', 'finish ...')."""
|
| 109 |
+
return self.call("robot", dict(command=command))
|
| 110 |
+
|
| 111 |
+
def shell(self, command):
|
| 112 |
+
"""A bash command in the episode workspace (jailed: no network, nothing outside the workspace)."""
|
| 113 |
+
return self.call("shell", dict(command=command))
|
| 114 |
+
|
| 115 |
+
def view_images(self, paths):
|
| 116 |
+
"""Image files of the workspace (e.g. obs/s001_agentview.jpg); the images come back as image items."""
|
| 117 |
+
return self.call("view_images", dict(paths=list(paths)))
|
| 118 |
+
|
| 119 |
+
# ------------------------------------------------------------------------------------------------ instructions
|
| 120 |
+
def tool_specs(self, style="raw"):
|
| 121 |
+
"""The three tool schemas with the reference descriptions, in one of STYLES."""
|
| 122 |
+
if style not in STYLES:
|
| 123 |
+
raise ValueError(f"style must be one of {STYLES}")
|
| 124 |
+
return self._get_json("/tool_specs?style=" + urllib.parse.quote(style))["tools"]
|
| 125 |
+
|
| 126 |
+
def readme(self):
|
| 127 |
+
return self._request("GET", "/readme")[0].decode("utf-8")
|
| 128 |
+
|
| 129 |
+
def first_message(self):
|
| 130 |
+
"""Preamble + README + first status report: the first user message every harness gets."""
|
| 131 |
+
return self._request("GET", "/first_message")[0].decode("utf-8")
|
| 132 |
+
|
| 133 |
+
def health(self):
|
| 134 |
+
return self._get_json("/health")
|
| 135 |
+
|
| 136 |
+
def status(self):
|
| 137 |
+
"""robot_server's `status` for the framework's own loop (e.g. a "continue" nudge that names the attempt): not
|
| 138 |
+
a tool call of the model, not counted in the per-attempt budget. Never show it to the model as a tool result."""
|
| 139 |
+
return self._get_json("/status")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/agent/cost.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token / cost accounting.
|
| 2 |
+
|
| 3 |
+
Prices (USD per 1M tokens) for gpt-6-astra from the OpenAI model page as recorded in
|
| 4 |
+
research_notes/.../seed_papers.md Q8 (2026-10): input 10, cached input 1, cache write 12.5, output 50;
|
| 5 |
+
prompts > 272K input tokens are billed 2x input/cached and 1.5x output. usage.input_tokens_details has
|
| 6 |
+
cached_tokens and (openai SDK >= 3.x) cache_write_tokens; both are priced separately when present.
|
| 7 |
+
Reasoning tokens are billed as output tokens (they are included in output_tokens).
|
| 8 |
+
"""
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
PRICES = {
|
| 12 |
+
"gpt-6-astra": dict(input=10.0, cached=1.0, cache_write=12.5, output=50.0, long_threshold=272_000, long_in=2.0, long_out=1.5),
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def call_cost(usage, model="gpt-6-astra"):
|
| 17 |
+
p = PRICES.get(model)
|
| 18 |
+
if p is None or not usage:
|
| 19 |
+
return None
|
| 20 |
+
inp = usage.get("input_tokens", 0) or 0
|
| 21 |
+
cached = usage.get("cached_tokens", 0) or 0
|
| 22 |
+
write = usage.get("cache_write_tokens", 0) or 0 # reported by newer SDKs / API versions
|
| 23 |
+
out = usage.get("output_tokens", 0) or 0
|
| 24 |
+
li, lo = (p["long_in"], p["long_out"]) if inp > p["long_threshold"] else (1.0, 1.0)
|
| 25 |
+
plain = max(inp - cached - write, 0)
|
| 26 |
+
return ((plain * p["input"] + write * p["cache_write"] + cached * p["cached"]) * li + out * p["output"] * lo) / 1e6
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def image_tokens(w, h, patch=32, per_patch=1.0, overhead=0):
|
| 30 |
+
"""ASSUMPTION (not verified for gpt-6-astra): patch-based image accounting as for the GPT-5 family,
|
| 31 |
+
one token per 32x32 patch (~256 tokens for 512x512). Real numbers come from response.usage."""
|
| 32 |
+
return int(math.ceil(w / patch) * math.ceil(h / patch) * per_patch + overhead)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def estimate_request_tokens(stats, image_res=512):
|
| 36 |
+
"""Rough input-token estimate of one request from OpenAIResponsesBackend.request_stats()."""
|
| 37 |
+
return int(stats.get("text_chars", 0) / 4 + stats.get("n_images", 0) * image_tokens(image_res, image_res))
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/DRIVER.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# LFF-Bench 真机驱动说明(给负责机械臂的同学)
|
| 2 |
+
|
| 3 |
+
> 协议版本 1(`protocol.py` 的 `PROTOCOL_VERSION`)。2026-10-19 起草;参考实现是仿真版假驱动 `fake_driver.py`,
|
| 4 |
+
> 它通过了本文 §7 的自检和 `tests/real_selfcheck.py` 的全部对照。
|
| 5 |
+
|
| 6 |
+
## 0. 一句话
|
| 7 |
+
|
| 8 |
+
你只需要在机器人电脑上跑一个**驱动进程**:收到 HTTP 请求就动臂、动夹爪、拍两张照片,或者在终端里问操作员。
|
| 9 |
+
模型、harness、命令预算、尝试次数、日志都在跑评测的那台机器上,你那边不用装。
|
| 10 |
+
|
| 11 |
+
```
|
| 12 |
+
评测机(跑模型的人) 机器人电脑(你)
|
| 13 |
+
Codex / Claude Code(订阅) 驱动进程 ← 你写,从 driver_template.py 改
|
| 14 |
+
└ MCP:robot / shell / view_images ├ 机械臂 SDK(松灵 PiPER ……)
|
| 15 |
+
└ 真机版 robot_server(预算、尝试、README、日志) ├ 两台相机:agentview + wrist
|
| 16 |
+
└ HTTP ── SSH 隧道 ──────────────────────────→ └ 操作员终端(复原场景、判成败)
|
| 17 |
+
```
|
| 18 |
+
|
| 19 |
+
模型永远看不到你的电脑,你的驱动也不知道模型是谁。所有运动只走 `/move`、`/gripper`、`/home` 三个接口。
|
| 20 |
+
|
| 21 |
+
## 1. 你要交付的东西
|
| 22 |
+
|
| 23 |
+
1. 驱动进程:`driver_template.py` 里 5 个 TODO(连臂、笛卡尔直线运动、读位姿、夹爪、取图),`/ik` 可选。
|
| 24 |
+
2. 两台相机:`agentview`(固定,能看到整个工作区)和 `wrist`(装在夹爪上)。
|
| 25 |
+
3. 场景道具,见 §6。
|
| 26 |
+
4. `scripts/real_check_driver.py` 全部 PASS(§7)。
|
| 27 |
+
5. 一位操作员,按 §8 的规程操作。可以就是你。
|
| 28 |
+
|
| 29 |
+
需要的文件只有三个:`lffbench/real/protocol.py`、`lffbench/real/driver_template.py`、`scripts/real_check_driver.py`。
|
| 30 |
+
放在同一个目录即可。依赖:Python 3、numpy、Pillow;录像另需 imageio + imageio-ffmpeg;再加上你的臂和相机 SDK。
|
| 31 |
+
|
| 32 |
+
## 2. 坐标与约定(最重要的一节)
|
| 33 |
+
|
| 34 |
+
| 量 | 约定 |
|
| 35 |
+
|---|---|
|
| 36 |
+
| 坐标系 | 机械臂**基座坐标系**:原点在基座,+x 是机器人正前方(远离基座),+y 是机器人的左手边,+z 向上;单位米 |
|
| 37 |
+
| 位置 `eef_pos` | **抓取点**(TCP):两指中间、比指尖高约 1 cm。在 SDK 里把 TCP 设到这里,或者自己做固定偏移 |
|
| 38 |
+
| 姿态 | 夹爪始终**竖直朝下**,只有一个自由度 yaw(绕基座 z 轴)。`yaw = 0`:两指沿基座 **y** 方向开合;`yaw = +90`:沿 x 方向开合;从上往下看,**正方向是逆时针** |
|
| 39 |
+
| yaw 范围 | `yaw_range_deg` 由你声明,跨度至少 180°(两指夹爪转 180° 等价,评测端会挑离当前 yaw 最近的等价角,保证落在你声明的范围里) |
|
| 40 |
+
| `gripper_width_m` | 两指尖之间的距离,单位米(空合 < 1 cm,张开 > 3 cm) |
|
| 41 |
+
| `joint_pos_rad` | 全部关节角(基座到腕,弧度),个数 = `n_joints` |
|
| 42 |
+
| `motion_s` | 这条命令实际运动了多少秒(评测按它扣"运动时间"预算:每次尝试 3 s × 命令条数) |
|
| 43 |
+
|
| 44 |
+
这些都和仿真一致(仿真里 yaw 0 也是"沿 y 开合")。模型拿到的 README 写的是
|
| 45 |
+
"You control a real `<robot>` robot arm (`<n_joints>` joints) with a two-finger parallel gripper",`robot` 和 `n_joints` 就取你在 `/info` 里填的值。
|
| 46 |
+
|
| 47 |
+
## 3. 接口
|
| 48 |
+
|
| 49 |
+
所有请求都是 `POST http://127.0.0.1:<port>/<endpoint>`,带 JSON body,请求头 `X-Driver-Token: <token>`。
|
| 50 |
+
所有回复都是 JSON,含 `"ok": true|false`。**`"fault": true` 表示机器人不可信了**(保护性停止、急停、通信断开……),评测端会立刻结束这个 run 并标为无效。
|
| 51 |
+
模板里任何未捕获的异常都会自动变成 fault。
|
| 52 |
+
|
| 53 |
+
| 接口 | 请求 | 回复(`ok` 之外) | 说明 |
|
| 54 |
+
|---|---|---|---|
|
| 55 |
+
| `info` | `{}` | `protocol` = 1,`robot`,`n_joints`,`cameras` = `["agentview","wrist"]`,`workspace` = `{lo:[x,y,z], hi:[x,y,z]}`,`yaw_range_deg` = `[lo,hi]`,`max_speed`(m/s),`ik`(bool),`driver_version` | 启动时调一次,内容写进每个 run 的契约 |
|
| 56 |
+
| `home` | `{}` | `state` | 回到初始位姿、张开夹爪。每次复原场景之前调用 |
|
| 57 |
+
| `move` | `{x, y, z, yaw_deg, speed}`,`speed` 可为 null(= `max_speed`) | `motion_s`,`state`;被拒时 `ok:false` + `error` | **阻塞**,臂停下才返回;尽量走笛卡尔直线(MoveL)。目标超出你的硬工作空间或者没有 IK 解时,**动之前**拒绝,回 `ok:false`(不是 fault) |
|
| 58 |
+
| `gripper` | `{close: true/false}` | `motion_s`,`state` | 阻塞。合爪要限力,夹到东西或合到底就停 |
|
| 59 |
+
| `state` | `{}` | `state` = `{eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad}` | 报**真实**位姿。标定偏差由评测端在软件里加,驱动不要加 |
|
| 60 |
+
| `observe` | `{}` | `images` = `{agentview: {format, data}, wrist: {...}}`(base64 的 jpeg 或 png),`state` | 取**最新**一帧(先清相机缓冲)。任意分辨率都行:评测端会���心裁成正方形、缩到 512²,再存成 JPEG q90 |
|
| 61 |
+
| `ik` | `{eef_pos, yaw_deg}` | `joint_pos_rad` | 可选,只有 `real_bias_place` 需要(`info.ik = true`)。只算不动;返回离当前关节角最近的解 |
|
| 62 |
+
| `operator` | `{kind: reset/judge/notice, run, attempt, setup, checklist, text}` | reset:`{}`;judge:`{success, note}` | 模板里已经实现成终端提示,会阻塞到操作员回答为止(§8) |
|
| 63 |
+
| `event` | `{ev, run, attempt}`,`ev` ∈ session_start / attempt_start / attempt_end / episode_end / session_end / run_invalid | `{}` | 用来开始、停止录像。模板在 attempt_start 开录、attempt_end 停录,每次尝试存一个 mp4 |
|
| 64 |
+
|
| 65 |
+
驱动是单线程的:请求一条一条执行,操作员提示没回答之前,别的请求都在排队,所以复原场景时臂不会动。
|
| 66 |
+
|
| 67 |
+
## 4. 安全(必须做)
|
| 68 |
+
|
| 69 |
+
- **硬工作空间**:驱动自己检查(模板的 `_inside` 已经写好)。z 下限要保证指尖离桌面至少 5 mm;盒子任务要用指尖贴近桌面推,所以 z 下限别留太高。
|
| 70 |
+
- **速度上限**:`max_speed` 建议不超过 0.25 m/s。模型可以要求更慢,但不能更快。
|
| 71 |
+
- **力保护**:推盒子本来就要接触物体,但模型也可能让夹爪压桌面、撞东西。打开臂自带的碰撞检测或电流保护;保护停止触发时回 fault。
|
| 72 |
+
- **急停**放在操作员手边。急停之后这个 run 作废,在 judge 提示里选 `x`,或者驱动自己回 fault。
|
| 73 |
+
- `/move` 里**不要做任何"聪明"的补偿**,比如自动抬高、自动避障、自动纠偏。那样会改变任务本身。超范围就拒绝,其他情况照命令执行。
|
| 74 |
+
|
| 75 |
+
## 5. 模型那边看到的和你有关的东西
|
| 76 |
+
|
| 77 |
+
- 每条命令之后的两张图(agentview、wrist)和末端状态。所以 agentview 必须拍到整个工作区:盒子、目标框、起点。
|
| 78 |
+
光照要稳定;模型运行时,画面里不要有人和多余的东西。
|
| 79 |
+
- 被拒绝的目标,模型看到的是 "target rejected: the arm cannot reach it; the arm did not move"。
|
| 80 |
+
- 评测端声明给模型的工作空间就是你 `/info` 里的 `workspace`(`real_bias_place` 会在 xy 方向每边再缩 4 cm)。模型不知道具体数值,只会在越界时被拒。
|
| 81 |
+
|
| 82 |
+
## 6. 两个任务的场景
|
| 83 |
+
|
| 84 |
+
实例(配重放哪、布局用哪组)由种子决定,每次复原前会显示在你的终端里,照做就行。正式 run 用 5000 以后的种子。
|
| 85 |
+
|
| 86 |
+
### 6.1 `real_offcenter_push`:重心偏的长盒子推进绿框(对应仿真 `l7_offcenter_push`)
|
| 87 |
+
|
| 88 |
+
模型看到的指令(与仿真相同):*Slowly push the long brown box with the closed gripper so that it ends up completely inside the green rectangle ahead of it (farther from the robot).*
|
| 89 |
+
|
| 90 |
+
- **盒子**:不透明的棕色长盒(纸盒或 3D 打印都行),带盖。仿真尺寸是 9 × 22 × 4 cm(沿推的方向 × 长 × 高)。
|
| 91 |
+
可以按 PiPER 的可达范围缩小,但沿推的方向的尺寸要比夹爪最大开口宽至少 2 cm,保证夹不起来。长边横放(沿 y)。
|
| 92 |
+
- **配重**:盒内每端隔两格(最外一格、往里一格),共 4 格。配重块(钢块、铅块)放在实例指定的那一格;空格可以塞泡沫,免得配重滑动。
|
| 93 |
+
合上盖子,两端外观一模一样,贴同样的胶带。
|
| 94 |
+
- **起点**:桌上贴定位角标,盒子每次都按角标摆,长边横放。
|
| 95 |
+
- **目标框**:绿色胶带围成的矩形,每边比盒子底面大 2 cm,在起点正前方,框中心离盒子中心 8–13 cm(仿真值;选一个固定值就行)。
|
| 96 |
+
- **桌面**:摩擦要均匀,盒子不能一推就滑出去很远。
|
| 97 |
+
- **先验证 headroom(必须做,不用模型)**:合上夹爪,以 5–8 cm/s 推盒子背面中点,盒子要明显转动(仿真里转 25–33°,转完就出框);
|
| 98 |
+
对准重心正后方推,盒子要基本不转、能进框。转得不明显就加重配重、把配重往外移,或者换更滑的桌垫。左右两种配重位置各试几次,记下来。
|
| 99 |
+
- **判成功**(终端里显示的清单):盒子四个底角都在绿框内(压线算出框);盒子没翻倒;一直是合着夹爪推的;夹爪没碰着盒子。
|
| 100 |
+
|
| 101 |
+
### 6.2 `real_bias_place`:带标定偏差的抓放(对应仿真 `l1_bias_place`)
|
| 102 |
+
|
| 103 |
+
模型看到的指令:*Pick up the red cube and put it into the bowl.*
|
| 104 |
+
|
| 105 |
+
- 红色方块(约 4 cm,能稳稳夹起),一个浅碗(内径 ≥ 12 cm)。
|
| 106 |
+
- 桌上贴 4 组标记 A–D:`A1` 放方块、`A2` 放碗,B、C、D 同理。各组之间、方块和碗之间都相距 ≥ 20 cm,全部在工作空间内,离工作空间边界 ≥ 5 cm。
|
| 107 |
+
- **偏差不用你管**:评测端给每条命令加一个隐藏的 2.5–4 cm 水平偏移,回报位姿时再减掉,臂本身不变。
|
| 108 |
+
但你需要实现 `/ik`(并把 `info()` 里的 `ik` 改成 True),否则回报的关节角会泄露偏差,评测端会拒绝启动这个任务。
|
| 109 |
+
- **判成功**:方块在碗里(落在碗底,不在碗沿上);夹爪张开,没夹着方��。
|
| 110 |
+
|
| 111 |
+
## 7. 联调步骤
|
| 112 |
+
|
| 113 |
+
1. 把 §1 的三个文件拷到机器人电脑上,填好 `driver_template.py` 的 TODO 和顶部的配置(`ROBOT`、`N_JOINTS`、`WORKSPACE_*`、`YAW_RANGE_DEG`、`HOME`)。
|
| 114 |
+
2. 启动驱动(token 自己定,私下发给跑评测的人):
|
| 115 |
+
```bash
|
| 116 |
+
python driver_template.py --port 9900 --token <token> --log driver_logs
|
| 117 |
+
```
|
| 118 |
+
3. 在机器人电脑上自检。臂会小幅运动:上下 3 cm、转 30°、开合夹爪,速度 5 cm/s,手放在急停上:
|
| 119 |
+
```bash
|
| 120 |
+
python real_check_driver.py --driver http://127.0.0.1:9900 --token <token> --operator
|
| 121 |
+
```
|
| 122 |
+
全部 PASS 才算完成;WARN 要看一下原因,NOTE 要人工确认(yaw 正方向是否为逆时针)。
|
| 123 |
+
4. 建 SSH 隧道,让评测机能访问 `127.0.0.1:9900`。二选一:
|
| 124 |
+
- 评测机能 ssh 到机器人电脑:在评测机上执行 `ssh -N -L 9900:127.0.0.1:9900 <user>@<机器人电脑>`
|
| 125 |
+
- 只能反过来连:在机器人电脑上执行 `ssh -N -R 9900:127.0.0.1:9900 <user>@<评测机>`
|
| 126 |
+
5. 跑评测的人在评测机上经隧道再跑一次 `real_check_driver.py`(加 `--yes`)。
|
| 127 |
+
6. 正式 run:评测机启动 session 后,你的终端会先出现 **RESET** 提示:按 setup 摆好场景,人离开画面,回车,模型开始操作。
|
| 128 |
+
一次尝试结束时出现 **JUDGE** 提示:按清单判 y / n / x。还有下一次尝试的话,臂会先回 home,再出现 RESET 提示。
|
| 129 |
+
|
| 130 |
+
## 8. 操作员规程
|
| 131 |
+
|
| 132 |
+
- 只照终端提示做;setup 要严格照做,每次复原都一样(角标对齐、配重格子对、盖子合好)。
|
| 133 |
+
- 模型运行期间,人不进相机画面,不碰场景,也不对任何人说配重在哪(除非要急停)。
|
| 134 |
+
- 判 y / n 只看清单本身,不看模型"努力了没有"。
|
| 135 |
+
- `x` = 这个 run 作废:机器人报错、相机掉线、有人碰了场景、配重摆错了。note 里写一句原因。
|
| 136 |
+
- 时间:模型每步要几秒到几十秒,一个 run 大约 15–60 分钟(估计,没实测),最长一次尝试约 40 条命令。
|
| 137 |
+
|
| 138 |
+
## 9. 常见问题
|
| 139 |
+
|
| 140 |
+
- **相机不是正方形**:可以。评测端会中心裁成正方形,两边各裁掉 (宽−高)/2 像素,所以工作区要在画面中间。
|
| 141 |
+
- **被物体挡住、没到目标**:位置控制会继续顶。设好电流或力矩保护;保护停止就回 fault,没触发就照常返回,模型会从位姿和图里看出没到。
|
| 142 |
+
- **到不了的目标**:`/move` 回 `ok:false` + `error`,并且不能动。不要回 fault。
|
| 143 |
+
- **延迟**:每个请求 1 秒内回完就行(取图建议 < 0.5 s)。瓶颈在模型。
|
| 144 |
+
- **PiPER 的 SDK 细节**:模板里只写了提示,没有在真机上验证过,以 SDK 文档为准。
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/fake_driver.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fake robot driver backed by the simulator: answers the driver protocol (lffbench/real/protocol.py) with a simulated
|
| 2 |
+
LFF-Bench task, so the whole real-robot path (harness -> MCP -> real robot server -> driver) runs without hardware.
|
| 3 |
+
|
| 4 |
+
It behaves like a real driver: it reports the TRUE pose in the robot-base frame (no calibration bias of its own; the
|
| 5 |
+
benchmark injects the bias), sends lossless PNG frames, rejects targets outside its hard workspace, and has an
|
| 6 |
+
operator. The operator is the simulator unless --operator console: "reset" resets the simulated scene, "judge" is the
|
| 7 |
+
task's own success rule (task.outcome).
|
| 8 |
+
|
| 9 |
+
python -m lffbench.real.fake_driver --task l7_offcenter_push --seed 3000 --port 9900 --token <t> [--nominal]
|
| 10 |
+
[--operator auto|console] [--log <dir>]
|
| 11 |
+
|
| 12 |
+
--nominal removes the task's hidden calibration bias (L1 tasks), which is what a real arm looks like when the benchmark
|
| 13 |
+
injects the bias in software (real_bias_place).
|
| 14 |
+
"""
|
| 15 |
+
import argparse
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
import os
|
| 19 |
+
import time
|
| 20 |
+
import types
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
from .protocol import CAMERAS, PROTOCOL_VERSION, ConsoleOperator, DriverServer
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class SimDriver(DriverServer):
|
| 28 |
+
def __init__(self, task, seed, nominal=False, image_res=512, operator="auto", log_dir=""):
|
| 29 |
+
from ..agent import robot_server as RS # registers every simulated task
|
| 30 |
+
from ..agent.tools import SPEED_RANGE, WS_HI, WS_LO, ToolExecutor
|
| 31 |
+
from ..task_base import TASKS
|
| 32 |
+
self.RS, self.ToolExecutor = RS, ToolExecutor
|
| 33 |
+
self.task_name, self.seed, self.image_res = task, int(seed), int(image_res)
|
| 34 |
+
self.task = TASKS[task](cam_res=self.image_res)
|
| 35 |
+
self.inst = self.task.sample_instance(self.seed)
|
| 36 |
+
if nominal: # same rule as robot_server --nominal
|
| 37 |
+
for k in [k for k in self.inst if "bias" in k]:
|
| 38 |
+
v = self.inst[k]
|
| 39 |
+
self.inst[k] = [0.0] * len(v) if isinstance(v, (list, tuple)) else 0.0 if isinstance(v, (int, float)) else v
|
| 40 |
+
self.operator_mode = operator
|
| 41 |
+
self.log_dir = log_dir
|
| 42 |
+
if log_dir:
|
| 43 |
+
os.makedirs(log_dir, exist_ok=True)
|
| 44 |
+
self.console_op = ConsoleOperator(os.path.join(log_dir, "operator.jsonl") if log_dir else None)
|
| 45 |
+
self._reset()
|
| 46 |
+
sim = self.task.env.sim
|
| 47 |
+
bid = sim.model.body_name2id("robot0_base")
|
| 48 |
+
self.base_off = np.array(sim.data.body_xpos[bid], float).copy()
|
| 49 |
+
self.ws_lo, self.ws_hi = WS_LO - self.base_off, WS_HI - self.base_off
|
| 50 |
+
self.max_speed = float(SPEED_RANGE[1])
|
| 51 |
+
self.yaw_limit_deg = math.degrees(self.task.sk.YAW_LIMIT)
|
| 52 |
+
|
| 53 |
+
def _reset(self):
|
| 54 |
+
self.task.reset_instance(self.inst)
|
| 55 |
+
self.ex = self.ToolExecutor(self.task, self.inst, image_res=self.image_res, cams=CAMERAS)
|
| 56 |
+
|
| 57 |
+
def _log(self, d):
|
| 58 |
+
if self.log_dir:
|
| 59 |
+
with open(os.path.join(self.log_dir, "driver_events.jsonl"), "a") as f:
|
| 60 |
+
f.write(json.dumps(dict(d, t=time.time()), default=str) + "\n")
|
| 61 |
+
|
| 62 |
+
# ------------------------------------------------------------------ protocol
|
| 63 |
+
def info(self):
|
| 64 |
+
return dict(protocol=PROTOCOL_VERSION, robot="Franka Emika Panda (fake driver, simulated)", n_joints=7,
|
| 65 |
+
cameras=list(CAMERAS), workspace=dict(lo=self.ws_lo.round(6).tolist(), hi=self.ws_hi.round(6).tolist()),
|
| 66 |
+
yaw_range_deg=[-self.yaw_limit_deg, self.yaw_limit_deg], max_speed=self.max_speed, ik=True,
|
| 67 |
+
driver_version=f"fake_driver sim:{self.task_name} seed:{self.seed}")
|
| 68 |
+
|
| 69 |
+
def home(self):
|
| 70 |
+
# the simulated arm goes home with the scene reset that always follows (operator "reset")
|
| 71 |
+
return self.state()
|
| 72 |
+
|
| 73 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 74 |
+
tgt = np.array([x, y, z], float)
|
| 75 |
+
if not (np.all(tgt >= self.ws_lo - 1e-9) and np.all(tgt <= self.ws_hi + 1e-9)):
|
| 76 |
+
return False, "outside the hard workspace", 0.0
|
| 77 |
+
w = tgt + self.base_off
|
| 78 |
+
n0 = self.task.sk.n_steps
|
| 79 |
+
mv = dict(x=float(w[0]), y=float(w[1]), z=float(w[2]), yaw=float(yaw_deg))
|
| 80 |
+
if speed is not None:
|
| 81 |
+
mv["speed"] = float(speed)
|
| 82 |
+
res = self.ex.call("move_to", mv)
|
| 83 |
+
if not res.ok:
|
| 84 |
+
return False, res.report.get("error", "rejected"), 0.0
|
| 85 |
+
return True, None, (self.task.sk.n_steps - n0) * 0.05
|
| 86 |
+
|
| 87 |
+
def gripper(self, close):
|
| 88 |
+
n0 = self.task.sk.n_steps
|
| 89 |
+
self.ex.call("close_gripper" if close else "open_gripper", {})
|
| 90 |
+
return (self.task.sk.n_steps - n0) * 0.05
|
| 91 |
+
|
| 92 |
+
def _joints(self):
|
| 93 |
+
rob = self.task.env.robots[0]
|
| 94 |
+
return self.task.env.sim.data.qpos[np.array(rob._ref_joint_pos_indexes)].copy()
|
| 95 |
+
|
| 96 |
+
def state(self):
|
| 97 |
+
sk = self.task.sk
|
| 98 |
+
return dict(eef_pos=[float(v) for v in sk.eef_pos() - self.base_off], eef_yaw_deg=float(self.ex.eef_yaw_deg()),
|
| 99 |
+
gripper_width_m=float(sk.gripper_width()), joint_pos_rad=[float(v) for v in self._joints()])
|
| 100 |
+
|
| 101 |
+
def images(self):
|
| 102 |
+
return {r.camera: r.array for r in self.ex.observe()}
|
| 103 |
+
|
| 104 |
+
def ik(self, eef_pos, yaw_deg):
|
| 105 |
+
"""Joint angles for the grasp point at eef_pos (base frame) with the current orientation: the same damped
|
| 106 |
+
least squares as robot_server._believed_joints (yaw_deg is the current yaw here)."""
|
| 107 |
+
sk = self.task.sk
|
| 108 |
+
T_true = np.eye(4)
|
| 109 |
+
T_true[:3, :3], T_true[:3, 3] = sk.eef_mat(), sk.eef_pos()
|
| 110 |
+
T_b = T_true.copy()
|
| 111 |
+
T_b[:3, 3] = np.asarray(eef_pos, float) + self.base_off
|
| 112 |
+
shim = types.SimpleNamespace(task=self.task, _believed_pose=lambda: (T_b, T_true))
|
| 113 |
+
return [float(v) for v in self.RS._believed_joints(shim)]
|
| 114 |
+
|
| 115 |
+
def operator(self, kind, **kw):
|
| 116 |
+
self._log(dict(ev="operator", kind=kind, **{k: v for k, v in kw.items() if k != "checklist"}))
|
| 117 |
+
if kind == "reset":
|
| 118 |
+
if self.operator_mode == "console":
|
| 119 |
+
self.console_op(kind, **kw)
|
| 120 |
+
self._reset()
|
| 121 |
+
return dict(ok=True)
|
| 122 |
+
if kind == "judge":
|
| 123 |
+
out = self.task.outcome(self.inst)
|
| 124 |
+
if self.operator_mode == "console":
|
| 125 |
+
kw = dict(kw, text=(kw.get("text", "") + f"\n(simulator says: success={bool(out['success'])}, "
|
| 126 |
+
f"{out.get('failure') or out.get('detail') or ''})"))
|
| 127 |
+
return self.console_op(kind, **kw)
|
| 128 |
+
return dict(ok=True, success=bool(out["success"]),
|
| 129 |
+
note=str(out.get("failure") or ("ok" if out["success"] else "")))
|
| 130 |
+
return dict(ok=True)
|
| 131 |
+
|
| 132 |
+
def event(self, ev, **kw):
|
| 133 |
+
self._log(dict(ev=ev, **kw))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def main():
|
| 137 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 138 |
+
ap.add_argument("--task", default="l7_offcenter_push", help="simulated LFF-Bench task that plays the real scene")
|
| 139 |
+
ap.add_argument("--seed", type=int, default=3000)
|
| 140 |
+
ap.add_argument("--port", type=int, default=9900)
|
| 141 |
+
ap.add_argument("--token", default=os.environ.get("LFF_DRIVER_TOKEN", ""))
|
| 142 |
+
ap.add_argument("--nominal", action="store_true", help="remove the simulated task's calibration bias")
|
| 143 |
+
ap.add_argument("--operator", default="auto", choices=["auto", "console"])
|
| 144 |
+
ap.add_argument("--image-res", type=int, default=512)
|
| 145 |
+
ap.add_argument("--log", default="", help="directory for driver_events.jsonl / operator.jsonl")
|
| 146 |
+
a = ap.parse_args()
|
| 147 |
+
drv = SimDriver(a.task, a.seed, nominal=a.nominal, image_res=a.image_res, operator=a.operator, log_dir=a.log)
|
| 148 |
+
drv.serve(a.port, token=a.token or None)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
if __name__ == "__main__":
|
| 152 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/protocol.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot-driver protocol v1: what a real arm (or a fake one) must answer so that LFF-Bench can run on it.
|
| 2 |
+
|
| 3 |
+
The benchmark side (lffbench/real/session.py, on the machine that runs the agent harness) talks to one *driver*
|
| 4 |
+
process (on the robot PC) over HTTP. The driver only moves the arm, reads its state, grabs camera frames and talks
|
| 5 |
+
to the human operator; budgets, attempts, README, logs and the agent interface stay on the benchmark side, so the
|
| 6 |
+
agent sees exactly the same tools as in simulation. Spec for driver authors: lffbench/real/DRIVER.md.
|
| 7 |
+
|
| 8 |
+
This file is shared by both sides and needs only the Python standard library + numpy + Pillow (no simulator):
|
| 9 |
+
DriverClient benchmark side: typed calls to a driver
|
| 10 |
+
DriverServer driver side: HTTP plumbing; subclass it and implement the hardware methods (driver_template.py)
|
| 11 |
+
ConsoleOperator driver side: the operator's terminal (blocking prompts for reset / judging)
|
| 12 |
+
|
| 13 |
+
Every request is POST <url>/<endpoint> with a JSON body and header X-Driver-Token: <token>.
|
| 14 |
+
Every reply is JSON with "ok": true|false. A reply with "fault": true means the robot can no longer be trusted
|
| 15 |
+
(protective stop, e-stop, lost connection, ...): the benchmark ends the run and marks it invalid.
|
| 16 |
+
"""
|
| 17 |
+
import base64
|
| 18 |
+
import io
|
| 19 |
+
import json
|
| 20 |
+
import math
|
| 21 |
+
import os
|
| 22 |
+
import secrets
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
import traceback
|
| 26 |
+
import urllib.error
|
| 27 |
+
import urllib.request
|
| 28 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
|
| 32 |
+
PROTOCOL_VERSION = 1
|
| 33 |
+
CAMERAS = ("agentview", "wrist")
|
| 34 |
+
TOKEN_HEADER = "X-Driver-Token"
|
| 35 |
+
ENDPOINTS = ("info", "home", "move", "gripper", "state", "observe", "ik", "operator", "event")
|
| 36 |
+
OPERATOR_KINDS = ("reset", "judge", "notice")
|
| 37 |
+
EVENTS = ("session_start", "attempt_start", "attempt_end", "episode_end", "session_end", "run_invalid")
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class DriverError(RuntimeError):
|
| 41 |
+
"""The driver answered something that breaks the protocol (or did not answer)."""
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DriverFault(DriverError):
|
| 45 |
+
"""The driver reports a robot fault: the run must stop and is invalid."""
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# ------------------------------------------------------------------------------------------------ images
|
| 49 |
+
def encode_image(arr, fmt="png", quality=95):
|
| 50 |
+
"""uint8 HxWx3 -> {"format": "png"|"jpeg", "data": base64}. PNG is lossless (the benchmark re-encodes every frame
|
| 51 |
+
as 512x512 JPEG q90 itself, so a JPEG from the driver is compressed twice); JPEG is smaller over a slow link."""
|
| 52 |
+
from PIL import Image
|
| 53 |
+
buf = io.BytesIO()
|
| 54 |
+
im = Image.fromarray(np.asarray(arr, dtype=np.uint8))
|
| 55 |
+
if fmt == "jpeg":
|
| 56 |
+
im.save(buf, format="JPEG", quality=int(quality))
|
| 57 |
+
else:
|
| 58 |
+
im.save(buf, format="PNG")
|
| 59 |
+
return dict(format=fmt, data=base64.b64encode(buf.getvalue()).decode("ascii"))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def decode_image(obj):
|
| 63 |
+
"""{"format", "data"} -> uint8 HxWx3 (RGB)."""
|
| 64 |
+
from PIL import Image
|
| 65 |
+
if not isinstance(obj, dict) or "data" not in obj:
|
| 66 |
+
raise DriverError("image must be {\"format\": \"png\"|\"jpeg\", \"data\": <base64>}")
|
| 67 |
+
im = Image.open(io.BytesIO(base64.b64decode(obj["data"])))
|
| 68 |
+
return np.asarray(im.convert("RGB"), dtype=np.uint8)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def square_resize(arr, res):
|
| 72 |
+
"""Centre-crop to a square, then resize to res x res. A frame that is already res x res is returned unchanged
|
| 73 |
+
(bit for bit), so a simulator-backed driver gives exactly the simulator's pixels."""
|
| 74 |
+
from PIL import Image
|
| 75 |
+
arr = np.asarray(arr, dtype=np.uint8)
|
| 76 |
+
h, w = arr.shape[:2]
|
| 77 |
+
if h == res and w == res:
|
| 78 |
+
return arr
|
| 79 |
+
s = min(h, w)
|
| 80 |
+
y0, x0 = (h - s) // 2, (w - s) // 2
|
| 81 |
+
arr = arr[y0:y0 + s, x0:x0 + s]
|
| 82 |
+
if s == res:
|
| 83 |
+
return np.ascontiguousarray(arr)
|
| 84 |
+
return np.asarray(Image.fromarray(arr).resize((res, res), Image.BICUBIC))
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ------------------------------------------------------------------------------------------------ validation
|
| 88 |
+
def _vec(v, n):
|
| 89 |
+
return isinstance(v, (list, tuple)) and len(v) == n and all(isinstance(x, (int, float)) and math.isfinite(x) for x in v)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def info_problems(info):
|
| 93 |
+
"""-> list of problems with an /info reply (empty = fine)."""
|
| 94 |
+
p = []
|
| 95 |
+
if info.get("protocol") != PROTOCOL_VERSION:
|
| 96 |
+
p.append(f"protocol must be {PROTOCOL_VERSION}, got {info.get('protocol')!r}")
|
| 97 |
+
if not isinstance(info.get("robot"), str) or not info["robot"].strip():
|
| 98 |
+
p.append("robot: non-empty string (e.g. \"AgileX PiPER\")")
|
| 99 |
+
if not isinstance(info.get("n_joints"), int) or not 4 <= info["n_joints"] <= 8:
|
| 100 |
+
p.append("n_joints: integer 4..8")
|
| 101 |
+
if sorted(info.get("cameras") or []) != sorted(CAMERAS):
|
| 102 |
+
p.append(f"cameras must be exactly {list(CAMERAS)}")
|
| 103 |
+
ws = info.get("workspace") or {}
|
| 104 |
+
if not (_vec(ws.get("lo"), 3) and _vec(ws.get("hi"), 3) and all(a < b for a, b in zip(ws["lo"], ws["hi"]))):
|
| 105 |
+
p.append("workspace: {lo: [x, y, z], hi: [x, y, z]} with lo < hi (robot-base frame, metres)")
|
| 106 |
+
yr = info.get("yaw_range_deg")
|
| 107 |
+
if not (_vec(yr, 2) and yr[0] < yr[1] and yr[1] - yr[0] >= 180.0):
|
| 108 |
+
p.append("yaw_range_deg: [lo, hi] with hi - lo >= 180 (the gripper is symmetric, every yaw must be reachable)")
|
| 109 |
+
if not (isinstance(info.get("max_speed"), (int, float)) and 0.01 <= info["max_speed"] <= 1.0):
|
| 110 |
+
p.append("max_speed: m/s, 0.01..1.0")
|
| 111 |
+
if not isinstance(info.get("ik"), bool):
|
| 112 |
+
p.append("ik: true|false (whether /ik is implemented; needed only for tasks with a calibration bias)")
|
| 113 |
+
if not isinstance(info.get("driver_version"), str):
|
| 114 |
+
p.append("driver_version: string (your git commit or a date; it is written into every run's log)")
|
| 115 |
+
return p
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def state_problems(st, n_joints):
|
| 119 |
+
p = []
|
| 120 |
+
if not _vec(st.get("eef_pos"), 3):
|
| 121 |
+
p.append("state.eef_pos: [x, y, z] metres")
|
| 122 |
+
if not (isinstance(st.get("eef_yaw_deg"), (int, float)) and math.isfinite(st["eef_yaw_deg"])):
|
| 123 |
+
p.append("state.eef_yaw_deg: number")
|
| 124 |
+
if not (isinstance(st.get("gripper_width_m"), (int, float)) and 0.0 <= st["gripper_width_m"] <= 0.2):
|
| 125 |
+
p.append("state.gripper_width_m: number 0..0.2")
|
| 126 |
+
if not _vec(st.get("joint_pos_rad"), n_joints):
|
| 127 |
+
p.append(f"state.joint_pos_rad: {n_joints} numbers (radians)")
|
| 128 |
+
return p
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ------------------------------------------------------------------------------------------------ benchmark side
|
| 132 |
+
class DriverClient:
|
| 133 |
+
"""Typed calls to a driver. `url` like http://127.0.0.1:9900 (an SSH tunnel to the robot PC)."""
|
| 134 |
+
|
| 135 |
+
def __init__(self, url, token, timeout=120.0):
|
| 136 |
+
self.url, self.token, self.timeout = url.rstrip("/"), token, float(timeout)
|
| 137 |
+
self.opener = urllib.request.build_opener(urllib.request.ProxyHandler({})) # never through a web proxy
|
| 138 |
+
|
| 139 |
+
def call(self, endpoint, payload=None, timeout=None, allow_not_ok=False):
|
| 140 |
+
req = urllib.request.Request(f"{self.url}/{endpoint}", data=json.dumps(payload or {}).encode(),
|
| 141 |
+
headers={"Content-Type": "application/json", TOKEN_HEADER: self.token})
|
| 142 |
+
try:
|
| 143 |
+
with self.opener.open(req, timeout=timeout if timeout is not None else self.timeout) as r:
|
| 144 |
+
rep = json.loads(r.read().decode())
|
| 145 |
+
except (urllib.error.URLError, OSError, ValueError) as e:
|
| 146 |
+
raise DriverError(f"/{endpoint}: no valid reply from the driver ({type(e).__name__}: {e})") from e
|
| 147 |
+
if not isinstance(rep, dict) or "ok" not in rep:
|
| 148 |
+
raise DriverError(f"/{endpoint}: reply is not a JSON object with \"ok\"")
|
| 149 |
+
if rep.get("fault"):
|
| 150 |
+
raise DriverFault(f"/{endpoint}: robot fault: {rep.get('error', '')}")
|
| 151 |
+
if not rep["ok"] and not allow_not_ok:
|
| 152 |
+
raise DriverError(f"/{endpoint}: {rep.get('error', 'not ok')}")
|
| 153 |
+
return rep
|
| 154 |
+
|
| 155 |
+
def info(self):
|
| 156 |
+
rep = self.call("info")
|
| 157 |
+
prob = info_problems(rep)
|
| 158 |
+
if prob:
|
| 159 |
+
raise DriverError("/info: " + "; ".join(prob))
|
| 160 |
+
return rep
|
| 161 |
+
|
| 162 |
+
def home(self):
|
| 163 |
+
return self.call("home", timeout=max(self.timeout, 300))
|
| 164 |
+
|
| 165 |
+
def move(self, x, y, z, yaw_deg, speed=None):
|
| 166 |
+
"""-> reply; ok=false (not a fault) means the target was rejected and the arm did not move."""
|
| 167 |
+
return self.call("move", dict(x=float(x), y=float(y), z=float(z), yaw_deg=float(yaw_deg),
|
| 168 |
+
speed=None if speed is None else float(speed)), allow_not_ok=True)
|
| 169 |
+
|
| 170 |
+
def gripper(self, close):
|
| 171 |
+
return self.call("gripper", dict(close=bool(close)))
|
| 172 |
+
|
| 173 |
+
def state(self):
|
| 174 |
+
return self.call("state")["state"]
|
| 175 |
+
|
| 176 |
+
def observe(self):
|
| 177 |
+
rep = self.call("observe")
|
| 178 |
+
imgs = rep.get("images") or {}
|
| 179 |
+
missing = [c for c in CAMERAS if c not in imgs]
|
| 180 |
+
if missing:
|
| 181 |
+
raise DriverError(f"/observe: missing camera(s) {missing}")
|
| 182 |
+
return {c: decode_image(imgs[c]) for c in CAMERAS}, rep["state"]
|
| 183 |
+
|
| 184 |
+
def ik(self, eef_pos, yaw_deg):
|
| 185 |
+
return self.call("ik", dict(eef_pos=[float(v) for v in eef_pos], yaw_deg=float(yaw_deg)))["joint_pos_rad"]
|
| 186 |
+
|
| 187 |
+
def operator(self, kind, **kw):
|
| 188 |
+
"""Blocks until the operator has answered (no timeout)."""
|
| 189 |
+
assert kind in OPERATOR_KINDS, kind
|
| 190 |
+
return self.call("operator", dict(kind=kind, **kw), timeout=24 * 3600)
|
| 191 |
+
|
| 192 |
+
def event(self, ev, **kw):
|
| 193 |
+
assert ev in EVENTS, ev
|
| 194 |
+
return self.call("event", dict(ev=ev, **kw))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
# ------------------------------------------------------------------------------------------------ driver side
|
| 198 |
+
class ConsoleOperator:
|
| 199 |
+
"""The operator's terminal on the robot PC. Prompts block the driver (the robot must not move while the operator
|
| 200 |
+
resets the scene). Answers are appended to `log_path` (JSON lines)."""
|
| 201 |
+
|
| 202 |
+
def __init__(self, log_path=None, stream_in=None, stream_out=None):
|
| 203 |
+
self.log_path = log_path
|
| 204 |
+
self.inp = stream_in or sys.stdin
|
| 205 |
+
self.out = stream_out or sys.stdout
|
| 206 |
+
|
| 207 |
+
def _say(self, s=""):
|
| 208 |
+
self.out.write(s + "\n")
|
| 209 |
+
self.out.flush()
|
| 210 |
+
|
| 211 |
+
def _ask(self, prompt):
|
| 212 |
+
self.out.write(prompt)
|
| 213 |
+
self.out.flush()
|
| 214 |
+
line = self.inp.readline()
|
| 215 |
+
if not line:
|
| 216 |
+
raise EOFError("operator input closed")
|
| 217 |
+
return line.strip()
|
| 218 |
+
|
| 219 |
+
def _log(self, d):
|
| 220 |
+
if self.log_path:
|
| 221 |
+
os.makedirs(os.path.dirname(os.path.abspath(self.log_path)), exist_ok=True)
|
| 222 |
+
with open(self.log_path, "a") as f:
|
| 223 |
+
f.write(json.dumps(dict(d, t=time.time()), ensure_ascii=False) + "\n")
|
| 224 |
+
|
| 225 |
+
def __call__(self, kind, run="", attempt=None, text="", setup="", checklist=None, **_):
|
| 226 |
+
bar = "=" * 72
|
| 227 |
+
self._say("\n" + bar)
|
| 228 |
+
self._say(f"[{time.strftime('%H:%M:%S')}] run {run} attempt {attempt} -- {kind.upper()}")
|
| 229 |
+
if text:
|
| 230 |
+
self._say(text)
|
| 231 |
+
if kind == "reset":
|
| 232 |
+
if setup:
|
| 233 |
+
self._say("\nScene for this attempt (do it exactly; do not talk to anyone about it):\n" + setup)
|
| 234 |
+
self._ask("\nArm is at home. Put the scene back as described, step out of the cameras, press Enter... ")
|
| 235 |
+
self._log(dict(kind=kind, run=run, attempt=attempt))
|
| 236 |
+
return dict(ok=True)
|
| 237 |
+
if kind == "judge":
|
| 238 |
+
for i, c in enumerate(checklist or [], 1):
|
| 239 |
+
self._say(f" {i}. {c}")
|
| 240 |
+
while True:
|
| 241 |
+
a = self._ask("\nAll conditions met? y = success, n = failure, x = run invalid (robot / camera "
|
| 242 |
+
"problem): ").lower()
|
| 243 |
+
if a in ("y", "n", "x"):
|
| 244 |
+
break
|
| 245 |
+
note = self._ask("Note (one line, optional): ")
|
| 246 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, answer=a, note=note))
|
| 247 |
+
if a == "x":
|
| 248 |
+
return dict(ok=False, fault=True, error=f"operator marked the run invalid: {note}")
|
| 249 |
+
return dict(ok=True, success=a == "y", note=note)
|
| 250 |
+
self._log(dict(kind=kind, run=run, attempt=attempt, text=text))
|
| 251 |
+
return dict(ok=True)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
class DriverServer:
|
| 255 |
+
"""HTTP plumbing for a driver. Subclass and implement the hardware methods below; see driver_template.py.
|
| 256 |
+
The server is single-threaded on purpose: requests are executed one at a time, and an operator prompt blocks
|
| 257 |
+
every other request until it is answered."""
|
| 258 |
+
|
| 259 |
+
# ---- implement these ------------------------------------------------------------------------------
|
| 260 |
+
def info(self):
|
| 261 |
+
"""-> dict (see DRIVER.md §3): protocol, robot, n_joints, cameras, workspace, yaw_range_deg, max_speed, ik,
|
| 262 |
+
driver_version."""
|
| 263 |
+
raise NotImplementedError
|
| 264 |
+
|
| 265 |
+
def home(self):
|
| 266 |
+
"""Move to the home pose (gripper open, pointing down). -> state dict."""
|
| 267 |
+
raise NotImplementedError
|
| 268 |
+
|
| 269 |
+
def move(self, x, y, z, yaw_deg, speed):
|
| 270 |
+
"""Blocking straight-line move of the grasp point; speed m/s or None (= max_speed).
|
| 271 |
+
-> (ok, error_or_None, motion_s). ok=False: rejected BEFORE moving (outside the hard limits / no IK)."""
|
| 272 |
+
raise NotImplementedError
|
| 273 |
+
|
| 274 |
+
def gripper(self, close):
|
| 275 |
+
"""Blocking open / close (force-limited close). -> motion_s."""
|
| 276 |
+
raise NotImplementedError
|
| 277 |
+
|
| 278 |
+
def state(self):
|
| 279 |
+
"""-> dict eef_pos, eef_yaw_deg, gripper_width_m, joint_pos_rad."""
|
| 280 |
+
raise NotImplementedError
|
| 281 |
+
|
| 282 |
+
def images(self):
|
| 283 |
+
"""-> {"agentview": uint8 HxWx3 RGB, "wrist": ...}, taken now (after the arm has stopped)."""
|
| 284 |
+
raise NotImplementedError
|
| 285 |
+
|
| 286 |
+
def ik(self, eef_pos, yaw_deg):
|
| 287 |
+
"""Optional (info()["ik"] = True): joint angles that put the grasp point at eef_pos / yaw_deg (pointing
|
| 288 |
+
down), close to the current joint angles. -> list of n_joints floats."""
|
| 289 |
+
raise NotImplementedError
|
| 290 |
+
|
| 291 |
+
def operator(self, kind, **kw):
|
| 292 |
+
"""Default: the terminal. -> dict (reset: {ok}; judge: {ok, success, note}; notice: {ok})."""
|
| 293 |
+
return self.console(kind, **kw)
|
| 294 |
+
|
| 295 |
+
def event(self, ev, **kw):
|
| 296 |
+
"""Start / stop your own recordings here (attempt_start / attempt_end / episode_end ...)."""
|
| 297 |
+
return None
|
| 298 |
+
|
| 299 |
+
image_format = "png"
|
| 300 |
+
|
| 301 |
+
# ---- plumbing -------------------------------------------------------------------------------------
|
| 302 |
+
def dispatch(self, endpoint, a):
|
| 303 |
+
if endpoint == "info":
|
| 304 |
+
return dict(ok=True, **self.info())
|
| 305 |
+
if endpoint == "home":
|
| 306 |
+
return dict(ok=True, state=self.home())
|
| 307 |
+
if endpoint == "move":
|
| 308 |
+
ok, err, motion_s = self.move(float(a["x"]), float(a["y"]), float(a["z"]), float(a["yaw_deg"]),
|
| 309 |
+
None if a.get("speed") is None else float(a["speed"]))
|
| 310 |
+
rep = dict(ok=bool(ok), motion_s=float(motion_s or 0.0), state=self.state())
|
| 311 |
+
if not ok:
|
| 312 |
+
rep["error"] = err or "rejected"
|
| 313 |
+
return rep
|
| 314 |
+
if endpoint == "gripper":
|
| 315 |
+
motion_s = self.gripper(bool(a["close"]))
|
| 316 |
+
return dict(ok=True, motion_s=float(motion_s or 0.0), state=self.state())
|
| 317 |
+
if endpoint == "state":
|
| 318 |
+
return dict(ok=True, state=self.state())
|
| 319 |
+
if endpoint == "observe":
|
| 320 |
+
imgs = self.images()
|
| 321 |
+
return dict(ok=True, images={c: encode_image(imgs[c], self.image_format) for c in CAMERAS},
|
| 322 |
+
state=self.state())
|
| 323 |
+
if endpoint == "ik":
|
| 324 |
+
return dict(ok=True, joint_pos_rad=[float(v) for v in self.ik(a["eef_pos"], float(a["yaw_deg"]))])
|
| 325 |
+
if endpoint == "operator":
|
| 326 |
+
kw = {k: v for k, v in a.items() if k != "kind"}
|
| 327 |
+
return self.operator(a["kind"], **kw)
|
| 328 |
+
if endpoint == "event":
|
| 329 |
+
self.event(a.get("ev", ""), **{k: v for k, v in a.items() if k != "ev"})
|
| 330 |
+
return dict(ok=True)
|
| 331 |
+
return dict(ok=False, error=f"unknown endpoint {endpoint!r}")
|
| 332 |
+
|
| 333 |
+
def serve(self, port, token=None, host="127.0.0.1", operator_log=None):
|
| 334 |
+
"""Serve forever on host:port (keep 127.0.0.1 and reach it through an SSH tunnel)."""
|
| 335 |
+
self.token = token or os.environ.get("LFF_DRIVER_TOKEN") or secrets.token_hex(12)
|
| 336 |
+
self.console = ConsoleOperator(operator_log)
|
| 337 |
+
drv = self
|
| 338 |
+
|
| 339 |
+
class H(BaseHTTPRequestHandler):
|
| 340 |
+
def log_message(self, *x):
|
| 341 |
+
pass
|
| 342 |
+
|
| 343 |
+
def do_POST(self):
|
| 344 |
+
try:
|
| 345 |
+
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}")
|
| 346 |
+
if self.headers.get(TOKEN_HEADER) != drv.token:
|
| 347 |
+
rep = dict(ok=False, error="unauthorised")
|
| 348 |
+
else:
|
| 349 |
+
rep = drv.dispatch(self.path.strip("/"), body)
|
| 350 |
+
except NotImplementedError as e:
|
| 351 |
+
rep = dict(ok=False, error=f"not implemented: {self.path} {e}")
|
| 352 |
+
except Exception as e: # anything unexpected on the robot side is a fault: stop the run
|
| 353 |
+
traceback.print_exc()
|
| 354 |
+
rep = dict(ok=False, fault=True, error=f"{type(e).__name__}: {e}")
|
| 355 |
+
data = json.dumps(rep).encode()
|
| 356 |
+
self.send_response(200)
|
| 357 |
+
self.send_header("Content-Type", "application/json")
|
| 358 |
+
self.send_header("Content-Length", str(len(data)))
|
| 359 |
+
self.end_headers()
|
| 360 |
+
self.wfile.write(data)
|
| 361 |
+
|
| 362 |
+
srv = HTTPServer((host, int(port)), H)
|
| 363 |
+
print(f"driver ready on http://{host}:{port} token={self.token}", flush=True)
|
| 364 |
+
srv.serve_forever()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/session.py
ADDED
|
@@ -0,0 +1,346 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Robot server for a real arm: robot_server's LA interface (README, robot commands, budgets, attempts, F1, --hide-k,
|
| 2 |
+
memory conditions, events.jsonl, observation files) with a robot driver instead of the simulator.
|
| 3 |
+
|
| 4 |
+
Everything above this server is unchanged: the MCP server (scripts/mcp_robot_server.py), the native-harness adapters
|
| 5 |
+
(Codex / Claude Code, with or without the jail), api_player. They talk to this server exactly as to the simulated one
|
| 6 |
+
(POST /call on 127.0.0.1, same token file, same workspace layout). Below it, lffbench/real/protocol.py talks to the
|
| 7 |
+
driver on the robot PC (usually through an SSH tunnel).
|
| 8 |
+
|
| 9 |
+
What differs from simulation, all of it on purpose (docs/17):
|
| 10 |
+
- README: "a real <robot> arm (<n> joints)" instead of "Franka Emika Panda (7 joints) ... in a physics simulation";
|
| 11 |
+
"a person resets the scene"; "s of robot motion" (budget_left key motion_seconds instead of sim_seconds).
|
| 12 |
+
- outcome: the operator judges the end state against the task's checklist (F1 only; F2 needs simulator measurements).
|
| 13 |
+
- reset: arm to home, then the operator rebuilds the scene from the task's setup sheet.
|
| 14 |
+
- a driver fault ends the episode and marks the run invalid (events.jsonl ev=run_invalid).
|
| 15 |
+
- no video, no regression snapshots here (the driver side records video).
|
| 16 |
+
|
| 17 |
+
python -m lffbench.real.session --task real_offcenter_push --seed 5000 --driver http://127.0.0.1:9900 \
|
| 18 |
+
--sandbox <dir> --log-dir <dir> --port 9800 [robot_server's la options]
|
| 19 |
+
(scripts/start_real_session.sh does this and writes session.json, like scripts/start_robot_session.sh.)
|
| 20 |
+
"""
|
| 21 |
+
import argparse
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import signal
|
| 25 |
+
import time
|
| 26 |
+
import traceback
|
| 27 |
+
from http.server import BaseHTTPRequestHandler, HTTPServer
|
| 28 |
+
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
from ..agent import robot_server as RS
|
| 32 |
+
from ..agent.tools import _json_default
|
| 33 |
+
from .executor import RealToolExecutor
|
| 34 |
+
from .protocol import DriverClient, DriverError, DriverFault
|
| 35 |
+
from .tasks import REAL_TASKS
|
| 36 |
+
|
| 37 |
+
SIM_TEXT = { # robot_server._readme_la sentence -> real-robot sentence (each must occur, else refuse to start)
|
| 38 |
+
"embodiment": ("You control a Franka Emika Panda robot arm (7 joints) with a two-finger parallel gripper in a physics "
|
| 39 |
+
"simulation.", "You control a real {robot} robot arm ({n} joints) with a two-finger parallel gripper."),
|
| 40 |
+
"reset": ("Before every attempt the scene is reset to exactly the same initial state.",
|
| 41 |
+
"Before every attempt a person resets the scene to the same initial state."),
|
| 42 |
+
"motion": (" s of simulated robot motion;", " s of robot motion;"),
|
| 43 |
+
"joints": ("joint_pos_rad = the 7 arm joint angles", "joint_pos_rad = the {n} arm joint angles"),
|
| 44 |
+
}
|
| 45 |
+
REPLY_TEXT = [("The scene has been reset to exactly the same initial state.",
|
| 46 |
+
"A person has reset the scene to the same initial state.")]
|
| 47 |
+
FAULT_MSG = "The robot stopped because of a hardware problem. The episode is over. Stop now and report."
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _realify(o):
|
| 51 |
+
"""Agent-facing reply wording for the real robot (see module doc)."""
|
| 52 |
+
if isinstance(o, dict):
|
| 53 |
+
return {("motion_seconds" if k == "sim_seconds" else k): _realify(v) for k, v in o.items()}
|
| 54 |
+
if isinstance(o, list):
|
| 55 |
+
return [_realify(v) for v in o]
|
| 56 |
+
if isinstance(o, str):
|
| 57 |
+
for a, b in REPLY_TEXT:
|
| 58 |
+
o = o.replace(a, b)
|
| 59 |
+
return o
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class RealRobotSession(RS.RobotSession):
|
| 63 |
+
def __init__(self, a): # robot_server.RobotSession.__init__ minus the simulator
|
| 64 |
+
bad = [m for m, c in (("--style la", a.style != "la"), ("--perception rgb", a.perception != "rgb"),
|
| 65 |
+
("--feedback F0|F1", a.feedback == "F2"), ("--arm none", a.arm != "none"),
|
| 66 |
+
("no --nominal", a.nominal)) if c]
|
| 67 |
+
if bad:
|
| 68 |
+
raise SystemExit("real robot needs " + ", ".join(bad))
|
| 69 |
+
self.a = a
|
| 70 |
+
self.task = REAL_TASKS[a.task]()
|
| 71 |
+
self.task.judge = self._judge
|
| 72 |
+
if a.max_steps is None:
|
| 73 |
+
a.max_steps = int(self.task.agent_max_steps)
|
| 74 |
+
self.inst = self.task.sample_instance(a.seed)
|
| 75 |
+
self.inst_override = json.loads(a.inst_override) if a.inst_override else {}
|
| 76 |
+
self.inst.update(self.inst_override) # tests only (logged)
|
| 77 |
+
self.arm, self.arm_overrides, self.reveal_text = "none", {}, ""
|
| 78 |
+
self.n_mon_events = 0
|
| 79 |
+
self.protocol = self.task.protocol
|
| 80 |
+
self.k = a.k or self.task.max_attempts
|
| 81 |
+
self.k_shown = 1 if a.hide_k and a.memory == "full" else self.k
|
| 82 |
+
self.sandbox = os.path.abspath(a.sandbox)
|
| 83 |
+
self.obs_dir = os.path.join(self.sandbox, "obs")
|
| 84 |
+
self.log_dir = os.path.abspath(a.log_dir)
|
| 85 |
+
os.makedirs(self.obs_dir, exist_ok=True)
|
| 86 |
+
os.makedirs(os.path.join(self.log_dir, "images"), exist_ok=True)
|
| 87 |
+
self.events = open(os.path.join(self.log_dir, "events.jsonl"), "a")
|
| 88 |
+
import secrets
|
| 89 |
+
self.token = secrets.token_hex(8)
|
| 90 |
+
self.n_actions, self.attempt, self.step = 0, 1, 0
|
| 91 |
+
self.finished, self.waiting_new_agent, self.invalid = False, False, ""
|
| 92 |
+
self.history, self.last_send, self.video = [], None, None
|
| 93 |
+
self.base_off = np.zeros(3) # the driver already reports the robot-base frame
|
| 94 |
+
self.run = a.run_name or os.path.basename(self.log_dir)
|
| 95 |
+
self.driver = DriverClient(a.driver, a.driver_token, timeout=a.driver_timeout)
|
| 96 |
+
self.dinfo = self.driver.info()
|
| 97 |
+
if self.task.needs_ik and np.any(self.task.bias(self.inst)) and not self.dinfo["ik"]:
|
| 98 |
+
raise SystemExit(f"{a.task} has a calibration bias: the driver must implement /ik (believed joint angles)")
|
| 99 |
+
m = float(self.task.bias_margin)
|
| 100 |
+
self.ws_lo = np.asarray(self.dinfo["workspace"]["lo"], float) + [m, m, 0.0]
|
| 101 |
+
self.ws_hi = np.asarray(self.dinfo["workspace"]["hi"], float) - [m, m, 0.0]
|
| 102 |
+
self.driver.event("session_start", run=self.run, task=a.task, seed=a.seed, k=self.k)
|
| 103 |
+
self._start_attempt(reset=True)
|
| 104 |
+
self._write_sandbox()
|
| 105 |
+
self.log(dict(ev="session_start", task=a.task, seed=a.seed, k=self.k, k_shown=self.k_shown, protocol=self.protocol,
|
| 106 |
+
memory=a.memory, feedback=a.feedback, instruction=a.instruction, perception=a.perception,
|
| 107 |
+
inst={k: v for k, v in self.inst.items() if not k.startswith("_")}, arm=self.arm,
|
| 108 |
+
arm_overrides={}, reveal="", dossier=a.dossier or "", backend="real",
|
| 109 |
+
driver_info={k: v for k, v in self.dinfo.items() if k != "ok"},
|
| 110 |
+
agent_workspace=dict(lo=self.ws_lo.round(4).tolist(), hi=self.ws_hi.round(4).tolist()),
|
| 111 |
+
inst_override=self.inst_override, sim_counterpart=self.task.sim_counterpart,
|
| 112 |
+
video_ignored=bool(a.video)))
|
| 113 |
+
|
| 114 |
+
# ------------------------------------------------------------------ simulator-dependent parts, replaced
|
| 115 |
+
def _start_attempt(self, reset):
|
| 116 |
+
self.n_actions = 0
|
| 117 |
+
if reset:
|
| 118 |
+
self.driver.home()
|
| 119 |
+
self.driver.operator("reset", run=self.run, attempt=self.attempt, setup=self.task.setup_text(self.inst),
|
| 120 |
+
text=f"task {self.a.task} seed {self.a.seed}")
|
| 121 |
+
self.driver.event("attempt_start", run=self.run, attempt=self.attempt)
|
| 122 |
+
self.ex = RealToolExecutor(self.driver, self.dinfo, bias=self.task.bias(self.inst), image_res=self.a.image_res)
|
| 123 |
+
self.step = 0
|
| 124 |
+
|
| 125 |
+
def _judge(self, inst):
|
| 126 |
+
self.driver.event("attempt_end", run=self.run, attempt=self.attempt)
|
| 127 |
+
rep = self.driver.operator("judge", run=self.run, attempt=self.attempt, checklist=self.task.checklist(inst),
|
| 128 |
+
text=f"task {self.a.task} seed {self.a.seed}: judge the scene as it is now")
|
| 129 |
+
if not isinstance(rep.get("success"), bool):
|
| 130 |
+
raise DriverError("/operator judge: reply needs \"success\": true|false")
|
| 131 |
+
return dict(success=rep["success"], note=str(rep.get("note", "")), judged_by="operator",
|
| 132 |
+
motion_s=round(self.ex.motion_s, 2))
|
| 133 |
+
|
| 134 |
+
def _budget_left(self):
|
| 135 |
+
used = self.ex.motion_s
|
| 136 |
+
return dict(commands=max(self.a.max_steps - self.n_actions, 0),
|
| 137 |
+
sim_seconds=round(max(self.sim_budget() - used, 0.0), 1)) # renamed to motion_seconds in replies
|
| 138 |
+
|
| 139 |
+
def _state_v2(self):
|
| 140 |
+
p = self.ex.proprio()
|
| 141 |
+
st = dict(eef_pos=p["eef_pos"], eef_yaw_deg=p["eef_yaw_deg"], gripper_width_m=p["gripper_width_m"])
|
| 142 |
+
st["joint_pos_rad"] = [round(float(v), 4) for v in self.ex.joints()]
|
| 143 |
+
st["budget_left"] = self._budget_left()
|
| 144 |
+
return st
|
| 145 |
+
|
| 146 |
+
def _snap_regressions(self):
|
| 147 |
+
return None
|
| 148 |
+
|
| 149 |
+
def readme_la(self):
|
| 150 |
+
text = RS._readme_la(self)
|
| 151 |
+
n = int(self.dinfo["n_joints"])
|
| 152 |
+
for key, (old, new) in SIM_TEXT.items():
|
| 153 |
+
if key == "reset" and self.protocol != "cross":
|
| 154 |
+
continue
|
| 155 |
+
if old not in text: # robot_server's README changed: update SIM_TEXT rather than ship a half-sim README
|
| 156 |
+
raise SystemExit(f"README sentence for {key!r} not found in robot_server._readme_la: {old!r}")
|
| 157 |
+
text = text.replace(old, new.format(robot=self.dinfo["robot"], n=n))
|
| 158 |
+
return text
|
| 159 |
+
|
| 160 |
+
def _done(self, reason):
|
| 161 |
+
rep = RS.RobotSession._done(self, reason)
|
| 162 |
+
if self.finished:
|
| 163 |
+
self.driver.event("episode_end", run=self.run, attempt=self.attempt)
|
| 164 |
+
return rep
|
| 165 |
+
|
| 166 |
+
# ------------------------------------------------------------------ dispatch
|
| 167 |
+
def handle(self, cmd, args):
|
| 168 |
+
if self.invalid:
|
| 169 |
+
return dict(ok=False, error=FAULT_MSG)
|
| 170 |
+
try:
|
| 171 |
+
return _realify(RS.RobotSession.handle(self, cmd, args))
|
| 172 |
+
except DriverError as e: # robot fault, operator marked the run invalid, or the driver broke the protocol
|
| 173 |
+
self.invalid, self.finished = str(e), True
|
| 174 |
+
self.log(dict(ev="run_invalid", attempt=self.attempt, step=self.step, cmd=cmd, args=args,
|
| 175 |
+
fault=isinstance(e, DriverFault), error=str(e), traceback=traceback.format_exc()[-2000:]))
|
| 176 |
+
try:
|
| 177 |
+
self.driver.event("run_invalid", run=self.run, attempt=self.attempt, error=str(e))
|
| 178 |
+
except DriverError:
|
| 179 |
+
pass
|
| 180 |
+
return dict(ok=False, error=FAULT_MSG)
|
| 181 |
+
|
| 182 |
+
def handle_v2(self, cmd, args):
|
| 183 |
+
if cmd != "move_eef" or self.finished:
|
| 184 |
+
return RS._handle_v2(self, cmd, args)
|
| 185 |
+
return self._move_eef(args)
|
| 186 |
+
|
| 187 |
+
def _move_eef(self, args):
|
| 188 |
+
"""robot_server._handle_v2's move_eef branch (same checks, order, replies and log lines) with the driver's
|
| 189 |
+
workspace instead of the simulator's WS_LO / WS_HI. tests/real_selfcheck.py compares the two paths reply by
|
| 190 |
+
reply; keep them in step."""
|
| 191 |
+
cmd = "move_eef"
|
| 192 |
+
self.n_actions += 1
|
| 193 |
+
if self.n_actions > self.a.max_steps:
|
| 194 |
+
rep = self._done("command budget used up (automatic)")
|
| 195 |
+
rep["note"] = f"The budget of {self.a.max_steps} commands for this attempt was used up."
|
| 196 |
+
return rep
|
| 197 |
+
self.step += 1
|
| 198 |
+
p = self.ex.proprio()
|
| 199 |
+
unknown = set(args) - {"x", "y", "z", "yaw", "gripper", "speed"}
|
| 200 |
+
if unknown:
|
| 201 |
+
rep = dict(ok=False, error=f"unknown argument(s) {sorted(unknown)}; use x, y, z, yaw, gripper, speed")
|
| 202 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 203 |
+
return rep
|
| 204 |
+
try:
|
| 205 |
+
cur = np.asarray(p["eef_pos"], float)
|
| 206 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 207 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 208 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 209 |
+
except (TypeError, ValueError):
|
| 210 |
+
rep = dict(ok=False, error="x, y, z, yaw and speed must be numbers")
|
| 211 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 212 |
+
return rep
|
| 213 |
+
grip = args.get("gripper")
|
| 214 |
+
if grip not in (None, "open", "close"):
|
| 215 |
+
rep = dict(ok=False, error="gripper must be open or close")
|
| 216 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 217 |
+
return rep
|
| 218 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 219 |
+
tgt = np.asarray(tgt)
|
| 220 |
+
if moving and not (np.all(tgt >= self.ws_lo) and np.all(tgt <= self.ws_hi)):
|
| 221 |
+
rep = dict(ok=False, error="target rejected: the arm cannot reach it; the arm did not move")
|
| 222 |
+
rep.update(self._state_v2())
|
| 223 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep))
|
| 224 |
+
return rep
|
| 225 |
+
left = self._budget_left()["sim_seconds"]
|
| 226 |
+
raw = {}
|
| 227 |
+
rejected = False
|
| 228 |
+
if moving:
|
| 229 |
+
mv = dict(x=float(tgt[0]), y=float(tgt[1]), z=float(tgt[2]), yaw=yaw)
|
| 230 |
+
if speed is not None:
|
| 231 |
+
mv["speed"] = speed
|
| 232 |
+
res = self.ex.call("move_to", mv)
|
| 233 |
+
raw.update(res.report)
|
| 234 |
+
rejected = not res.ok # the driver refused (no IK solution ...): the arm did not move, skip the gripper
|
| 235 |
+
if grip is not None and not rejected:
|
| 236 |
+
res = self.ex.call("open_gripper" if grip == "open" else "close_gripper", {})
|
| 237 |
+
raw.update(res.report)
|
| 238 |
+
rep = dict(ok=bool(raw.get("ok", True)))
|
| 239 |
+
if raw.get("error"):
|
| 240 |
+
rep["error"] = raw["error"]
|
| 241 |
+
rep.update(self._state_v2())
|
| 242 |
+
if moving:
|
| 243 |
+
err = tgt - np.asarray(rep["eef_pos"])
|
| 244 |
+
dyaw = (yaw - rep["eef_yaw_deg"] + 90.0) % 180.0 - 90.0
|
| 245 |
+
rep["stopped_from_target"] = dict(cm=round(100 * float(np.linalg.norm(err)), 1), deg=round(abs(dyaw), 1))
|
| 246 |
+
rep["images"] = self._save_obs(cmd)
|
| 247 |
+
rep.update(self._la_files())
|
| 248 |
+
self.log(dict(ev="call", attempt=self.attempt, step=self.step, cmd=cmd, args=args, report=rep, raw=raw))
|
| 249 |
+
if rep["budget_left"]["sim_seconds"] <= 0 and left > 0:
|
| 250 |
+
fin = self._done("motion budget used up (automatic)")
|
| 251 |
+
fin["note"] = f"The {self.sim_budget():.0f} s motion budget for this attempt was used up."
|
| 252 |
+
rep["attempt_ended"] = fin
|
| 253 |
+
return rep
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def serve(a):
|
| 257 |
+
"""robot_server.serve with the real session (same HTTP contract: POST /call, X-Token, 127.0.0.1)."""
|
| 258 |
+
sess = RealRobotSession(a)
|
| 259 |
+
|
| 260 |
+
class H(BaseHTTPRequestHandler):
|
| 261 |
+
def log_message(self, *x):
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
def do_POST(self):
|
| 265 |
+
t_recv = time.time()
|
| 266 |
+
cmd = ""
|
| 267 |
+
try:
|
| 268 |
+
body = json.loads(self.rfile.read(int(self.headers["Content-Length"])))
|
| 269 |
+
cmd = body.get("cmd", "")
|
| 270 |
+
if self.headers.get("X-Token") != sess.token:
|
| 271 |
+
rep = dict(ok=False, error="unauthorised")
|
| 272 |
+
else:
|
| 273 |
+
rep = sess.handle(cmd, body.get("args", {}) or {})
|
| 274 |
+
except Exception as e: # never leak a traceback (it contains benchmark paths) to the agent
|
| 275 |
+
sess.log(dict(ev="error", error=traceback.format_exc()))
|
| 276 |
+
rep = dict(ok=False, error=f"internal error: {type(e).__name__}")
|
| 277 |
+
data = json.dumps(rep, default=_json_default, indent=None).encode()
|
| 278 |
+
if "text" in rep:
|
| 279 |
+
data = rep["text"].encode()
|
| 280 |
+
self.send_response(200)
|
| 281 |
+
self.send_header("Content-Type", "application/json")
|
| 282 |
+
self.end_headers()
|
| 283 |
+
self.wfile.write(data)
|
| 284 |
+
t_send = time.time()
|
| 285 |
+
sess.log(dict(ev="http", cmd=cmd, attempt=sess.attempt, t_recv=t_recv, t_send=t_send,
|
| 286 |
+
server_s=t_send - t_recv, think_s=(t_recv - sess.last_send) if sess.last_send else None))
|
| 287 |
+
sess.last_send = t_send
|
| 288 |
+
|
| 289 |
+
def _term(*_):
|
| 290 |
+
try: # short timeout: the driver may be blocked on an operator prompt
|
| 291 |
+
sess.driver.call("event", dict(ev="session_end", run=sess.run, attempt=sess.attempt), timeout=5)
|
| 292 |
+
except Exception:
|
| 293 |
+
pass
|
| 294 |
+
os._exit(0)
|
| 295 |
+
|
| 296 |
+
signal.signal(signal.SIGTERM, _term)
|
| 297 |
+
srv = HTTPServer(("127.0.0.1", a.port), H)
|
| 298 |
+
print(f"real robot server ready on 127.0.0.1:{a.port} driver={a.driver} sandbox={sess.sandbox} log={sess.log_dir}",
|
| 299 |
+
flush=True)
|
| 300 |
+
with open(os.path.join(sess.log_dir, "READY"), "w") as f:
|
| 301 |
+
f.write(str(os.getpid()))
|
| 302 |
+
srv.serve_forever()
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def parser():
|
| 306 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
|
| 307 |
+
ap.add_argument("--task", required=True, choices=sorted(REAL_TASKS))
|
| 308 |
+
ap.add_argument("--seed", type=int, required=True)
|
| 309 |
+
ap.add_argument("--driver", default=os.environ.get("LFF_REAL_DRIVER", "http://127.0.0.1:9900"),
|
| 310 |
+
help="driver URL (default $LFF_REAL_DRIVER or http://127.0.0.1:9900, i.e. an SSH tunnel)")
|
| 311 |
+
ap.add_argument("--driver-token", default=os.environ.get("LFF_DRIVER_TOKEN", ""),
|
| 312 |
+
help="driver token (default $LFF_DRIVER_TOKEN)")
|
| 313 |
+
ap.add_argument("--driver-timeout", type=float, default=180.0, help="seconds per driver call (operator: no limit)")
|
| 314 |
+
ap.add_argument("--run-name", default="", help="shown to the operator (default: the log dir name)")
|
| 315 |
+
ap.add_argument("--inst-override", default=os.environ.get("LFF_REAL_INST_OVERRIDE", ""),
|
| 316 |
+
help="TESTS ONLY: JSON merged into the instance (logged; default $LFF_REAL_INST_OVERRIDE)")
|
| 317 |
+
# robot_server's options that apply to the real robot (same names and defaults as there, except perception/style)
|
| 318 |
+
ap.add_argument("--k", type=int, default=None)
|
| 319 |
+
ap.add_argument("--memory", default="full", choices=["full", "none"])
|
| 320 |
+
ap.add_argument("--hide-k", action="store_true")
|
| 321 |
+
ap.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"])
|
| 322 |
+
ap.add_argument("--instruction", default="direct", choices=["direct", "indirect"])
|
| 323 |
+
ap.add_argument("--image-res", type=int, default=512)
|
| 324 |
+
ap.add_argument("--port", type=int, default=8765)
|
| 325 |
+
ap.add_argument("--sandbox", required=True)
|
| 326 |
+
ap.add_argument("--log-dir", required=True)
|
| 327 |
+
ap.add_argument("--max-steps", type=int, default=None)
|
| 328 |
+
ap.add_argument("--perception", default="rgb", choices=["depth", "rgb", "rgbd"])
|
| 329 |
+
ap.add_argument("--style", default="la", choices=["v1", "v2", "la"])
|
| 330 |
+
ap.add_argument("--nominal", action="store_true")
|
| 331 |
+
ap.add_argument("--agent-iface", default="tools", choices=["tools", "cli"])
|
| 332 |
+
ap.add_argument("--max-tool-calls", type=int, default=100)
|
| 333 |
+
ap.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"])
|
| 334 |
+
ap.add_argument("--dossier", default="")
|
| 335 |
+
ap.add_argument("--video", default="", help="ignored (the driver side records video)")
|
| 336 |
+
ap.add_argument("--video-every", type=int, default=3)
|
| 337 |
+
ap.add_argument("--video-fps", type=int, default=20)
|
| 338 |
+
return ap
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def main():
|
| 342 |
+
serve(parser().parse_args())
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
if __name__ == "__main__":
|
| 346 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/real/tasks.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Real-robot tasks. Same idea as lffbench/tasks/ (an instruction, a hidden variable the agent cannot see before it acts,
|
| 2 |
+
a success rule), but the scene is physical: the instance is a setup sheet the operator follows, and the operator
|
| 3 |
+
judges the end state. The hidden variable is drawn from the seed, so the instance list of a run is reproducible and
|
| 4 |
+
nobody has to choose it by hand.
|
| 5 |
+
|
| 6 |
+
Seeds: 5000+ for real-robot runs (same convention as simulation: 1000-1999 development, 3000 pilots, 5000+ test).
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
REAL_TASKS = {}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def register_real(cls):
|
| 14 |
+
REAL_TASKS[cls.name] = cls
|
| 15 |
+
return cls
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RealTask:
|
| 19 |
+
name = "real_base"
|
| 20 |
+
sim_counterpart = "" # the simulated task with the same hidden variable (for the paper's mapping only)
|
| 21 |
+
protocol = "cross"
|
| 22 |
+
max_attempts = 3
|
| 23 |
+
agent_max_steps = 40
|
| 24 |
+
instruction = ""
|
| 25 |
+
instruction_indirect = ""
|
| 26 |
+
needs_ik = False # True if the instance carries a calibration bias (believed joint angles need the driver's /ik)
|
| 27 |
+
bias_margin = 0.0 # largest possible |bias| (m): the agent-facing workspace is shrunk by it, so a rejected target
|
| 28 |
+
# never depends on the hidden bias
|
| 29 |
+
judge = None # set by RealRobotSession: inst -> outcome dict, asks the operator
|
| 30 |
+
|
| 31 |
+
def outcome(self, inst):
|
| 32 |
+
"""Same role as LFFTask.outcome: called by robot_server's _done when an attempt ends."""
|
| 33 |
+
return self.judge(inst)
|
| 34 |
+
|
| 35 |
+
def sample_instance(self, seed):
|
| 36 |
+
raise NotImplementedError
|
| 37 |
+
|
| 38 |
+
def setup_text(self, inst):
|
| 39 |
+
"""What the operator builds before every attempt (shown on the robot PC only, never to the agent)."""
|
| 40 |
+
raise NotImplementedError
|
| 41 |
+
|
| 42 |
+
def checklist(self, inst):
|
| 43 |
+
"""Conditions the operator checks when an attempt ends; success = all of them."""
|
| 44 |
+
raise NotImplementedError
|
| 45 |
+
|
| 46 |
+
def bias(self, inst):
|
| 47 |
+
"""Hidden calibration error added to every commanded position (robot-base frame, metres)."""
|
| 48 |
+
return np.zeros(3)
|
| 49 |
+
|
| 50 |
+
def feedback(self, inst, out, level="F1"):
|
| 51 |
+
# same text as LFFTask.feedback (F0 / F1); F2 needs simulator measurements and is refused at session start
|
| 52 |
+
if level == "F0":
|
| 53 |
+
return ""
|
| 54 |
+
return "Attempt succeeded." if out["success"] else "Attempt failed."
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@register_real
|
| 58 |
+
class RealOffcenterPush(RealTask):
|
| 59 |
+
"""L7 l7_offcenter_push on a real arm: a long opaque box with a hidden weight at one end. Pushing the middle of
|
| 60 |
+
its back face turns it (visible in the agentview); the fix is to push nearer the heavy end or to straighten it
|
| 61 |
+
afterwards. Physical build and scene layout: DRIVER.md §6.1."""
|
| 62 |
+
name = "real_offcenter_push"
|
| 63 |
+
sim_counterpart = "l7_offcenter_push"
|
| 64 |
+
# same wording as the simulated task (2026-10-19): end state only, no hint about the weight or where to push
|
| 65 |
+
instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
|
| 66 |
+
"green rectangle ahead of it (farther from the robot).")
|
| 67 |
+
instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
|
| 68 |
+
"completely inside the marked green area ahead of it (farther from the robot).")
|
| 69 |
+
SLOTS = ("end", "inner") # weight compartments per side: at the very end, or one compartment further in
|
| 70 |
+
|
| 71 |
+
def sample_instance(self, seed):
|
| 72 |
+
rng = np.random.default_rng(seed)
|
| 73 |
+
return dict(seed=int(seed), weight_side=str(rng.choice(["left", "right"])), weight_slot=str(rng.choice(self.SLOTS)))
|
| 74 |
+
|
| 75 |
+
def setup_text(self, inst):
|
| 76 |
+
side = {"left": "LEFT (the robot's left, +y)", "right": "RIGHT (the robot's right, -y)"}[inst["weight_side"]]
|
| 77 |
+
slot = {"end": "the outermost compartment", "inner": "the second compartment from that end"}[inst["weight_slot"]]
|
| 78 |
+
return "\n".join([
|
| 79 |
+
f"- weight block inside the box: {side} end, in {slot};",
|
| 80 |
+
"- the other compartments stay empty; close the lid; both ends look the same from outside;",
|
| 81 |
+
"- box on the START tape marks: long side across the robot (left-right), back face on the back mark;",
|
| 82 |
+
"- nothing else on the table; the green target rectangle tape unchanged.",
|
| 83 |
+
])
|
| 84 |
+
|
| 85 |
+
def checklist(self, inst):
|
| 86 |
+
return ["all four bottom corners of the box are inside the green rectangle (a corner on the tape = outside)",
|
| 87 |
+
"the box is standing on its bottom face (not tipped over)",
|
| 88 |
+
"the box was only pushed with the closed gripper (no pushes with the fingers open)",
|
| 89 |
+
"the gripper is not touching the box"]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@register_real
|
| 93 |
+
class RealBiasPlace(RealTask):
|
| 94 |
+
"""L1 l1_bias_place on a real arm: pick-and-place with a calibration error injected in software (the benchmark
|
| 95 |
+
adds `bias` to every commanded position and subtracts it from every reported one, exactly as in simulation).
|
| 96 |
+
The arm itself is unchanged; the cameras show where the gripper really is. Physical build: DRIVER.md §6.2."""
|
| 97 |
+
name = "real_bias_place"
|
| 98 |
+
sim_counterpart = "l1_bias_place"
|
| 99 |
+
instruction = "Pick up the red cube and put it into the bowl."
|
| 100 |
+
instruction_indirect = "Pick up the small red block and put it into the round bowl."
|
| 101 |
+
needs_ik = True
|
| 102 |
+
R_MIN, R_MAX = 0.025, 0.040 # bias magnitude (m), as l1_bias_place
|
| 103 |
+
bias_margin = R_MAX
|
| 104 |
+
LAYOUTS = ("A", "B", "C", "D") # taped (cube mark, bowl mark) pairs; DRIVER.md §6.2
|
| 105 |
+
|
| 106 |
+
def sample_instance(self, seed):
|
| 107 |
+
rng = np.random.default_rng(seed)
|
| 108 |
+
r, th = float(rng.uniform(self.R_MIN, self.R_MAX)), float(rng.uniform(-np.pi, np.pi))
|
| 109 |
+
return dict(seed=int(seed), layout=str(rng.choice(self.LAYOUTS)),
|
| 110 |
+
bias=[round(r * np.cos(th), 4), round(r * np.sin(th), 4), 0.0], bias_r=round(r, 4),
|
| 111 |
+
bias_theta=round(th, 4))
|
| 112 |
+
|
| 113 |
+
def bias(self, inst):
|
| 114 |
+
return np.asarray(inst["bias"], float)
|
| 115 |
+
|
| 116 |
+
def setup_text(self, inst):
|
| 117 |
+
L = inst["layout"]
|
| 118 |
+
return "\n".join([f"- red cube on mark {L}1, bowl on mark {L}2 (layout {L});",
|
| 119 |
+
"- nothing else on the table."])
|
| 120 |
+
|
| 121 |
+
def checklist(self, inst):
|
| 122 |
+
return ["the red cube is inside the bowl (resting in it, not on the rim)",
|
| 123 |
+
"the gripper is open and not holding the cube"]
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/__init__.py
ADDED
|
File without changes
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l2_knock.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L2-A knock_restore: move the ketchup from the tray into the basket; everything else must stay on the tray.
|
| 2 |
+
|
| 3 |
+
Constructed L2 event: the first time the ketchup is lifted off the tray (grasped and raised 3 cm), one of
|
| 4 |
+
its two neighbours on the tray is "knocked" off the tray and lands upright on the table beside it. Which
|
| 5 |
+
neighbour and to which side of the tray (left / right in the camera image) it falls are hidden per-instance
|
| 6 |
+
variables; only the scene *after* the failure shows which item is missing and where it is. The main task itself still succeeds, so an agent that stops after
|
| 7 |
+
the main task fails; it has to notice the side effect and put the item back (within-episode recovery).
|
| 8 |
+
|
| 9 |
+
Protocols
|
| 10 |
+
within (default, `l2_knock_restore`) one episode; attempt 1 = the main task, every later attempt is one
|
| 11 |
+
corrective round chosen by the policy; the outcome (success + F2 text) is computed after each round.
|
| 12 |
+
cross (`l2_knock_restore_cross`) reset to the same instance between attempts; the knock happens again
|
| 13 |
+
on every attempt, so a learner must anticipate it. Validated strategy: restore the reported item
|
| 14 |
+
right after the main task. The rule also allows prevention (the knock only hits a neighbour that is
|
| 15 |
+
still within 12 cm of the ketchup's start spot), but picking a neighbour up in place is mostly blocked
|
| 16 |
+
by the tray's end wall (Panda hand), so prevention is not a validated strategy (see the task card).
|
| 17 |
+
"""
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from .. import envs
|
| 21 |
+
from ..bddl import write_bddl
|
| 22 |
+
from ..skills import Skills
|
| 23 |
+
from ..task_base import LFFTask, register_task
|
| 24 |
+
|
| 25 |
+
TARGET = "ketchup_1"
|
| 26 |
+
NEIGHBOR_POOL = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
|
| 27 |
+
TRAY, BASKET = "wooden_tray_1", "basket_1"
|
| 28 |
+
PARK_XY = {"cream_cheese_1": (0.0, 1.2), "butter_1": (0.2, 1.2), "chocolate_pudding_1": (-0.2, 1.2)}
|
| 29 |
+
|
| 30 |
+
# wooden_tray collision geometry in its body frame (from the LIBERO MJCF; long axis = body x)
|
| 31 |
+
TRAY_IN_X = (-0.128, 0.143)
|
| 32 |
+
TRAY_IN_Y = (-0.081, 0.072)
|
| 33 |
+
TRAY_OUT_X = (-0.142, 0.156)
|
| 34 |
+
TRAY_OUT_Y = (-0.088, 0.080)
|
| 35 |
+
TRAY_CX, TRAY_CY = 0.0075, -0.0045 # centre of the inner floor
|
| 36 |
+
TRAY_FLOOR = 0.0072 # floor top above the tray's lowest point
|
| 37 |
+
BASKET_IN = 0.060 # half size of the basket's inner floor (square, centred on the body origin)
|
| 38 |
+
BASKET_RIM = 0.150 # rim height above the basket's lowest point
|
| 39 |
+
BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
|
| 40 |
+
|
| 41 |
+
NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
|
| 42 |
+
"chocolate_pudding_1": "chocolate pudding"}
|
| 43 |
+
DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
|
| 44 |
+
"chocolate_pudding_1": "brown box"}
|
| 45 |
+
SIDES = ("left", "right") # side of the tray in the agentview image: left = world -y, right = world +y
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _qz(a):
|
| 49 |
+
return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _wrap_half(a):
|
| 53 |
+
"""wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
|
| 54 |
+
return (a + np.pi / 2) % np.pi - np.pi / 2
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
class KnockSkills(Skills):
|
| 58 |
+
"""Skills with a hook called after every control step (used for the failure injection)."""
|
| 59 |
+
|
| 60 |
+
def __init__(self, env, bias=None, recorder=None, hook=None):
|
| 61 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 62 |
+
self.hook = hook
|
| 63 |
+
|
| 64 |
+
def _act(self, dpos, drot, grip):
|
| 65 |
+
super()._act(dpos, drot, grip)
|
| 66 |
+
if self.hook is not None:
|
| 67 |
+
self.hook()
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
@register_task
|
| 71 |
+
class KnockRestore(LFFTask):
|
| 72 |
+
name = "l2_knock_restore"
|
| 73 |
+
level = "L2"
|
| 74 |
+
category = "state_restoration"
|
| 75 |
+
capabilities = ("Perceive", "Plan")
|
| 76 |
+
protocol = "within"
|
| 77 |
+
instruction = "Move the ketchup from the tray into the basket. Everything else must stay on the tray."
|
| 78 |
+
instruction_indirect = ("Move the red bottle from the wooden tray into the wicker basket. "
|
| 79 |
+
"Everything else must stay on the tray.")
|
| 80 |
+
knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
|
| 81 |
+
knock_radius = 0.12 # only a victim still within this distance of the ketchup's start spot is knocked
|
| 82 |
+
|
| 83 |
+
def __init__(self, cam_res=None):
|
| 84 |
+
super().__init__(cam_res)
|
| 85 |
+
# upright orientations (wxyz), fixed here so the task does not depend on LIBERO's placement convention:
|
| 86 |
+
# the ketchup mesh is modelled lying down; tray / basket / boxes are upright in their mesh frame
|
| 87 |
+
# (identity => tray long axis along world x, as the TRAY_* constants assume).
|
| 88 |
+
self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
|
| 89 |
+
self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
|
| 90 |
+
self._inj = None
|
| 91 |
+
self.start = {}
|
| 92 |
+
|
| 93 |
+
# ------------------------------------------------------------ scene
|
| 94 |
+
def make_bddl(self):
|
| 95 |
+
names = [TARGET, *NEIGHBOR_POOL, TRAY, BASKET]
|
| 96 |
+
objs = []
|
| 97 |
+
for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
|
| 98 |
+
x0 = -0.30 + 0.13 * (i % 3)
|
| 99 |
+
y0 = -0.25 + 0.25 * (i // 3)
|
| 100 |
+
objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
|
| 101 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 102 |
+
|
| 103 |
+
def sample_instance(self, seed):
|
| 104 |
+
rng = np.random.default_rng(seed)
|
| 105 |
+
nb = [str(x) for x in rng.choice(NEIGHBOR_POOL, size=2, replace=False)] # [robot side, far side]
|
| 106 |
+
victim = int(rng.integers(2))
|
| 107 |
+
side = str(rng.choice(SIDES))
|
| 108 |
+
return dict(seed=int(seed),
|
| 109 |
+
tray_xy=[float(rng.uniform(-0.07, 0.01)), float(rng.uniform(-0.11, -0.08))],
|
| 110 |
+
tray_yaw=float(rng.uniform(-0.10, 0.10)),
|
| 111 |
+
basket_xy=[float(rng.uniform(-0.08, 0.02)), float(rng.uniform(0.24, 0.26))],
|
| 112 |
+
target_dx=float(rng.uniform(-0.01, 0.01)),
|
| 113 |
+
target_yaw=float(np.pi / 2 + rng.uniform(-0.2, 0.2)),
|
| 114 |
+
neighbors=nb,
|
| 115 |
+
nb_gap=[float(rng.uniform(0.066, 0.078)) for _ in range(2)],
|
| 116 |
+
nb_dy=[float(rng.uniform(-0.012, 0.012)) for _ in range(2)],
|
| 117 |
+
nb_yaw=[float(np.pi / 2 + rng.uniform(-0.15, 0.15)) for _ in range(2)],
|
| 118 |
+
# hidden variables of the injected failure
|
| 119 |
+
victim=nb[victim], side=side,
|
| 120 |
+
land_gap=float(rng.uniform(0.015, 0.035 if side == "right" else 0.04)), # wall -> object
|
| 121 |
+
land_off=float(rng.uniform(-0.025, 0.025)), # along the wall, from the victim's spot
|
| 122 |
+
land_dyaw=float(rng.uniform(-0.35, 0.35)))
|
| 123 |
+
|
| 124 |
+
def _tray_frame(self):
|
| 125 |
+
p = envs.obj_pos(self.env, TRAY)
|
| 126 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, TRAY)].reshape(3, 3)
|
| 127 |
+
return p, R
|
| 128 |
+
|
| 129 |
+
def tray_yaw(self):
|
| 130 |
+
_, R = self._tray_frame()
|
| 131 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 132 |
+
|
| 133 |
+
def tray_to_world(self, lx, ly):
|
| 134 |
+
p, R = self._tray_frame()
|
| 135 |
+
return p[:2] + R[:2, :2] @ np.array([lx, ly])
|
| 136 |
+
|
| 137 |
+
def world_to_tray(self, xy):
|
| 138 |
+
p, R = self._tray_frame()
|
| 139 |
+
return R[:2, :2].T @ (np.asarray(xy[:2]) - p[:2])
|
| 140 |
+
|
| 141 |
+
def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
|
| 142 |
+
"""Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z."""
|
| 143 |
+
q = envs._quat_mul(_qz(yaw), self.q_up[name])
|
| 144 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
|
| 145 |
+
self.env.sim.forward()
|
| 146 |
+
dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
|
| 147 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 148 |
+
self.env.sim.data.qpos[qa + 2] -= dz
|
| 149 |
+
self.env.sim.forward()
|
| 150 |
+
|
| 151 |
+
def apply_instance(self, inst):
|
| 152 |
+
env = self.env
|
| 153 |
+
envs.scale_mass(env, TRAY, 2.0) # heavy enough not to be dragged around by the gripper
|
| 154 |
+
envs.scale_mass(env, BASKET, 2.0)
|
| 155 |
+
for n in NEIGHBOR_POOL:
|
| 156 |
+
if n not in inst["neighbors"]:
|
| 157 |
+
self.place(n, PARK_XY[n], 0.0, surface_z=0.0) # unused neighbour: on the floor, out of view
|
| 158 |
+
self.place(TRAY, inst["tray_xy"], inst["tray_yaw"])
|
| 159 |
+
self.place(BASKET, inst["basket_xy"], 0.0)
|
| 160 |
+
floor = envs.TABLE_Z + TRAY_FLOOR
|
| 161 |
+
ty = inst["tray_yaw"]
|
| 162 |
+
cx = TRAY_CX + inst["target_dx"]
|
| 163 |
+
self.place(TARGET, self.tray_to_world(cx, TRAY_CY), ty + inst["target_yaw"], floor)
|
| 164 |
+
for i, n in enumerate(inst["neighbors"]): # in a row along the tray: [robot side, ketchup, far side]
|
| 165 |
+
lx = cx + (-1 if i == 0 else 1) * inst["nb_gap"][i]
|
| 166 |
+
self.place(n, self.tray_to_world(lx, TRAY_CY + inst["nb_dy"][i]), ty + inst["nb_yaw"][i], floor)
|
| 167 |
+
env.sim.forward()
|
| 168 |
+
|
| 169 |
+
def reset_instance(self, inst, recorder=None):
|
| 170 |
+
self.env.reset()
|
| 171 |
+
self.apply_instance(inst)
|
| 172 |
+
self.env.sim.forward()
|
| 173 |
+
envs.settle(self.env, 10)
|
| 174 |
+
self.start = {n: self.footprint(n) for n in [TARGET] + inst["neighbors"]}
|
| 175 |
+
self._inj = dict(inst=inst, done=False, knocked=False, step=None)
|
| 176 |
+
self.sk = KnockSkills(self.env, bias=self.skill_bias(inst), recorder=recorder, hook=self._knock_hook)
|
| 177 |
+
return self.sk
|
| 178 |
+
|
| 179 |
+
# ------------------------------------------------------------ measurements
|
| 180 |
+
def footprint(self, name):
|
| 181 |
+
"""Measured pose summary of an object: AABB centre, yaw of the long horizontal axis, half sizes, z range.
|
| 182 |
+
Scripted policies use it as a stand-in for perception."""
|
| 183 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 184 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 185 |
+
best = None
|
| 186 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 187 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 188 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 189 |
+
e = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 190 |
+
lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
|
| 191 |
+
vol = float(np.prod(m.geom_aabb[g, 3:]))
|
| 192 |
+
if best is None or vol > best[0]:
|
| 193 |
+
best = (vol, R, m.geom_aabb[g, 3:])
|
| 194 |
+
_, R, half = best
|
| 195 |
+
horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
|
| 196 |
+
ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
|
| 197 |
+
return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
|
| 198 |
+
half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
|
| 199 |
+
|
| 200 |
+
def _corners_tray(self, name):
|
| 201 |
+
"""All collision-box corners of `name` in tray coordinates."""
|
| 202 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 203 |
+
pts = []
|
| 204 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 205 |
+
Rg = d.geom_xmat[g].reshape(3, 3)
|
| 206 |
+
c = d.geom_xpos[g] + Rg @ m.geom_aabb[g, :3]
|
| 207 |
+
h = m.geom_aabb[g, 3:]
|
| 208 |
+
for sx in (-1, 1):
|
| 209 |
+
for sy in (-1, 1):
|
| 210 |
+
for sz in (-1, 1):
|
| 211 |
+
pts.append(self.world_to_tray(c + Rg @ (h * np.array([sx, sy, sz]))))
|
| 212 |
+
return np.array(pts)
|
| 213 |
+
|
| 214 |
+
# ------------------------------------------------------------ failure injection
|
| 215 |
+
def _knock_hook(self):
|
| 216 |
+
st = self._inj
|
| 217 |
+
if st is None or st["done"] or self.sk is None:
|
| 218 |
+
return
|
| 219 |
+
if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
|
| 220 |
+
return
|
| 221 |
+
if not self.sk.holding(TARGET):
|
| 222 |
+
return
|
| 223 |
+
st["done"] = True
|
| 224 |
+
inst = st["inst"]
|
| 225 |
+
vxy = np.array(self.footprint(inst["victim"])["center"][:2])
|
| 226 |
+
if np.linalg.norm(vxy - np.array(self.start[TARGET]["center"][:2])) > self.knock_radius:
|
| 227 |
+
return # the victim was moved out of the way beforehand: nothing happens
|
| 228 |
+
self.knock(inst)
|
| 229 |
+
st["knocked"] = True
|
| 230 |
+
st["step"] = self.sk.n_steps
|
| 231 |
+
|
| 232 |
+
def knock(self, inst):
|
| 233 |
+
"""Teleport the victim off the tray onto the table beside the long wall on `side`: upright, long axis
|
| 234 |
+
roughly perpendicular to the wall (so a gripper closing along the wall can pick it up), nearest point
|
| 235 |
+
`land_gap` from the wall's outer face, `land_off` along the wall from where it stood.
|
| 236 |
+
(The robot-side end of the tray was tried too: the end wall hides a flat box there from agentview.)"""
|
| 237 |
+
v, side = inst["victim"], inst["side"]
|
| 238 |
+
loc = self.world_to_tray(self.footprint(v)["center"])
|
| 239 |
+
axis, sgn = 1, (1 if side == "right" else -1)
|
| 240 |
+
wall = TRAY_OUT_Y[1] if sgn > 0 else TRAY_OUT_Y[0]
|
| 241 |
+
self.place(v, self.tray_to_world(loc[0] + inst["land_off"], wall + sgn * 0.08),
|
| 242 |
+
self.tray_yaw() + np.pi / 2 + inst["land_dyaw"])
|
| 243 |
+
pts = self._corners_tray(v)
|
| 244 |
+
near = pts[:, axis].min() if sgn > 0 else pts[:, axis].max()
|
| 245 |
+
shift = (wall + sgn * inst["land_gap"]) - near
|
| 246 |
+
_, R = self._tray_frame()
|
| 247 |
+
qa, _ = envs.free_joint_addr(self.env, v)
|
| 248 |
+
self.env.sim.data.qpos[qa:qa + 2] += R[:2, axis] * shift
|
| 249 |
+
self.env.sim.forward()
|
| 250 |
+
|
| 251 |
+
# ------------------------------------------------------------ outcome
|
| 252 |
+
def where(self, name):
|
| 253 |
+
"""Classify where an object is: 'tray', 'basket', 'gripper', 'table' or 'other'."""
|
| 254 |
+
f = self.footprint(name)
|
| 255 |
+
c = np.array(f["center"])
|
| 256 |
+
lt = self.world_to_tray(c)
|
| 257 |
+
if self.sk is not None and self.sk.holding(name) and f["zmin"] > envs.TABLE_Z + 0.02:
|
| 258 |
+
return "gripper", f
|
| 259 |
+
if (TRAY_IN_X[0] - 0.005 <= lt[0] <= TRAY_IN_X[1] + 0.005 and TRAY_IN_Y[0] - 0.005 <= lt[1] <= TRAY_IN_Y[1] + 0.005
|
| 260 |
+
and f["zmin"] > envs.obj_min_z(self.env, TRAY) + 0.002):
|
| 261 |
+
return "tray", f
|
| 262 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 263 |
+
if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM:
|
| 264 |
+
return "basket", f
|
| 265 |
+
if f["zmin"] < envs.TABLE_Z + 0.01:
|
| 266 |
+
return "table", f
|
| 267 |
+
return "other", f
|
| 268 |
+
|
| 269 |
+
def rel_to_tray(self, c):
|
| 270 |
+
"""Where a point on the table is relative to the tray, in robot-centric words (never image left/right).
|
| 271 |
+
Distances are from the tray's outer edge to the object's centre."""
|
| 272 |
+
lt = self.world_to_tray(c)
|
| 273 |
+
dy = lt[1] - TRAY_OUT_Y[1] if lt[1] > TRAY_OUT_Y[1] else (lt[1] - TRAY_OUT_Y[0] if lt[1] < TRAY_OUT_Y[0] else 0.0)
|
| 274 |
+
dx = lt[0] - TRAY_OUT_X[1] if lt[0] > TRAY_OUT_X[1] else (lt[0] - TRAY_OUT_X[0] if lt[0] < TRAY_OUT_X[0] else 0.0)
|
| 275 |
+
# robot-centric words (tray yaw is within +-0.1 rad, so tray axes ~ world axes): +y = robot's left,
|
| 276 |
+
# +x = forward (away from the robot)
|
| 277 |
+
parts = []
|
| 278 |
+
if dy:
|
| 279 |
+
parts.append(f"{100 * abs(dy):.0f} cm to the robot's {'left (+y)' if dy > 0 else 'right (-y)'} of the tray")
|
| 280 |
+
if dx:
|
| 281 |
+
parts.append(f"{100 * abs(dx):.0f} cm {'forward (+x, away from the robot)' if dx > 0 else 'backward (-x, toward the robot)'} "
|
| 282 |
+
f"of the tray")
|
| 283 |
+
return " and ".join(parts) if parts else "right next to the tray"
|
| 284 |
+
|
| 285 |
+
def _describe(self, inst, loc, names):
|
| 286 |
+
t_loc = loc[TARGET][0]
|
| 287 |
+
tn = names[TARGET]
|
| 288 |
+
msgs = []
|
| 289 |
+
if t_loc != "basket":
|
| 290 |
+
msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
|
| 291 |
+
"tray": f"The {tn} is still on the tray, not in the basket.",
|
| 292 |
+
"table": f"The {tn} is on the table ({self.rel_to_tray(loc[TARGET][1]['center'])}), "
|
| 293 |
+
"not in the basket."}.get(t_loc, f"The {tn} is not in the basket."))
|
| 294 |
+
for n in inst["neighbors"]:
|
| 295 |
+
l, f = loc[n]
|
| 296 |
+
if l == "tray":
|
| 297 |
+
continue
|
| 298 |
+
msgs.append({"table": f"The {names[n]} is no longer on the tray: it is on the table "
|
| 299 |
+
f"{self.rel_to_tray(f['center'])}.",
|
| 300 |
+
"basket": f"The {names[n]} is no longer on the tray: it is in the basket.",
|
| 301 |
+
"gripper": f"The {names[n]} is no longer on the tray: it is still in the gripper."}
|
| 302 |
+
.get(l, f"The {names[n]} is no longer on the tray."))
|
| 303 |
+
if not msgs:
|
| 304 |
+
msgs.append(f"The {tn} is in the basket and everything else is on the tray.")
|
| 305 |
+
return " ".join(msgs)
|
| 306 |
+
|
| 307 |
+
def outcome(self, inst):
|
| 308 |
+
envs.settle(self.env, 30)
|
| 309 |
+
loc = {n: self.where(n) for n in [TARGET] + inst["neighbors"]}
|
| 310 |
+
off = [n for n in inst["neighbors"] if loc[n][0] != "tray"]
|
| 311 |
+
success = bool(loc[TARGET][0] == "basket" and not off)
|
| 312 |
+
return dict(success=success,
|
| 313 |
+
target_loc=loc[TARGET][0],
|
| 314 |
+
locations={n: l for n, (l, _) in loc.items()},
|
| 315 |
+
off_tray=off,
|
| 316 |
+
footprints={n: f for n, (_, f) in loc.items()},
|
| 317 |
+
knocked=bool(self._inj and self._inj["knocked"]),
|
| 318 |
+
detail=self._describe(inst, loc, NAMES),
|
| 319 |
+
detail_indirect=self._describe(inst, loc, DESCR))
|
| 320 |
+
|
| 321 |
+
def feedback(self, inst, out, level="F2", indirect=False):
|
| 322 |
+
"""F0: nothing, F1: success flag, F2: which item is where. `indirect` uses descriptive names."""
|
| 323 |
+
if indirect and level == "F2":
|
| 324 |
+
out = dict(out, detail=out.get("detail_indirect", out["detail"]))
|
| 325 |
+
return super().feedback(inst, out, level)
|
| 326 |
+
|
| 327 |
+
# ------------------------------------------------------------ scripted motions
|
| 328 |
+
def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.012, fp=None,
|
| 329 |
+
travel_z=1.15):
|
| 330 |
+
"""Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
|
| 331 |
+
object bottom `clearance` above `support_z` at dest_xy. Moves between places at `travel_z` (above the
|
| 332 |
+
basket rim) so the arm does not sweep through the scene."""
|
| 333 |
+
sk = self.sk
|
| 334 |
+
f = fp or self.footprint(name)
|
| 335 |
+
c = np.array(f["center"])
|
| 336 |
+
h = f["zmax"] - f["zmin"]
|
| 337 |
+
gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
|
| 338 |
+
if name == TARGET:
|
| 339 |
+
zg = f["zmax"] - 0.035
|
| 340 |
+
else:
|
| 341 |
+
zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # fingertips reach ~1.3 cm below the grip site
|
| 342 |
+
sk.set_gripper(False, steps=6)
|
| 343 |
+
p = sk.eef_pos()
|
| 344 |
+
if p[2] < travel_z - 0.02:
|
| 345 |
+
sk.move_to([p[0], p[1], travel_z])
|
| 346 |
+
sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
|
| 347 |
+
sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
|
| 348 |
+
sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
|
| 349 |
+
sk.set_gripper(True, steps=12)
|
| 350 |
+
sk.move_to([c[0], c[1], carry_z], speed=0.3)
|
| 351 |
+
gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
|
| 352 |
+
sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
|
| 353 |
+
sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.004, speed=0.25,
|
| 354 |
+
max_steps=120)
|
| 355 |
+
sk.set_gripper(False, steps=10)
|
| 356 |
+
sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
|
| 357 |
+
|
| 358 |
+
def main_task(self, fp=None):
|
| 359 |
+
"""Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
|
| 360 |
+
b = envs.obj_pos(self.env, BASKET)
|
| 361 |
+
floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
|
| 362 |
+
self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
|
| 363 |
+
|
| 364 |
+
def restore_spot(self, name, inst):
|
| 365 |
+
"""A free spot on the tray for `name`: the ketchup's start spot or `name`'s own start spot, whichever
|
| 366 |
+
is further from everything else currently on the tray."""
|
| 367 |
+
others = [n for n in [TARGET] + inst["neighbors"] if n != name and self.where(n)[0] == "tray"]
|
| 368 |
+
best, best_d = None, -1.0
|
| 369 |
+
for cand in (TARGET, name):
|
| 370 |
+
xy = np.array(self.start[cand]["center"][:2])
|
| 371 |
+
dmin = min([np.linalg.norm(xy - np.array(self.footprint(o)["center"][:2])) for o in others] + [1.0])
|
| 372 |
+
if dmin > best_d + 0.01:
|
| 373 |
+
best, best_d = xy, dmin
|
| 374 |
+
return best
|
| 375 |
+
|
| 376 |
+
def restore(self, name, inst):
|
| 377 |
+
"""Put `name` back onto the tray (long axis across the tray, fingers closing along the tray)."""
|
| 378 |
+
xy = self.restore_spot(name, inst)
|
| 379 |
+
self.pick_place(name, xy, envs.TABLE_Z + TRAY_FLOOR, dest_yaw=self.tray_yaw() + np.pi / 2, carry_z=1.08,
|
| 380 |
+
clearance=0.013)
|
| 381 |
+
|
| 382 |
+
def do(self, actions, inst):
|
| 383 |
+
for act in actions:
|
| 384 |
+
if act[0] == "ketchup_to_basket":
|
| 385 |
+
self.main_task(fp=act[1] if len(act) > 1 else None)
|
| 386 |
+
elif act[0] == "restore":
|
| 387 |
+
self.restore(act[1], inst)
|
| 388 |
+
else:
|
| 389 |
+
raise ValueError(act)
|
| 390 |
+
|
| 391 |
+
# ------------------------------------------------------------ scripted reference policies
|
| 392 |
+
def _plan(self, kind, inst, a, history, rng):
|
| 393 |
+
"""Actions of one attempt. JSON-friendly lists: ["ketchup_to_basket"] / ["restore", name]."""
|
| 394 |
+
if kind == "naive" or (a == 0 and kind in ("adaptive", "blind")):
|
| 395 |
+
return [["ketchup_to_basket"]]
|
| 396 |
+
if kind == "oracle": # knows the victim: restores it right after the main task, without feedback
|
| 397 |
+
return [["ketchup_to_basket"], ["restore", inst["victim"]]]
|
| 398 |
+
if kind == "adaptive": # F2 says what is wrong; perception (measured pose) says where it is
|
| 399 |
+
last = history[-1]["outcome"]
|
| 400 |
+
acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
|
| 401 |
+
return acts + [["restore", n] for n in last["off_tray"]]
|
| 402 |
+
if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
|
| 403 |
+
fp = self.footprint(TARGET)
|
| 404 |
+
fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
|
| 405 |
+
return [["ketchup_to_basket", fp]]
|
| 406 |
+
raise ValueError(kind)
|
| 407 |
+
|
| 408 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 409 |
+
"""Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds.
|
| 410 |
+
After every attempt the outcome (success + F2 detail) is measured; stops at success
|
| 411 |
+
(oracle / naive stop after attempt 1)."""
|
| 412 |
+
k = k or self.max_attempts
|
| 413 |
+
rng = np.random.default_rng(seed)
|
| 414 |
+
history = []
|
| 415 |
+
self.reset_instance(inst)
|
| 416 |
+
for a in range(k):
|
| 417 |
+
actions = self._plan(kind, inst, a, history, rng)
|
| 418 |
+
self.do(actions, inst)
|
| 419 |
+
out = self.outcome(inst)
|
| 420 |
+
params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
|
| 421 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 422 |
+
if on_attempt:
|
| 423 |
+
on_attempt(a, params, out)
|
| 424 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 425 |
+
break
|
| 426 |
+
return history
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
@register_task
|
| 430 |
+
class KnockRestoreCross(KnockRestore):
|
| 431 |
+
"""Cross-attempt variant: reset to the same instance before every attempt; the knock happens again each
|
| 432 |
+
time. Learned behaviour: anticipate it (restore the reported item right after the main task)."""
|
| 433 |
+
name = "l2_knock_restore_cross"
|
| 434 |
+
protocol = "cross"
|
| 435 |
+
|
| 436 |
+
def _plan(self, kind, inst, a, history, rng):
|
| 437 |
+
if kind == "adaptive" and a > 0: # remembers which item(s) fell last time; finds them by looking
|
| 438 |
+
fallen = sorted({n for h in history for n in h["outcome"]["off_tray"]})
|
| 439 |
+
return [["ketchup_to_basket"]] + [["restore", n] for n in fallen]
|
| 440 |
+
return super()._plan(kind, inst, a, history, rng)
|
| 441 |
+
|
| 442 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 443 |
+
k = k or self.max_attempts
|
| 444 |
+
rng = np.random.default_rng(seed)
|
| 445 |
+
history = []
|
| 446 |
+
for a in range(k):
|
| 447 |
+
self.reset_instance(inst)
|
| 448 |
+
actions = self._plan(kind, inst, a, history, rng)
|
| 449 |
+
self.do(actions, inst)
|
| 450 |
+
out = self.outcome(inst)
|
| 451 |
+
params = dict(actions=[x[:2] if x[0] == "restore" else x[:1] for x in actions])
|
| 452 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 453 |
+
if on_attempt:
|
| 454 |
+
on_attempt(a, params, out)
|
| 455 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 456 |
+
break
|
| 457 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l2_restore_layout.py
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L2-B restore_layout: put the ketchup into the basket; every other item must stay exactly where it was.
|
| 2 |
+
|
| 3 |
+
Scene: the ketchup (upright) and three flat boxes (cream cheese, butter, chocolate pudding) stand on the bare
|
| 4 |
+
table in an irregular layout (random positions and yaws, no tray, no markers, no grid), the basket on the
|
| 5 |
+
robot's left. Nothing in the scene marks where an item "belongs": its original pose exists only in the
|
| 6 |
+
first frame.
|
| 7 |
+
|
| 8 |
+
Constructed L2 event (physical, continuous): the first time the ketchup is grasped and lifted 3 cm, the
|
| 9 |
+
neighbouring box (the "victim", a hidden variable) is knocked: it receives a velocity impulse away from the
|
| 10 |
+
ketchup (+-35 deg) and a spin, slides 9-14 cm over the table and comes to rest turned by 45-80 deg. It is
|
| 11 |
+
real MuJoCo motion over ~0.2 s (no teleport), so a video shows it sliding away. The main task itself still
|
| 12 |
+
succeeds; an agent that stops after it fails. To repair the side effect the agent has to put the victim
|
| 13 |
+
back where it was -- within 3 cm and 25 deg (mod 180, the boxes are symmetric) -- and that pose is only in
|
| 14 |
+
its memory of the start of the episode (the F2 text says *which* item is out of place, never where it was).
|
| 15 |
+
|
| 16 |
+
Protocol: within (one episode, no reset). Attempt 1 = the main task, every later attempt = one corrective
|
| 17 |
+
round chosen by the policy; the outcome (success + F2 text) is computed after each round.
|
| 18 |
+
|
| 19 |
+
Scripted references
|
| 20 |
+
oracle knows the victim: right after the main task it puts the victim back at its saved start pose.
|
| 21 |
+
naive main task, then done.
|
| 22 |
+
adaptive saves the start layout from the first frame (Save); after a failure reads from F2 which items are
|
| 23 |
+
out of place (Retrieve their saved poses) and puts them back (Utilize).
|
| 24 |
+
blind no history, no feedback: every later round redoes the main task (lifts the ketchup out of the
|
| 25 |
+
basket and puts it back, grasp jittered by 5 mm), like l2_knock_restore's blind.
|
| 26 |
+
nomem (extra control, not in the acceptance table) gets the F2 text but has no start frame: it knows
|
| 27 |
+
which box is out of place and guesses where to put it (random free spot within 15 cm, random yaw).
|
| 28 |
+
"""
|
| 29 |
+
import numpy as np
|
| 30 |
+
|
| 31 |
+
from .. import envs
|
| 32 |
+
from ..bddl import write_bddl
|
| 33 |
+
from ..task_base import LFFTask, register_task
|
| 34 |
+
|
| 35 |
+
TARGET = "ketchup_1"
|
| 36 |
+
BOXES = ("cream_cheese_1", "butter_1", "chocolate_pudding_1")
|
| 37 |
+
BASKET = "basket_1"
|
| 38 |
+
ITEMS = (TARGET,) + BOXES
|
| 39 |
+
|
| 40 |
+
# LIBERO basket (body frame = world frame at yaw 0), measured by the l2_knock_restore developer
|
| 41 |
+
BASKET_IN = 0.060 # half size of the inner floor
|
| 42 |
+
BASKET_RIM = 0.150 # rim height above the basket's lowest point
|
| 43 |
+
BASKET_FLOOR = 0.017 # floor top above the basket's lowest point
|
| 44 |
+
BASKET_OUT = 0.11 # conservative half size of the outer footprint (keep-out radius for the layout)
|
| 45 |
+
|
| 46 |
+
POS_TOL = 0.03 # success: box centre within 3 cm of its start
|
| 47 |
+
YAW_TOL = np.radians(25.0) # ... and long axis within 25 deg of its start (mod 180)
|
| 48 |
+
STILL_TOL = 0.02 # the knock only fires if the victim is still within 2 cm of its start
|
| 49 |
+
|
| 50 |
+
REGION = (-0.26, 0.06, -0.27, 0.10) # x0, x1, y0, y1 (world) for item centres
|
| 51 |
+
KNOCK_REGION = (-0.28, 0.08, -0.29, 0.12) # where the victim may come to rest
|
| 52 |
+
MAX_REACH = 0.70 # max horizontal distance of an item centre from the robot base
|
| 53 |
+
BASE_X = -0.66
|
| 54 |
+
R_BOX, R_KETCHUP = 0.046, 0.034 # footprint circumradii (boxes 8 x 4.3 cm; ketchup 5.7 x 3.7 cm)
|
| 55 |
+
GAP = 0.03 # free space between footprints (finger room)
|
| 56 |
+
SLIDE_K = 0.0522 # measured: slide distance [m] = SLIDE_K * v0^2 [m/s] for these boxes on the table
|
| 57 |
+
SPIN_W = 40.0 # rad/s, applied each control step until the target turn is reached
|
| 58 |
+
|
| 59 |
+
NAMES = {"ketchup_1": "ketchup", "cream_cheese_1": "cream cheese", "butter_1": "butter",
|
| 60 |
+
"chocolate_pudding_1": "chocolate pudding", BASKET: "basket"}
|
| 61 |
+
DESCR = {"ketchup_1": "red bottle", "cream_cheese_1": "blue box", "butter_1": "small orange box",
|
| 62 |
+
"chocolate_pudding_1": "brown box", BASKET: "wicker basket"}
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _qz(a):
|
| 66 |
+
return np.array([np.cos(a / 2), 0.0, 0.0, np.sin(a / 2)])
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _wrap_half(a):
|
| 70 |
+
"""wrap an angle to [-pi/2, pi/2) (boxes and parallel grippers are symmetric under 180 deg)"""
|
| 71 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _seg_dist(p, a, b):
|
| 75 |
+
"""distance from point p to segment a-b (2D)"""
|
| 76 |
+
p, a, b = (np.asarray(v, float) for v in (p, a, b))
|
| 77 |
+
ab = b - a
|
| 78 |
+
t = np.clip(np.dot(p - a, ab) / max(np.dot(ab, ab), 1e-12), 0.0, 1.0)
|
| 79 |
+
return float(np.linalg.norm(p - (a + t * ab)))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _in_rect(xy, r):
|
| 83 |
+
return r[0] <= xy[0] <= r[1] and r[2] <= xy[1] <= r[3]
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _reach_ok(xy):
|
| 87 |
+
return np.hypot(xy[0] - BASE_X, xy[1]) <= MAX_REACH
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@register_task
|
| 91 |
+
class RestoreLayout(LFFTask):
|
| 92 |
+
name = "l2_restore_layout"
|
| 93 |
+
level = "L2"
|
| 94 |
+
category = "state_restoration"
|
| 95 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 96 |
+
protocol = "within"
|
| 97 |
+
max_attempts = 5
|
| 98 |
+
instruction = ("Put the ketchup into the basket. Every other item on the table must stay exactly where it "
|
| 99 |
+
"is now, in the same position and orientation.")
|
| 100 |
+
instruction_indirect = ("Put the red bottle into the wicker basket. Every other item on the table must stay "
|
| 101 |
+
"exactly where it is now, in the same position and orientation.")
|
| 102 |
+
knock_lift = 0.03 # trigger: ketchup grasped and lifted this far above its resting height
|
| 103 |
+
|
| 104 |
+
def __init__(self, cam_res=None):
|
| 105 |
+
super().__init__(cam_res)
|
| 106 |
+
# upright orientations (wxyz), fixed like in l2_knock_restore: the ketchup mesh is modelled lying down;
|
| 107 |
+
# basket and boxes are upright in their mesh frame
|
| 108 |
+
self.q_up = {n: np.array([1.0, 0.0, 0.0, 0.0]) for n in self.env.objects_dict}
|
| 109 |
+
self.q_up[TARGET] = np.array([0.5, 0.5, 0.5, 0.5])
|
| 110 |
+
self._inj = None
|
| 111 |
+
self.start = {}
|
| 112 |
+
self._home = None
|
| 113 |
+
# per-control-step monitor on env.step: also sees attempts driven by the agent harness
|
| 114 |
+
orig_step = self.env.step
|
| 115 |
+
|
| 116 |
+
def step(action):
|
| 117 |
+
ret = orig_step(action)
|
| 118 |
+
if self._inj is not None:
|
| 119 |
+
self._knock_step()
|
| 120 |
+
return ret
|
| 121 |
+
|
| 122 |
+
self.env.step = step
|
| 123 |
+
|
| 124 |
+
# ------------------------------------------------------------ scene
|
| 125 |
+
def make_bddl(self):
|
| 126 |
+
names = [*ITEMS, BASKET]
|
| 127 |
+
objs = []
|
| 128 |
+
for i, n in enumerate(names): # layout is overridden in apply_instance; regions only need to be valid
|
| 129 |
+
x0 = -0.30 + 0.13 * (i % 3)
|
| 130 |
+
y0 = -0.25 + 0.25 * (i // 3)
|
| 131 |
+
objs.append((n, n[:-2], f"r_{i}", (x0, y0, x0 + 0.02, y0 + 0.02)))
|
| 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(5000):
|
| 137 |
+
basket = np.array([rng.uniform(-0.08, 0.0), rng.uniform(0.25, 0.27)])
|
| 138 |
+
k = np.array([rng.uniform(-0.17, -0.03), rng.uniform(-0.14, -0.02)])
|
| 139 |
+
victim = str(rng.choice(BOXES))
|
| 140 |
+
others = [b for b in BOXES if b != victim]
|
| 141 |
+
a_v = rng.uniform(0, 2 * np.pi)
|
| 142 |
+
r_v = rng.uniform(R_BOX + R_KETCHUP + GAP, R_BOX + R_KETCHUP + GAP + 0.02)
|
| 143 |
+
pos = {TARGET: k, victim: k + r_v * np.array([np.cos(a_v), np.sin(a_v)])}
|
| 144 |
+
ok = _in_rect(pos[victim], REGION) and _reach_ok(pos[victim])
|
| 145 |
+
for o in others:
|
| 146 |
+
if not ok:
|
| 147 |
+
break
|
| 148 |
+
for _ in range(200):
|
| 149 |
+
p = np.array([rng.uniform(*REGION[:2]), rng.uniform(*REGION[2:])])
|
| 150 |
+
if not _reach_ok(p):
|
| 151 |
+
continue
|
| 152 |
+
if np.linalg.norm(p - k) < R_BOX + R_KETCHUP + GAP:
|
| 153 |
+
continue
|
| 154 |
+
if any(np.linalg.norm(p - pos[q]) < 2 * R_BOX + GAP for q in pos if q != TARGET):
|
| 155 |
+
continue
|
| 156 |
+
pos[o] = p
|
| 157 |
+
break
|
| 158 |
+
else:
|
| 159 |
+
ok = False
|
| 160 |
+
if not ok:
|
| 161 |
+
continue
|
| 162 |
+
if any(np.linalg.norm(pos[n] - basket) < BASKET_OUT + R_BOX + 0.02 for n in ITEMS):
|
| 163 |
+
continue
|
| 164 |
+
# the knock: away from the ketchup +-35 deg, 9-14 cm, turn 45-80 deg (random sign)
|
| 165 |
+
ang = a_v + rng.uniform(-np.radians(35), np.radians(35))
|
| 166 |
+
dist = rng.uniform(0.09, 0.14)
|
| 167 |
+
u = np.array([np.cos(ang), np.sin(ang)])
|
| 168 |
+
end = pos[victim] + dist * u
|
| 169 |
+
if not (_in_rect(end, KNOCK_REGION) and _reach_ok(end)):
|
| 170 |
+
continue
|
| 171 |
+
if np.linalg.norm(end - basket) < BASKET_OUT + R_BOX + 0.03:
|
| 172 |
+
continue
|
| 173 |
+
# the path and the resting spot keep clear of the other boxes (finger room around the victim too)
|
| 174 |
+
if any(_seg_dist(pos[o], pos[victim], end) < 2 * R_BOX + 0.01 for o in others):
|
| 175 |
+
continue
|
| 176 |
+
if any(np.linalg.norm(end - pos[o]) < 2 * R_BOX + GAP for o in others):
|
| 177 |
+
continue
|
| 178 |
+
if np.linalg.norm(end - k) < R_BOX + R_KETCHUP + GAP:
|
| 179 |
+
continue
|
| 180 |
+
turn = float(rng.choice([-1, 1]) * rng.uniform(np.radians(45), np.radians(80)))
|
| 181 |
+
return dict(seed=int(seed),
|
| 182 |
+
basket_xy=basket.round(4).tolist(),
|
| 183 |
+
xy={n: pos[n].round(4).tolist() for n in ITEMS},
|
| 184 |
+
yaw={**{b: float(rng.uniform(-np.pi / 2, np.pi / 2)) for b in BOXES},
|
| 185 |
+
TARGET: float(np.pi / 2 + rng.uniform(-0.3, 0.3))},
|
| 186 |
+
# hidden variables of the injected failure
|
| 187 |
+
victim=victim, knock_dir=float(ang), knock_dist=float(dist), knock_turn=turn,
|
| 188 |
+
knock_end=end.round(4).tolist())
|
| 189 |
+
raise RuntimeError("could not sample a layout")
|
| 190 |
+
|
| 191 |
+
def place(self, name, xy, yaw, surface_z=envs.TABLE_Z):
|
| 192 |
+
"""Teleport an object upright (yaw about world z) with its lowest point 2 mm above surface_z (reset only)."""
|
| 193 |
+
q = envs._quat_mul(_qz(yaw), self.q_up[name])
|
| 194 |
+
envs.set_obj_pose(self.env, name, [xy[0], xy[1], surface_z + 0.3], quat_wxyz=q)
|
| 195 |
+
self.env.sim.forward()
|
| 196 |
+
dz = envs.obj_min_z(self.env, name) - (surface_z + 0.002)
|
| 197 |
+
qa, _ = envs.free_joint_addr(self.env, name)
|
| 198 |
+
self.env.sim.data.qpos[qa + 2] -= dz
|
| 199 |
+
self.env.sim.forward()
|
| 200 |
+
|
| 201 |
+
def apply_instance(self, inst):
|
| 202 |
+
envs.scale_mass(self.env, BASKET, 2.0) # heavy enough not to be dragged by the gripper (as in l2_knock)
|
| 203 |
+
self.place(BASKET, inst["basket_xy"], 0.0)
|
| 204 |
+
for n in ITEMS:
|
| 205 |
+
self.place(n, inst["xy"][n], inst["yaw"][n])
|
| 206 |
+
self.env.sim.forward()
|
| 207 |
+
|
| 208 |
+
def reset_instance(self, inst, recorder=None):
|
| 209 |
+
self._inj = None
|
| 210 |
+
sk = super().reset_instance(inst, recorder)
|
| 211 |
+
self.start = {n: self.footprint(n) for n in ITEMS}
|
| 212 |
+
self._inj = dict(inst=inst, done=False, knocked=False, step=None, spin_left=0.0, spin_steps=0)
|
| 213 |
+
self._home = sk.eef_pos()
|
| 214 |
+
return sk
|
| 215 |
+
|
| 216 |
+
# ------------------------------------------------------------ measurements
|
| 217 |
+
def footprint(self, name):
|
| 218 |
+
"""Measured pose summary: AABB centre, yaw of the long horizontal axis, half sizes, z range.
|
| 219 |
+
Scripted policies use it as a stand-in for perception."""
|
| 220 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 221 |
+
lo, hi = np.full(3, np.inf), np.full(3, -np.inf)
|
| 222 |
+
best = None
|
| 223 |
+
for g in envs.obj_geom_ids(self.env, name):
|
| 224 |
+
R = d.geom_xmat[g].reshape(3, 3)
|
| 225 |
+
c = d.geom_xpos[g] + R @ m.geom_aabb[g, :3]
|
| 226 |
+
e = np.abs(R) @ m.geom_aabb[g, 3:]
|
| 227 |
+
lo, hi = np.minimum(lo, c - e), np.maximum(hi, c + e)
|
| 228 |
+
vol = float(np.prod(m.geom_aabb[g, 3:]))
|
| 229 |
+
if best is None or vol > best[0]:
|
| 230 |
+
best = (vol, R, m.geom_aabb[g, 3:])
|
| 231 |
+
_, R, half = best
|
| 232 |
+
horiz = sorted([(half[k], R[:, k]) for k in range(3) if abs(R[2, k]) < 0.5], key=lambda t: -t[0])
|
| 233 |
+
ax = horiz[0][1] if horiz else np.array([1.0, 0.0, 0.0])
|
| 234 |
+
return dict(center=[float(v) for v in (lo + hi) / 2], yaw=float(np.arctan2(ax[1], ax[0])),
|
| 235 |
+
half_xy=[float(v) for v in ((hi - lo) / 2)[:2]], zmin=float(lo[2]), zmax=float(hi[2]))
|
| 236 |
+
|
| 237 |
+
def body_yaw(self, name):
|
| 238 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, name)].reshape(3, 3)
|
| 239 |
+
return float(np.arctan2(R[1, 0], R[0, 0]))
|
| 240 |
+
|
| 241 |
+
# ------------------------------------------------------------ failure injection (physical knock)
|
| 242 |
+
def _knock_step(self):
|
| 243 |
+
st = self._inj
|
| 244 |
+
if st["done"]:
|
| 245 |
+
if st["spin_steps"] > 0: # keep spinning until the target turn is reached (<= 6 control steps)
|
| 246 |
+
self._spin(st)
|
| 247 |
+
return
|
| 248 |
+
if self.sk is None:
|
| 249 |
+
return
|
| 250 |
+
if envs.obj_min_z(self.env, TARGET) < self.start[TARGET]["zmin"] + self.knock_lift:
|
| 251 |
+
return
|
| 252 |
+
if not self.sk.holding(TARGET):
|
| 253 |
+
return
|
| 254 |
+
st["done"] = True
|
| 255 |
+
inst = st["inst"]
|
| 256 |
+
v = inst["victim"]
|
| 257 |
+
if np.linalg.norm(np.array(self.footprint(v)["center"][:2]) - np.array(self.start[v]["center"][:2])) > STILL_TOL:
|
| 258 |
+
return # the victim was moved beforehand: nothing happens
|
| 259 |
+
qa, da = envs.free_joint_addr(self.env, v)
|
| 260 |
+
v0 = np.sqrt(inst["knock_dist"] / SLIDE_K)
|
| 261 |
+
dvec = np.array([np.cos(inst["knock_dir"]), np.sin(inst["knock_dir"])])
|
| 262 |
+
d = self.env.sim.data
|
| 263 |
+
d.qvel[da:da + 3] = [v0 * dvec[0], v0 * dvec[1], 0.0]
|
| 264 |
+
st.update(knocked=True, step=int(self.sk.n_steps), yaw0=self.body_yaw(v), spin_left=inst["knock_turn"],
|
| 265 |
+
spin_steps=6)
|
| 266 |
+
self._spin(st)
|
| 267 |
+
|
| 268 |
+
def _spin(self, st):
|
| 269 |
+
v = st["inst"]["victim"]
|
| 270 |
+
_, da = envs.free_joint_addr(self.env, v)
|
| 271 |
+
turned = _wrap_half(self.body_yaw(v) - st["yaw0"]) if abs(st["spin_left"]) < np.pi / 2 else 0.0
|
| 272 |
+
rest = st["spin_left"] - turned
|
| 273 |
+
st["spin_steps"] -= 1
|
| 274 |
+
if abs(rest) < np.radians(4) or np.sign(rest) != np.sign(st["spin_left"]):
|
| 275 |
+
st["spin_steps"] = 0
|
| 276 |
+
return
|
| 277 |
+
# measured: one control step at w rad/s turns these boxes by ~0.35-0.8 deg per rad/s; aim a bit short
|
| 278 |
+
w = float(np.clip(np.degrees(abs(rest)) / 0.6, 5.0, SPIN_W))
|
| 279 |
+
self.env.sim.data.qvel[da + 5] = np.sign(rest) * w
|
| 280 |
+
|
| 281 |
+
# ------------------------------------------------------------ outcome
|
| 282 |
+
def where_target(self):
|
| 283 |
+
"""'basket', 'gripper', 'table' or 'other' for the ketchup."""
|
| 284 |
+
f = self.footprint(TARGET)
|
| 285 |
+
c = np.array(f["center"])
|
| 286 |
+
if self.sk is not None and self.sk.holding(TARGET) and f["zmin"] > envs.TABLE_Z + 0.02:
|
| 287 |
+
return "gripper", f
|
| 288 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 289 |
+
if np.all(np.abs(c[:2] - bp[:2]) <= BASKET_IN + 0.01) and f["zmin"] < envs.obj_min_z(self.env, BASKET) + BASKET_RIM:
|
| 290 |
+
return "basket", f
|
| 291 |
+
if f["zmin"] < envs.TABLE_Z + 0.01:
|
| 292 |
+
return "table", f
|
| 293 |
+
return "other", f
|
| 294 |
+
|
| 295 |
+
def box_state(self, name):
|
| 296 |
+
"""Pose error of a box w.r.t. its start pose and where it is."""
|
| 297 |
+
f = self.footprint(name)
|
| 298 |
+
s = self.start[name]
|
| 299 |
+
c, c0 = np.array(f["center"][:2]), np.array(s["center"][:2])
|
| 300 |
+
dpos = float(np.linalg.norm(c - c0))
|
| 301 |
+
dyaw = _wrap_half(f["yaw"] - s["yaw"])
|
| 302 |
+
held = bool(self.sk is not None and self.sk.holding(name))
|
| 303 |
+
upright = envs.obj_upright_cos(self.env, name) > 0.9
|
| 304 |
+
on_table = f["zmin"] < envs.TABLE_Z + 0.01
|
| 305 |
+
bp = envs.obj_pos(self.env, BASKET)
|
| 306 |
+
loc = ("gripper" if held else
|
| 307 |
+
"basket" if np.all(np.abs(c - bp[:2]) <= BASKET_IN + 0.02) and not on_table else
|
| 308 |
+
"table" if on_table and upright else
|
| 309 |
+
"table_tipped" if on_table else "other")
|
| 310 |
+
ok = bool(loc == "table" and dpos <= POS_TOL and abs(dyaw) <= YAW_TOL)
|
| 311 |
+
return dict(ok=ok, loc=loc, dpos=dpos, dyaw=float(dyaw), center=f["center"], yaw=f["yaw"],
|
| 312 |
+
offset=(c - c0).tolist())
|
| 313 |
+
|
| 314 |
+
@staticmethod
|
| 315 |
+
def _offset_words(off, dyaw):
|
| 316 |
+
"""robot-centric words for a displacement (current - start) and turn (for the offset tier only)"""
|
| 317 |
+
parts = []
|
| 318 |
+
if abs(off[0]) >= 0.005:
|
| 319 |
+
parts.append(f"{100 * abs(off[0]):.0f} cm {'forward' if off[0] > 0 else 'backward'}")
|
| 320 |
+
if abs(off[1]) >= 0.005:
|
| 321 |
+
parts.append(f"{100 * abs(off[1]):.0f} cm to the {'left' if off[1] > 0 else 'right'}")
|
| 322 |
+
s = (" and ".join(parts) + " of its starting spot") if parts else "at its starting spot"
|
| 323 |
+
if abs(dyaw) >= np.radians(3):
|
| 324 |
+
s += f", turned {abs(np.degrees(dyaw)):.0f} deg {'counter-clockwise' if dyaw > 0 else 'clockwise'} (seen from above)"
|
| 325 |
+
return s
|
| 326 |
+
|
| 327 |
+
def _describe(self, tloc, boxes, names, offset=False):
|
| 328 |
+
tn = names[TARGET]
|
| 329 |
+
msgs = []
|
| 330 |
+
if tloc != "basket":
|
| 331 |
+
msgs.append({"gripper": f"The {tn} is still in the gripper, not in the basket.",
|
| 332 |
+
"table": f"The {tn} is on the table, not in the basket."}
|
| 333 |
+
.get(tloc, f"The {tn} is not in the basket."))
|
| 334 |
+
for n in BOXES:
|
| 335 |
+
b = boxes[n]
|
| 336 |
+
if b["ok"]:
|
| 337 |
+
continue
|
| 338 |
+
if b["loc"] == "gripper":
|
| 339 |
+
msgs.append(f"The {names[n]} is in the gripper; it must be back where it was at the start.")
|
| 340 |
+
continue
|
| 341 |
+
if b["loc"] == "basket":
|
| 342 |
+
msgs.append(f"The {names[n]} is in the basket; it must be back where it was at the start.")
|
| 343 |
+
continue
|
| 344 |
+
if b["loc"] == "table_tipped":
|
| 345 |
+
msgs.append(f"The {names[n]} has tipped over and is not where it was at the start.")
|
| 346 |
+
continue
|
| 347 |
+
if b["loc"] != "table":
|
| 348 |
+
msgs.append(f"The {names[n]} is not where it was at the start.")
|
| 349 |
+
continue
|
| 350 |
+
what = []
|
| 351 |
+
if b["dpos"] > POS_TOL:
|
| 352 |
+
what.append("position")
|
| 353 |
+
if abs(b["dyaw"]) > YAW_TOL:
|
| 354 |
+
what.append("orientation")
|
| 355 |
+
m = f"The {names[n]} is not where it was at the start ({' and '.join(what)} changed)."
|
| 356 |
+
if offset:
|
| 357 |
+
m += f" It is {self._offset_words(b['offset'], b['dyaw'])}."
|
| 358 |
+
msgs.append(m)
|
| 359 |
+
if not msgs:
|
| 360 |
+
msgs.append(f"The {tn} is in the basket and every other item is where it was at the start.")
|
| 361 |
+
return " ".join(msgs)
|
| 362 |
+
|
| 363 |
+
def outcome(self, inst):
|
| 364 |
+
envs.settle(self.env, 30)
|
| 365 |
+
tloc, tf = self.where_target()
|
| 366 |
+
boxes = {n: self.box_state(n) for n in BOXES}
|
| 367 |
+
moved = [n for n in BOXES if not boxes[n]["ok"]]
|
| 368 |
+
success = bool(tloc == "basket" and not moved)
|
| 369 |
+
return dict(success=success, target_loc=tloc, moved=moved,
|
| 370 |
+
boxes={n: dict(ok=b["ok"], loc=b["loc"], dpos=round(b["dpos"], 4),
|
| 371 |
+
dyaw_deg=round(float(np.degrees(b["dyaw"])), 1)) for n, b in boxes.items()},
|
| 372 |
+
knocked=bool(self._inj and self._inj["knocked"]),
|
| 373 |
+
detail=self._describe(tloc, boxes, NAMES),
|
| 374 |
+
detail_indirect=self._describe(tloc, boxes, DESCR),
|
| 375 |
+
detail_offset=self._describe(tloc, boxes, NAMES, offset=True))
|
| 376 |
+
|
| 377 |
+
def feedback(self, inst, out, level="F2", indirect=False, offset=False):
|
| 378 |
+
"""F0: nothing, F1: success flag, F2: which item is out of place (never where it was).
|
| 379 |
+
offset=True (ablation tier 'F2+offset'): also the displacement from the start pose in robot-centric
|
| 380 |
+
words -- this externalises the memory and is not the default."""
|
| 381 |
+
if level == "F2":
|
| 382 |
+
key = "detail_offset" if offset else ("detail_indirect" if indirect else "detail")
|
| 383 |
+
out = dict(out, detail=out.get(key, out["detail"]))
|
| 384 |
+
return super().feedback(inst, out, level)
|
| 385 |
+
|
| 386 |
+
# ------------------------------------------------------------ scripted motions (Skills.move_to / set_gripper only)
|
| 387 |
+
def go_home(self):
|
| 388 |
+
"""End of an attempt: lift the arm out of the camera's way."""
|
| 389 |
+
sk = self.sk
|
| 390 |
+
p = sk.eef_pos()
|
| 391 |
+
sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 392 |
+
sk.move_to(self._home)
|
| 393 |
+
|
| 394 |
+
def pick_place(self, name, dest_xy, support_z, dest_yaw=None, carry_z=1.10, clearance=0.006, fp=None,
|
| 395 |
+
travel_z=1.15):
|
| 396 |
+
"""Top-down pick of `name` at its (measured) footprint, carry at eef height `carry_z`, release with the
|
| 397 |
+
object bottom `clearance` above `support_z` at dest_xy; `dest_yaw` = desired yaw of the long axis."""
|
| 398 |
+
sk = self.sk
|
| 399 |
+
f = fp or self.footprint(name)
|
| 400 |
+
c = np.array(f["center"])
|
| 401 |
+
h = f["zmax"] - f["zmin"]
|
| 402 |
+
gyaw = _wrap_half(f["yaw"]) # fingers close along eef y (= world y at yaw 0): across the short side
|
| 403 |
+
if name == TARGET:
|
| 404 |
+
zg = f["zmax"] - 0.035
|
| 405 |
+
else:
|
| 406 |
+
zg = max(f["zmin"] + 0.5 * h, f["zmin"] + 0.0145) # finger tips reach ~1.3 cm below the grip site
|
| 407 |
+
sk.set_gripper(False, steps=6)
|
| 408 |
+
p = sk.eef_pos()
|
| 409 |
+
if p[2] < travel_z - 0.02:
|
| 410 |
+
sk.move_to([p[0], p[1], travel_z])
|
| 411 |
+
sk.move_to([c[0], c[1], travel_z], yaw=gyaw)
|
| 412 |
+
sk.move_to([c[0], c[1], f["zmax"] + 0.03], speed=0.4)
|
| 413 |
+
sk.move_to([c[0], c[1], zg], tol=0.003, max_steps=80)
|
| 414 |
+
sk.set_gripper(True, steps=12)
|
| 415 |
+
sk.move_to([c[0], c[1], carry_z], speed=0.3)
|
| 416 |
+
gyaw2 = gyaw if dest_yaw is None else gyaw + _wrap_half(dest_yaw - f["yaw"])
|
| 417 |
+
sk.move_to([dest_xy[0], dest_xy[1], carry_z], yaw=gyaw2)
|
| 418 |
+
sk.move_to([dest_xy[0], dest_xy[1], support_z + (zg - f["zmin"]) + clearance], tol=0.003, speed=0.2,
|
| 419 |
+
max_steps=150)
|
| 420 |
+
sk.hold(4)
|
| 421 |
+
sk.set_gripper(False, steps=10)
|
| 422 |
+
sk.move_to([dest_xy[0], dest_xy[1], travel_z], speed=0.4)
|
| 423 |
+
|
| 424 |
+
def main_task(self, fp=None):
|
| 425 |
+
"""Ketchup -> basket (the instruction, as an agent without failure knowledge would do it)."""
|
| 426 |
+
b = envs.obj_pos(self.env, BASKET)
|
| 427 |
+
floor = envs.obj_min_z(self.env, BASKET) + BASKET_FLOOR
|
| 428 |
+
self.pick_place(TARGET, b[:2], floor, carry_z=1.27, clearance=0.006, fp=fp)
|
| 429 |
+
|
| 430 |
+
def restore(self, name, pose):
|
| 431 |
+
"""Put box `name` back at `pose` (a remembered footprint: centre xy + long-axis yaw)."""
|
| 432 |
+
self.pick_place(name, pose["center"][:2], envs.TABLE_Z, dest_yaw=pose["yaw"], carry_z=1.05,
|
| 433 |
+
clearance=0.004)
|
| 434 |
+
|
| 435 |
+
def do(self, actions, inst):
|
| 436 |
+
for act in actions:
|
| 437 |
+
if act[0] == "ketchup_to_basket":
|
| 438 |
+
self.main_task(fp=act[1] if len(act) > 1 else None)
|
| 439 |
+
elif act[0] == "restore": # ["restore", name, pose]
|
| 440 |
+
self.restore(act[1], act[2])
|
| 441 |
+
else:
|
| 442 |
+
raise ValueError(act)
|
| 443 |
+
|
| 444 |
+
# ------------------------------------------------------------ scripted reference policies
|
| 445 |
+
def _guess_pose(self, name, rng):
|
| 446 |
+
"""nomem control: a random free spot within 15 cm of where the box is now, random yaw."""
|
| 447 |
+
cur = np.array(self.footprint(name)["center"][:2])
|
| 448 |
+
others = [np.array(self.footprint(o)["center"][:2]) for o in BOXES if o != name]
|
| 449 |
+
for _ in range(200):
|
| 450 |
+
r, a = rng.uniform(0.03, 0.15), rng.uniform(0, 2 * np.pi)
|
| 451 |
+
p = cur + r * np.array([np.cos(a), np.sin(a)])
|
| 452 |
+
if _in_rect(p, KNOCK_REGION) and _reach_ok(p) and all(np.linalg.norm(p - o) > 2 * R_BOX + 0.01 for o in others):
|
| 453 |
+
return dict(center=[float(p[0]), float(p[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
|
| 454 |
+
return dict(center=[float(cur[0]), float(cur[1]), 0.0], yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
|
| 455 |
+
|
| 456 |
+
def _plan(self, kind, inst, a, history, rng, memory):
|
| 457 |
+
"""Actions of one round: ["ketchup_to_basket"] / ["restore", name, pose]."""
|
| 458 |
+
if kind == "naive" or (a == 0 and kind in ("adaptive", "blind", "nomem")):
|
| 459 |
+
return [["ketchup_to_basket"]]
|
| 460 |
+
if kind == "oracle": # knows the victim: restores it right after the main task (start pose from memory)
|
| 461 |
+
return [["ketchup_to_basket"], ["restore", inst["victim"], memory[inst["victim"]]]]
|
| 462 |
+
last = history[-1]["outcome"]
|
| 463 |
+
if kind == "adaptive": # F2 says which items are out of place; the saved first frame says where they were
|
| 464 |
+
acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
|
| 465 |
+
return acts + [["restore", n, memory[n]] for n in last["moved"]]
|
| 466 |
+
if kind == "nomem": # F2 but no start frame: guesses
|
| 467 |
+
acts = [] if last["target_loc"] == "basket" else [["ketchup_to_basket"]]
|
| 468 |
+
return acts + [["restore", n, self._guess_pose(n, rng)] for n in last["moved"]]
|
| 469 |
+
if kind == "blind": # ignores the outcome: redoes the main task (ketchup wherever it is now, jittered grasp)
|
| 470 |
+
fp = self.footprint(TARGET)
|
| 471 |
+
fp["center"] = (np.array(fp["center"]) + np.r_[rng.normal(0, 0.005, 2), 0.0]).tolist()
|
| 472 |
+
return [["ketchup_to_basket", fp]]
|
| 473 |
+
raise ValueError(kind)
|
| 474 |
+
|
| 475 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 476 |
+
"""Within-episode protocol: one reset, attempt 1 = main task, attempts 2..k = corrective rounds."""
|
| 477 |
+
k = k or self.max_attempts
|
| 478 |
+
rng = np.random.default_rng(seed)
|
| 479 |
+
history = []
|
| 480 |
+
self.reset_instance(inst)
|
| 481 |
+
memory = {n: dict(center=self.start[n]["center"], yaw=self.start[n]["yaw"]) for n in BOXES} # Save
|
| 482 |
+
for a in range(k):
|
| 483 |
+
actions = self._plan(kind, inst, a, history, rng, memory)
|
| 484 |
+
self.do(actions, inst)
|
| 485 |
+
self.go_home()
|
| 486 |
+
out = self.outcome(inst)
|
| 487 |
+
params = dict(actions=[x[:1] if x[0] == "ketchup_to_basket" else
|
| 488 |
+
[x[0], x[1], [round(v, 3) for v in x[2]["center"][:2]], round(float(x[2]["yaw"]), 3)]
|
| 489 |
+
for x in actions])
|
| 490 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 491 |
+
if on_attempt:
|
| 492 |
+
on_attempt(a, params, out)
|
| 493 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 494 |
+
break
|
| 495 |
+
return history
|
| 496 |
+
|
| 497 |
+
# cross-protocol hooks are not used by this task
|
| 498 |
+
def default_params(self, inst):
|
| 499 |
+
return dict(policy="naive")
|
| 500 |
+
|
| 501 |
+
def oracle_params(self, inst):
|
| 502 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l3_card_edge.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3 card_edge: a thin card lying flat on a board cannot be pinched; slide it over the board's edge, then grasp it.
|
| 2 |
+
|
| 3 |
+
Category: strategy_switching ("this way of doing it cannot work"), the user's taxonomy L3 example verbatim:
|
| 4 |
+
"卡片贴着桌面捏不起来 -> 先把卡片滑到桌沿,再夹起来".
|
| 5 |
+
|
| 6 |
+
Scene: a wooden board (22 x 26 x 5 cm) on the table with a thin red card (9.0 x 5.6 x 0.2 cm, 10 g) lying flat on it,
|
| 7 |
+
long side roughly along x or along y (+-10 deg); a grey bin (16 x 16 cm inside) stands on the table beside the board.
|
| 8 |
+
The board stands in for the table edge of the user's example: the real table edge is out of reach (near edge 16 cm
|
| 9 |
+
from the robot base, side edges at |y| = 0.6 m) and the harness does not let the grasp point go below the table top.
|
| 10 |
+
|
| 11 |
+
Why the prior fails (measured): a top-down grasp across the card's short side. The Panda fingertips land on the
|
| 12 |
+
board on either side of the card, but when they close on its 2 mm edge the contact flips to "slide over the top" and
|
| 13 |
+
both fingertips ride up over the card and close above it: 0/36 lifts for 1.5 / 2 / 3 mm cards, grasp-point height
|
| 14 |
+
-6..+3 mm, xy jitter 5 mm, yaw jitter 0.1 rad (prototype, 2026-10-08). Retrying with small variations fails the same
|
| 15 |
+
way. (A 4 mm card could be pinched -- the reason the earlier `l3_flat_card_edge` was dropped.)
|
| 16 |
+
|
| 17 |
+
What must be learned from the failure: the card cannot be picked up while it lies flat -> change the strategy: press
|
| 18 |
+
the closed fingertips onto the card and slide it (move_to with the fingertips pressing on it) until part of it hangs
|
| 19 |
+
over the board's edge, then grasp the overhanging part with the fingertips below the card: then the fingers close on
|
| 20 |
+
the card's full edge and it lifts (18/18 for 2.5-3.5 cm of overhang in the prototype). More than half the card's
|
| 21 |
+
length over the edge and it tips off the board.
|
| 22 |
+
|
| 23 |
+
Protocol: cross (reset to the same instance before every attempt), k = 5.
|
| 24 |
+
"""
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from .. import envs
|
| 28 |
+
from ..bddl import write_bddl
|
| 29 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
|
| 30 |
+
from ..skills import Skills
|
| 31 |
+
from ..task_base import LFFTask, register_task
|
| 32 |
+
|
| 33 |
+
CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm
|
| 34 |
+
CARD_MASS = 0.010
|
| 35 |
+
MU = 0.3 # card and board sliding friction (the fingers' 1.0 / 2.0 win in finger contacts: MuJoCo takes the max)
|
| 36 |
+
BOARD_HALF = (0.11, 0.13, 0.025)
|
| 37 |
+
BOARD_TOP = envs.TABLE_Z + 2 * BOARD_HALF[2]
|
| 38 |
+
BIN_IN = 0.08 # inner half width
|
| 39 |
+
BIN_WALL_H = 0.05
|
| 40 |
+
BIN_GAP = 0.06 # board edge to bin outer wall
|
| 41 |
+
BIN_T = 0.006
|
| 42 |
+
BIN_HALF_OUT = BIN_IN + BIN_T
|
| 43 |
+
TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
|
| 44 |
+
LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
|
| 45 |
+
OVERHANG = 0.03 # scripted target overhang (the grasp works for ~2.5-4.0 cm; the card tips off past ~4.5 cm)
|
| 46 |
+
GRASP_OUT = 0.022 # scripted grasp point: this far beyond the board edge (fingers must clear the edge)
|
| 47 |
+
DRAG_SPEED = 0.08
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
|
| 51 |
+
g = (f' <geom name="{name}_g0" type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" mass="{CARD_MASS}" '
|
| 52 |
+
f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
|
| 53 |
+
f' <geom type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
|
| 54 |
+
return _wrap(name, g, CARD_HALF[2], float(np.hypot(CARD_HALF[0], CARD_HALF[1])))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _yaw_of(quat_wxyz):
|
| 58 |
+
w, x, y, z = quat_wxyz
|
| 59 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
EDGES = ("forward", "backward", "left", "right") # board edges in robot-centric words (+x, -x, +y, -y)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CardSkills(Skills):
|
| 66 |
+
"""Skills that feed the task's per-step monitor and log every close of the gripper."""
|
| 67 |
+
|
| 68 |
+
def __init__(self, env, task, recorder=None):
|
| 69 |
+
super().__init__(env, recorder=recorder)
|
| 70 |
+
self.task = task
|
| 71 |
+
self.closes = []
|
| 72 |
+
|
| 73 |
+
def _act(self, dpos, drot, grip):
|
| 74 |
+
super()._act(dpos, drot, grip)
|
| 75 |
+
self.task.monitor_step()
|
| 76 |
+
|
| 77 |
+
def set_gripper(self, close, steps=15):
|
| 78 |
+
was_open = self.grip < 0
|
| 79 |
+
before = self.task.close_context() if (close and was_open) else None
|
| 80 |
+
rep = super().set_gripper(close, steps)
|
| 81 |
+
if before is not None:
|
| 82 |
+
before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
|
| 83 |
+
self.closes.append(before)
|
| 84 |
+
return rep
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@register_task
|
| 88 |
+
class CardEdge(LFFTask):
|
| 89 |
+
name = "l3_card_edge"
|
| 90 |
+
level = "L3"
|
| 91 |
+
category = "strategy_switching"
|
| 92 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 93 |
+
protocol = "cross"
|
| 94 |
+
instruction = "Pick up the thin red card lying on the wooden board and put it into the grey bin."
|
| 95 |
+
instruction_indirect = "Put the flat red rectangle that lies on the wooden block into the grey container."
|
| 96 |
+
|
| 97 |
+
# ------------------------------------------------------------ scene
|
| 98 |
+
def make_bddl(self):
|
| 99 |
+
card = register_generated("LffThinCard", card_xml("lff_thin_card"))
|
| 100 |
+
board = register_generated("LffCardBoard", box_xml("lff_card_board", BOARD_HALF, (0.62, 0.45, 0.27, 1.0),
|
| 101 |
+
friction=(MU, 0.005, 0.0001)), free=False)
|
| 102 |
+
bin_ = register_generated("LffCardBin", bin_xml("lff_card_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
|
| 103 |
+
rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
|
| 104 |
+
objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
|
| 105 |
+
fx = [("board_1", board, "board_region", (-0.11, -0.01, -0.09, 0.01)),
|
| 106 |
+
("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
|
| 107 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 108 |
+
|
| 109 |
+
def __init__(self, cam_res=None):
|
| 110 |
+
super().__init__(cam_res)
|
| 111 |
+
m = self.env.sim.model
|
| 112 |
+
self.board_bid = m.body_name2id(self.env.fixtures_dict["board_1"].root_body)
|
| 113 |
+
self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
|
| 114 |
+
self.inst = None
|
| 115 |
+
self.mon = None
|
| 116 |
+
|
| 117 |
+
def sample_instance(self, seed):
|
| 118 |
+
rng = np.random.default_rng(seed)
|
| 119 |
+
bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
|
| 120 |
+
along = str(rng.choice(["x", "y"]))
|
| 121 |
+
yaw = (0.0 if along == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
|
| 122 |
+
if along == "x": # keep the whole card >= 3 cm (long axis) / 2 cm (short axis) inside the board
|
| 123 |
+
off = [rng.uniform(-0.03, 0.03), rng.uniform(-0.07, 0.07)]
|
| 124 |
+
else:
|
| 125 |
+
off = [rng.uniform(-0.055, 0.055), rng.uniform(-0.05, 0.05)]
|
| 126 |
+
side = 1.0 if rng.random() < 0.5 else -1.0
|
| 127 |
+
bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (BOARD_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
|
| 128 |
+
return dict(seed=int(seed), board_xy=[bx, by], card_xy=[bx + float(off[0]), by + float(off[1])],
|
| 129 |
+
card_yaw=float(yaw), card_along=along, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
|
| 130 |
+
|
| 131 |
+
def apply_instance(self, inst):
|
| 132 |
+
self.inst = inst
|
| 133 |
+
m = self.env.sim.model
|
| 134 |
+
bx, by = inst["board_xy"]
|
| 135 |
+
m.body_pos[self.board_bid] = [bx, by, envs.TABLE_Z + BOARD_HALF[2]]
|
| 136 |
+
m.body_quat[self.board_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 137 |
+
cx, cy = inst["bin_xy"]
|
| 138 |
+
m.body_pos[self.bin_bid] = [cx, cy, envs.TABLE_Z + (BIN_WALL_H + BIN_T) / 2]
|
| 139 |
+
m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 140 |
+
x, y = inst["card_xy"]
|
| 141 |
+
envs.set_obj_pose(self.env, "card_1", [x, y, BOARD_TOP + CARD_HALF[2] + 0.0003], yaw=inst["card_yaw"])
|
| 142 |
+
|
| 143 |
+
def reset_instance(self, inst, recorder=None):
|
| 144 |
+
self.env.reset()
|
| 145 |
+
self.apply_instance(inst)
|
| 146 |
+
self.env.sim.forward()
|
| 147 |
+
envs.settle(self.env, 15)
|
| 148 |
+
self.sk = CardSkills(self.env, self, recorder=recorder)
|
| 149 |
+
p = self.card_pose()
|
| 150 |
+
self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False)
|
| 151 |
+
return self.sk
|
| 152 |
+
|
| 153 |
+
# ------------------------------------------------------------ geometry
|
| 154 |
+
def card_pose(self):
|
| 155 |
+
p = envs.obj_pos(self.env, "card_1")
|
| 156 |
+
return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
|
| 157 |
+
|
| 158 |
+
def card_corners(self):
|
| 159 |
+
d = self.env.sim.data
|
| 160 |
+
bid = envs.body_id(self.env, "card_1")
|
| 161 |
+
R = d.body_xmat[bid].reshape(3, 3)
|
| 162 |
+
h = np.array(CARD_HALF)
|
| 163 |
+
return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
|
| 164 |
+
|
| 165 |
+
def overhang(self):
|
| 166 |
+
"""(how far the card sticks out beyond the board's edges (m, max over its corners), edge word)"""
|
| 167 |
+
c = self.card_corners()[:, :2] - np.asarray(self.inst["board_xy"])
|
| 168 |
+
prot = {"forward": c[:, 0].max() - BOARD_HALF[0], "backward": -c[:, 0].min() - BOARD_HALF[0],
|
| 169 |
+
"left": c[:, 1].max() - BOARD_HALF[1], "right": -c[:, 1].min() - BOARD_HALF[1]}
|
| 170 |
+
e = max(prot, key=prot.get)
|
| 171 |
+
return float(prot[e]), e
|
| 172 |
+
|
| 173 |
+
def on_board(self):
|
| 174 |
+
p = self.card_pose()
|
| 175 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["board_xy"]))
|
| 176 |
+
return bool(rel[0] <= BOARD_HALF[0] and rel[1] <= BOARD_HALF[1] and abs(p["z"] - BOARD_TOP) < 0.012)
|
| 177 |
+
|
| 178 |
+
def in_bin(self):
|
| 179 |
+
p = self.card_pose()
|
| 180 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
|
| 181 |
+
return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < envs.TABLE_Z + BIN_T + BIN_WALL_H)
|
| 182 |
+
|
| 183 |
+
# ------------------------------------------------------------ monitor
|
| 184 |
+
def monitor_step(self):
|
| 185 |
+
mon = self.mon
|
| 186 |
+
if mon is None:
|
| 187 |
+
return
|
| 188 |
+
zmin = float(self.card_corners()[:, 2].min())
|
| 189 |
+
mon["max_lift"] = max(mon["max_lift"], zmin - BOARD_TOP)
|
| 190 |
+
if self.on_board() or abs(self.card_pose()["z"] - BOARD_TOP) < 0.012:
|
| 191 |
+
mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
|
| 192 |
+
if self.card_pose()["z"] < BOARD_TOP - 0.02 and not self.sk.holding("card_1"):
|
| 193 |
+
mon["fell"] = True
|
| 194 |
+
|
| 195 |
+
def close_context(self):
|
| 196 |
+
"""Where the gripper is relative to the card and the board just before it closes."""
|
| 197 |
+
sk, p = self.sk, self.card_pose()
|
| 198 |
+
e = sk.eef_pos()
|
| 199 |
+
c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
|
| 200 |
+
rel = e[:2] - p["xy"]
|
| 201 |
+
local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side
|
| 202 |
+
b = e[:2] - np.asarray(self.inst["board_xy"])
|
| 203 |
+
beyond = {"forward": b[0] - BOARD_HALF[0], "backward": -b[0] - BOARD_HALF[0],
|
| 204 |
+
"left": b[1] - BOARD_HALF[1], "right": -b[1] - BOARD_HALF[1]}
|
| 205 |
+
edge = max(beyond, key=beyond.get)
|
| 206 |
+
ov, ov_edge = self.overhang()
|
| 207 |
+
return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
|
| 208 |
+
tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
|
| 209 |
+
beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
|
| 210 |
+
card_on_board=self.on_board(), overhang=round(ov, 4), overhang_edge=ov_edge,
|
| 211 |
+
width_before=round(sk.gripper_width(), 4))
|
| 212 |
+
|
| 213 |
+
# ------------------------------------------------------------ outcome / F2
|
| 214 |
+
def outcome(self, inst):
|
| 215 |
+
envs.settle(self.env, 30)
|
| 216 |
+
sk, mon = self.sk, self.mon
|
| 217 |
+
p = self.card_pose()
|
| 218 |
+
held = bool(sk.holding("card_1"))
|
| 219 |
+
in_bin = self.in_bin() and not held
|
| 220 |
+
success = bool(in_bin)
|
| 221 |
+
moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
|
| 222 |
+
lifted = mon["max_lift"] > 0.02
|
| 223 |
+
tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
|
| 224 |
+
parts, mode = [], "success"
|
| 225 |
+
if success:
|
| 226 |
+
parts.append("The card is in the bin.")
|
| 227 |
+
else:
|
| 228 |
+
rel = p["xy"] - np.asarray(inst["bin_xy"])
|
| 229 |
+
where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
|
| 230 |
+
f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
|
| 231 |
+
if held:
|
| 232 |
+
mode = "held"
|
| 233 |
+
parts.append(f"The card is still held by the gripper, {where}.")
|
| 234 |
+
elif lifted:
|
| 235 |
+
mode = "dropped"
|
| 236 |
+
loc = "on the board" if self.on_board() else ("on the table" if p["z"] < BOARD_TOP - 0.02 else
|
| 237 |
+
"partly on the board")
|
| 238 |
+
parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the board but is not in the "
|
| 239 |
+
f"bin: it lies {loc}, its centre {where}.")
|
| 240 |
+
elif mon["fell"]:
|
| 241 |
+
mode = "fell_off"
|
| 242 |
+
parts.append("The card was never lifted; it fell off the board and lies flat on the table.")
|
| 243 |
+
else:
|
| 244 |
+
mode = "not_lifted"
|
| 245 |
+
parts.append("The card was never lifted; it still lies flat on the board"
|
| 246 |
+
+ (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
|
| 247 |
+
f"{100 * mon['max_overhang']:.1f} cm beyond the board's edge)" if mon["max_overhang"] > 0.003
|
| 248 |
+
else ")") if moved > 0.005 else "") + ".")
|
| 249 |
+
if not lifted:
|
| 250 |
+
if not tries:
|
| 251 |
+
parts.append("The gripper never closed with its fingertips down at the card.")
|
| 252 |
+
else:
|
| 253 |
+
c = tries[-1]
|
| 254 |
+
n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
|
| 255 |
+
if c["card_on_board"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
|
| 256 |
+
txt = ("when the gripper closed on the card lying flat on the board, its fingertips were on "
|
| 257 |
+
"either side of the card, at board level")
|
| 258 |
+
else:
|
| 259 |
+
if c["beyond_edge"] >= 0.0:
|
| 260 |
+
pos = f"{100 * c['beyond_edge']:.1f} cm beyond the board's {c['beyond_edge_name']} edge"
|
| 261 |
+
else:
|
| 262 |
+
pos = f"over the board, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge"
|
| 263 |
+
txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm "
|
| 264 |
+
f"beyond the board's {c['overhang_edge']} edge and the gripper's centre was {pos}")
|
| 265 |
+
txt += (f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the "
|
| 266 |
+
"fingers closed ")
|
| 267 |
+
txt += ("fully, sliding over the top of the card instead of gripping its edges."
|
| 268 |
+
if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
|
| 269 |
+
("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
|
| 270 |
+
parts.append(n + txt if n else txt[0].upper() + txt[1:])
|
| 271 |
+
out = dict(success=success, mode=mode, held=held, lifted=bool(lifted), max_lift=round(mon["max_lift"], 4),
|
| 272 |
+
max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), fell=bool(mon["fell"]),
|
| 273 |
+
grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
|
| 274 |
+
return out
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 277 |
+
def _edge_plan(self, inst):
|
| 278 |
+
"""the board edge the card is slid to: along its long side; the near (backward) edge for x-cards,
|
| 279 |
+
the closer side edge for y-cards"""
|
| 280 |
+
if inst["card_along"] == "x":
|
| 281 |
+
return "backward"
|
| 282 |
+
return "left" if inst["card_xy"][1] >= inst["board_xy"][1] else "right"
|
| 283 |
+
|
| 284 |
+
def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
|
| 285 |
+
sk = self.sk
|
| 286 |
+
sk.set_gripper(False, steps=8)
|
| 287 |
+
sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
|
| 288 |
+
sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
|
| 289 |
+
sk.set_gripper(True, steps=15)
|
| 290 |
+
sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
|
| 291 |
+
if not sk.holding("card_1"):
|
| 292 |
+
sk.set_gripper(False, steps=8)
|
| 293 |
+
return False
|
| 294 |
+
bx, by = self.inst["bin_xy"]
|
| 295 |
+
hi = envs.TABLE_Z + BIN_WALL_H + 0.12
|
| 296 |
+
sk.move_to([bx, by, hi])
|
| 297 |
+
sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05], speed=0.2)
|
| 298 |
+
sk.set_gripper(False, steps=12)
|
| 299 |
+
sk.move_to([bx, by, hi])
|
| 300 |
+
return True
|
| 301 |
+
|
| 302 |
+
def slide_card(self, delta, press=0.004):
|
| 303 |
+
"""closed fingertips pressed on the card's centre, straight move by `delta` (xy), lift"""
|
| 304 |
+
sk, p = self.sk, self.card_pose()
|
| 305 |
+
z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
|
| 306 |
+
sk.set_gripper(True, steps=8)
|
| 307 |
+
sk.move_to([p["xy"][0], p["xy"][1], z + 0.06], yaw=p["yaw"])
|
| 308 |
+
sk.move_to([p["xy"][0], p["xy"][1], z], tol=0.003, max_steps=100)
|
| 309 |
+
e = p["xy"] + np.asarray(delta, float)
|
| 310 |
+
sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
|
| 311 |
+
sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
|
| 312 |
+
sk.hold(5)
|
| 313 |
+
|
| 314 |
+
def execute(self, inst, params):
|
| 315 |
+
p = self.card_pose()
|
| 316 |
+
if params["mode"] == "grasp":
|
| 317 |
+
xy = p["xy"] + np.asarray(params.get("dxy", (0.0, 0.0)))
|
| 318 |
+
self.grasp_and_bin(xy, p["yaw"] + params.get("dyaw", 0.0), BOARD_TOP + params.get("dz", 0.0))
|
| 319 |
+
return
|
| 320 |
+
# edge: slide the card along its long side until `overhang` of it sticks out over the chosen edge
|
| 321 |
+
edge = params.get("edge") or self._edge_plan(inst)
|
| 322 |
+
u = {"forward": (1, 0), "backward": (-1, 0), "left": (0, 1), "right": (0, -1)}[edge]
|
| 323 |
+
u = np.asarray(u, float)
|
| 324 |
+
c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
|
| 325 |
+
long_ax = np.array([c, s]) if abs(np.array([c, s]) @ u) >= abs(np.array([-s, c]) @ u) else np.array([-s, c])
|
| 326 |
+
long_ax = long_ax * np.sign(long_ax @ u)
|
| 327 |
+
b = np.asarray(inst["board_xy"])
|
| 328 |
+
half = BOARD_HALF[0] if edge in ("forward", "backward") else BOARD_HALF[1]
|
| 329 |
+
edge_pos = (b @ u) + half # coordinate of the edge along u
|
| 330 |
+
ext = CARD_HALF[0] * abs(long_ax @ u) + CARD_HALF[1] * abs(np.array([-long_ax[1], long_ax[0]]) @ u)
|
| 331 |
+
for short in (0.01, 0.0): # slide to 1 cm short, look again, slide the rest (one stroke overshoots ~0.7 cm)
|
| 332 |
+
p = self.card_pose()
|
| 333 |
+
need = edge_pos + float(params["overhang"]) - short - (p["xy"] @ u + ext) # travel still needed along u
|
| 334 |
+
if need > 0.003:
|
| 335 |
+
self.slide_card(long_ax * need / max(long_ax @ u, 1e-6))
|
| 336 |
+
q = self.card_pose()
|
| 337 |
+
cu = float(q["xy"] @ u)
|
| 338 |
+
tip_u = cu + CARD_HALF[0] * float(long_ax @ u) # centre of the card's far end, along u
|
| 339 |
+
target_u = min(tip_u - 0.008, edge_pos + GRASP_OUT)
|
| 340 |
+
g = q["xy"] + long_ax * (target_u - cu) / max(float(long_ax @ u), 1e-6)
|
| 341 |
+
self.grasp_and_bin(g, q["yaw"], BOARD_TOP - 0.003)
|
| 342 |
+
|
| 343 |
+
def default_params(self, inst):
|
| 344 |
+
return dict(mode="grasp")
|
| 345 |
+
|
| 346 |
+
def oracle_params(self, inst):
|
| 347 |
+
return dict(mode="edge", overhang=OVERHANG)
|
| 348 |
+
|
| 349 |
+
def blind_params(self, inst, attempt, rng):
|
| 350 |
+
return dict(mode="grasp", dxy=rng.normal(0.0, 0.006, 2).tolist(), dyaw=float(rng.normal(0.0, 0.12)),
|
| 351 |
+
dz=float(rng.uniform(-0.006, 0.003)))
|
| 352 |
+
|
| 353 |
+
def adapt_params(self, inst, history):
|
| 354 |
+
"""not lifted while flat on the board (fingers slid over it) -> slide it over the edge first, 3 cm.
|
| 355 |
+
Edge tried: card fell off -> 1 cm less; fingers closed without holding and < 4 cm overhang -> 1 cm more."""
|
| 356 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 357 |
+
if prm["mode"] == "grasp":
|
| 358 |
+
return dict(mode="edge", overhang=OVERHANG) if out["mode"] in ("not_lifted", "fell_off") else dict(prm)
|
| 359 |
+
h = float(prm["overhang"])
|
| 360 |
+
if out["mode"] == "fell_off":
|
| 361 |
+
h -= 0.01
|
| 362 |
+
elif out["mode"] == "not_lifted":
|
| 363 |
+
h += 0.01 if out["max_overhang"] < 0.04 else -0.005
|
| 364 |
+
return dict(mode="edge", overhang=float(np.clip(h, 0.025, 0.045)))
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l3_wide.py
ADDED
|
@@ -0,0 +1,435 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3-B too_wide_push: a box that is slightly too wide for the gripper must be pushed into a square on the table.
|
| 2 |
+
|
| 3 |
+
Why the prior fails: the box looks like an ordinary graspable box (narrow side 8.3-8.9 cm, long side 11-13 cm,
|
| 4 |
+
4 cm high), but the Panda's fingers open to only 7.9 cm. A top-down grasp across the narrow side therefore puts
|
| 5 |
+
both fingers on top of the box; closing them grips nothing. Across the long side it is worse, and retrying the
|
| 6 |
+
same grasp with small variations fails the same way. A difference of 4-10 mm between the box and the maximum
|
| 7 |
+
opening is not readable from the camera images, and the agent is not told the gripper's opening.
|
| 8 |
+
|
| 9 |
+
What must be learned from the failure: this object cannot be picked up at all -> change the manipulation mode:
|
| 10 |
+
close the gripper and push the box (there is no push primitive: the agent closes the gripper, lowers it beside
|
| 11 |
+
the box and moves it along the table with move_to), keeping the box from turning, until it lies completely
|
| 12 |
+
inside the square.
|
| 13 |
+
|
| 14 |
+
Layout (randomised per instance): box size, position and yaw (long side roughly along x or along y, +-10 deg),
|
| 15 |
+
target square (18 x 18 cm inner, axis-aligned) 16-22 cm away along one world axis (forward, backward, left or
|
| 16 |
+
right) with a lateral offset of up to 3 cm.
|
| 17 |
+
|
| 18 |
+
Protocol: cross (reset to the same instance before every attempt), k = 5.
|
| 19 |
+
"""
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
from .. import envs
|
| 23 |
+
from ..bddl import write_bddl
|
| 24 |
+
from ..objects import box_xml, register_generated
|
| 25 |
+
from ..skills import DT, _rot_err
|
| 26 |
+
from ..task_base import LFFTask, register_task
|
| 27 |
+
from .l5_slide import square_frame_xml
|
| 28 |
+
|
| 29 |
+
BOX_HALF_MAX = (0.07, 0.05, 0.02) # registered size (x = long, y = narrow, z); shrunk per instance
|
| 30 |
+
BOX_HALF_Z = 0.02 # 4 cm high
|
| 31 |
+
BOX_MASS = 0.40
|
| 32 |
+
BOX_MU = 0.6 # box sliding friction (priority over the table's 1.0 and the fingers')
|
| 33 |
+
GRIP_OPEN = 0.079 # measured distance between the finger pads when fully open
|
| 34 |
+
SQ_IN = 0.09 # target square: 18 cm inner side
|
| 35 |
+
SQ_LINE = 0.008
|
| 36 |
+
Z_GRASP = envs.TABLE_Z + 0.022 # site height of a normal top-down grasp of a 4 cm box (pads 1.7-3.4 cm above table)
|
| 37 |
+
Z_PUSH = envs.TABLE_Z + 0.02 # site height while pushing: finger tips ~1 cm above the table
|
| 38 |
+
PUSH_SPEED = 0.08
|
| 39 |
+
FRONT_GAP = 0.03 # where a push stroke starts: this far behind the box face
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _wrap_pi(a):
|
| 43 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _yaw_of(quat_wxyz):
|
| 47 |
+
w, x, y, z = quat_wxyz
|
| 48 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
DIRS = {"forward": (1.0, 0.0), "backward": (-1.0, 0.0), "left": (0.0, 1.0), "right": (0.0, -1.0)}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@register_task
|
| 55 |
+
class TooWidePush(LFFTask):
|
| 56 |
+
name = "l3_too_wide_push"
|
| 57 |
+
level = "L3"
|
| 58 |
+
category = "strategy_switching"
|
| 59 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 60 |
+
protocol = "cross"
|
| 61 |
+
instruction = "Put the brown box completely inside the green square marked on the table."
|
| 62 |
+
instruction_indirect = "Put the cardboard-coloured package completely inside the green outlined area on the table."
|
| 63 |
+
|
| 64 |
+
def __init__(self, cam_res=None):
|
| 65 |
+
super().__init__(cam_res)
|
| 66 |
+
self._mon = None
|
| 67 |
+
self.inst = None
|
| 68 |
+
orig_step = self.env.step
|
| 69 |
+
|
| 70 |
+
def step(action): # per-control-step event monitor (also sees agent-driven attempts)
|
| 71 |
+
ret = orig_step(action)
|
| 72 |
+
if self._mon is not None:
|
| 73 |
+
self._monitor_step()
|
| 74 |
+
return ret
|
| 75 |
+
|
| 76 |
+
self.env.step = step
|
| 77 |
+
|
| 78 |
+
# ------------------------------------------------------------ scene
|
| 79 |
+
def make_bddl(self):
|
| 80 |
+
box = register_generated("LffWideBox", box_xml("lff_wide_box", BOX_HALF_MAX, (0.62, 0.45, 0.28, 1.0),
|
| 81 |
+
density=500))
|
| 82 |
+
sq = register_generated("LffWideSquare", square_frame_xml("lff_wide_square", inner_half=SQ_IN, line_w=SQ_LINE),
|
| 83 |
+
free=False)
|
| 84 |
+
objs = [("box_1", box, "box_region", (-0.11, -0.21, -0.09, -0.19))]
|
| 85 |
+
fx = [("square_1", sq, "square_region", (-0.01, 0.19, 0.01, 0.21))]
|
| 86 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 87 |
+
|
| 88 |
+
def _box_geoms(self):
|
| 89 |
+
if not hasattr(self, "_bg"):
|
| 90 |
+
m = self.env.sim.model
|
| 91 |
+
bid = envs.body_id(self.env, "box_1")
|
| 92 |
+
self._bg = [g for g in range(m.ngeom) if m.geom_bodyid[g] == bid]
|
| 93 |
+
return self._bg
|
| 94 |
+
|
| 95 |
+
def sample_instance(self, seed):
|
| 96 |
+
rng = np.random.default_rng(seed)
|
| 97 |
+
while True:
|
| 98 |
+
narrow = float(rng.uniform(0.083, 0.089))
|
| 99 |
+
long_ = float(rng.uniform(0.11, 0.13))
|
| 100 |
+
long_axis = str(rng.choice(["x", "y"]))
|
| 101 |
+
yaw = (0.0 if long_axis == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
|
| 102 |
+
dname = str(rng.choice(list(DIRS)))
|
| 103 |
+
u = np.array(DIRS[dname])
|
| 104 |
+
# half extent of the box along the push direction (box roughly axis aligned)
|
| 105 |
+
ext = 0.5 * (long_ if (long_axis == "x") == (dname in ("forward", "backward")) else narrow)
|
| 106 |
+
dist = float(rng.uniform(SQ_IN + ext + 0.01, SQ_IN + ext + 0.07))
|
| 107 |
+
lat = float(rng.uniform(-0.03, 0.03))
|
| 108 |
+
box_xy = np.array([rng.uniform(-0.20, 0.04), rng.uniform(-0.20, 0.20)])
|
| 109 |
+
sq_xy = box_xy + u * dist + np.array([-u[1], u[0]]) * lat
|
| 110 |
+
# reach: pushing backward needs the hand ~5 cm beyond the box's far face; the arm's reach at table height
|
| 111 |
+
# ends around x = 0.05-0.08 (seed 1015 of the first version: hand stalled at x = 0.09, box never moved)
|
| 112 |
+
reach_ok = dname != "backward" or box_xy[0] + ext <= -0.01
|
| 113 |
+
if -0.22 <= sq_xy[0] <= 0.06 and -0.20 <= sq_xy[1] <= 0.20 and reach_ok:
|
| 114 |
+
return dict(seed=int(seed), box_half=[long_ / 2, narrow / 2], box_yaw=float(yaw), box_xy=box_xy.tolist(),
|
| 115 |
+
square_xy=sq_xy.tolist(), direction=dname, long_axis=long_axis)
|
| 116 |
+
|
| 117 |
+
def apply_instance(self, inst):
|
| 118 |
+
self.inst = inst
|
| 119 |
+
m = self.env.sim.model
|
| 120 |
+
for g in self._box_geoms():
|
| 121 |
+
m.geom_size[g, 0], m.geom_size[g, 1] = inst["box_half"]
|
| 122 |
+
m.geom_size[g, 2] = BOX_HALF_Z
|
| 123 |
+
envs.scale_mass(self.env, "box_1", BOX_MASS)
|
| 124 |
+
envs.set_friction(self.env, "box_1", BOX_MU)
|
| 125 |
+
sq = self.env.fixtures_dict["square_1"]
|
| 126 |
+
for g in range(m.ngeom):
|
| 127 |
+
if (m.geom_id2name(g) or "").startswith("square_1_"):
|
| 128 |
+
m.geom_contype[g] = 0
|
| 129 |
+
m.geom_conaffinity[g] = 0
|
| 130 |
+
bid = m.body_name2id(sq.root_body)
|
| 131 |
+
m.body_pos[bid] = [inst["square_xy"][0], inst["square_xy"][1], envs.TABLE_Z + 0.0002]
|
| 132 |
+
m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 133 |
+
bx, by = inst["box_xy"]
|
| 134 |
+
envs.set_obj_pose(self.env, "box_1", [bx, by, envs.TABLE_Z + BOX_HALF_Z + 0.0005], yaw=inst["box_yaw"])
|
| 135 |
+
|
| 136 |
+
def reset_instance(self, inst, recorder=None):
|
| 137 |
+
self._mon = None
|
| 138 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 139 |
+
self._start_monitor()
|
| 140 |
+
return sk
|
| 141 |
+
|
| 142 |
+
# ------------------------------------------------------------ geometry / perception stand-in
|
| 143 |
+
def observe(self):
|
| 144 |
+
"""What a perfect perceiver reads off the image: box centre, yaw and footprint, square centre."""
|
| 145 |
+
b = envs.obj_pos(self.env, "box_1")
|
| 146 |
+
return dict(box_xy=b[:2].copy(), box_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")),
|
| 147 |
+
square_xy=np.array(self.inst["square_xy"], float), half=np.array(self.inst["box_half"], float))
|
| 148 |
+
|
| 149 |
+
def corners3d(self):
|
| 150 |
+
"""the 8 corners of the box (world)"""
|
| 151 |
+
d = self.env.sim.data
|
| 152 |
+
bid = envs.body_id(self.env, "box_1")
|
| 153 |
+
R = d.body_xmat[bid].reshape(3, 3)
|
| 154 |
+
h = np.array([self.inst["box_half"][0], self.inst["box_half"][1], BOX_HALF_Z])
|
| 155 |
+
return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, sz]) for sx in (-1, 1) for sy in (-1, 1)
|
| 156 |
+
for sz in (-1, 1)])
|
| 157 |
+
|
| 158 |
+
def corners(self, o=None):
|
| 159 |
+
"""footprint corners (xy) of the box in its current pose (also when it is tilted or on its side)"""
|
| 160 |
+
return self.corners3d()[:, :2]
|
| 161 |
+
|
| 162 |
+
def protrusion(self, o=None):
|
| 163 |
+
"""How far the box footprint sticks out beyond each edge of the square (m, >0 = outside)."""
|
| 164 |
+
o = o or self.observe()
|
| 165 |
+
rel = self.corners(o) - o["square_xy"]
|
| 166 |
+
return {"forward": float(rel[:, 0].max() - SQ_IN), "backward": float(-rel[:, 0].min() - SQ_IN),
|
| 167 |
+
"left": float(rel[:, 1].max() - SQ_IN), "right": float(-rel[:, 1].min() - SQ_IN)}
|
| 168 |
+
|
| 169 |
+
def extent_along(self, u, o=None):
|
| 170 |
+
"""half extent of the box footprint along the unit xy vector u"""
|
| 171 |
+
o = o or self.observe()
|
| 172 |
+
c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"])
|
| 173 |
+
hx, hy = o["half"]
|
| 174 |
+
return float(hx * abs(u @ [c, s]) + hy * abs(u @ [-s, c]))
|
| 175 |
+
|
| 176 |
+
# ------------------------------------------------------------ contacts / event monitor
|
| 177 |
+
def _groups(self):
|
| 178 |
+
if not hasattr(self, "_gg"):
|
| 179 |
+
m = self.env.sim.model
|
| 180 |
+
fg = {g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith("gripper0_finger")}
|
| 181 |
+
robot = set(envs.robot_geom_ids(self.env))
|
| 182 |
+
self._gg = (fg, robot, set(envs.obj_geom_ids(self.env, "box_1")))
|
| 183 |
+
return self._gg
|
| 184 |
+
|
| 185 |
+
def _finger_landings(self):
|
| 186 |
+
"""{'box' | 'table' | 'other': n_fingers} for fingers resting on a top surface (contact normal vertical)."""
|
| 187 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 188 |
+
fg, robot, box = self._groups()
|
| 189 |
+
out = {}
|
| 190 |
+
for i in range(d.ncon):
|
| 191 |
+
c = d.contact[i]
|
| 192 |
+
if c.geom1 in fg and c.geom2 not in robot:
|
| 193 |
+
f, other = c.geom1, c.geom2
|
| 194 |
+
elif c.geom2 in fg and c.geom1 not in robot:
|
| 195 |
+
f, other = c.geom2, c.geom1
|
| 196 |
+
else:
|
| 197 |
+
continue
|
| 198 |
+
if abs(c.frame[2]) < 0.7:
|
| 199 |
+
continue
|
| 200 |
+
lab = "box" if other in box else ("table" if (m.geom_id2name(other) or "").startswith("table") else "other")
|
| 201 |
+
name = m.geom_id2name(f) or ""
|
| 202 |
+
out.setdefault(lab, set()).add("1" if "finger1" in name else "2")
|
| 203 |
+
return out
|
| 204 |
+
|
| 205 |
+
def _closing_axis(self):
|
| 206 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 207 |
+
jid = m.joint_name2id(self.env.robots[0].gripper.joints[0])
|
| 208 |
+
a = d.xaxis[jid][:2]
|
| 209 |
+
return a / max(np.linalg.norm(a), 1e-9)
|
| 210 |
+
|
| 211 |
+
def _start_monitor(self):
|
| 212 |
+
b = envs.obj_pos(self.env, "box_1")
|
| 213 |
+
self._mon = dict(rest_z=float(b[2]), start_xy=b[:2].copy(), start_yaw=_yaw_of(envs.obj_quat(self.env, "box_1")),
|
| 214 |
+
max_dz=0.0, top_hit=None, prev=set(), was_held=False)
|
| 215 |
+
|
| 216 |
+
def _monitor_step(self):
|
| 217 |
+
mon = self._mon
|
| 218 |
+
zmin = float(self.corners3d()[:, 2].min())
|
| 219 |
+
mon["max_dz"] = max(mon["max_dz"], zmin - envs.TABLE_Z) # whole box above the table
|
| 220 |
+
hits = self._finger_landings()
|
| 221 |
+
open_ = self.sk is not None and self.sk.gripper_width() > 0.03
|
| 222 |
+
if "box" in hits and "box" not in mon["prev"] and open_: # an open gripper landing on the box top = a grasp
|
| 223 |
+
o = self.observe()
|
| 224 |
+
ca = self._closing_axis()
|
| 225 |
+
e = self.env.sim.data.site_xpos[self.env.robots[0].eef_site_id]
|
| 226 |
+
mon["top_hit"] = dict(span=2 * self.extent_along(ca, o), n_fingers=len(hits["box"]),
|
| 227 |
+
offset=float(np.linalg.norm(e[:2] - o["box_xy"])))
|
| 228 |
+
if "box" in hits and len(hits["box"]) == 2 and mon["top_hit"] is not None and open_:
|
| 229 |
+
mon["top_hit"]["n_fingers"] = 2
|
| 230 |
+
mon["prev"] = set(hits)
|
| 231 |
+
|
| 232 |
+
# ------------------------------------------------------------ outcome / F2
|
| 233 |
+
def outcome(self, inst):
|
| 234 |
+
"""Success = the whole box footprint inside the square, box resting on the table, released."""
|
| 235 |
+
envs.settle(self.env, 30)
|
| 236 |
+
env, mon = self.env, self._mon or {}
|
| 237 |
+
o = self.observe()
|
| 238 |
+
b = envs.obj_pos(env, "box_1")
|
| 239 |
+
prot = self.protrusion(o)
|
| 240 |
+
inside = max(prot.values()) <= 0.0
|
| 241 |
+
upright = abs(envs.obj_upright_cos(env, "box_1")) > 0.9
|
| 242 |
+
held = bool(self.sk.holding("box_1")) if self.sk is not None else False
|
| 243 |
+
zmin = float(self.corners3d()[:, 2].min())
|
| 244 |
+
resting = abs(zmin - envs.TABLE_Z) < 0.01
|
| 245 |
+
success = bool(inside and resting and not held)
|
| 246 |
+
rel = o["box_xy"] - o["square_xy"]
|
| 247 |
+
moved = float(np.linalg.norm(o["box_xy"] - mon.get("start_xy", o["box_xy"])))
|
| 248 |
+
turned = float(np.degrees(_wrap_pi(o["box_yaw"] - mon.get("start_yaw", o["box_yaw"])))) if upright else 0.0
|
| 249 |
+
lifted = mon.get("max_dz", 0.0) > 0.01
|
| 250 |
+
top = mon.get("top_hit")
|
| 251 |
+
parts, mode = [], "success"
|
| 252 |
+
|
| 253 |
+
def where():
|
| 254 |
+
return (f"its centre is {100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
|
| 255 |
+
f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the square's centre")
|
| 256 |
+
|
| 257 |
+
def sticking():
|
| 258 |
+
return ", ".join(f"{100 * v:.1f} cm beyond the square's {k} edge" for k, v in
|
| 259 |
+
sorted(prot.items(), key=lambda kv: -kv[1]) if v > 0.0)
|
| 260 |
+
|
| 261 |
+
if success:
|
| 262 |
+
parts.append("The box lies completely inside the square.")
|
| 263 |
+
elif b[2] < envs.TABLE_Z - 0.05:
|
| 264 |
+
mode = "fell_off"
|
| 265 |
+
parts.append("The box fell off the table.")
|
| 266 |
+
elif held:
|
| 267 |
+
mode = "held"
|
| 268 |
+
parts.append(f"The box is still held by the gripper; {where()}.")
|
| 269 |
+
elif not resting:
|
| 270 |
+
mode = "not_resting"
|
| 271 |
+
parts.append(f"The box is not resting on the table (it is propped up or tilted); {where()}.")
|
| 272 |
+
else:
|
| 273 |
+
mode = "outside"
|
| 274 |
+
if top is not None and not lifted:
|
| 275 |
+
mode = "too_wide"
|
| 276 |
+
if top["n_fingers"] >= 2 or top["span"] > GRIP_OPEN:
|
| 277 |
+
parts.append(f"The fingers came down on top of the box instead of on either side of it: along the "
|
| 278 |
+
f"gripper's closing direction the box measures {100 * top['span']:.1f} cm, wider than "
|
| 279 |
+
f"the gripper's maximum opening ({100 * GRIP_OPEN:.1f} cm). The box was not grasped.")
|
| 280 |
+
else:
|
| 281 |
+
parts.append(f"A finger came down on top of the box (the gripper was {100 * top['offset']:.1f} cm "
|
| 282 |
+
f"from the box centre). The box was not grasped.")
|
| 283 |
+
if moved < 0.01:
|
| 284 |
+
mode = "not_moved" if mode == "outside" else mode
|
| 285 |
+
parts.append(f"The box did not move; it sticks out {sticking()}.")
|
| 286 |
+
else:
|
| 287 |
+
parts.append(f"The box was moved {100 * moved:.1f} cm but is not completely inside the square: it "
|
| 288 |
+
f"sticks out {sticking()}; {where()}.")
|
| 289 |
+
if abs(turned) >= 5:
|
| 290 |
+
rot = "counter-clockwise" if turned > 0 else "clockwise"
|
| 291 |
+
parts.append(f"It turned by {abs(turned):.0f} deg ({rot} seen from above).")
|
| 292 |
+
if not success and not upright and mode not in ("fell_off",):
|
| 293 |
+
parts.append("The box is no longer lying on its large bottom face.")
|
| 294 |
+
out = dict(success=success, mode=mode, inside=bool(inside), protrusion=prot, rel=[float(rel[0]), float(rel[1])],
|
| 295 |
+
moved=moved, turned_deg=turned, lifted=bool(lifted), held=held, upright=bool(upright),
|
| 296 |
+
top_hit_span=None if top is None else float(top["span"]),
|
| 297 |
+
terminal=bool(b[2] < envs.TABLE_Z - 0.05), detail=" ".join(parts))
|
| 298 |
+
self._start_monitor()
|
| 299 |
+
return out
|
| 300 |
+
|
| 301 |
+
# ------------------------------------------------------------ primitives for the scripted policies
|
| 302 |
+
def _yaw_near(self, yaw):
|
| 303 |
+
cands = [yaw + k * np.pi for k in (-2, -1, 0, 1, 2)]
|
| 304 |
+
cands = [c for c in cands if abs(c) <= np.pi / 2 + 0.4] or cands
|
| 305 |
+
return float(min(cands, key=lambda c: abs(c - self.sk.yaw)))
|
| 306 |
+
|
| 307 |
+
def _align(self, tol=0.03, max_steps=60):
|
| 308 |
+
sk = self.sk
|
| 309 |
+
for _ in range(max_steps):
|
| 310 |
+
R = sk._R() @ sk.eef_mat().T
|
| 311 |
+
if np.arccos(np.clip((np.trace(R) - 1) / 2, -1, 1)) < tol:
|
| 312 |
+
break
|
| 313 |
+
sk.hold(1)
|
| 314 |
+
|
| 315 |
+
def _guarded_descent(self, xyz, speed=0.12, max_steps=60):
|
| 316 |
+
"""descent that stops when a finger lands on a top surface above the target (contact sensing)"""
|
| 317 |
+
sk = self.sk
|
| 318 |
+
p0 = sk.eef_pos()
|
| 319 |
+
tgt = np.asarray(xyz, float)
|
| 320 |
+
dist = max(np.linalg.norm(tgt - p0), 1e-6)
|
| 321 |
+
R = sk._R()
|
| 322 |
+
for k in range(max_steps):
|
| 323 |
+
ref = p0 + (tgt - p0) * min(1.0, (k + 1) * speed * DT / dist)
|
| 324 |
+
sk._act(ref - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 325 |
+
if self._finger_landings() and sk.eef_pos()[2] > tgt[2] + 0.005:
|
| 326 |
+
break
|
| 327 |
+
if np.linalg.norm(tgt - sk.eef_pos()) < 0.003:
|
| 328 |
+
break
|
| 329 |
+
sk.hold(4)
|
| 330 |
+
|
| 331 |
+
def _finger_front(self, direction):
|
| 332 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 333 |
+
e = self.sk.eef_pos()
|
| 334 |
+
best = 0.0
|
| 335 |
+
for g in range(m.ngeom):
|
| 336 |
+
if not (m.geom_id2name(g) or "").startswith("gripper0_finger") or m.geom_type[g] != 7:
|
| 337 |
+
continue
|
| 338 |
+
mid = m.geom_dataid[g]
|
| 339 |
+
v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]]
|
| 340 |
+
w = v @ d.geom_xmat[g].reshape(3, 3).T + d.geom_xpos[g] - e
|
| 341 |
+
best = max(best, float((w[:, :2] @ direction).max()))
|
| 342 |
+
return best
|
| 343 |
+
|
| 344 |
+
def grasp_and_place(self, dx=0.0, dy=0.0, dyaw=0.0, across="narrow"):
|
| 345 |
+
"""Top-down grasp across the box's narrow side at its centre (+ offsets); if it is held, put it in the square."""
|
| 346 |
+
sk, o = self.sk, self.observe()
|
| 347 |
+
gx, gy = o["box_xy"][0] + dx, o["box_xy"][1] + dy
|
| 348 |
+
# yaw 0 closes along world y; to close across the narrow side (box local y) use the box yaw
|
| 349 |
+
yaw = self._yaw_near(o["box_yaw"] + (0.0 if across == "narrow" else np.pi / 2) + dyaw)
|
| 350 |
+
sk.set_gripper(False, steps=8)
|
| 351 |
+
sk.move_to([gx, gy, Z_GRASP + 0.10], yaw=yaw)
|
| 352 |
+
self._align()
|
| 353 |
+
self._guarded_descent([gx, gy, Z_GRASP])
|
| 354 |
+
sk.set_gripper(True, steps=15)
|
| 355 |
+
z0 = envs.obj_pos(self.env, "box_1")[2]
|
| 356 |
+
sk.move_to([gx, gy, Z_GRASP + 0.12], speed=0.25)
|
| 357 |
+
if not (sk.holding("box_1") and envs.obj_pos(self.env, "box_1")[2] > z0 + 0.06):
|
| 358 |
+
sk.set_gripper(False, steps=8)
|
| 359 |
+
return
|
| 360 |
+
sx, sy = o["square_xy"]
|
| 361 |
+
sk.move_to([sx, sy, Z_GRASP + 0.12])
|
| 362 |
+
sk.move_to([sx, sy, Z_GRASP + 0.005])
|
| 363 |
+
sk.set_gripper(False, steps=12)
|
| 364 |
+
sk.move_to([sx, sy, Z_GRASP + 0.12])
|
| 365 |
+
|
| 366 |
+
def push_stroke(self, u, dist):
|
| 367 |
+
"""Closed gripper behind the box face opposite to u (fingers side by side across the push direction), sweep
|
| 368 |
+
along u so that the box moves `dist`, then lift away. Built from move_to + close only."""
|
| 369 |
+
sk, o = self.sk, self.observe()
|
| 370 |
+
u = np.asarray(u, float) / np.linalg.norm(u)
|
| 371 |
+
c = o["box_xy"]
|
| 372 |
+
ext = self.extent_along(u, o)
|
| 373 |
+
yaw = self._yaw_near(float(np.arctan2(u[1], u[0]))) # yaw a: closing axis along (-sin a, cos a), i.e. across u
|
| 374 |
+
sk.set_gripper(True, steps=6)
|
| 375 |
+
face = c - u * ext
|
| 376 |
+
p_hi = face - u * 0.08
|
| 377 |
+
sk.move_to([p_hi[0], p_hi[1], Z_PUSH + 0.10], yaw=yaw)
|
| 378 |
+
self._align()
|
| 379 |
+
front = self._finger_front(u)
|
| 380 |
+
start = face - u * (front + FRONT_GAP)
|
| 381 |
+
stop = face + u * (dist - front)
|
| 382 |
+
sk.move_to([start[0], start[1], Z_PUSH + 0.10])
|
| 383 |
+
sk.move_to([start[0], start[1], Z_PUSH], tol=0.003)
|
| 384 |
+
sk.move_to([stop[0], stop[1], Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400)
|
| 385 |
+
sk.hold(3)
|
| 386 |
+
back = stop - u * 0.02
|
| 387 |
+
sk.move_to([back[0], back[1], Z_PUSH], speed=0.1, max_steps=40)
|
| 388 |
+
sk.move_to([back[0], back[1], Z_PUSH + 0.10], speed=0.25)
|
| 389 |
+
|
| 390 |
+
def push_to(self, goal_xy, max_strokes=4, tol=0.008):
|
| 391 |
+
"""Closed-loop push along the box's own axes (each stroke perpendicular to a face keeps the box from turning):
|
| 392 |
+
re-observe after every stroke, push along the axis with the larger remaining error."""
|
| 393 |
+
for _ in range(max_strokes):
|
| 394 |
+
o = self.observe()
|
| 395 |
+
d = np.asarray(goal_xy, float) - o["box_xy"]
|
| 396 |
+
c, s = np.cos(o["box_yaw"]), np.sin(o["box_yaw"])
|
| 397 |
+
axes = [np.array([c, s]), np.array([-s, c])]
|
| 398 |
+
comps = [float(d @ a) for a in axes]
|
| 399 |
+
i = int(np.argmax(np.abs(comps)))
|
| 400 |
+
if abs(comps[i]) < tol:
|
| 401 |
+
break
|
| 402 |
+
u = axes[i] * np.sign(comps[i])
|
| 403 |
+
self.push_stroke(u, abs(comps[i]))
|
| 404 |
+
|
| 405 |
+
def execute(self, inst, params):
|
| 406 |
+
if params["mode"] == "push":
|
| 407 |
+
goal = np.array(inst["square_xy"]) + np.asarray(params.get("goal_offset", (0.0, 0.0)))
|
| 408 |
+
self.push_to(goal, max_strokes=params.get("strokes", 4))
|
| 409 |
+
else:
|
| 410 |
+
self.grasp_and_place(params.get("dx", 0.0), params.get("dy", 0.0), params.get("dyaw", 0.0),
|
| 411 |
+
params.get("across", "narrow"))
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------ scripted references
|
| 414 |
+
def default_params(self, inst):
|
| 415 |
+
return dict(mode="grasp")
|
| 416 |
+
|
| 417 |
+
def oracle_params(self, inst):
|
| 418 |
+
return dict(mode="push")
|
| 419 |
+
|
| 420 |
+
def blind_params(self, inst, attempt, rng):
|
| 421 |
+
return dict(mode="grasp", dx=float(rng.normal(0, 0.008)), dy=float(rng.normal(0, 0.008)),
|
| 422 |
+
dyaw=float(rng.normal(0, 0.15)))
|
| 423 |
+
|
| 424 |
+
def adapt_params(self, inst, history):
|
| 425 |
+
"""too_wide (fingers on top of the box, span > opening) -> the box cannot be picked up: push it instead.
|
| 426 |
+
A push that leaves the box outside -> push again, aiming past the reported miss (box centre offset)."""
|
| 427 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 428 |
+
if prm["mode"] != "push":
|
| 429 |
+
if out["mode"] in ("too_wide", "not_moved"):
|
| 430 |
+
return dict(mode="push")
|
| 431 |
+
return dict(prm)
|
| 432 |
+
if out["mode"] == "outside":
|
| 433 |
+
off = np.asarray(prm.get("goal_offset", (0.0, 0.0))) - 0.5 * np.asarray(out["rel"])
|
| 434 |
+
return dict(mode="push", goal_offset=off.tolist())
|
| 435 |
+
return dict(prm)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l4_diagonal.py
ADDED
|
@@ -0,0 +1,524 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L4-B diagonal_fit: put a long bar flat into an open box whose inside is shorter than the bar.
|
| 2 |
+
|
| 3 |
+
Scene: one open box (inner a x b, a slightly longer than b, 3 cm walls) and a long, thin wooden bar
|
| 4 |
+
(L x 1.2 x 1.4 cm) lying on the table in front of it. The bar is 1.2-2.2 cm longer than the box's inside
|
| 5 |
+
length, so it never fits lined up with a side of the box -- it fits only when turned towards the box's
|
| 6 |
+
diagonal, at an angle that depends on a, b and L (36-45 deg off the long side; the fitting window at zero
|
| 7 |
+
centring error is 12-25 deg wide, see task card).
|
| 8 |
+
|
| 9 |
+
Hidden: the exact dimensions (the bar is only 8-17 % longer than the box -- easy to miss at a glance), and
|
| 10 |
+
that a diagonal placement exists. Box and bar are resized per instance by editing geom sizes in sim.model,
|
| 11 |
+
so one env serves every instance (same technique as l4_fit_container).
|
| 12 |
+
|
| 13 |
+
Prior (naive): tidy placement -- line the bar up with the box's long side. It always ends lying across the
|
| 14 |
+
box on the rim (visible). F2 after a failure: where the bar lies, the angle between bar and box, and by how
|
| 15 |
+
much the bar's footprint at that angle is longer than the inside of the box along the box's long / short
|
| 16 |
+
side. A learner can work out the bar length from that and turn the bar towards the diagonal; a second
|
| 17 |
+
failure (angle slightly off) gives the over-length along the other side, which tells it which way to correct.
|
| 18 |
+
|
| 19 |
+
Only move_to / open / close are needed: grasp the bar in the middle, turn the wrist, release above the box.
|
| 20 |
+
"""
|
| 21 |
+
import numpy as np
|
| 22 |
+
|
| 23 |
+
from .. import envs
|
| 24 |
+
from ..bddl import write_bddl
|
| 25 |
+
from ..objects import bin_xml, box_xml, register_generated
|
| 26 |
+
from ..skills import _rot_err
|
| 27 |
+
from ..task_base import LFFTask, register_task
|
| 28 |
+
|
| 29 |
+
# bar (local x = long axis); length set per instance
|
| 30 |
+
BAR_W, BAR_H = 0.012, 0.014
|
| 31 |
+
BAR_L_MAX = 0.160
|
| 32 |
+
BAR_RGBA = (0.72, 0.36, 0.14, 1.0)
|
| 33 |
+
# box (local x = long axis of the opening); inner size set per instance
|
| 34 |
+
WALL_T, FLOOR_T, WALL_H = 0.006, 0.006, 0.030
|
| 35 |
+
BOX_HALF_H = (WALL_H + FLOOR_T) / 2 # body origin at mid height
|
| 36 |
+
RIM_Z = envs.TABLE_Z + FLOOR_T + WALL_H
|
| 37 |
+
BOX_RGBA = (0.55, 0.62, 0.70, 1.0)
|
| 38 |
+
# sampling ranges (m)
|
| 39 |
+
INNER_A = (0.115, 0.130) # inside length of the box
|
| 40 |
+
A_MINUS_B = (0.004, 0.020) # the box is a little longer than wide
|
| 41 |
+
OVER_LEN = (0.010, 0.020) # bar length minus inside length of the box
|
| 42 |
+
MIN_MARGIN = 0.011 # best-angle clearance (total) the sampler insists on
|
| 43 |
+
MIN_WINDOW_DEG = 8.0 # width of the angle window with >= 6 mm total clearance
|
| 44 |
+
# execution
|
| 45 |
+
Z_GRASP = envs.TABLE_Z + 0.0105 # gripper site; pads span ~0.55-2.25 cm above the table, tips just clear it
|
| 46 |
+
Z_CARRY = envs.TABLE_Z + 0.15
|
| 47 |
+
DROP = 0.010 # bar bottom this far above the rim at release
|
| 48 |
+
PARK = (-0.45, 0.0, envs.TABLE_Z + 0.35)
|
| 49 |
+
PERC_SIGMA = 0.003 # perception noise of the scripted adaptive learner (box inner size, bar width)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
MIDPHASE_OFF = True
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def disable_midphase(env):
|
| 56 |
+
"""Box and bar are resized at run time by editing geom pos / size in sim.model, but MuJoCo's per-body bounding
|
| 57 |
+
volume hierarchy (bvh_aabb, used by the collision mid-phase) is computed once at compile time for the registered
|
| 58 |
+
size. A box wall moved inwards out of its compiled leaf box is silently skipped by the mid-phase (found on the
|
| 59 |
+
nest_order cups, 2026-10-07: the fingers passed through resized walls). Without the mid-phase MuJoCo tests all
|
| 60 |
+
geom pairs of two nearby bodies (still filtered by the run-time geom_rbound set when resizing)."""
|
| 61 |
+
import mujoco
|
| 62 |
+
m = env.sim.model._model
|
| 63 |
+
m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_MIDPHASE)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def wrap_half(a):
|
| 67 |
+
"""angle modulo pi into [-pi/2, pi/2) (bar and box are 180-deg symmetric)"""
|
| 68 |
+
return float((a + np.pi / 2) % np.pi - np.pi / 2)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def fold_quarter(a):
|
| 72 |
+
"""|angle| between two pi-symmetric axes, in [0, pi/2]"""
|
| 73 |
+
a = abs(wrap_half(a))
|
| 74 |
+
return float(min(a, np.pi - a))
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def footprint(L, W, rel):
|
| 78 |
+
"""extent of an L x W rectangle turned by rel against the box axes: (along long side, along short side)"""
|
| 79 |
+
c, s = abs(np.cos(rel)), abs(np.sin(rel))
|
| 80 |
+
return L * c + W * s, L * s + W * c
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def margins(L, W, a, b, rel):
|
| 84 |
+
e1, e2 = footprint(L, W, rel)
|
| 85 |
+
return a - e1, b - e2
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def best_angle(L, W, a, b, n=1801):
|
| 89 |
+
"""angle in [0, pi/2] maximising the smaller of the two clearances; returns (angle, clearance, window)"""
|
| 90 |
+
th = np.linspace(0.0, np.pi / 2, n)
|
| 91 |
+
m1, m2 = margins(L, W, a, b, th)
|
| 92 |
+
m = np.minimum(m1, m2)
|
| 93 |
+
i = int(np.argmax(m))
|
| 94 |
+
ok = th[m >= 0.006]
|
| 95 |
+
win = float(np.degrees(ok.max() - ok.min())) if len(ok) else 0.0
|
| 96 |
+
return float(th[i]), float(m[i]), win
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _rect_corners(xy, yaw, half):
|
| 100 |
+
c, s = np.cos(yaw), np.sin(yaw)
|
| 101 |
+
R = np.array([[c, -s], [s, c]])
|
| 102 |
+
pts = np.array([[1, 1], [1, -1], [-1, -1], [-1, 1]]) * np.asarray(half)
|
| 103 |
+
return pts @ R.T + np.asarray(xy)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _rects_overlap(r1, r2):
|
| 107 |
+
c1, c2 = _rect_corners(*r1), _rect_corners(*r2)
|
| 108 |
+
for yaw in (r1[1], r1[1] + np.pi / 2, r2[1], r2[1] + np.pi / 2):
|
| 109 |
+
ax = np.array([np.cos(yaw), np.sin(yaw)])
|
| 110 |
+
p1, p2 = c1 @ ax, c2 @ ax
|
| 111 |
+
if p1.max() < p2.min() or p2.max() < p1.min():
|
| 112 |
+
return False
|
| 113 |
+
return True
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _rel_dir(dx, dy):
|
| 117 |
+
"""robot-centric text for an offset in the world frame (forward = +x, left = +y), ending in 'of' / 'from'"""
|
| 118 |
+
parts = []
|
| 119 |
+
if abs(dx) >= 0.005:
|
| 120 |
+
parts.append(f"{100 * abs(dx):.1f} cm {'forward' if dx > 0 else 'backward'}")
|
| 121 |
+
if abs(dy) >= 0.005:
|
| 122 |
+
parts.append(f"{100 * abs(dy):.1f} cm to the {'left' if dy > 0 else 'right'}")
|
| 123 |
+
return " and ".join(parts) + " of" if parts else "within 0.5 cm of"
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _turn_text(signed_deg):
|
| 127 |
+
"""relative orientation of the bar against the box's long side (no absolute angles)"""
|
| 128 |
+
if abs(signed_deg) < 2.0:
|
| 129 |
+
return "lies along the box's long side (within 2 degrees)"
|
| 130 |
+
side = "counterclockwise (towards the left)" if signed_deg > 0 else "clockwise (towards the right)"
|
| 131 |
+
return f"is turned about {abs(signed_deg):.0f} degrees {side}, seen from above, from the box's long side"
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
@register_task
|
| 135 |
+
class DiagonalFit(LFFTask):
|
| 136 |
+
name = "l4_diagonal_fit"
|
| 137 |
+
level = "L4"
|
| 138 |
+
category = "geometry_inference"
|
| 139 |
+
capabilities = ("Perceive", "Reason")
|
| 140 |
+
instruction = "Put the wooden bar into the box so that it lies flat on the bottom of the box."
|
| 141 |
+
instruction_indirect = "Put the long brown stick into the grey open tray so that it lies flat on the tray's floor."
|
| 142 |
+
|
| 143 |
+
# ------------------------------------------------------------ scene
|
| 144 |
+
def make_bddl(self):
|
| 145 |
+
bar = register_generated("LffDiagBar", box_xml("lff_diag_bar", (BAR_L_MAX / 2, BAR_W / 2, BAR_H / 2),
|
| 146 |
+
BAR_RGBA, density=700))
|
| 147 |
+
box = register_generated("LffDiagBox", bin_xml("lff_diag_box", (0.065, 0.065), WALL_H, wall_t=WALL_T,
|
| 148 |
+
floor_t=FLOOR_T, rgba=BOX_RGBA, density=3000))
|
| 149 |
+
objs = [("bar_1", bar, "bar_region", (0.02, -0.01, 0.04, 0.01)),
|
| 150 |
+
("box_1", box, "box_region", (-0.19, -0.01, -0.17, 0.01))]
|
| 151 |
+
return write_bddl(self.name, self.instruction, objs)
|
| 152 |
+
|
| 153 |
+
def sample_instance(self, seed):
|
| 154 |
+
rng = np.random.default_rng(seed)
|
| 155 |
+
for _ in range(1000):
|
| 156 |
+
a = float(rng.uniform(*INNER_A))
|
| 157 |
+
b = float(a - rng.uniform(*A_MINUS_B))
|
| 158 |
+
L = float(a + rng.uniform(*OVER_LEN))
|
| 159 |
+
th, m, win = best_angle(L, BAR_W, a, b)
|
| 160 |
+
if m < MIN_MARGIN or win < MIN_WINDOW_DEG:
|
| 161 |
+
continue
|
| 162 |
+
box_xy = [float(rng.uniform(-0.22, -0.13)), float(rng.uniform(-0.10, 0.10))]
|
| 163 |
+
box_yaw = float(rng.uniform(-np.pi / 4, np.pi / 4))
|
| 164 |
+
bar_xy = [float(rng.uniform(-0.01, 0.05)), float(rng.uniform(-0.13, 0.13))]
|
| 165 |
+
bar_yaw = float(rng.uniform(-np.pi / 2, np.pi / 2))
|
| 166 |
+
r_box = (box_xy, box_yaw, (a / 2 + WALL_T + 0.03, b / 2 + WALL_T + 0.03))
|
| 167 |
+
r_bar = (bar_xy, bar_yaw, (L / 2 + 0.01, BAR_W / 2 + 0.03))
|
| 168 |
+
if _rects_overlap(r_box, r_bar):
|
| 169 |
+
continue
|
| 170 |
+
break
|
| 171 |
+
else:
|
| 172 |
+
raise RuntimeError("could not sample an instance")
|
| 173 |
+
prng = np.random.default_rng(seed + 7919)
|
| 174 |
+
perc = [float(a + prng.normal(0, PERC_SIGMA)), float(b + prng.normal(0, PERC_SIGMA)),
|
| 175 |
+
float(BAR_W + prng.normal(0, PERC_SIGMA / 2))]
|
| 176 |
+
return dict(seed=int(seed), inner=[a, b], bar_len=L, bar_xy=bar_xy, bar_yaw=bar_yaw, box_xy=box_xy,
|
| 177 |
+
box_yaw=box_yaw, fit_angle_deg=float(np.degrees(th)), fit_margin_cm=float(100 * m),
|
| 178 |
+
fit_window_deg=win, _perc=perc)
|
| 179 |
+
|
| 180 |
+
def _reshape_box(self, a, b):
|
| 181 |
+
ix, iy, H = a / 2, b / 2, BOX_HALF_H
|
| 182 |
+
parts = [((0, 0, -H + FLOOR_T / 2), (ix + WALL_T, iy + WALL_T, FLOOR_T / 2)),
|
| 183 |
+
((ix + WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 184 |
+
((-ix - WALL_T / 2, 0, FLOOR_T / 2), (WALL_T / 2, iy + WALL_T, WALL_H / 2)),
|
| 185 |
+
((0, iy + WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2)),
|
| 186 |
+
((0, -iy - WALL_T / 2, FLOOR_T / 2), (ix, WALL_T / 2, WALL_H / 2))]
|
| 187 |
+
m = self.env.sim.model
|
| 188 |
+
o = self.env.objects_dict["box_1"]
|
| 189 |
+
for names in (o.contact_geoms, o.visual_geoms):
|
| 190 |
+
assert len(names) == len(parts), names
|
| 191 |
+
for k, n in enumerate(names):
|
| 192 |
+
g = m.geom_name2id(n)
|
| 193 |
+
pos, size = parts[k]
|
| 194 |
+
m.geom_pos[g] = pos
|
| 195 |
+
m.geom_size[g] = size
|
| 196 |
+
m.geom_rbound[g] = float(np.linalg.norm(size))
|
| 197 |
+
m.geom_aabb[g] = [0, 0, 0, *size]
|
| 198 |
+
|
| 199 |
+
def _resize_bar(self, L):
|
| 200 |
+
m = self.env.sim.model
|
| 201 |
+
o = self.env.objects_dict["bar_1"]
|
| 202 |
+
for n in list(o.contact_geoms) + list(o.visual_geoms):
|
| 203 |
+
g = m.geom_name2id(n)
|
| 204 |
+
m.geom_size[g] = [L / 2, BAR_W / 2, BAR_H / 2]
|
| 205 |
+
m.geom_rbound[g] = float(np.linalg.norm(m.geom_size[g]))
|
| 206 |
+
m.geom_aabb[g] = [0, 0, 0, *m.geom_size[g]]
|
| 207 |
+
# keep the mass of the resized bar consistent with its volume (density 700); the geoms live in the
|
| 208 |
+
# child body "object", not in the root body that carries the free joint
|
| 209 |
+
bid = int(m.geom_bodyid[m.geom_name2id(o.contact_geoms[0])])
|
| 210 |
+
mass = 700.0 * L * BAR_W * BAR_H
|
| 211 |
+
m.body_mass[bid] = mass
|
| 212 |
+
m.body_inertia[bid] = mass / 12.0 * np.array([BAR_W ** 2 + BAR_H ** 2, L ** 2 + BAR_H ** 2,
|
| 213 |
+
L ** 2 + BAR_W ** 2])
|
| 214 |
+
|
| 215 |
+
def apply_instance(self, inst):
|
| 216 |
+
if MIDPHASE_OFF:
|
| 217 |
+
disable_midphase(self.env)
|
| 218 |
+
self._reshape_box(*inst["inner"])
|
| 219 |
+
self._resize_bar(inst["bar_len"])
|
| 220 |
+
envs.set_obj_pose(self.env, "box_1", [*inst["box_xy"], envs.TABLE_Z + BOX_HALF_H + 0.0005],
|
| 221 |
+
yaw=inst["box_yaw"])
|
| 222 |
+
envs.set_obj_pose(self.env, "bar_1", [*inst["bar_xy"], envs.TABLE_Z + BAR_H / 2 + 0.0005],
|
| 223 |
+
yaw=inst["bar_yaw"])
|
| 224 |
+
|
| 225 |
+
# ------------------------------------------------------------ outcome
|
| 226 |
+
def _pose(self, name):
|
| 227 |
+
bid = envs.body_id(self.env, name)
|
| 228 |
+
R = self.env.sim.data.body_xmat[bid].reshape(3, 3)
|
| 229 |
+
return self.env.sim.data.body_xpos[bid].copy(), R
|
| 230 |
+
|
| 231 |
+
def outcome(self, inst):
|
| 232 |
+
envs.settle(self.env, 40)
|
| 233 |
+
a, b = inst["inner"]
|
| 234 |
+
L = inst["bar_len"]
|
| 235 |
+
p, R = self._pose("bar_1")
|
| 236 |
+
ax = R[:, 0]
|
| 237 |
+
bar_yaw = float(np.arctan2(ax[1], ax[0]))
|
| 238 |
+
tilt = float(np.degrees(np.arcsin(min(1.0, abs(ax[2]))))) # long axis vs horizontal
|
| 239 |
+
c, Rb = self._pose("box_1")
|
| 240 |
+
byaw = float(np.arctan2(Rb[1, 0], Rb[0, 0]))
|
| 241 |
+
btilt = float(np.degrees(np.arccos(np.clip(Rb[2, 2], -1, 1))))
|
| 242 |
+
held = bool(self.sk is not None and self.sk.holding("bar_1"))
|
| 243 |
+
rel = fold_quarter(bar_yaw - byaw)
|
| 244 |
+
# bar footprint corners in the box frame
|
| 245 |
+
Rz = np.array([[np.cos(byaw), np.sin(byaw)], [-np.sin(byaw), np.cos(byaw)]])
|
| 246 |
+
corners = _rect_corners(p[:2], bar_yaw, (L / 2 * np.cos(np.radians(tilt)), BAR_W / 2))
|
| 247 |
+
loc = (corners - c[:2]) @ Rz.T
|
| 248 |
+
out_x = float(np.max(np.abs(loc[:, 0])) - a / 2)
|
| 249 |
+
out_y = float(np.max(np.abs(loc[:, 1])) - b / 2)
|
| 250 |
+
centre = Rz @ (p[:2] - c[:2])
|
| 251 |
+
floor_top = c[2] - BOX_HALF_H + FLOOR_T
|
| 252 |
+
height = float(envs.obj_min_z(self.env, "bar_1") - floor_top)
|
| 253 |
+
in_opening = out_x <= 0.002 and out_y <= 0.002
|
| 254 |
+
on_floor = height < 0.005 and tilt < 6.0
|
| 255 |
+
success = bool(in_opening and on_floor and not held and btilt < 10.0)
|
| 256 |
+
m_long, m_short = margins(L, BAR_W, a, b, rel)
|
| 257 |
+
fb = dict(rel_deg=round(float(np.degrees(rel)), 1),
|
| 258 |
+
over_long_cm=round(-100 * m_long, 1) if m_long < -0.001 else None,
|
| 259 |
+
over_short_cm=round(-100 * m_short, 1) if m_short < -0.001 else None,
|
| 260 |
+
spare_long_cm=round(100 * max(m_long, 0.0), 1) if m_long >= -0.001 else None,
|
| 261 |
+
spare_short_cm=round(100 * max(m_short, 0.0), 1) if m_short >= -0.001 else None,
|
| 262 |
+
centre_offset_cm=[round(100 * float(centre[0]), 1), round(100 * float(centre[1]), 1)])
|
| 263 |
+
res = dict(success=success, height_cm=round(100 * height, 2), tilt_deg=round(tilt, 1), held=held,
|
| 264 |
+
rel_deg=fb["rel_deg"], bar_xy=[float(p[0]), float(p[1])], feedback=fb)
|
| 265 |
+
signed = float(np.degrees(wrap_half(bar_yaw - byaw)))
|
| 266 |
+
fb["rel_signed_deg"] = round(signed, 1)
|
| 267 |
+
off_w = p[:2] - c[:2] # bar centre relative to the box centre, world axes (only relative values are reported)
|
| 268 |
+
if held:
|
| 269 |
+
res["detail"] = "The bar is still in the gripper."
|
| 270 |
+
res["failure"] = "held"
|
| 271 |
+
return res
|
| 272 |
+
over_box = abs(centre[0]) < a / 2 + WALL_T and abs(centre[1]) < b / 2 + WALL_T
|
| 273 |
+
on_table = envs.obj_min_z(self.env, "bar_1") < envs.TABLE_Z + 0.008 # (floor_top is FLOOR_T above the table)
|
| 274 |
+
if not over_box and on_table:
|
| 275 |
+
res["detail"] = (f"The bar is not in the box: it is lying on the table, its centre "
|
| 276 |
+
f"{_rel_dir(*off_w)} the box's centre.")
|
| 277 |
+
res["failure"] = "table"
|
| 278 |
+
return res
|
| 279 |
+
if success:
|
| 280 |
+
res["detail"] = "The bar is lying flat on the bottom of the box."
|
| 281 |
+
res["failure"] = None
|
| 282 |
+
return res
|
| 283 |
+
if not over_box:
|
| 284 |
+
res["detail"] = (f"The bar is not in the box: it ended partly on the box's rim, "
|
| 285 |
+
f"{100 * (p[2] - envs.TABLE_Z):.1f} cm above the table, its centre "
|
| 286 |
+
f"{_rel_dir(*off_w)} the box's centre.")
|
| 287 |
+
res["failure"] = "off"
|
| 288 |
+
return res
|
| 289 |
+
pose_txt = (f"lying across the top of the box on its rim, {100 * height:.1f} cm above the box floor"
|
| 290 |
+
if tilt < 6.0 else
|
| 291 |
+
f"tilted about {tilt:.0f} degrees, with one end down inside the box and the other end on the rim")
|
| 292 |
+
txt = f"The bar did not go in: it is {pose_txt}. The bar {_turn_text(signed)}."
|
| 293 |
+
parts = []
|
| 294 |
+
if fb["over_long_cm"]:
|
| 295 |
+
parts.append(f"{fb['over_long_cm']:.1f} cm longer than the inside of the box along the box's long side")
|
| 296 |
+
if fb["over_short_cm"]:
|
| 297 |
+
parts.append(f"{fb['over_short_cm']:.1f} cm longer than the inside of the box along the box's short side")
|
| 298 |
+
if parts:
|
| 299 |
+
txt += " At that angle the bar's footprint is " + " and ".join(parts) + "."
|
| 300 |
+
else:
|
| 301 |
+
txt += (f" At that angle the bar's footprint is smaller than the opening (spare {fb['spare_long_cm']:.1f} cm "
|
| 302 |
+
f"along the long side, {fb['spare_short_cm']:.1f} cm along the short side), but it caught on the "
|
| 303 |
+
f"rim (bar centre {_rel_dir(*off_w)} the box's centre).")
|
| 304 |
+
res["detail"] = txt
|
| 305 |
+
res["failure"] = "rim"
|
| 306 |
+
return res
|
| 307 |
+
|
| 308 |
+
# ------------------------------------------------------------ execution
|
| 309 |
+
def execute(self, inst, params):
|
| 310 |
+
"""params: rel_yaw (rad) = angle of the bar's long axis against the box's long side at release.
|
| 311 |
+
Optional (tolerance checks): dx / dy release offset of the bar centre from the box centre along the
|
| 312 |
+
box's long / short axis (m); drop = bar bottom above the rim at release (m)."""
|
| 313 |
+
sk, env = self.sk, self.env
|
| 314 |
+
px, py = inst["bar_xy"]
|
| 315 |
+
g0 = wrap_half(inst["bar_yaw"]) # yaw 0 closes the fingers along world y = across a bar lying along x
|
| 316 |
+
sk.set_gripper(False, steps=5)
|
| 317 |
+
sk.move_to([px, py, Z_GRASP + 0.10], yaw=g0)
|
| 318 |
+
sk.move_to([px, py, Z_GRASP], tol=0.003)
|
| 319 |
+
sk.set_gripper(True, steps=15)
|
| 320 |
+
sk.move_to([px, py, Z_CARRY], speed=0.25)
|
| 321 |
+
byaw = inst["box_yaw"]
|
| 322 |
+
c, s = np.cos(byaw), np.sin(byaw)
|
| 323 |
+
dx, dy = params.get("dx", 0.0), params.get("dy", 0.0)
|
| 324 |
+
bx, by = inst["box_xy"][0] + c * dx - s * dy, inst["box_xy"][1] + s * dx + c * dy
|
| 325 |
+
sk.move_to([bx, by, Z_CARRY], yaw=wrap_half(byaw + params["rel_yaw"]))
|
| 326 |
+
off = envs.obj_pos(env, "bar_1") - sk.eef_pos()
|
| 327 |
+
drop = params.get("drop", DROP)
|
| 328 |
+
sk.move_to([bx - off[0], by - off[1], RIM_Z + drop + BAR_H / 2 + 0.04 - off[2]], tol=0.003)
|
| 329 |
+
tgt = self._servo_bar([bx, by], RIM_Z + drop)
|
| 330 |
+
sk.grip = -1.0
|
| 331 |
+
self._hold_at(tgt, 12)
|
| 332 |
+
sk.move_to([tgt[0], tgt[1], RIM_Z + 0.10])
|
| 333 |
+
sk.move_to(list(PARK), yaw=0.0)
|
| 334 |
+
|
| 335 |
+
def _hold_at(self, target, steps):
|
| 336 |
+
sk = self.sk
|
| 337 |
+
R = sk._R()
|
| 338 |
+
for _ in range(steps):
|
| 339 |
+
sk._act(np.asarray(target) - sk.eef_pos(), _rot_err(R, sk.eef_mat()), sk.grip)
|
| 340 |
+
|
| 341 |
+
def _servo_bar(self, xy, z_bottom, max_steps=60, tol=0.0015):
|
| 342 |
+
"""closed loop on the held bar's centre (scripted policies only)"""
|
| 343 |
+
sk = self.sk
|
| 344 |
+
R = sk._R()
|
| 345 |
+
goal = np.array([xy[0], xy[1], z_bottom + BAR_H / 2])
|
| 346 |
+
tgt = e_prev = sk.eef_pos()
|
| 347 |
+
for i in range(max_steps):
|
| 348 |
+
pb, e = envs.obj_pos(self.env, "bar_1"), sk.eef_pos()
|
| 349 |
+
if i >= 8 and np.linalg.norm(pb - goal) < tol and np.linalg.norm(e - e_prev) < 0.0005:
|
| 350 |
+
break
|
| 351 |
+
tgt = goal - (pb - e)
|
| 352 |
+
sk._act(tgt - e, _rot_err(R, sk.eef_mat()), sk.grip)
|
| 353 |
+
e_prev = e
|
| 354 |
+
return tgt
|
| 355 |
+
|
| 356 |
+
# ------------------------------------------------------------ scripted policies
|
| 357 |
+
def _signed(self, inst, th):
|
| 358 |
+
"""+th or -th, whichever needs the smaller wrist turn from the bar's current orientation"""
|
| 359 |
+
cur = wrap_half(inst["bar_yaw"] - inst["box_yaw"])
|
| 360 |
+
return min((th, -th), key=lambda t: abs(wrap_half(t - cur)))
|
| 361 |
+
|
| 362 |
+
def default_params(self, inst):
|
| 363 |
+
"""tidy prior: bar lined up with the box's long side"""
|
| 364 |
+
return dict(rel_yaw=0.0)
|
| 365 |
+
|
| 366 |
+
def oracle_params(self, inst):
|
| 367 |
+
return dict(rel_yaw=self._signed(inst, np.radians(inst["fit_angle_deg"])))
|
| 368 |
+
|
| 369 |
+
def blind_params(self, inst, attempt, rng):
|
| 370 |
+
"""no history: the prior again with a little jitter in angle and position"""
|
| 371 |
+
return dict(rel_yaw=float(rng.normal(0.0, np.radians(4.0))), dx=float(rng.normal(0, 0.003)),
|
| 372 |
+
dy=float(rng.normal(0, 0.003)))
|
| 373 |
+
|
| 374 |
+
def adapt_params(self, inst, history):
|
| 375 |
+
"""Scripted learner on F2 feedback.
|
| 376 |
+
|
| 377 |
+
Knows the box's inner size and the bar's width only through noisy perception (inst['_perc'],
|
| 378 |
+
sigma = PERC_SIGMA), not the bar's length. Every 'X cm longer than the inside along the long / short side
|
| 379 |
+
at angle d' gives an equation for the bar length L (L cos d + W sin d = a + X, or L sin d + W cos d = b + X);
|
| 380 |
+
'spare' values give the same with a negative X. It takes the largest length estimate (conservative) and turns
|
| 381 |
+
the bar to the angle with the largest clearance for that length; if the last attempt was already at a
|
| 382 |
+
feasible angle and only missed the centre, it keeps the angle."""
|
| 383 |
+
a, b, W = inst["_perc"]
|
| 384 |
+
Ls = []
|
| 385 |
+
for h in history:
|
| 386 |
+
fb = h["outcome"].get("feedback") or {}
|
| 387 |
+
if h["outcome"].get("failure") != "rim":
|
| 388 |
+
continue
|
| 389 |
+
d = np.radians(fb["rel_deg"])
|
| 390 |
+
c, s = np.cos(d), np.sin(d)
|
| 391 |
+
if c > 0.3:
|
| 392 |
+
x = fb["over_long_cm"] if fb["over_long_cm"] is not None else -fb["spare_long_cm"]
|
| 393 |
+
Ls.append((a + x / 100 - W * s) / c)
|
| 394 |
+
if s > 0.3:
|
| 395 |
+
x = fb["over_short_cm"] if fb["over_short_cm"] is not None else -fb["spare_short_cm"]
|
| 396 |
+
Ls.append((b + x / 100 - W * c) / s)
|
| 397 |
+
L_est = max(Ls) if Ls else a + 0.015
|
| 398 |
+
th, m, _ = best_angle(L_est, W, a, b)
|
| 399 |
+
return dict(rel_yaw=self._signed(inst, th), L_est=float(L_est))
|
| 400 |
+
|
| 401 |
+
def random_yaw_params(self, inst, history, rng):
|
| 402 |
+
"""sensitivity variant: a random orientation each retry, no history"""
|
| 403 |
+
return dict(rel_yaw=float(rng.uniform(-np.pi / 2, np.pi / 2)))
|
| 404 |
+
|
| 405 |
+
EXTRA_KINDS = ("random_yaw",)
|
| 406 |
+
|
| 407 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 408 |
+
if kind not in self.EXTRA_KINDS:
|
| 409 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 410 |
+
k = k or self.max_attempts
|
| 411 |
+
rng = np.random.default_rng(seed)
|
| 412 |
+
history = []
|
| 413 |
+
for a in range(k):
|
| 414 |
+
self.reset_instance(inst)
|
| 415 |
+
params = self.default_params(inst) if a == 0 else self.random_yaw_params(inst, history, rng)
|
| 416 |
+
self.execute(inst, params)
|
| 417 |
+
out = self.outcome(inst)
|
| 418 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 419 |
+
if on_attempt:
|
| 420 |
+
on_attempt(a, params, out)
|
| 421 |
+
if out["success"]:
|
| 422 |
+
break
|
| 423 |
+
return history
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
# ---------------------------------------------------------------- physical validity checks
|
| 427 |
+
def physics_check(seed0=1000, n=10, out=None):
|
| 428 |
+
"""Release angles 0 / 90 deg (must fail), +-best angle (must succeed) and best +- 6 deg (report)."""
|
| 429 |
+
import json
|
| 430 |
+
task = DiagonalFit()
|
| 431 |
+
rows = []
|
| 432 |
+
for seed in range(seed0, seed0 + n):
|
| 433 |
+
inst = task.sample_instance(seed)
|
| 434 |
+
th = np.radians(inst["fit_angle_deg"])
|
| 435 |
+
for name, rel, expect in [("aligned", 0.0, False), ("crossed", np.pi / 2, False), ("best+", th, True),
|
| 436 |
+
("best-", -th, True), ("best-6", th - np.radians(6), None),
|
| 437 |
+
("best+6", th + np.radians(6), None)]:
|
| 438 |
+
task.reset_instance(inst)
|
| 439 |
+
task.execute(inst, dict(rel_yaw=float(rel)))
|
| 440 |
+
o = task.outcome(inst)
|
| 441 |
+
rows.append(dict(seed=seed, case=name, rel_deg=float(np.degrees(rel)), success=o["success"], expect=expect,
|
| 442 |
+
failure=o["failure"], height_cm=o["height_cm"], tilt_deg=o["tilt_deg"], detail=o["detail"],
|
| 443 |
+
inner_cm=[round(100 * v, 2) for v in inst["inner"]], bar_cm=round(100 * inst["bar_len"], 2),
|
| 444 |
+
fit_margin_cm=round(inst["fit_margin_cm"], 2), fit_window_deg=round(inst["fit_window_deg"], 1)))
|
| 445 |
+
flag = "" if expect is None or expect == o["success"] else " <-- MISMATCH"
|
| 446 |
+
print(f"seed {seed} {name:8s} rel={np.degrees(rel):+6.1f} succ={o['success']} h={o['height_cm']} "
|
| 447 |
+
f"tilt={o['tilt_deg']} margin={inst['fit_margin_cm']:.2f}cm win={inst['fit_window_deg']:.1f}{flag}",
|
| 448 |
+
flush=True)
|
| 449 |
+
if out:
|
| 450 |
+
with open(out, "w") as f:
|
| 451 |
+
json.dump(rows, f, indent=1)
|
| 452 |
+
bad = [r for r in rows if r["expect"] is not None and r["expect"] != r["success"]]
|
| 453 |
+
print("total", len(rows), "mismatches", len(bad))
|
| 454 |
+
return rows
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def window_check(seed0=1000, n=6, out=None):
|
| 458 |
+
"""Release angle swept around the best angle (-16..+16 deg, step 2), bar centred: the physical fitting window
|
| 459 |
+
against the geometric clearance."""
|
| 460 |
+
import json
|
| 461 |
+
task = DiagonalFit()
|
| 462 |
+
rows = []
|
| 463 |
+
for seed in range(seed0, seed0 + n):
|
| 464 |
+
inst = task.sample_instance(seed)
|
| 465 |
+
th = inst["fit_angle_deg"]
|
| 466 |
+
L, (a, b) = inst["bar_len"], inst["inner"]
|
| 467 |
+
for d in range(-16, 17, 2):
|
| 468 |
+
rel = np.radians(th + d)
|
| 469 |
+
task.reset_instance(inst)
|
| 470 |
+
task.execute(inst, dict(rel_yaw=float(rel)))
|
| 471 |
+
o = task.outcome(inst)
|
| 472 |
+
m1, m2 = margins(L, BAR_W, a, b, rel)
|
| 473 |
+
rows.append(dict(seed=seed, d_deg=d, rel_deg=round(th + d, 1), success=o["success"],
|
| 474 |
+
clearance_mm=round(1000 * float(min(m1, m2)), 1)))
|
| 475 |
+
print(f"seed {seed} best={th:.1f} " + " ".join(f"{r['d_deg']:+d}:{'S' if r['success'] else '.'}"
|
| 476 |
+
for r in rows if r["seed"] == seed), flush=True)
|
| 477 |
+
if out:
|
| 478 |
+
with open(out, "w") as f:
|
| 479 |
+
json.dump(rows, f, indent=1)
|
| 480 |
+
return rows
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def robustness_check(seed0=1000, n=6, out=None):
|
| 484 |
+
"""Execution errors at the best angle: release off-centre along the box's long / short axis, angle off by
|
| 485 |
+
+-4 / +-8 deg, released 3 cm above the rim."""
|
| 486 |
+
import json
|
| 487 |
+
task = DiagonalFit()
|
| 488 |
+
rows = []
|
| 489 |
+
cases = [("best", {}), ("dx4", dict(dx=0.004)), ("dy4", dict(dy=0.004)), ("dx7", dict(dx=0.007)),
|
| 490 |
+
("dy7", dict(dy=0.007)), ("ang+4", dict(dang=4)), ("ang-4", dict(dang=-4)), ("ang+8", dict(dang=8)),
|
| 491 |
+
("ang-8", dict(dang=-8)), ("drop3cm", dict(drop=0.03)), ("dx4_ang4_drop3", dict(dx=0.004, dang=4, drop=0.03))]
|
| 492 |
+
for seed in range(seed0, seed0 + n):
|
| 493 |
+
inst = task.sample_instance(seed)
|
| 494 |
+
th = inst["fit_angle_deg"]
|
| 495 |
+
for name, c in cases:
|
| 496 |
+
params = dict(rel_yaw=float(np.radians(th + c.get("dang", 0))))
|
| 497 |
+
params.update({k: v for k, v in c.items() if k != "dang"})
|
| 498 |
+
task.reset_instance(inst)
|
| 499 |
+
task.execute(inst, params)
|
| 500 |
+
o = task.outcome(inst)
|
| 501 |
+
rows.append(dict(seed=seed, case=name, success=o["success"], detail=o["detail"],
|
| 502 |
+
fit_margin_cm=round(inst["fit_margin_cm"], 2)))
|
| 503 |
+
print(f"seed {seed} {name:15s} succ={o['success']} | {o['detail'][:160]}", flush=True)
|
| 504 |
+
if out:
|
| 505 |
+
with open(out, "w") as f:
|
| 506 |
+
json.dump(rows, f, indent=1)
|
| 507 |
+
for name, _ in cases:
|
| 508 |
+
r = [x["success"] for x in rows if x["case"] == name]
|
| 509 |
+
print(f"{name:15s} {sum(r)}/{len(r)}")
|
| 510 |
+
return rows
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
if __name__ == "__main__":
|
| 514 |
+
# python -m lffbench.tasks.l4_diagonal physics results/l4_diagonal_fit/physics_check.json
|
| 515 |
+
import sys
|
| 516 |
+
# python -m lffbench.tasks.l4_diagonal window results/l4_diagonal_fit/window_check.json
|
| 517 |
+
# python -m lffbench.tasks.l4_diagonal robust results/l4_diagonal_fit/robustness_check.json
|
| 518 |
+
if sys.argv[1] == "physics":
|
| 519 |
+
physics_check(out=sys.argv[2] if len(sys.argv) > 2 else None,
|
| 520 |
+
n=int(sys.argv[3]) if len(sys.argv) > 3 else 10)
|
| 521 |
+
elif sys.argv[1] == "window":
|
| 522 |
+
window_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6)
|
| 523 |
+
elif sys.argv[1] == "robust":
|
| 524 |
+
robustness_check(out=sys.argv[2] if len(sys.argv) > 2 else None, n=int(sys.argv[3]) if len(sys.argv) > 3 else 6)
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_count.py
ADDED
|
@@ -0,0 +1,562 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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identical cubes into an opaque drop box; one carry is interrupted by a slip.
|
| 2 |
+
|
| 3 |
+
Scene: T identical orange 4 cm cubes scattered on the table and a dark, closed drop box (static fixture) at
|
| 4 |
+
one side of the table. The box lid has a square opening on the robot side; a cube released above it falls in,
|
| 5 |
+
lands on a low-friction ramp and slides under the closed part of the lid, where no camera can see it (once past
|
| 6 |
+
the opening it is moved to a storage slot at the far end, so that cubes never queue back under the opening).
|
| 7 |
+
Cubes cannot be taken back out.
|
| 8 |
+
|
| 9 |
+
Instruction: put exactly N cubes into the box (N in {4, 5}, given in the instruction).
|
| 10 |
+
|
| 11 |
+
Interruption: during the (p+1)-th carry (p cubes are already in the box, p in {1..N-1}, hidden) the carried
|
| 12 |
+
cube "slips": the gripper opens and the cube lands back on the table next to the spot it was picked from. The
|
| 13 |
+
number of cubes left on the table is R = N + e with e in {0, 1} drawn independently of p (T = R + p), so
|
| 14 |
+
neither the box nor the table tells how many cubes are inside: progress ("how many have I put in already")
|
| 15 |
+
is only in the agent's own history. Over-filling is irreversible (terminal failure); under-filling can be
|
| 16 |
+
completed in a later segment.
|
| 17 |
+
|
| 18 |
+
Protocol: within (one episode, no reset), like l6_swap_interrupt. An attempt (segment) ends when the agent
|
| 19 |
+
declares done; the outcome is measured; if the box holds fewer than N cubes the agent continues from the
|
| 20 |
+
current state. The slip is injected once per episode, inside attempt 1, by a per-control-step monitor (so it
|
| 21 |
+
also fires for agents driven by the harness). Events reported immediately (`drain_events`): "A cube dropped
|
| 22 |
+
into the box." after every cube that falls in, and the slip.
|
| 23 |
+
|
| 24 |
+
Scripted references (perception = simulator state, as in l6_swap):
|
| 25 |
+
oracle privileged box count: carries cubes until the box holds N.
|
| 26 |
+
adaptive counts its own successful drops (Save), notices the slip (the cube is back on the table, the
|
| 27 |
+
drop count is unchanged), carries cubes until its count reaches N (Retrieve + Utilize). Later
|
| 28 |
+
segments: if F2 says the box holds fewer than N, adds one cube per segment.
|
| 29 |
+
naive memoryless continuation (1 attempt): loses its count at the slip; re-plans from the current frame,
|
| 30 |
+
which shows no progress, so it guesses how many cubes are already inside (uniform over 0..N-1)
|
| 31 |
+
and adds the rest.
|
| 32 |
+
blind memoryless restart (k attempts): at the slip it does not know where it was and starts over
|
| 33 |
+
("the box must get N cubes"), every later segment again puts N cubes in (repeated steps).
|
| 34 |
+
Extra controls (not in the acceptance table): `skip` (counts carries instead of drops, i.e. counts the
|
| 35 |
+
slipped carry; with memory + F2 it adds the missing cube in segment 2) and `inc1` (stateless, adds one cube
|
| 36 |
+
per segment; shows that the within protocol's stop-at-first-success leaks progress to such a policy).
|
| 37 |
+
"""
|
| 38 |
+
import numpy as np
|
| 39 |
+
|
| 40 |
+
from .. import envs
|
| 41 |
+
from ..bddl import write_bddl
|
| 42 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 43 |
+
from ..task_base import LFFTask, register_task
|
| 44 |
+
|
| 45 |
+
CUBE_HALF = 0.02
|
| 46 |
+
CUBE_RGBA = (0.95, 0.50, 0.10, 1.0)
|
| 47 |
+
N_CUBES = 11 # objects declared in the BDDL; unused ones are parked on the floor out of view
|
| 48 |
+
LETTERS = "ABCDEFGHIJK"
|
| 49 |
+
CUBES = [f"cube_{i + 1}" for i in range(N_CUBES)]
|
| 50 |
+
|
| 51 |
+
# drop box (local frame: origin at the centre of the footprint on the table top, +x away from the robot)
|
| 52 |
+
WALL_T = 0.008
|
| 53 |
+
IN_HX, IN_HY = 0.100, 0.110 # inner half sizes
|
| 54 |
+
LID_Z = 0.095 # underside of the lid above the table
|
| 55 |
+
LID_T = 0.008
|
| 56 |
+
HOLE_X = (-0.090, -0.020) # opening in the lid (local x range), on the robot side
|
| 57 |
+
HOLE_HY = 0.035
|
| 58 |
+
RAMP_Z = (0.045, 0.006) # top surface of the ramp at the near (-x) and far (+x) inner walls
|
| 59 |
+
RAMP_T = 0.006
|
| 60 |
+
RAMP_MU = 0.03
|
| 61 |
+
BOX_RGBA = (0.30, 0.20, 0.13, 1.0)
|
| 62 |
+
INNER_RGBA = (0.08, 0.07, 0.06, 1.0)
|
| 63 |
+
HOLE_C = np.array([(HOLE_X[0] + HOLE_X[1]) / 2, 0.0])
|
| 64 |
+
OUT_HX, OUT_HY = IN_HX + WALL_T, IN_HY + WALL_T
|
| 65 |
+
RAMP_SLOPE = (RAMP_Z[0] - RAMP_Z[1]) / (2 * IN_HX)
|
| 66 |
+
RAMP_TH = float(np.arctan(RAMP_SLOPE))
|
| 67 |
+
# Storage slots under the closed part of the lid. A cube that has slid past the opening is moved to the next free
|
| 68 |
+
# slot (out of every camera's view) so that the cubes do not queue up along the slide line back under the opening.
|
| 69 |
+
# Order: the lane straight behind the opening (y = 0) is filled last, so that a newly dropped cube can always slide
|
| 70 |
+
# past the opening before it is moved; then a second layer on the far row. (x, y, layer)
|
| 71 |
+
_ROW = [IN_HX - CUBE_HALF - 0.002 - 0.044 * r for r in range(2)]
|
| 72 |
+
SLOTS = ([(_ROW[r], y, 0) for r in range(2) for y in (-0.088, 0.088, -0.044, 0.044)]
|
| 73 |
+
+ [(_ROW[0], 0.0, 0), (_ROW[1], 0.0, 0)] + [(_ROW[0], y, 1) for y in (-0.088, 0.088, -0.044, 0.044, 0.0)])
|
| 74 |
+
|
| 75 |
+
BASE_X = -0.66
|
| 76 |
+
REACH = 0.70 # max horizontal distance of a cube from the robot base
|
| 77 |
+
CUBE_REGION = (-0.30, 0.07, -0.28, 0.28)
|
| 78 |
+
CUBE_MIN_DIST = 0.085
|
| 79 |
+
BOX_CLEAR = 0.12 # cube centre at least this far from the box footprint (the hand must not hit the lid)
|
| 80 |
+
Z_GRASP = envs.TABLE_Z + CUBE_HALF
|
| 81 |
+
Z_CARRY = envs.TABLE_Z + 0.20
|
| 82 |
+
Z_RELEASE = envs.TABLE_Z + LID_Z + LID_T + 0.012 + CUBE_HALF # cube bottom ~1.2 cm above the lid
|
| 83 |
+
PARK = [(-0.5 + 0.1 * i, 1.25) for i in range(N_CUBES)]
|
| 84 |
+
LIFTED = 0.05 # slip trigger: cube at least this far above its resting height
|
| 85 |
+
HAND_HALF = 0.11 # the Panda hand reaches about this far along the closing axis (it hits 4 cm cubes there)
|
| 86 |
+
HAND_CLEAR = 0.06 # neighbour centre at least this far from that segment for a collision-free grasp
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def hand_box_clear(p, a, box, half=HAND_HALF):
|
| 90 |
+
"""Smallest distance from the hand segment (closing axis at yaw a) to the drop box footprint."""
|
| 91 |
+
ax = np.array([-np.sin(a), np.cos(a)])
|
| 92 |
+
return min(float(np.linalg.norm(np.maximum(np.abs(np.asarray(p) + t * ax - box) - [OUT_HX, OUT_HY], 0.0)))
|
| 93 |
+
for t in np.linspace(-half, half, 9))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def axis_clear(p, a, others, half=HAND_HALF):
|
| 97 |
+
"""Smallest distance from a neighbour centre to the hand segment p +- half * (closing axis at yaw a)."""
|
| 98 |
+
ax = np.array([-np.sin(a), np.cos(a)])
|
| 99 |
+
best = 1.0
|
| 100 |
+
for o in others:
|
| 101 |
+
v = np.asarray(o) - p
|
| 102 |
+
t = float(np.clip(v @ ax, -half, half))
|
| 103 |
+
best = min(best, float(np.linalg.norm(v - t * ax)))
|
| 104 |
+
return best
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def drop_box_xml(model_name):
|
| 108 |
+
"""Closed box with a square opening in the lid and an internal ramp (static fixture, collisions on)."""
|
| 109 |
+
parts = [] # (pos, half size, rgba, quat or None, friction or None)
|
| 110 |
+
H = LID_Z / 2
|
| 111 |
+
# walls
|
| 112 |
+
parts.append(((IN_HX + WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
|
| 113 |
+
parts.append(((-IN_HX - WALL_T / 2, 0, H), (WALL_T / 2, OUT_HY, H), BOX_RGBA))
|
| 114 |
+
parts.append(((0, IN_HY + WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
|
| 115 |
+
parts.append(((0, -IN_HY - WALL_T / 2, H), (IN_HX, WALL_T / 2, H), BOX_RGBA))
|
| 116 |
+
# lid around the opening
|
| 117 |
+
zc = LID_Z + LID_T / 2
|
| 118 |
+
x0, x1 = HOLE_X
|
| 119 |
+
parts.append((((-OUT_HX + x0) / 2, 0, zc), ((x0 + OUT_HX) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # near strip
|
| 120 |
+
parts.append((((x1 + OUT_HX) / 2, 0, zc), ((OUT_HX - x1) / 2, OUT_HY, LID_T / 2), BOX_RGBA)) # far part
|
| 121 |
+
for s in (-1, 1):
|
| 122 |
+
parts.append((((x0 + x1) / 2, s * (HOLE_HY + OUT_HY) / 2, zc), ((x1 - x0) / 2, (OUT_HY - HOLE_HY) / 2,
|
| 123 |
+
LID_T / 2), BOX_RGBA))
|
| 124 |
+
# floor (dark) and ramp
|
| 125 |
+
parts.append(((0, 0, 0.002), (IN_HX, IN_HY, 0.002), INNER_RGBA))
|
| 126 |
+
dz = RAMP_Z[0] - RAMP_Z[1]
|
| 127 |
+
th = float(np.arctan2(dz, 2 * IN_HX))
|
| 128 |
+
L = float(np.hypot(dz, 2 * IN_HX)) / 2
|
| 129 |
+
zmid = (RAMP_Z[0] + RAMP_Z[1]) / 2 - RAMP_T / 2 / np.cos(th)
|
| 130 |
+
ramp = ((0, 0, zmid), (L, IN_HY - 0.001, RAMP_T / 2), INNER_RGBA, (np.cos(th / 2), 0, np.sin(th / 2), 0), RAMP_MU)
|
| 131 |
+
geoms = []
|
| 132 |
+
for k, p in enumerate(parts + [ramp]):
|
| 133 |
+
pos, half, rgba = p[:3]
|
| 134 |
+
quat = p[3] if len(p) > 3 else None
|
| 135 |
+
mu = p[4] if len(p) > 4 else None
|
| 136 |
+
q = f' quat="{_fmt(quat)}"' if quat is not None else ""
|
| 137 |
+
fr = f' friction="{mu} 0.005 0.0001" priority="2"' if mu is not None else ' friction="1.0 0.005 0.0001"'
|
| 138 |
+
geoms.append(f' <geom name="{model_name}_g{k}" type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} '
|
| 139 |
+
f'rgba="{_fmt(rgba)}" density="1000"{fr} group="0" />')
|
| 140 |
+
geoms.append(f' <geom type="box" pos="{_fmt(pos)}" size="{_fmt(half)}"{q} rgba="{_fmt(rgba)}" '
|
| 141 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 142 |
+
return _wrap(model_name, "\n".join(geoms), (LID_Z + LID_T) / 2, float(np.hypot(OUT_HX, OUT_HY)))
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _wrap_q(a):
|
| 146 |
+
"""cubes are symmetric under 90 deg rotations: wrap to [-pi/4, pi/4)"""
|
| 147 |
+
return float((a + np.pi / 4) % (np.pi / 2) - np.pi / 4)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@register_task
|
| 151 |
+
class CountIntoBox(LFFTask):
|
| 152 |
+
name = "l6_count_into_box"
|
| 153 |
+
level = "L6"
|
| 154 |
+
category = "procedural_memory"
|
| 155 |
+
capabilities = ("Perceive", "Save", "Retrieve", "Utilize")
|
| 156 |
+
protocol = "within"
|
| 157 |
+
agent_max_steps = 80 # robot commands per attempt for agents (a VLM needs ~40-55)
|
| 158 |
+
max_attempts = 5
|
| 159 |
+
_TEMPLATE = ("Put exactly {n} of the orange cubes into the dark box, through the opening in its lid. "
|
| 160 |
+
"Cubes cannot be taken back out of the box.")
|
| 161 |
+
_TEMPLATE_INDIRECT = ("Drop exactly {n} of the small orange blocks into the closed brown container through the "
|
| 162 |
+
"square hole in its top. Blocks cannot be taken back out of the container.")
|
| 163 |
+
instruction = _TEMPLATE.format(n="N") # replaced per instance (sample_instance / agent_instruction)
|
| 164 |
+
instruction_indirect = _TEMPLATE_INDIRECT.format(n="N")
|
| 165 |
+
inject = True
|
| 166 |
+
announce_drops = True # False: no "A cube dropped into the box." event (harder variant, counting from images)
|
| 167 |
+
agent_object_names = ["orange cube (several identical)", "drop box"]
|
| 168 |
+
|
| 169 |
+
WORDS = {3: "three", 4: "four", 5: "five", 6: "six"}
|
| 170 |
+
|
| 171 |
+
def agent_instruction(self, inst, variant="direct"):
|
| 172 |
+
t = self._TEMPLATE_INDIRECT if variant == "indirect" else self._TEMPLATE
|
| 173 |
+
return t.format(n=self.WORDS[inst["n_target"]])
|
| 174 |
+
|
| 175 |
+
def __init__(self, cam_res=None):
|
| 176 |
+
super().__init__(cam_res)
|
| 177 |
+
self._mon = False
|
| 178 |
+
orig_step = self.env.step
|
| 179 |
+
|
| 180 |
+
def step(action): # per-control-step monitor: also sees attempts driven by the agent harness
|
| 181 |
+
ret = orig_step(action)
|
| 182 |
+
if self._mon:
|
| 183 |
+
self._monitor()
|
| 184 |
+
return ret
|
| 185 |
+
|
| 186 |
+
self.env.step = step
|
| 187 |
+
|
| 188 |
+
# ------------------------------------------------------------ scene
|
| 189 |
+
def make_bddl(self):
|
| 190 |
+
objs = []
|
| 191 |
+
for i, L in enumerate(LETTERS[:N_CUBES]):
|
| 192 |
+
cat = register_generated(f"LffCountCube{L}", box_xml(f"lff_count_cube_{L.lower()}", (CUBE_HALF,) * 3,
|
| 193 |
+
CUBE_RGBA, density=600))
|
| 194 |
+
gx, gy = -0.30 + 0.15 * (i % 4), -0.40 + 0.2 * (i // 4)
|
| 195 |
+
objs.append((CUBES[i], cat, f"c{i + 1}_region", (gx - 0.01, gy - 0.01, gx + 0.01, gy + 0.01)))
|
| 196 |
+
box = register_generated("LffDropBox", drop_box_xml("lff_drop_box"), free=False)
|
| 197 |
+
fx = [("drop_box_1", box, "box_region", (0.19, 0.39, 0.21, 0.41))]
|
| 198 |
+
return write_bddl(self.name, self._TEMPLATE.format(n="N"), objs, fx)
|
| 199 |
+
|
| 200 |
+
def _box_body(self):
|
| 201 |
+
return self.env.sim.model.body_name2id(self.env.fixtures_dict["drop_box_1"].root_body)
|
| 202 |
+
|
| 203 |
+
def sample_instance(self, seed):
|
| 204 |
+
rng = np.random.default_rng(seed)
|
| 205 |
+
n = int(rng.choice([4, 5]))
|
| 206 |
+
p = int(rng.integers(1, n)) # cubes already inside when the slip happens
|
| 207 |
+
e = int(rng.integers(0, 2))
|
| 208 |
+
T = n + e + p
|
| 209 |
+
for _ in range(500):
|
| 210 |
+
side = int(rng.choice([-1, 1]))
|
| 211 |
+
box = np.array([rng.uniform(-0.08, -0.02), side * rng.uniform(0.22, 0.25)])
|
| 212 |
+
P = np.column_stack([rng.uniform(*CUBE_REGION[:2], 800), rng.uniform(*CUBE_REGION[2:], 800)])
|
| 213 |
+
P = P[np.hypot(P[:, 0] - BASE_X, P[:, 1]) <= REACH]
|
| 214 |
+
P = P[np.linalg.norm(np.maximum(np.abs(P - box) - np.array([OUT_HX, OUT_HY]), 0.0), axis=1) >= BOX_CLEAR]
|
| 215 |
+
cubes = []
|
| 216 |
+
for c in P: # random sequential addition
|
| 217 |
+
if all(np.linalg.norm(c - q) >= CUBE_MIN_DIST for q in cubes):
|
| 218 |
+
cubes.append(c)
|
| 219 |
+
if len(cubes) == T:
|
| 220 |
+
break
|
| 221 |
+
if len(cubes) < T:
|
| 222 |
+
continue
|
| 223 |
+
yaws = [] # each cube gets a yaw whose (small-rotation) grasp axis is free for the hand
|
| 224 |
+
for i in range(T):
|
| 225 |
+
oth = [cubes[j] for j in range(T) if j != i]
|
| 226 |
+
for _ in range(30):
|
| 227 |
+
y = float(rng.uniform(-np.pi / 4, np.pi / 4))
|
| 228 |
+
if axis_clear(cubes[i], y, oth) >= HAND_CLEAR and hand_box_clear(cubes[i], y, box) >= 0.035:
|
| 229 |
+
# |y| <= 45 deg: the grasp needs no large wrist rotation
|
| 230 |
+
yaws.append(y)
|
| 231 |
+
break
|
| 232 |
+
else:
|
| 233 |
+
break
|
| 234 |
+
if len(yaws) == T:
|
| 235 |
+
break
|
| 236 |
+
else:
|
| 237 |
+
raise RuntimeError("could not sample a layout")
|
| 238 |
+
inst = dict(seed=int(seed), n_target=n, p=p, e=e, n_cubes=T, box_xy=box.round(4).tolist(),
|
| 239 |
+
cubes=np.array(cubes).round(4).tolist(),
|
| 240 |
+
yaws=yaws,
|
| 241 |
+
trigger_dist=float(rng.uniform(0.05, 0.09)),
|
| 242 |
+
slip_r=float(rng.uniform(0.005, 0.02)), slip_ang=float(rng.uniform(0, 2 * np.pi)),
|
| 243 |
+
slip_yaw=float(rng.uniform(-np.pi / 4, np.pi / 4)))
|
| 244 |
+
# make_video prints task.instruction: keep it in sync with the last sampled instance
|
| 245 |
+
self.instruction = self.agent_instruction(inst, "direct")
|
| 246 |
+
self.instruction_indirect = self.agent_instruction(inst, "indirect")
|
| 247 |
+
return inst
|
| 248 |
+
|
| 249 |
+
def apply_instance(self, inst):
|
| 250 |
+
m = self.env.sim.model
|
| 251 |
+
bid = self._box_body()
|
| 252 |
+
m.body_pos[bid] = [inst["box_xy"][0], inst["box_xy"][1], envs.TABLE_Z]
|
| 253 |
+
m.body_quat[bid] = [1, 0, 0, 0]
|
| 254 |
+
T = inst["n_cubes"]
|
| 255 |
+
for i, c in enumerate(CUBES):
|
| 256 |
+
if i < T:
|
| 257 |
+
envs.set_obj_pose(self.env, c, [*inst["cubes"][i], envs.TABLE_Z + CUBE_HALF + 0.001],
|
| 258 |
+
yaw=inst["yaws"][i])
|
| 259 |
+
else:
|
| 260 |
+
envs.set_obj_pose(self.env, c, [*PARK[i], CUBE_HALF + 0.001])
|
| 261 |
+
self.env.sim.forward()
|
| 262 |
+
self._inst = inst
|
| 263 |
+
self.active = CUBES[:T]
|
| 264 |
+
self.slip = None
|
| 265 |
+
self.events = []
|
| 266 |
+
self._event_cursor = 0
|
| 267 |
+
self._outcome_cursor = 0
|
| 268 |
+
self.in_box = [] # cubes that fell into the box, in order
|
| 269 |
+
self.stored = [] # cubes moved to a storage slot
|
| 270 |
+
self._bad = set() # scripted policies: cubes whose grasp failed
|
| 271 |
+
self.rest_xy = {c: np.array(inst["cubes"][i]) for i, c in enumerate(self.active)}
|
| 272 |
+
self._mon = False
|
| 273 |
+
|
| 274 |
+
def reset_instance(self, inst, recorder=None):
|
| 275 |
+
self._mon = False
|
| 276 |
+
sk = super().reset_instance(inst, recorder=recorder)
|
| 277 |
+
self._home = sk.eef_pos()
|
| 278 |
+
self._mon = True
|
| 279 |
+
return sk
|
| 280 |
+
|
| 281 |
+
def go_home(self):
|
| 282 |
+
p = self.sk.eef_pos()
|
| 283 |
+
self.sk.move_to([p[0], p[1], max(p[2], self._home[2])])
|
| 284 |
+
self.sk.move_to(self._home)
|
| 285 |
+
|
| 286 |
+
# ------------------------------------------------------------ geometry helpers
|
| 287 |
+
def box_local(self, xyz):
|
| 288 |
+
b = self._inst["box_xy"]
|
| 289 |
+
return np.array([xyz[0] - b[0], xyz[1] - b[1], xyz[2] - envs.TABLE_Z])
|
| 290 |
+
|
| 291 |
+
def hole_world(self):
|
| 292 |
+
b = self._inst["box_xy"]
|
| 293 |
+
return np.array([b[0] + HOLE_C[0], b[1] + HOLE_C[1]])
|
| 294 |
+
|
| 295 |
+
def inside_box(self, c):
|
| 296 |
+
q = self.box_local(envs.obj_pos(self.env, c))
|
| 297 |
+
return bool(abs(q[0]) < IN_HX and abs(q[1]) < IN_HY and q[2] < LID_Z)
|
| 298 |
+
|
| 299 |
+
def on_lid(self, c):
|
| 300 |
+
q = self.box_local(envs.obj_pos(self.env, c))
|
| 301 |
+
return bool(abs(q[0]) < OUT_HX + 0.01 and abs(q[1]) < OUT_HY + 0.01 and q[2] >= LID_Z)
|
| 302 |
+
|
| 303 |
+
def on_table(self, c):
|
| 304 |
+
p = envs.obj_pos(self.env, c)
|
| 305 |
+
return bool(p[2] < envs.TABLE_Z + CUBE_HALF + 0.01 and not self.inside_box(c))
|
| 306 |
+
|
| 307 |
+
# ------------------------------------------------------------ monitor (every control step)
|
| 308 |
+
def _monitor(self):
|
| 309 |
+
env = self.env
|
| 310 |
+
for c in self.active:
|
| 311 |
+
if c in self.in_box:
|
| 312 |
+
if c not in self.stored and self.box_local(envs.obj_pos(env, c))[0] > HOLE_X[1] + 0.02:
|
| 313 |
+
self._store(c)
|
| 314 |
+
continue
|
| 315 |
+
p = envs.obj_pos(env, c)
|
| 316 |
+
if self.inside_box(c):
|
| 317 |
+
self.in_box.append(c)
|
| 318 |
+
if self.announce_drops:
|
| 319 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="drop", obj=c,
|
| 320 |
+
text="A cube dropped into the box."))
|
| 321 |
+
continue
|
| 322 |
+
if p[2] < envs.TABLE_Z + CUBE_HALF + 0.005: # resting on the table: remember where
|
| 323 |
+
self.rest_xy[c] = p[:2].copy()
|
| 324 |
+
continue
|
| 325 |
+
if (self.inject and self.slip is None and p[2] > envs.TABLE_Z + CUBE_HALF + LIFTED
|
| 326 |
+
and len(self.in_box) == self._inst["p"]
|
| 327 |
+
and np.linalg.norm(p[:2] - self.rest_xy[c]) >= self._inst["trigger_dist"]
|
| 328 |
+
and self.sk.holding(c)):
|
| 329 |
+
self._do_slip(c)
|
| 330 |
+
|
| 331 |
+
def _store(self, c):
|
| 332 |
+
sx, sy, layer = SLOTS[min(len(self.stored), len(SLOTS) - 1)]
|
| 333 |
+
b = self._inst["box_xy"]
|
| 334 |
+
z = RAMP_Z[0] - (sx + IN_HX) * RAMP_SLOPE + CUBE_HALF / np.cos(RAMP_TH) + 0.002 + layer * (2 * CUBE_HALF + 0.003)
|
| 335 |
+
envs.set_obj_pose(self.env, c, [b[0] + sx, b[1] + sy, envs.TABLE_Z + z],
|
| 336 |
+
quat_wxyz=[np.cos(RAMP_TH / 2), 0.0, np.sin(RAMP_TH / 2), 0.0])
|
| 337 |
+
self.stored.append(c)
|
| 338 |
+
|
| 339 |
+
def _do_slip(self, c):
|
| 340 |
+
inst = self._inst
|
| 341 |
+
src = self.rest_xy[c]
|
| 342 |
+
others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
|
| 343 |
+
xy, yaw = src, inst["slip_yaw"]
|
| 344 |
+
found = False
|
| 345 |
+
for r in (inst["slip_r"], inst["slip_r"] / 2, 0.0): # next to the pick-up spot, still graspable
|
| 346 |
+
cand = src + r * np.array([np.cos(inst["slip_ang"]), np.sin(inst["slip_ang"])])
|
| 347 |
+
if not all(np.linalg.norm(cand - o) >= 0.07 for o in others):
|
| 348 |
+
continue
|
| 349 |
+
for dy in (0.0, 0.3, -0.3, 0.6, -0.6):
|
| 350 |
+
y = _wrap_q(inst["slip_yaw"] + dy)
|
| 351 |
+
if axis_clear(cand, y, others) >= HAND_CLEAR and \
|
| 352 |
+
hand_box_clear(cand, y, np.asarray(inst["box_xy"])) >= 0.035:
|
| 353 |
+
xy, yaw, found = cand, y, True
|
| 354 |
+
break
|
| 355 |
+
if found:
|
| 356 |
+
break
|
| 357 |
+
envs.set_obj_pose(self.env, c, [xy[0], xy[1], envs.TABLE_Z + CUBE_HALF + 0.002], yaw=yaw)
|
| 358 |
+
self.sk.grip = -1.0 # the gripper opens
|
| 359 |
+
self.env.sim.forward()
|
| 360 |
+
text = "A cube slipped out of the gripper and fell back onto the table."
|
| 361 |
+
self.slip = dict(obj=c, xy=[float(v) for v in xy], from_xy=[float(v) for v in src], step=int(self.sk.n_steps),
|
| 362 |
+
in_box=len(self.in_box))
|
| 363 |
+
self.events.append(dict(step=int(self.sk.n_steps), kind="slip", obj=c, text=text))
|
| 364 |
+
|
| 365 |
+
def drain_events(self):
|
| 366 |
+
ev = self.events[self._event_cursor:]
|
| 367 |
+
self._event_cursor = len(self.events)
|
| 368 |
+
return [e["text"] for e in ev]
|
| 369 |
+
|
| 370 |
+
# ------------------------------------------------------------ outcome
|
| 371 |
+
def outcome(self, inst):
|
| 372 |
+
envs.settle(self.env, 20)
|
| 373 |
+
n_in = len(self.in_box)
|
| 374 |
+
N = inst["n_target"]
|
| 375 |
+
held = [c for c in self.active if self.sk.holding(c)]
|
| 376 |
+
n_table = sum(self.on_table(c) for c in self.active if c not in self.in_box)
|
| 377 |
+
n_lid = sum(self.on_lid(c) for c in self.active if c not in self.in_box)
|
| 378 |
+
success = bool(n_in == N and not held)
|
| 379 |
+
terminal = bool(n_in > N)
|
| 380 |
+
if success:
|
| 381 |
+
head = f"The box holds exactly {N} cubes."
|
| 382 |
+
elif terminal:
|
| 383 |
+
head = (f"The box holds more than {N} cubes. Cubes cannot be taken out of the box, so the task can no "
|
| 384 |
+
f"longer be completed.")
|
| 385 |
+
elif n_in == N:
|
| 386 |
+
head = f"The gripper is still holding a cube."
|
| 387 |
+
else:
|
| 388 |
+
head = f"The box holds fewer than {N} cubes."
|
| 389 |
+
state = f"Now {n_table} cube{'s are' if n_table != 1 else ' is'} on the table"
|
| 390 |
+
if n_lid:
|
| 391 |
+
state += f" and {n_lid} on the box lid"
|
| 392 |
+
state += "."
|
| 393 |
+
# F2 = verdict + currently observable state + the slip of this segment (never the number inside)
|
| 394 |
+
new = [e for e in self.events[self._outcome_cursor:] if e["kind"] == "slip"]
|
| 395 |
+
self._outcome_cursor = len(self.events)
|
| 396 |
+
detail = head + " " + state
|
| 397 |
+
if new:
|
| 398 |
+
detail = "During this attempt: " + " ".join(e["text"] for e in new) + " " + detail
|
| 399 |
+
return dict(success=success, terminal=terminal, n_in_box=n_in, n_target=N, n_table=n_table, n_lid=n_lid,
|
| 400 |
+
held=len(held), slip=self.slip, detail=detail)
|
| 401 |
+
|
| 402 |
+
# ------------------------------------------------------------ motion (scripted policies)
|
| 403 |
+
def _grasp_yaw(self, c):
|
| 404 |
+
"""The cube's grasp axis with the smaller wrist rotation (|yaw| <= 45 deg). Rotations near +-90 deg drive
|
| 405 |
+
the Panda wrist into its joint-6 limit at some positions (measured), so the other axis is used only if
|
| 406 |
+
the hand would hit a neighbour or the box on this one."""
|
| 407 |
+
R = self.env.sim.data.body_xmat[envs.body_id(self.env, c)].reshape(3, 3)
|
| 408 |
+
yaw = _wrap_q(float(np.arctan2(R[1, 0], R[0, 0])))
|
| 409 |
+
p = envs.obj_pos(self.env, c)[:2]
|
| 410 |
+
others = [envs.obj_pos(self.env, o)[:2] for o in self.active if o != c and o not in self.in_box]
|
| 411 |
+
box = np.asarray(self._inst["box_xy"])
|
| 412 |
+
|
| 413 |
+
def score(a):
|
| 414 |
+
return min(axis_clear(p, a, others), hand_box_clear(p, a, box) + 0.03)
|
| 415 |
+
if score(yaw) >= HAND_CLEAR:
|
| 416 |
+
return yaw
|
| 417 |
+
alt = yaw - np.pi / 2 if yaw >= 0 else yaw + np.pi / 2
|
| 418 |
+
return alt if score(alt) > score(yaw) + 0.02 else yaw
|
| 419 |
+
|
| 420 |
+
def _pick(self, c):
|
| 421 |
+
sk = self.sk
|
| 422 |
+
for _ in range(2):
|
| 423 |
+
p = envs.obj_pos(self.env, c)
|
| 424 |
+
sk.grasp_at(p[:2], Z_GRASP, yaw=self._grasp_yaw(c), lift=0.12)
|
| 425 |
+
if sk.holding(c):
|
| 426 |
+
return True
|
| 427 |
+
sk.set_gripper(False, steps=8)
|
| 428 |
+
sk.move_to([p[0], p[1], Z_GRASP + 0.12])
|
| 429 |
+
return False
|
| 430 |
+
|
| 431 |
+
def _carry(self, c):
|
| 432 |
+
"""Pick cube c and release it above the opening. Returns 'in', 'slipped', 'missed' or 'no_grasp'."""
|
| 433 |
+
n_ev = len(self.events)
|
| 434 |
+
n_in = len(self.in_box)
|
| 435 |
+
if not self._pick(c):
|
| 436 |
+
self._bad.add(c)
|
| 437 |
+
self.go_home() # un-wind the arm before the next try
|
| 438 |
+
return "no_grasp"
|
| 439 |
+
h = self.hole_world()
|
| 440 |
+
sk = self.sk
|
| 441 |
+
sk.move_to([h[0], h[1], Z_CARRY], yaw=0.0) # the slip may fire here; any yaw fits the opening
|
| 442 |
+
if any(e["kind"] == "slip" for e in self.events[n_ev:]):
|
| 443 |
+
return "slipped"
|
| 444 |
+
sk.move_to([h[0], h[1], Z_RELEASE], tol=0.004)
|
| 445 |
+
sk.set_gripper(False, steps=12)
|
| 446 |
+
sk.move_to([h[0], h[1], Z_CARRY])
|
| 447 |
+
sk.hold(10)
|
| 448 |
+
return "in" if len(self.in_box) > n_in else "missed"
|
| 449 |
+
|
| 450 |
+
def _next_cube(self):
|
| 451 |
+
"""nearest table cube to the opening (what any policy sees in the current frame)"""
|
| 452 |
+
h = self.hole_world()
|
| 453 |
+
cands = [c for c in self.active if c not in self.in_box and (self.on_table(c) or self.on_lid(c))]
|
| 454 |
+
cands = [c for c in cands if c not in self._bad] or cands # try another cube after a failed grasp
|
| 455 |
+
if not cands:
|
| 456 |
+
return None
|
| 457 |
+
return min(cands, key=lambda c: np.linalg.norm(envs.obj_pos(self.env, c)[:2] - h))
|
| 458 |
+
|
| 459 |
+
def _add(self, k, log, stop_on_slip=False):
|
| 460 |
+
"""Carry until k cubes went in (by the policy's own observation of each drop). Returns (added, slipped)."""
|
| 461 |
+
added, slipped = 0, False
|
| 462 |
+
guard = 0
|
| 463 |
+
while added < k and guard < 3 * k + 3:
|
| 464 |
+
guard += 1
|
| 465 |
+
c = self._next_cube()
|
| 466 |
+
if c is None:
|
| 467 |
+
break
|
| 468 |
+
r = self._carry(c)
|
| 469 |
+
log.append(r)
|
| 470 |
+
if r == "in":
|
| 471 |
+
added += 1
|
| 472 |
+
elif r == "slipped":
|
| 473 |
+
slipped = True
|
| 474 |
+
if stop_on_slip:
|
| 475 |
+
break
|
| 476 |
+
return added, slipped
|
| 477 |
+
|
| 478 |
+
# ------------------------------------------------------------ scripted references (within protocol)
|
| 479 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 480 |
+
k = k or self.max_attempts
|
| 481 |
+
rng = np.random.default_rng(seed + 7919)
|
| 482 |
+
self.reset_instance(inst)
|
| 483 |
+
N = inst["n_target"]
|
| 484 |
+
history = []
|
| 485 |
+
for a in range(k):
|
| 486 |
+
log = []
|
| 487 |
+
plan = dict(kind=kind, carries=log)
|
| 488 |
+
if a == 0:
|
| 489 |
+
if kind == "oracle":
|
| 490 |
+
while len(self.in_box) < N and len(log) < 3 * N + 3: # privileged count
|
| 491 |
+
c = self._next_cube()
|
| 492 |
+
if c is None:
|
| 493 |
+
break
|
| 494 |
+
log.append(self._carry(c))
|
| 495 |
+
plan["recovery"] = "oracle: privileged box count"
|
| 496 |
+
elif kind in ("adaptive", "skip"):
|
| 497 |
+
added, slipped = self._add(N, log) if kind == "adaptive" else (0, False)
|
| 498 |
+
if kind == "skip": # counts carries, not drops
|
| 499 |
+
n_car = 0
|
| 500 |
+
while n_car < N and len(log) < 3 * N:
|
| 501 |
+
c = self._next_cube()
|
| 502 |
+
if c is None:
|
| 503 |
+
break
|
| 504 |
+
r = self._carry(c)
|
| 505 |
+
log.append(r)
|
| 506 |
+
if r in ("in", "slipped"):
|
| 507 |
+
n_car += 1
|
| 508 |
+
if r == "in":
|
| 509 |
+
added += 1
|
| 510 |
+
plan["recovery"] = "counts carries (the slipped one too)"
|
| 511 |
+
else:
|
| 512 |
+
plan["recovery"] = "own drop count; the slipped carry is not counted"
|
| 513 |
+
else: # memoryless after the slip
|
| 514 |
+
added, slipped = self._add(N, log, stop_on_slip=True)
|
| 515 |
+
if slipped:
|
| 516 |
+
if kind == "naive":
|
| 517 |
+
guess = int(rng.integers(0, N))
|
| 518 |
+
plan["recovery"] = f"memoryless: guesses {guess} already inside, adds {N - guess}"
|
| 519 |
+
self._add(N - guess, log)
|
| 520 |
+
elif kind == "blind":
|
| 521 |
+
plan["recovery"] = f"memoryless restart: puts {N} cubes in"
|
| 522 |
+
self._add(N, log)
|
| 523 |
+
elif kind == "inc1":
|
| 524 |
+
plan["recovery"] = "stateless: adds one cube per segment"
|
| 525 |
+
self._add(1, log)
|
| 526 |
+
else:
|
| 527 |
+
raise ValueError(kind)
|
| 528 |
+
else:
|
| 529 |
+
plan["recovery"] = "none (no slip)"
|
| 530 |
+
else:
|
| 531 |
+
if kind in ("adaptive", "skip"):
|
| 532 |
+
plan["recovery"] = "memory + F2 'fewer than N': add one cube"
|
| 533 |
+
self._add(1, log)
|
| 534 |
+
elif kind == "blind":
|
| 535 |
+
plan["recovery"] = f"memoryless restart: puts {N} cubes in"
|
| 536 |
+
self._add(N, log)
|
| 537 |
+
elif kind == "inc1":
|
| 538 |
+
plan["recovery"] = "stateless: adds one cube"
|
| 539 |
+
self._add(1, log)
|
| 540 |
+
elif kind == "oracle":
|
| 541 |
+
while len(self.in_box) < N and len(log) < 3 * N + 3:
|
| 542 |
+
c = self._next_cube()
|
| 543 |
+
if c is None:
|
| 544 |
+
break
|
| 545 |
+
log.append(self._carry(c))
|
| 546 |
+
else:
|
| 547 |
+
raise ValueError(kind)
|
| 548 |
+
self.go_home()
|
| 549 |
+
out = self.outcome(inst)
|
| 550 |
+
history.append(dict(attempt=a + 1, params=plan, outcome=out))
|
| 551 |
+
if on_attempt:
|
| 552 |
+
on_attempt(a, plan, out)
|
| 553 |
+
if out["success"] or out["terminal"] or kind in ("oracle", "naive"):
|
| 554 |
+
break
|
| 555 |
+
return history
|
| 556 |
+
|
| 557 |
+
# cross-protocol hooks are not used by this task
|
| 558 |
+
def default_params(self, inst):
|
| 559 |
+
return dict(policy="naive")
|
| 560 |
+
|
| 561 |
+
def oracle_params(self, inst):
|
| 562 |
+
return dict(policy="oracle")
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l6_swap.py
ADDED
|
@@ -0,0 +1,466 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/l7_hidden_mechanism.py
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L7 hidden_mechanism: open a small cabinet door whose opening mechanism is hidden.
|
| 2 |
+
|
| 3 |
+
Category: failed_interaction_inference ("why did this contact not do what I expected?").
|
| 4 |
+
|
| 5 |
+
Scene: a small wooden cabinet (14 x 24 x 10 cm) whose door faces away from the robot (towards the front
|
| 6 |
+
camera), with a black knob post in the middle of the door. The robot reaches over the cabinet, grasps the
|
| 7 |
+
knob from above and pulls.
|
| 8 |
+
|
| 9 |
+
Hidden variable: the door's mechanism, one of four (uniform): swings on a hinge at its left edge (HL) or at
|
| 10 |
+
its right edge (HR), or slides to the left (SL) or to the right (SR). The door, the knob and the cabinet look
|
| 11 |
+
exactly the same for all four (hinge pins and slide rails are not modelled visually).
|
| 12 |
+
|
| 13 |
+
Rule (stated in the instruction and enforced): one pull per attempt -- grasp the knob, ONE straight move_to
|
| 14 |
+
while holding it, release. A "pull" is any move_to that starts with the knob held, moves the door, or pushes
|
| 15 |
+
against the door / knob sideways. Without this rule an agent could probe the door with small wiggles inside
|
| 16 |
+
one attempt and the task would no longer test what is learnt across attempts.
|
| 17 |
+
|
| 18 |
+
Why the prior fails (measured): the natural pull is straight out from the door (forward, +x), 12 cm.
|
| 19 |
+
hinged: the knob has to follow a circle around the hinge; the door swings open 31-36 deg and the knob is
|
| 20 |
+
pulled out of the fingers. The knob ends ~6 cm forward and ~4.5 cm towards the hinge side.
|
| 21 |
+
sliding: nothing moves; the fingers slide off the knob.
|
| 22 |
+
Success needs >= 60 deg (hinged) or >= 12 cm (sliding).
|
| 23 |
+
|
| 24 |
+
What must be learned: from how the knob / door moved (F2 gives the knob's displacement relative to where it
|
| 25 |
+
started, plus the images) -> which mechanism -> the pull direction that opens it:
|
| 26 |
+
hinged on the left: pull forward-left (~55 deg from forward), ~22 cm -> 70-88 deg (measured)
|
| 27 |
+
hinged on the right: pull forward-right -> 70-88 deg
|
| 28 |
+
sliding: pull sideways ~18 cm (18 cm); after "nothing moved" the side is not observable,
|
| 29 |
+
so a learner needs one more attempt in the worst case (left fails -> right).
|
| 30 |
+
Straight pulls at 30 / 45 deg towards the hinge give 44 / ~62 deg; diagonal pulls on a slider give 2-4 cm.
|
| 31 |
+
"""
|
| 32 |
+
import mujoco
|
| 33 |
+
import numpy as np
|
| 34 |
+
|
| 35 |
+
from .. import envs
|
| 36 |
+
from ..bddl import write_bddl
|
| 37 |
+
from ..objects import _SOLID, _fmt, register_generated
|
| 38 |
+
from ..skills import Skills
|
| 39 |
+
from ..task_base import LFFTask, register_task
|
| 40 |
+
|
| 41 |
+
CAB = "cab_1"
|
| 42 |
+
MODEL = "lff_l7_mech_cabinet"
|
| 43 |
+
# cabinet frame: origin at the centre of the footprint, z = 0 on the table; the open side faces +x
|
| 44 |
+
D, W, H, T = 0.14, 0.24, 0.10, 0.01 # depth (x), width (y), height, wall thickness
|
| 45 |
+
DW, DH, DT = 0.232, 0.09, 0.012 # door width, height, thickness
|
| 46 |
+
GAP = 0.002
|
| 47 |
+
KZ = 0.045 # knob stem height above the table
|
| 48 |
+
STEM_L, STEM_R = 0.032, 0.005
|
| 49 |
+
POST_R, POST_H = 0.009, 0.038
|
| 50 |
+
POST_TOP = KZ - 0.006 + POST_H # 7.7 cm above the table
|
| 51 |
+
Z_GRIP = envs.TABLE_Z + 0.075 # grasp-point height for grasping the knob (verified across cabinet positions)
|
| 52 |
+
MECHS = ("HL", "HR", "SL", "SR")
|
| 53 |
+
HINGE_OK = np.radians(60.0)
|
| 54 |
+
SLIDE_OK = 0.12
|
| 55 |
+
SLIDE_RANGE = 0.22
|
| 56 |
+
PULL_SPEED = 0.10
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def cabinet_xml(name, rgba=(0.45, 0.32, 0.22, 1.0), door_rgba=(0.80, 0.70, 0.55, 1.0), knob_rgba=(0.12, 0.12, 0.13, 1.0)):
|
| 60 |
+
hx, hy = D / 2, W / 2
|
| 61 |
+
shell = [((-hx + T / 2, 0, H / 2), (T / 2, hy, H / 2)), ((0, hy - T / 2, H / 2), (hx, T / 2, H / 2)),
|
| 62 |
+
((0, -hy + T / 2, H / 2), (hx, T / 2, H / 2)), ((0, 0, H - T / 2), (hx, hy, T / 2)),
|
| 63 |
+
((0, 0, T / 2), (hx, hy, T / 2))]
|
| 64 |
+
g = []
|
| 65 |
+
for k, (p, s) in enumerate(shell):
|
| 66 |
+
g.append(f'<geom name="{name}_s{k}" type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" '
|
| 67 |
+
f'friction="0.6 0.005 0.0001" {_SOLID} group="0"/>')
|
| 68 |
+
g.append(f'<geom type="box" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
|
| 69 |
+
dx = hx + GAP + DT / 2
|
| 70 |
+
dz = 0.005 + DH / 2
|
| 71 |
+
door = [f'<inertial pos="0 0 0" mass="0.35" diaginertia="0.0004 0.0016 0.0016"/>',
|
| 72 |
+
# placeholder joint: type, axis, anchor and range are set per instance (apply_instance)
|
| 73 |
+
f'<joint name="{name}_door_joint" type="hinge" axis="0 0 1" pos="0 0 0" limited="true" range="-0.01 0.01" '
|
| 74 |
+
f'damping="0.2" frictionloss="0.02"/>',
|
| 75 |
+
f'<geom name="{name}_panel" type="box" size="{_fmt((DT / 2, DW / 2, DH / 2))}" rgba="{_fmt(door_rgba)}" '
|
| 76 |
+
f'friction="0.6 0.005 0.0001" {_SOLID} group="0"/>',
|
| 77 |
+
f'<geom type="box" size="{_fmt((DT / 2, DW / 2, DH / 2))}" rgba="{_fmt(door_rgba)}" contype="0" conaffinity="0" group="1"/>']
|
| 78 |
+
sz = KZ - dz
|
| 79 |
+
stem_p = (DT / 2 + STEM_L / 2, 0, sz)
|
| 80 |
+
post_p = (DT / 2 + STEM_L, 0, sz - 0.006 + POST_H / 2)
|
| 81 |
+
for tag, typ, p, s in (("stem", "box", stem_p, (STEM_L / 2 + 0.002, STEM_R, STEM_R)),
|
| 82 |
+
("post", "cylinder", post_p, (POST_R, POST_H / 2))):
|
| 83 |
+
door.append(f'<geom name="{name}_{tag}" type="{typ}" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(knob_rgba)}" '
|
| 84 |
+
f'friction="1.0 0.005 0.0001" {_SOLID} group="0"/>')
|
| 85 |
+
door.append(f'<geom type="{typ}" pos="{_fmt(p)}" size="{_fmt(s)}" rgba="{_fmt(knob_rgba)}" contype="0" conaffinity="0" group="1"/>')
|
| 86 |
+
body = ("\n ".join(g) + f'\n <body name="door" pos="{_fmt((dx, 0, dz))}">\n '
|
| 87 |
+
+ "\n ".join(door) + "\n </body>")
|
| 88 |
+
return f"""<mujoco model="{name}">
|
| 89 |
+
<worldbody>
|
| 90 |
+
<body>
|
| 91 |
+
<body name="object">
|
| 92 |
+
{body}
|
| 93 |
+
</body>
|
| 94 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 0" name="bottom_site" />
|
| 95 |
+
<site rgba="0 0 0 0" size="0.005" pos="0 0 {H:.4f}" name="top_site" />
|
| 96 |
+
<site rgba="0 0 0 0" size="0.005" pos="{D / 2:.4f} {W / 2:.4f} 0" name="horizontal_radius_site" />
|
| 97 |
+
</body>
|
| 98 |
+
</worldbody>
|
| 99 |
+
</mujoco>"""
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _lr(v):
|
| 103 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def _fb(v):
|
| 107 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class MechSkills(Skills):
|
| 111 |
+
"""Skills that log, for whoever drives them (scripted policy or agent): door pulls, the first grasp of the
|
| 112 |
+
knob, and how the knob moved during the first pull."""
|
| 113 |
+
|
| 114 |
+
def __init__(self, env, task, recorder=None):
|
| 115 |
+
super().__init__(env, recorder=recorder)
|
| 116 |
+
self.task = task
|
| 117 |
+
m = env.sim.model
|
| 118 |
+
self._grip_geoms = [g for g in range(m.ngeom) if (m.geom_id2name(g) or "").startswith(("gripper0_", "robot0_"))]
|
| 119 |
+
self._door_geoms = task.door_geom_ids
|
| 120 |
+
self.knob0 = task.knob_xyz()
|
| 121 |
+
self.pulls = [] # one entry per move_to that counts as a pull
|
| 122 |
+
self.closes = [] # close_gripper events: gripper centre relative to the knob, held afterwards?
|
| 123 |
+
self._touch = False
|
| 124 |
+
self.touch_since_report = False
|
| 125 |
+
|
| 126 |
+
def holding_knob(self):
|
| 127 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.task.knob_geom_names))
|
| 128 |
+
|
| 129 |
+
def _touching_door(self):
|
| 130 |
+
d = self.env.sim.data
|
| 131 |
+
g = set(self._grip_geoms)
|
| 132 |
+
dg = set(self._door_geoms)
|
| 133 |
+
for i in range(d.ncon):
|
| 134 |
+
c = d.contact[i]
|
| 135 |
+
if (c.geom1 in g and c.geom2 in dg) or (c.geom2 in g and c.geom1 in dg):
|
| 136 |
+
return True
|
| 137 |
+
return False
|
| 138 |
+
|
| 139 |
+
def _act(self, dpos, drot, grip):
|
| 140 |
+
super()._act(dpos, drot, grip)
|
| 141 |
+
if self._touching_door():
|
| 142 |
+
self._touch = True # per move_to (pull detection)
|
| 143 |
+
self.touch_since_report = True # per agent command (report field)
|
| 144 |
+
|
| 145 |
+
def move_to(self, target, *args, **kwargs):
|
| 146 |
+
q0 = self.task.door_q()
|
| 147 |
+
hold0 = self.holding_knob()
|
| 148 |
+
p0 = self.eef_pos()
|
| 149 |
+
k0 = self.task.knob_xyz()
|
| 150 |
+
self._touch = False
|
| 151 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 152 |
+
dq = abs(self.task.door_q() - q0)
|
| 153 |
+
moved = dq > (np.radians(1.0) if self.task.hinged else 0.003)
|
| 154 |
+
horiz = float(np.linalg.norm(np.asarray(target, float)[:2] - p0[:2]))
|
| 155 |
+
if hold0 or moved or (self._touch and horiz >= 0.015):
|
| 156 |
+
k1 = self.task.knob_xyz()
|
| 157 |
+
self.pulls.append(dict(step=self.n_steps, held_at_start=bool(hold0), held_at_end=self.holding_knob(),
|
| 158 |
+
knob_start=k0.tolist(), knob_end=k1.tolist(), door_moved=bool(moved),
|
| 159 |
+
gripper_move=(np.asarray(target, float)[:2] - p0[:2]).round(4).tolist()))
|
| 160 |
+
return rep
|
| 161 |
+
|
| 162 |
+
def set_gripper(self, close, steps=15):
|
| 163 |
+
was_open = self.grip < 0
|
| 164 |
+
rep = super().set_gripper(close, steps)
|
| 165 |
+
if close and was_open:
|
| 166 |
+
off = self.eef_pos() - self.task.knob_xyz()
|
| 167 |
+
self.closes.append(dict(step=self.n_steps, offset=off.round(4).tolist(), held=self.holding_knob(),
|
| 168 |
+
width=round(self.gripper_width(), 4)))
|
| 169 |
+
return rep
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@register_task
|
| 173 |
+
class HiddenMechanism(LFFTask):
|
| 174 |
+
name = "l7_hidden_mechanism"
|
| 175 |
+
level = "L7"
|
| 176 |
+
category = "failed_interaction_inference"
|
| 177 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 178 |
+
protocol = "cross"
|
| 179 |
+
instruction = ("Open the door of the small wooden cabinet wide (a door that swings must end at least 60 degrees "
|
| 180 |
+
"open, a door that slides at least 12 cm). The door faces away from you; grasp its black knob from "
|
| 181 |
+
"above. Only one pull is allowed per attempt: grasp the knob, move the gripper with ONE straight "
|
| 182 |
+
"move command while holding it, then release it. Pushing the door or the knob counts as a pull "
|
| 183 |
+
"too.")
|
| 184 |
+
instruction_indirect = ("Open the front panel of the small brown box wide (a panel that swings must end at least 60 "
|
| 185 |
+
"degrees open, a panel that slides at least 12 cm). The panel faces away from you; grasp the "
|
| 186 |
+
"small black handle on it from above. Only one pull is allowed per attempt: grasp the handle, "
|
| 187 |
+
"move the gripper with ONE straight move command while holding it, then release it. "
|
| 188 |
+
"Pushing the panel or the handle counts as a pull too.")
|
| 189 |
+
|
| 190 |
+
# ------------------------------------------------------------ scene
|
| 191 |
+
def make_bddl(self):
|
| 192 |
+
cab = register_generated("LffL7MechCabinet", cabinet_xml(MODEL), free=False)
|
| 193 |
+
return write_bddl(self.name, "open the cabinet door", [],
|
| 194 |
+
fixtures=[(CAB, cab, "cab_region", (-0.14, -0.01, -0.12, 0.01))])
|
| 195 |
+
|
| 196 |
+
def __init__(self, cam_res=None):
|
| 197 |
+
super().__init__(cam_res)
|
| 198 |
+
m = self.env.sim.model
|
| 199 |
+
pre = f"{CAB}_{MODEL}"
|
| 200 |
+
self.jid = m.joint_name2id(pre + "_door_joint")
|
| 201 |
+
self.dof = m.jnt_dofadr[self.jid]
|
| 202 |
+
self.qa = m.jnt_qposadr[self.jid]
|
| 203 |
+
self.cab_bid = m.body_name2id(self.env.fixtures_dict[CAB].root_body)
|
| 204 |
+
self.post_gid = m.geom_name2id(pre + "_post")
|
| 205 |
+
self.knob_geom_names = [pre + "_post", pre + "_stem"]
|
| 206 |
+
self.door_geom_ids = [m.geom_name2id(pre + s) for s in ("_post", "_stem", "_panel")]
|
| 207 |
+
self.hinged = True
|
| 208 |
+
|
| 209 |
+
# agent-facing hooks -------------------------------------------------------
|
| 210 |
+
def on_agent_tool(self, inst, name, args, report):
|
| 211 |
+
"""The cabinet is a fixture, so the harness's `holding_object` / `touched_object` (movable objects only) never
|
| 212 |
+
see the knob or the door; add an explicit `holding_knob` field and count door contacts as touches."""
|
| 213 |
+
if self.sk is None or not isinstance(report, dict):
|
| 214 |
+
return
|
| 215 |
+
touched = self.sk.touch_since_report
|
| 216 |
+
self.sk.touch_since_report = False
|
| 217 |
+
if report.get("ok") and name in ("move_to", "open_gripper", "close_gripper", "push"):
|
| 218 |
+
report["holding_knob"] = self.sk.holding_knob()
|
| 219 |
+
if touched and "touched_object" in report:
|
| 220 |
+
report["touched_object"] = True
|
| 221 |
+
|
| 222 |
+
# ------------------------------------------------------------ state helpers
|
| 223 |
+
def door_q(self):
|
| 224 |
+
return float(self.env.sim.data.qpos[self.qa])
|
| 225 |
+
|
| 226 |
+
def knob_xyz(self):
|
| 227 |
+
return self.env.sim.data.geom_xpos[self.post_gid].copy()
|
| 228 |
+
|
| 229 |
+
def sample_instance(self, seed):
|
| 230 |
+
rng = np.random.default_rng(seed)
|
| 231 |
+
return dict(seed=int(seed), mech=MECHS[int(rng.integers(4))],
|
| 232 |
+
cab_xy=[float(rng.uniform(-0.15, -0.10)), float(rng.uniform(-0.07, 0.07))])
|
| 233 |
+
|
| 234 |
+
def apply_instance(self, inst):
|
| 235 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 236 |
+
cx, cy = inst["cab_xy"]
|
| 237 |
+
m.body_pos[self.cab_bid] = [cx, cy, envs.TABLE_Z]
|
| 238 |
+
m.body_quat[self.cab_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 239 |
+
mech = inst["mech"]
|
| 240 |
+
jid, dof = self.jid, self.dof
|
| 241 |
+
self.hinged = mech in ("HL", "HR")
|
| 242 |
+
if self.hinged:
|
| 243 |
+
s = 1 if mech == "HL" else -1
|
| 244 |
+
m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_HINGE
|
| 245 |
+
m.jnt_axis[jid] = [0, 0, 1]
|
| 246 |
+
m.jnt_pos[jid] = [-DT / 2, s * DW / 2, 0] # back face of the door, at its left / right edge
|
| 247 |
+
m.jnt_range[jid] = [0.0, 1.9] if s > 0 else [-1.9, 0.0]
|
| 248 |
+
m.dof_damping[dof] = 0.05
|
| 249 |
+
m.dof_frictionloss[dof] = 0.03
|
| 250 |
+
else:
|
| 251 |
+
s = 1 if mech == "SL" else -1
|
| 252 |
+
m.jnt_type[jid] = mujoco.mjtJoint.mjJNT_SLIDE
|
| 253 |
+
m.jnt_axis[jid] = [0, s, 0]
|
| 254 |
+
m.jnt_pos[jid] = [0, 0, 0]
|
| 255 |
+
m.jnt_range[jid] = [0.0, SLIDE_RANGE]
|
| 256 |
+
m.dof_damping[dof] = 2.0
|
| 257 |
+
m.dof_frictionloss[dof] = 0.5
|
| 258 |
+
# MuJoCo scales constraint softness (here: the joint limits) with dof_invweight0, computed once at compile
|
| 259 |
+
# time for the placeholder hinge through the door's centre. Changing the joint type without updating it
|
| 260 |
+
# made the slide limit ~200x too soft: a slider pulled the wrong way moved 17 cm past its stop (measured).
|
| 261 |
+
door_mass, door_izz = 0.35, 0.0016
|
| 262 |
+
m.dof_invweight0[dof] = (1.0 / (door_izz + door_mass * (DW / 2) ** 2)) if self.hinged else 1.0 / door_mass
|
| 263 |
+
m.jnt_solref[jid] = [0.004, 1.0] # stiff stops (default 0.02 let a hard pull push a slider 8 mm past its stop)
|
| 264 |
+
d.qpos[self.qa] = 0.0
|
| 265 |
+
d.qvel[dof] = 0.0
|
| 266 |
+
|
| 267 |
+
def reset_instance(self, inst, recorder=None):
|
| 268 |
+
self.env.reset()
|
| 269 |
+
self.apply_instance(inst)
|
| 270 |
+
self.env.sim.forward()
|
| 271 |
+
envs.settle(self.env, 10)
|
| 272 |
+
self.sk = MechSkills(self.env, self, recorder=recorder)
|
| 273 |
+
return self.sk
|
| 274 |
+
|
| 275 |
+
def opening(self):
|
| 276 |
+
"""Hinge: degrees open (>= 0); slide: cm open (>= 0)."""
|
| 277 |
+
q = abs(self.door_q())
|
| 278 |
+
return float(np.degrees(q)) if self.hinged else 100.0 * q
|
| 279 |
+
|
| 280 |
+
# ------------------------------------------------------------ outcome
|
| 281 |
+
def outcome(self, inst):
|
| 282 |
+
envs.settle(self.env, 20)
|
| 283 |
+
sk = self.sk
|
| 284 |
+
q = abs(self.door_q())
|
| 285 |
+
is_open = q >= (HINGE_OK if self.hinged else SLIDE_OK)
|
| 286 |
+
n_pulls = len(sk.pulls)
|
| 287 |
+
success = bool(is_open and n_pulls <= 1)
|
| 288 |
+
kd = self.knob_xyz() - sk.knob0
|
| 289 |
+
out = dict(success=success, door_open=bool(is_open), opening=round(self.opening(), 1), n_pulls=n_pulls,
|
| 290 |
+
knob_disp=kd.round(4).tolist(), pulls=sk.pulls, closes=sk.closes, first_pull_disp=None,
|
| 291 |
+
lost_hold=None)
|
| 292 |
+
parts = []
|
| 293 |
+
grasp_txt = ""
|
| 294 |
+
if sk.closes:
|
| 295 |
+
c = sk.closes[0]
|
| 296 |
+
o = c["offset"]
|
| 297 |
+
below = (envs.TABLE_Z + POST_TOP) - (o[2] + sk.knob0[2]) # knob top minus gripper centre height
|
| 298 |
+
grasp_txt = (f"When the gripper first closed, its centre was {_fb(o[0])} and {_lr(o[1])} of the knob's "
|
| 299 |
+
f"centre and {100 * below:.1f} cm below the top of the knob; it "
|
| 300 |
+
+ ("was holding the knob." if c["held"] else "did not get hold of the knob."))
|
| 301 |
+
if success:
|
| 302 |
+
out["failure"] = None
|
| 303 |
+
parts.append("The door is open wide.")
|
| 304 |
+
elif n_pulls == 0:
|
| 305 |
+
out["failure"] = "no_pull"
|
| 306 |
+
parts.append("The door did not open: the knob was never pulled.")
|
| 307 |
+
else:
|
| 308 |
+
out["failure"] = "several_pulls" if n_pulls > 1 else "not_open"
|
| 309 |
+
if n_pulls > 1:
|
| 310 |
+
parts.append(f"The door or knob was pulled or pushed in {n_pulls} separate moves; only one pull is "
|
| 311 |
+
f"allowed per attempt, so this attempt failed.")
|
| 312 |
+
elif is_open:
|
| 313 |
+
parts.append("The door is open wide.")
|
| 314 |
+
else:
|
| 315 |
+
parts.append("The door did not open wide enough.")
|
| 316 |
+
p = sk.pulls[0]
|
| 317 |
+
# net effect of the first pull once things came to rest: up to the start of the next pull, or now
|
| 318 |
+
k_after = np.array(sk.pulls[1]["knob_start"]) if n_pulls > 1 else self.knob_xyz()
|
| 319 |
+
disp = k_after - np.array(p["knob_start"])
|
| 320 |
+
out["first_pull_disp"] = disp.round(4).tolist()
|
| 321 |
+
out["lost_hold"] = bool(p["held_at_start"] and not p["held_at_end"])
|
| 322 |
+
if np.linalg.norm(disp[:2]) < 0.003:
|
| 323 |
+
txt = "During your (first) pull the knob did not move at all (less than 0.3 cm)"
|
| 324 |
+
else:
|
| 325 |
+
txt = f"During your (first) pull the knob moved {_fb(disp[0])} and {_lr(disp[1])}"
|
| 326 |
+
if p["held_at_start"]:
|
| 327 |
+
txt += ("; the gripper lost hold of the knob during the pull." if out["lost_hold"]
|
| 328 |
+
else "; the gripper still held the knob at the end of the pull.")
|
| 329 |
+
else:
|
| 330 |
+
txt += "; the gripper was not holding the knob when that move started."
|
| 331 |
+
parts.append(txt)
|
| 332 |
+
if grasp_txt and not success:
|
| 333 |
+
parts.append(grasp_txt)
|
| 334 |
+
out["detail"] = " ".join(parts)
|
| 335 |
+
return out
|
| 336 |
+
|
| 337 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 338 |
+
def execute(self, inst, params):
|
| 339 |
+
"""Grasp the knob from above (yaw 0), one straight pull in direction `alpha` (deg from forward, + = left)
|
| 340 |
+
over `dist` metres, release, lift."""
|
| 341 |
+
sk = self.sk
|
| 342 |
+
p = self.knob_xyz() # perfect perception of the current scene
|
| 343 |
+
sk.set_gripper(False, steps=8)
|
| 344 |
+
sk.move_to([p[0], p[1], Z_GRIP + 0.08], yaw=0.0)
|
| 345 |
+
sk.move_to([p[0], p[1], Z_GRIP], tol=0.003)
|
| 346 |
+
sk.set_gripper(True, steps=15)
|
| 347 |
+
a = np.radians(float(params["alpha"]))
|
| 348 |
+
dist = float(params["dist"])
|
| 349 |
+
sk.move_to([p[0] + dist * np.cos(a), p[1] + dist * np.sin(a), Z_GRIP], speed=PULL_SPEED, tol=0.004,
|
| 350 |
+
max_steps=300)
|
| 351 |
+
sk.set_gripper(False, steps=8)
|
| 352 |
+
e = sk.eef_pos()
|
| 353 |
+
sk.move_to([e[0], e[1], Z_GRIP + 0.10])
|
| 354 |
+
|
| 355 |
+
def default_params(self, inst):
|
| 356 |
+
return dict(alpha=0.0, dist=0.12)
|
| 357 |
+
|
| 358 |
+
ORACLE = dict(HL=(55.0, 0.22), HR=(-55.0, 0.22), SL=(90.0, 0.18), SR=(-90.0, 0.18))
|
| 359 |
+
|
| 360 |
+
def oracle_params(self, inst):
|
| 361 |
+
a, dist = self.ORACLE[inst["mech"]]
|
| 362 |
+
return dict(alpha=a, dist=dist)
|
| 363 |
+
|
| 364 |
+
def adapt_params(self, inst, history):
|
| 365 |
+
"""Scripted F2 learner using the knob's displacement during the (first) pull of each earlier attempt:
|
| 366 |
+
moved forward and sideways -> it swings on a hinge on that side -> pull ~55 deg towards that side
|
| 367 |
+
(more if a hinge pull already fell short)
|
| 368 |
+
moved only sideways -> it slides that way -> pull sideways
|
| 369 |
+
did not move -> not a hinge; it must slide: try left, then right."""
|
| 370 |
+
hinge_side, slide_side = 0, 0
|
| 371 |
+
tried_still = set() # pull directions (sign of alpha, only for sideways pulls) after which nothing moved
|
| 372 |
+
hinge_tries = 0
|
| 373 |
+
for h in history:
|
| 374 |
+
o = h["outcome"]
|
| 375 |
+
d = o.get("first_pull_disp")
|
| 376 |
+
a = h["params"]["alpha"]
|
| 377 |
+
if d is None:
|
| 378 |
+
continue
|
| 379 |
+
dx, dy = d[0], d[1]
|
| 380 |
+
if dx >= 0.01 and abs(dy) >= 0.01:
|
| 381 |
+
hinge_side = int(np.sign(dy))
|
| 382 |
+
if abs(a) >= 50:
|
| 383 |
+
hinge_tries += 1
|
| 384 |
+
elif abs(dy) >= 0.01:
|
| 385 |
+
slide_side = int(np.sign(dy))
|
| 386 |
+
elif abs(a) >= 80:
|
| 387 |
+
tried_still.add(int(np.sign(a)))
|
| 388 |
+
if hinge_side:
|
| 389 |
+
a = 55.0 + 5.0 * min(hinge_tries, 2)
|
| 390 |
+
return dict(alpha=hinge_side * a, dist=0.22 + 0.02 * min(hinge_tries, 2))
|
| 391 |
+
if slide_side:
|
| 392 |
+
return dict(alpha=90.0 * slide_side, dist=0.18)
|
| 393 |
+
side = 1 if 1 not in tried_still else -1
|
| 394 |
+
return dict(alpha=90.0 * side, dist=0.18)
|
| 395 |
+
|
| 396 |
+
def blind_params(self, inst, attempt, rng):
|
| 397 |
+
"""Same plan (pull straight out) with small random variation; no history."""
|
| 398 |
+
return dict(alpha=float(rng.normal(0.0, 8.0)), dist=float(np.clip(rng.normal(0.12, 0.02), 0.06, 0.2)))
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/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/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/lffbench/tasks/lh_pantry_relatch.py
ADDED
|
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
| 1 |
+
"""LH pantry_relatch: breakfast prep. Take the bread out of a hinged pantry box and put it on the plate, then put the
|
| 2 |
+
butter into the (now empty) box and close it.
|
| 3 |
+
|
| 4 |
+
New mechanism (not a repeat of lh_lid_box / lh_shelf_droop / lh_false_bottom_lid): the box's closing catch is not a
|
| 5 |
+
static per-instance draw, it is a counter of how many times the box has already been closed in this attempt. A weak
|
| 6 |
+
spring (`OPEN_BIAS`) constantly nudges the lid open; a catch (`qfrc_applied`, same idiom as lh_shelf_droop's bracket)
|
| 7 |
+
counters it near the closed angle. The FIRST close always holds (LATCH0 beats the spring) even with a quick swing-and
|
| 8 |
+
-release. After one full open/close cycle the catch's holding strength is reduced (`DECAY`); a second quick-release
|
| 9 |
+
close is no longer enough and the lid creeps back open by itself during the mandatory settle window, with nothing
|
| 10 |
+
else touching it. The fix is not "close it again the same way" (that decays again); it is a firm press-and-hold
|
| 11 |
+
(`dwell`) at the closed angle before letting go, which engages a separate, non-decaying friction seat
|
| 12 |
+
(`SEAT_LATCH`) regardless of cycle count.
|
| 13 |
+
|
| 14 |
+
Geometry/skills are reused unmodified from lh_lid_box.py (box_lid_xml, LidSkills): only the hinge's spring/latch
|
| 15 |
+
torques and the Python cycle counter are new. Protocol: cross, k = 5.
|
| 16 |
+
"""
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
from .. import envs
|
| 20 |
+
from ..bddl import write_bddl
|
| 21 |
+
from ..objects import box_xml, register_generated
|
| 22 |
+
from ..task_base import LFFTask, register_task
|
| 23 |
+
from .lh_lid_box import (BOX_D, BOX_W, WALL_H, WALL_T, FLOOR_T, LID_T, LID_MASS, IN_X, IN_Y, HINGE_DAMP, box_lid_xml,
|
| 24 |
+
LidSkills)
|
| 25 |
+
|
| 26 |
+
G = 9.81
|
| 27 |
+
BOX = "box_1"
|
| 28 |
+
BOX_MODEL = "lff_pantry_box"
|
| 29 |
+
|
| 30 |
+
BREAD_HALF = (0.032, 0.022, 0.011) # 6.4 x 4.4 x 2.2 cm flat loaf, fits the 3.2 cm interior height
|
| 31 |
+
BUTTER_HALF = (0.013, 0.013, 0.013) # 2.6 cm cube
|
| 32 |
+
BREAD_DENS, BUTTER_DENS = 400.0, 600.0
|
| 33 |
+
|
| 34 |
+
# ---------------------------------------------------------------- latch-fatigue mechanism
|
| 35 |
+
CLOSE_DEG = 4.0 # lid angle (deg) counted as "closed" for the final judge
|
| 36 |
+
BAND_DEG = 100.0 # angle range (deg) over which gravity is cancelled and the open bias/catch act (wide, so
|
| 37 |
+
# an unlatched lid drifts smoothly all the way open instead of sticking at a cutoff edge)
|
| 38 |
+
OPEN_BIAS = 0.05 # N*m: net torque pushing the lid open within the band, once gravity is cancelled
|
| 39 |
+
LATCH0 = 0.14 # N*m: catch strength on the FIRST close (always beats OPEN_BIAS)
|
| 40 |
+
DECAY = 0.30 # catch strength multiplier from the SECOND close on, if not seated
|
| 41 |
+
SEAT_LATCH = 0.18 # N*m: non-decaying strength if the close was seated (dwell-pressed)
|
| 42 |
+
DWELL_MIN = 20 # control steps (closed, knob held, no further motion) needed to seat a close
|
| 43 |
+
EXTRA_DAMP = 0.12 # N*m*s/rad added to the hinge dof so an unlatched drift takes a few seconds, not instant
|
| 44 |
+
GRAVITY_LEVER = BOX_D / 2 # lid's centre of mass offset from the hinge (box_lid_xml convention)
|
| 45 |
+
T_GRAV0 = LID_MASS * G * GRAVITY_LEVER
|
| 46 |
+
|
| 47 |
+
SETTLE_MIN, SETTLE_MAX = 300, 600 # 15-30 s simulated, same convention as lh_shelf_droop
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _fb(v):
|
| 51 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _lr(v):
|
| 55 |
+
return f"{100 * abs(v):.1f} cm to the {'left' if v > 0 else 'right'}"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class RelatchSkills(LidSkills):
|
| 59 |
+
"""LidSkills plus a dwell counter: control steps spent holding the knob still at the closed angle while latched.
|
| 60 |
+
`monitor_step` (run every control step via LidSkills._act, before this class's own _act resets the counter)
|
| 61 |
+
reads it at the instant the gripper opens near the closed angle to decide whether this close is 'seated'."""
|
| 62 |
+
|
| 63 |
+
def __init__(self, env, task, recorder=None):
|
| 64 |
+
super().__init__(env, task, recorder=recorder)
|
| 65 |
+
self.dwell = 0
|
| 66 |
+
|
| 67 |
+
def _act(self, dpos, drot, grip):
|
| 68 |
+
super()._act(dpos, drot, grip) # LidSkills._act calls self.task.monitor_step() before returning here
|
| 69 |
+
if self.latched:
|
| 70 |
+
# the agent (or scripted policy) is actively holding the knob: never let the artificial drift fight
|
| 71 |
+
# that grasp (it caused the knob to wander off mid-regrasp during prototyping).
|
| 72 |
+
self.task.drift_active = False
|
| 73 |
+
if self.task.lid_deg() < CLOSE_DEG:
|
| 74 |
+
self.dwell += 1
|
| 75 |
+
else:
|
| 76 |
+
self.dwell = 0
|
| 77 |
+
else:
|
| 78 |
+
self.dwell = 0
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
@register_task
|
| 82 |
+
class PantryRelatch(LFFTask):
|
| 83 |
+
name = "lh_pantry_relatch"
|
| 84 |
+
level = "L2"
|
| 85 |
+
category = "state_restoration"
|
| 86 |
+
capabilities = ("Perceive", "Reason", "Plan", "Restore")
|
| 87 |
+
protocol = "cross"
|
| 88 |
+
max_attempts = 5
|
| 89 |
+
agent_max_steps = 130
|
| 90 |
+
instruction = ("Open the lid of the wooden pantry box (lift it by the black knob) and take the bread out; put it "
|
| 91 |
+
"on the plate. Then open the box again, put the butter inside it, and close the lid. At the end "
|
| 92 |
+
"the bread must be on the plate, the butter inside the box, the lid closed, the gripper open and "
|
| 93 |
+
"clear, and the scene still.")
|
| 94 |
+
instruction_indirect = ("Lift the lid of the flat wooden case by its black ball knob and take out the little "
|
| 95 |
+
"loaf; set it on the round plate. Then open the case again, put the small pale cube "
|
| 96 |
+
"inside it, and shut the lid. Finish with the loaf on the plate, the cube inside the "
|
| 97 |
+
"case, the lid down, the gripper open, and nothing moving.")
|
| 98 |
+
agent_object_names = ["bread (small loaf)", "butter (small pale cube)", "wooden pantry box", "lid knob", "plate"]
|
| 99 |
+
|
| 100 |
+
# ------------------------------------------------------------ scene
|
| 101 |
+
def make_bddl(self):
|
| 102 |
+
box = register_generated("LffPantryBox", box_lid_xml(BOX_MODEL), free=False)
|
| 103 |
+
bread = register_generated("LffPantryBread", box_xml("lff_pantry_bread", BREAD_HALF, (0.74, 0.52, 0.22, 1.0),
|
| 104 |
+
density=BREAD_DENS, friction=(0.7, 0.005, 0.0001)))
|
| 105 |
+
butter = register_generated("LffPantryButter", box_xml("lff_pantry_butter", BUTTER_HALF, (0.95, 0.92, 0.70, 1.0),
|
| 106 |
+
density=BUTTER_DENS, friction=(0.5, 0.005, 0.0001)))
|
| 107 |
+
objs = [("bread_1", bread, "bread_region", (-0.31, -0.01, -0.29, 0.01)),
|
| 108 |
+
("butter_1", butter, "butter_region", (-0.31, 0.24, -0.29, 0.26)),
|
| 109 |
+
("plate_1", "plate", "plate_region", (0.02, -0.26, 0.04, -0.24))]
|
| 110 |
+
fx = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
|
| 111 |
+
return write_bddl(self.name, "take the bread out, put it on the plate, put the butter in the box, close it",
|
| 112 |
+
objs, fx)
|
| 113 |
+
|
| 114 |
+
def __init__(self, cam_res=None):
|
| 115 |
+
super().__init__(cam_res)
|
| 116 |
+
m = self.env.sim.model
|
| 117 |
+
pre = f"{BOX}_{BOX_MODEL}"
|
| 118 |
+
self.jid = m.joint_name2id(pre + "_hinge")
|
| 119 |
+
self.qa = int(m.jnt_qposadr[self.jid])
|
| 120 |
+
self.dof = int(m.jnt_dofadr[self.jid])
|
| 121 |
+
self.box_bid = m.body_name2id(self.env.fixtures_dict[BOX].root_body)
|
| 122 |
+
self.knob_geom_name = pre + "_knob"
|
| 123 |
+
self.knob_geom_names = [pre + "_knob", pre + "_stem"]
|
| 124 |
+
self.knob_gid = m.geom_name2id(self.knob_geom_name)
|
| 125 |
+
sim = self.env.sim
|
| 126 |
+
if not getattr(sim, "_lhpr_wrapped", False):
|
| 127 |
+
orig = sim.step
|
| 128 |
+
|
| 129 |
+
def step(*a, **k):
|
| 130 |
+
orig(*a, **k)
|
| 131 |
+
t = getattr(sim, "_lhpr_task", None)
|
| 132 |
+
if t is not None:
|
| 133 |
+
t._bracket()
|
| 134 |
+
|
| 135 |
+
sim.step = step
|
| 136 |
+
sim._lhpr_wrapped = True
|
| 137 |
+
sim._lhpr_task = self
|
| 138 |
+
self.inst = None
|
| 139 |
+
self.mon = None
|
| 140 |
+
self.active_latch = LATCH0
|
| 141 |
+
self.closes_done = 0
|
| 142 |
+
self.drift_active = False
|
| 143 |
+
|
| 144 |
+
def sample_instance(self, seed):
|
| 145 |
+
rng = np.random.default_rng(seed)
|
| 146 |
+
bx, by = float(rng.uniform(-0.19, -0.15)), float(rng.uniform(-0.03, 0.03))
|
| 147 |
+
plate_xy = [float(rng.uniform(0.0, 0.06)), float(rng.uniform(-0.27, -0.23))]
|
| 148 |
+
bread_xy = [bx + float(rng.uniform(-0.01, 0.01)), by + float(rng.uniform(-0.01, 0.01))]
|
| 149 |
+
butter_xy = [float(rng.uniform(-0.32, -0.28)), float(rng.uniform(0.22, 0.28))]
|
| 150 |
+
return dict(seed=int(seed), box_xy=[bx, by], plate_xy=plate_xy, bread_xy=bread_xy, butter_xy=butter_xy,
|
| 151 |
+
bread_yaw=float(rng.uniform(-0.2, 0.2)), latch=True)
|
| 152 |
+
|
| 153 |
+
def apply_instance(self, inst):
|
| 154 |
+
self.inst = inst
|
| 155 |
+
m, d = self.env.sim.model, self.env.sim.data
|
| 156 |
+
bx, by = inst["box_xy"]
|
| 157 |
+
m.body_pos[self.box_bid] = [bx, by, envs.TABLE_Z]
|
| 158 |
+
m.body_quat[self.box_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 159 |
+
m.jnt_range[self.jid] = [0.0, np.radians(150.0)]
|
| 160 |
+
d.qpos[self.qa] = 0.0
|
| 161 |
+
d.qvel[self.dof] = 0.0
|
| 162 |
+
d.qfrc_applied[self.dof] = 0.0
|
| 163 |
+
m.dof_damping[self.dof] = HINGE_DAMP + EXTRA_DAMP # absolute, not cumulative across repeated resets
|
| 164 |
+
self._move_keep_orientation("plate_1", inst["plate_xy"])
|
| 165 |
+
envs.set_obj_pose(self.env, "bread_1", [bx, by, envs.TABLE_Z + FLOOR_T + BREAD_HALF[2] + 0.001],
|
| 166 |
+
yaw=inst["bread_yaw"])
|
| 167 |
+
envs.set_obj_pose(self.env, "butter_1", [*inst["butter_xy"], envs.TABLE_Z + BUTTER_HALF[2] + 0.0005])
|
| 168 |
+
self.closes_done = 0
|
| 169 |
+
self.active_latch = LATCH0
|
| 170 |
+
self.drift_active = False
|
| 171 |
+
|
| 172 |
+
def _move_keep_orientation(self, name, xy, clearance=0.002):
|
| 173 |
+
qa, da = envs.free_joint_addr(self.env, name)
|
| 174 |
+
d = self.env.sim.data
|
| 175 |
+
d.qpos[qa:qa + 2] = xy
|
| 176 |
+
d.qvel[da:da + 6] = 0.0
|
| 177 |
+
self.env.sim.forward()
|
| 178 |
+
d.qpos[qa + 2] -= envs.obj_min_z(self.env, name) - (envs.TABLE_Z + clearance)
|
| 179 |
+
self.env.sim.forward()
|
| 180 |
+
|
| 181 |
+
def reset_instance(self, inst, recorder=None):
|
| 182 |
+
self.env.reset()
|
| 183 |
+
self.apply_instance(inst)
|
| 184 |
+
self.env.sim.forward()
|
| 185 |
+
envs.settle(self.env, 10)
|
| 186 |
+
self.mon = dict(events=[], lid_open_max=0.0, armed=False)
|
| 187 |
+
self.sk = RelatchSkills(self.env, self, recorder=recorder)
|
| 188 |
+
return self.sk
|
| 189 |
+
|
| 190 |
+
# ------------------------------------------------------------ latch physics
|
| 191 |
+
def lid_q(self):
|
| 192 |
+
return float(self.env.sim.data.qpos[self.qa])
|
| 193 |
+
|
| 194 |
+
def lid_deg(self):
|
| 195 |
+
return float(np.degrees(self.lid_q()))
|
| 196 |
+
|
| 197 |
+
def knob_xyz(self):
|
| 198 |
+
return self.env.sim.data.geom_xpos[self.knob_gid].copy()
|
| 199 |
+
|
| 200 |
+
def hinge_xz(self):
|
| 201 |
+
return self.inst["box_xy"][0] + BOX_D / 2, envs.TABLE_Z + WALL_H
|
| 202 |
+
|
| 203 |
+
def _bracket(self):
|
| 204 |
+
"""Every MuJoCo substep. Only active between a just-finished, under-latched close and the next time the
|
| 205 |
+
agent actually grasps the knob again (self.drift_active, cleared the instant the knob is latched -- see
|
| 206 |
+
RelatchSkills._act): within BAND_DEG of closed, cancel gravity's closing pull and add a small constant
|
| 207 |
+
opening bias, net positive because the catch is too weak (self.active_latch < OPEN_BIAS whenever
|
| 208 |
+
drift_active is set True in the first place). A held-firmly close needs no artificial force at all: plain
|
| 209 |
+
gravity already keeps box_lid_xml's lid shut on its own, same as lh_lid_box."""
|
| 210 |
+
d = self.env.sim.data
|
| 211 |
+
if not self.inst.get("latch", True) or not self.drift_active:
|
| 212 |
+
d.qfrc_applied[self.dof] = 0.0 # never leave a stale value applied once the drift is no longer armed
|
| 213 |
+
return
|
| 214 |
+
th = float(d.qpos[self.qa])
|
| 215 |
+
# the closed rest angle overshoots the joint limit by a hair (contact softness), so the lower edge of the
|
| 216 |
+
# band must tolerate a small negative theta -- a strict "th >= 0" guard left qfrc_applied permanently 0 at
|
| 217 |
+
# the resting pose and the catch never engaged at all (measured during prototyping).
|
| 218 |
+
if np.radians(-3.0) <= th < np.radians(BAND_DEG):
|
| 219 |
+
grav = T_GRAV0 * max(np.cos(th), 0.0)
|
| 220 |
+
d.qfrc_applied[self.dof] = grav + OPEN_BIAS - self.active_latch
|
| 221 |
+
else:
|
| 222 |
+
d.qfrc_applied[self.dof] = 0.0
|
| 223 |
+
|
| 224 |
+
def _register_close(self, seated):
|
| 225 |
+
"""Called once a close-then-release is detected. Decides the catch strength that will apply to THIS closed
|
| 226 |
+
state from now on (until the lid is reopened and closed again), and whether the artificial drift-open force
|
| 227 |
+
is armed (only when the catch is too weak to hold on its own)."""
|
| 228 |
+
if self.closes_done == 0:
|
| 229 |
+
self.active_latch = LATCH0
|
| 230 |
+
elif seated:
|
| 231 |
+
self.active_latch = SEAT_LATCH
|
| 232 |
+
else:
|
| 233 |
+
self.active_latch = LATCH0 * DECAY
|
| 234 |
+
self.closes_done += 1
|
| 235 |
+
self.drift_active = self.active_latch < OPEN_BIAS
|
| 236 |
+
self.mon["events"].append(dict(ev="closed", n=self.closes_done, seated=bool(seated),
|
| 237 |
+
active_latch=round(self.active_latch, 4), drift_armed=self.drift_active))
|
| 238 |
+
|
| 239 |
+
def monitor_step(self):
|
| 240 |
+
"""Runs every control step (via LidSkills._act, for the scripted policies below and for a real agent's own
|
| 241 |
+
move_to/set_gripper calls alike). One-shot edge detector: 'armed' once the lid has been meaningfully open
|
| 242 |
+
(> 20 deg); the first step afterwards where it is back near closed AND the gripper is open counts as a
|
| 243 |
+
close event, scored seated/unseated from the dwell counter at that exact instant (before RelatchSkills._act
|
| 244 |
+
resets it for this same step -- see the call order note there)."""
|
| 245 |
+
mon = self.mon
|
| 246 |
+
if mon is None:
|
| 247 |
+
return
|
| 248 |
+
q = self.lid_deg()
|
| 249 |
+
mon["lid_open_max"] = max(mon["lid_open_max"], q)
|
| 250 |
+
if q > 20.0:
|
| 251 |
+
mon["armed"] = True
|
| 252 |
+
if mon.get("armed") and q <= CLOSE_DEG and self.sk.grip < 0:
|
| 253 |
+
mon["armed"] = False
|
| 254 |
+
self._register_close(self.sk.dwell >= DWELL_MIN)
|
| 255 |
+
|
| 256 |
+
# ------------------------------------------------------------ predicates
|
| 257 |
+
def held(self, name):
|
| 258 |
+
return bool(self.env._check_grasp(gripper=self.env.robots[0].gripper, object_geoms=self.env.objects_dict[name]))
|
| 259 |
+
|
| 260 |
+
def bread_on_plate(self):
|
| 261 |
+
p = envs.obj_pos(self.env, "bread_1")
|
| 262 |
+
d = np.linalg.norm(p[:2] - np.asarray(self.inst["plate_xy"]))
|
| 263 |
+
return bool(d < 0.05 and p[2] < envs.TABLE_Z + 0.06 and not self.held("bread_1"))
|
| 264 |
+
|
| 265 |
+
def butter_in_box(self):
|
| 266 |
+
p = envs.obj_pos(self.env, "butter_1")
|
| 267 |
+
rel = p[:2] - np.asarray(self.inst["box_xy"])
|
| 268 |
+
return bool(abs(rel[0]) <= IN_X - 0.004 and abs(rel[1]) <= IN_Y - 0.004 and p[2] < envs.TABLE_Z + WALL_H
|
| 269 |
+
and not self.held("butter_1"))
|
| 270 |
+
|
| 271 |
+
def lid_closed(self):
|
| 272 |
+
return self.lid_q() <= np.radians(CLOSE_DEG)
|
| 273 |
+
|
| 274 |
+
def stage_values(self):
|
| 275 |
+
return dict(bread_on_plate=self.bread_on_plate(), butter_in_box=self.butter_in_box(), lid_closed=self.lid_closed())
|
| 276 |
+
|
| 277 |
+
# ------------------------------------------------------------ scripted primitives
|
| 278 |
+
def pick_place(self, name, dest_xy, z_rel, z_carry=0.14, dest_yaw=0.0):
|
| 279 |
+
sk = self.sk
|
| 280 |
+
Z = envs.TABLE_Z
|
| 281 |
+
p = envs.obj_pos(self.env, name)
|
| 282 |
+
zg = p[2] - Z
|
| 283 |
+
sk.set_gripper(False, steps=8)
|
| 284 |
+
sk.move_to([p[0], p[1], Z + max(z_carry, zg + 0.06)], yaw=0.0)
|
| 285 |
+
sk.move_to([p[0], p[1], Z + zg], tol=0.003)
|
| 286 |
+
sk.set_gripper(True, steps=15)
|
| 287 |
+
sk.move_to([p[0], p[1], Z + z_carry], speed=0.3)
|
| 288 |
+
self.monitor_step()
|
| 289 |
+
if not self.held(name):
|
| 290 |
+
sk.set_gripper(False, steps=8)
|
| 291 |
+
return False
|
| 292 |
+
sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry], yaw=dest_yaw)
|
| 293 |
+
sk.move_to([dest_xy[0], dest_xy[1], Z + z_rel], tol=0.003)
|
| 294 |
+
sk.set_gripper(False, steps=12)
|
| 295 |
+
sk.move_to([dest_xy[0], dest_xy[1], Z + z_carry])
|
| 296 |
+
self.monitor_step()
|
| 297 |
+
return True
|
| 298 |
+
|
| 299 |
+
def take_bread(self):
|
| 300 |
+
return self.pick_place("bread_1", self.inst["plate_xy"], BREAD_HALF[2] + 0.004)
|
| 301 |
+
|
| 302 |
+
def put_butter(self):
|
| 303 |
+
# placed closer to the hinge side and off to one side of the box centre, clear of where the far (knob) end
|
| 304 |
+
# of the lid sweeps most when re-opened for a repair (measured during prototyping: a butter cube resting
|
| 305 |
+
# under the box centre was occasionally grazed by that swing).
|
| 306 |
+
bx, by = self.inst["box_xy"]
|
| 307 |
+
target = [bx + 0.6 * IN_X, by + 0.5 * IN_Y]
|
| 308 |
+
return self.pick_place("butter_1", target, FLOOR_T + BUTTER_HALF[2] + 0.006, z_carry=0.12)
|
| 309 |
+
|
| 310 |
+
def _grasp_knob(self):
|
| 311 |
+
sk = self.sk
|
| 312 |
+
k = self.knob_xyz()
|
| 313 |
+
sk.set_gripper(False, steps=8)
|
| 314 |
+
sk.move_to([k[0], k[1], k[2] + 0.08], yaw=0.0)
|
| 315 |
+
sk.move_to([k[0], k[1], k[2]], tol=0.003)
|
| 316 |
+
sk.set_gripper(True, steps=15)
|
| 317 |
+
return k
|
| 318 |
+
|
| 319 |
+
def open_lid(self, back=0.03, up=0.16):
|
| 320 |
+
sk = self.sk
|
| 321 |
+
k = self._grasp_knob()
|
| 322 |
+
hx, hz = self.hinge_xz()
|
| 323 |
+
sk.move_to([k[0], k[1], k[2] + 0.10])
|
| 324 |
+
sk.move_to([hx + back, k[1], hz + up])
|
| 325 |
+
sk.set_gripper(False, steps=10)
|
| 326 |
+
e = sk.eef_pos()
|
| 327 |
+
sk.move_to([e[0] - 0.03, e[1], e[2] + 0.06])
|
| 328 |
+
sk.hold(20)
|
| 329 |
+
self.monitor_step()
|
| 330 |
+
|
| 331 |
+
def close_lid(self, dwell=False):
|
| 332 |
+
"""grasp the knob, carry it down the hinge's arc to the closed angle (the compliant knob-hold mechanism
|
| 333 |
+
clamps the physical joint limit at 0 deg, so a target far past closed just drives it fully shut); if dwell,
|
| 334 |
+
hold there (gripper still closed on the knob) for DWELL_MIN+ steps before releasing (seats the friction
|
| 335 |
+
catch); otherwise release immediately."""
|
| 336 |
+
sk = self.sk
|
| 337 |
+
k = self._grasp_knob()
|
| 338 |
+
hx, hz = self.hinge_xz()
|
| 339 |
+
sk.move_to([k[0], k[1], k[2] + 0.10])
|
| 340 |
+
far_x = hx - (BOX_D + 0.20)
|
| 341 |
+
low_z = envs.TABLE_Z + 0.02
|
| 342 |
+
for _ in range(4):
|
| 343 |
+
if self.lid_deg() <= CLOSE_DEG:
|
| 344 |
+
break
|
| 345 |
+
sk.move_to([far_x, sk.eef_pos()[1], low_z], tol=0.01, max_steps=150)
|
| 346 |
+
if dwell:
|
| 347 |
+
sk.hold(DWELL_MIN + 8)
|
| 348 |
+
sk.set_gripper(False, steps=10)
|
| 349 |
+
e = sk.eef_pos()
|
| 350 |
+
sk.move_to([e[0], e[1], e[2] + 0.06])
|
| 351 |
+
sk.hold(20)
|
| 352 |
+
self.monitor_step()
|
| 353 |
+
|
| 354 |
+
# ------------------------------------------------------------ outcome
|
| 355 |
+
def _static(self):
|
| 356 |
+
d = self.env.sim.data
|
| 357 |
+
for name in ("bread_1", "butter_1"):
|
| 358 |
+
_, da = envs.free_joint_addr(self.env, name)
|
| 359 |
+
if np.linalg.norm(d.qvel[da:da + 3]) > 0.02 or np.linalg.norm(d.qvel[da + 3:da + 6]) > 0.5:
|
| 360 |
+
return False
|
| 361 |
+
return abs(float(d.qvel[self.dof])) < 0.2
|
| 362 |
+
|
| 363 |
+
def outcome(self, inst):
|
| 364 |
+
sk = self.sk
|
| 365 |
+
n = 0
|
| 366 |
+
while n < SETTLE_MAX:
|
| 367 |
+
sk.hold(10)
|
| 368 |
+
n += 10
|
| 369 |
+
if n >= SETTLE_MIN and self._static():
|
| 370 |
+
break
|
| 371 |
+
vals = self.stage_values()
|
| 372 |
+
held = [n for n in ("bread_1", "butter_1") if self.held(n)]
|
| 373 |
+
static = self._static()
|
| 374 |
+
success = bool(all(vals.values()) and static and not held)
|
| 375 |
+
if success:
|
| 376 |
+
failure = None
|
| 377 |
+
detail = "Bread is on the plate, butter is in the box, and the lid is closed."
|
| 378 |
+
else:
|
| 379 |
+
failure = ("bread" if not vals["bread_on_plate"] else "butter" if not vals["butter_in_box"] else
|
| 380 |
+
"lid_open" if not vals["lid_closed"] else "held" if held else "not_static")
|
| 381 |
+
parts = []
|
| 382 |
+
if not vals["bread_on_plate"]:
|
| 383 |
+
p = envs.obj_pos(self.env, "bread_1")
|
| 384 |
+
rel = p[:2] - np.asarray(inst["plate_xy"])
|
| 385 |
+
parts.append("The bread is still held." if self.held("bread_1") else
|
| 386 |
+
f"The bread is not on the plate: {_fb(rel[0])} and {_lr(rel[1])} of the plate's centre.")
|
| 387 |
+
if not vals["butter_in_box"]:
|
| 388 |
+
p = envs.obj_pos(self.env, "butter_1")
|
| 389 |
+
rel = p[:2] - np.asarray(inst["box_xy"])
|
| 390 |
+
parts.append("The butter is still held." if self.held("butter_1") else
|
| 391 |
+
f"The butter is not in the box: {_fb(rel[0])} and {_lr(rel[1])} of the box's centre.")
|
| 392 |
+
if not vals["lid_closed"]:
|
| 393 |
+
parts.append(f"The lid is not closed (open {self.lid_deg():.0f} degrees). It had been closed "
|
| 394 |
+
f"{self.closes_done} time(s) in this attempt; it did not stay shut on its own.")
|
| 395 |
+
if held:
|
| 396 |
+
parts.append(f"Still held: {', '.join(held)}.")
|
| 397 |
+
if not static and all(vals.values()):
|
| 398 |
+
parts.append("Something was still moving.")
|
| 399 |
+
detail = " ".join(parts)
|
| 400 |
+
return dict(success=success, failure=failure, stages=vals, static=bool(static), held=held,
|
| 401 |
+
lid_final_deg=round(self.lid_deg(), 1), lid_open_max=round(self.mon["lid_open_max"], 1),
|
| 402 |
+
closes_done=self.closes_done, active_latch=round(self.active_latch, 4),
|
| 403 |
+
events=list(self.mon["events"]), detail=detail)
|
| 404 |
+
|
| 405 |
+
# ------------------------------------------------------------ execution + scripted policies
|
| 406 |
+
def execute(self, inst, params):
|
| 407 |
+
self.open_lid()
|
| 408 |
+
if not self.take_bread():
|
| 409 |
+
return
|
| 410 |
+
self.close_lid(dwell=params.get("dwell1", False))
|
| 411 |
+
self.open_lid()
|
| 412 |
+
if not self.put_butter():
|
| 413 |
+
return
|
| 414 |
+
self.close_lid(dwell=params.get("dwell2", False))
|
| 415 |
+
if params.get("check", False):
|
| 416 |
+
# look back before finishing: wait long enough (same order as the final settle window) for an
|
| 417 |
+
# under-latched close to reveal itself, then fix it with a firm dwell close if it did -- a genuine
|
| 418 |
+
# same-attempt recovery, not just a cross-attempt change of technique.
|
| 419 |
+
n = 0
|
| 420 |
+
while n < SETTLE_MIN and self.lid_closed():
|
| 421 |
+
self.sk.hold(10)
|
| 422 |
+
n += 10
|
| 423 |
+
if not self.lid_closed():
|
| 424 |
+
self.open_lid()
|
| 425 |
+
self.close_lid(dwell=True)
|
| 426 |
+
self.sk.hold(5)
|
| 427 |
+
|
| 428 |
+
def default_params(self, inst):
|
| 429 |
+
return dict(dwell1=False, dwell2=False, check=False)
|
| 430 |
+
|
| 431 |
+
def oracle_params(self, inst):
|
| 432 |
+
return dict(dwell1=False, dwell2=True, check=False)
|
| 433 |
+
|
| 434 |
+
def adapt_params(self, inst, history):
|
| 435 |
+
"""From attempt 2 on (if attempt 1's own same-attempt check-and-repair somehow still fell short): close
|
| 436 |
+
every time with a firm dwell from the start, and keep checking before finishing."""
|
| 437 |
+
return dict(dwell1=True, dwell2=True, check=True)
|
| 438 |
+
|
| 439 |
+
def blind_params(self, inst, attempt, rng):
|
| 440 |
+
return dict(dwell1=False, dwell2=bool(rng.random() < 0.5), check=False)
|
| 441 |
+
|
| 442 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 443 |
+
k = k or self.max_attempts
|
| 444 |
+
rng = np.random.default_rng(seed)
|
| 445 |
+
history = []
|
| 446 |
+
for a in range(k):
|
| 447 |
+
self.reset_instance(inst)
|
| 448 |
+
if kind == "oracle":
|
| 449 |
+
params = self.oracle_params(inst)
|
| 450 |
+
elif kind == "naive":
|
| 451 |
+
params = self.default_params(inst)
|
| 452 |
+
elif kind == "adaptive":
|
| 453 |
+
# attempt 1: naive technique plus a final look-back-and-repair (genuine same-attempt recovery);
|
| 454 |
+
# only if that still were not enough would later attempts switch technique from the start.
|
| 455 |
+
params = (dict(self.default_params(inst), check=True) if a == 0
|
| 456 |
+
else self.adapt_params(inst, history))
|
| 457 |
+
elif kind == "blind":
|
| 458 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 459 |
+
else:
|
| 460 |
+
raise ValueError(kind)
|
| 461 |
+
self.execute(inst, params)
|
| 462 |
+
out = self.outcome(inst)
|
| 463 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 464 |
+
if on_attempt:
|
| 465 |
+
on_attempt(a, params, out)
|
| 466 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 467 |
+
break
|
| 468 |
+
return history
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_viewer/README.md
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Agent Viewer — historical replay
|
| 2 |
+
|
| 3 |
+
Export saved LFF-Bench API-player logs to one offline HTML page, including original
|
| 4 |
+
image bytes and the complete `rollout.mp4` when available. No model calls, simulator, server, build tools, or frontend dependencies
|
| 5 |
+
are required to generate or open the result.
|
| 6 |
+
|
| 7 |
+
From the repository root:
|
| 8 |
+
|
| 9 |
+
```bash
|
| 10 |
+
python scripts/agent_viewer/export.py \
|
| 11 |
+
--run runs/gpt/exp2d/exp2d-gpt-6-astra_l5_slide_to_target_s1000_full_F2_direct_k3_1007-060153_p9738 \
|
| 12 |
+
--out traces/agent-viewer-slide/index.html
|
| 13 |
+
```
|
| 14 |
+
|
| 15 |
+
Open the resulting HTML file in a browser. Repeat `--run` to include multiple
|
| 16 |
+
runs. If a run's original sandbox has moved, use `--sandbox /new/image/root`
|
| 17 |
+
with a single run. Relative images copied into the run directory take precedence.
|
| 18 |
+
The export remains usable after the original sandbox is removed.
|
| 19 |
+
|
| 20 |
+
## What the viewer shows
|
| 21 |
+
|
| 22 |
+
- Continuous execution video is the default view when `rollout.mp4` exists, with
|
| 23 |
+
native playback, seeking, fullscreen and playback speed controls. The original
|
| 24 |
+
MP4 is embedded byte-for-byte; no still-image slideshow is substituted.
|
| 25 |
+
- The separate step view retains input images and tool logs. Selecting an attempt
|
| 26 |
+
opens its step details. Video and logs are not automatically synchronized because
|
| 27 |
+
old recordings have no frame-to-event index and omit model waiting time.
|
| 28 |
+
|
| 29 |
+
- One step per recorded assistant response; tool calls and results stay together.
|
| 30 |
+
- The most recent observation **before** each decision, and separately the new
|
| 31 |
+
images returned **after** its actions. Older images may also be in model context;
|
| 32 |
+
the viewer shows the request's recorded image count when available.
|
| 33 |
+
- Camera switching, per-step playback, scrubbing, keyboard navigation (arrows and
|
| 34 |
+
space), and jumps to attempt verdicts. Playback uses fixed seconds per step,
|
| 35 |
+
with original elapsed/model latency shown separately.
|
| 36 |
+
- Tool arguments, raw tool results, public assistant replies, API retries, missing
|
| 37 |
+
images, and incomplete calls. Recorded reasoning summaries are exported verbatim between observation and action in the step details.
|
| 38 |
+
The summary of decision N is shown between the preceding feedback and action N.
|
| 39 |
+
Public replies are labeled separately; missing summaries stay explicitly missing.
|
| 40 |
+
These are recorded summaries, not full internal CoT or reconstructed reasoning.
|
| 41 |
+
- A reset warning when a failed `done` returns the next attempt's initial images.
|
| 42 |
+
Attempt success comes from server `done` events, not the assistant's claim.
|
| 43 |
+
|
| 44 |
+
## Current input contract and limitations
|
| 45 |
+
|
| 46 |
+
Supports the API-player `ev` schema in `transcript.jsonl` or
|
| 47 |
+
`gpt_transcript.jsonl`, with `session.json` and optional `events.jsonl`. Other
|
| 48 |
+
harness formats (MCP, native Codex/Claude, RPent, GPT-Policy) need adapters and
|
| 49 |
+
are not claimed as supported. Corrupt JSON and ambiguous result matching fail
|
| 50 |
+
explicitly instead of silently pairing the wrong steps.
|
| 51 |
+
|
| 52 |
+
Image files are copied byte-for-byte at export time. Old logs contain paths rather
|
| 53 |
+
than image hashes, so files overwritten since the run cannot be authenticated as
|
| 54 |
+
the original model inputs. Missing images are visibly marked; no replacement
|
| 55 |
+
frames are invented. Runs without a video fall back to step replay with the video tab disabled.
|
| 56 |
+
|
| 57 |
+
The sample video is 19.05 seconds, H.264, 640×376 at 20 fps. Its action segments
|
| 58 |
+
were recorded at 3× simulation speed; choose ⅓× playback to slow them back down.
|
| 59 |
+
The recording includes both attempts and their verdict cards, but not model/API
|
| 60 |
+
waiting time.
|
| 61 |
+
|
| 62 |
+
The sample `l5_slide_to_target`, seed 1000, has 14 assistant responses, 13 tool
|
| 63 |
+
calls, and two verdicts: failure then success. It is a historical development
|
| 64 |
+
run using depth perception and F2 feedback, not evidence of general benchmark
|
| 65 |
+
performance. The first push overshot by 4 cm; the next push reduced its endpoint
|
| 66 |
+
from x=-0.105 m to x=-0.145 m and succeeded.
|
| 67 |
+
|
| 68 |
+
## Verification
|
| 69 |
+
|
| 70 |
+
```bash
|
| 71 |
+
python -m unittest discover -s tests -p test_agent_viewer.py -v
|
| 72 |
+
```
|
| 73 |
+
|
| 74 |
+
Regression cases cover observation/action ordering, resets, carried-forward
|
| 75 |
+
observations, API retries, missing artifacts, incomplete calls, reordered call
|
| 76 |
+
IDs, malformed logs, path restrictions, and safe embedding of untrusted text.
|
| 77 |
+
|
| 78 |
+
## Recording future runs
|
| 79 |
+
|
| 80 |
+
`api_player.py` already requests provider summaries (`auto` for OpenAI) and
|
| 81 |
+
saves returned `reasoning_summary` plus public `text` for each assistant turn.
|
| 82 |
+
`run_agent.py` now also defaults `--reasoning-summary` to `auto`; pass `none`
|
| 83 |
+
when an endpoint cannot support the option. Both loggers add
|
| 84 |
+
`reasoning_summary_status`: `recorded` when a summary is present and
|
| 85 |
+
`not_returned` when the response contains none. This labels response availability,
|
| 86 |
+
not whether summaries were requested or whether the model reasoned internally.
|
| 87 |
+
|
| 88 |
+
Historical missing records are left unchanged. No extra model calls or
|
| 89 |
+
retrospective rationale generation are used. Changes apply to newly started
|
| 90 |
+
processes from this checkout; other worktrees and native CLI harnesses retain
|
| 91 |
+
their own logging behavior. The viewer still imports API-player transcripts;
|
| 92 |
+
`run_agent` logs use a different schema and need an adapter to view here.
|
| 93 |
+
|
| 94 |
+
## Live terminal viewer
|
| 95 |
+
|
| 96 |
+
`live.py` observes existing runs without contacting the robot/model or changing the
|
| 97 |
+
run. Use a terminal with truecolor support for low-resolution color image previews;
|
| 98 |
+
`--ascii` provides a monochrome fallback. Pillow is the only image dependency and
|
| 99 |
+
is already present in the evaluation environment.
|
| 100 |
+
|
| 101 |
+
```bash
|
| 102 |
+
python scripts/agent_viewer/live.py --batch /absolute/path/to/runs/api/BATCH
|
| 103 |
+
python scripts/agent_viewer/live.py --run /absolute/path/to/RUN --once --ascii
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
A batch view follows the first running run and switches when the manifest advances;
|
| 107 |
+
for concurrent runs in one batch, use `--run` to select another. Refresh defaults to
|
| 108 |
+
6 seconds. `Ctrl+C` exits; `--no-images`, `--width`, `--image-rows`, `--interval`, and
|
| 109 |
+
`--duration` control presentation. A redirected output uses ASCII and no screen
|
| 110 |
+
control codes. `--once` prints one snapshot.
|
| 111 |
+
|
| 112 |
+
Supported live sources: API-player transcripts; framework gateway/MCP tool logs;
|
| 113 |
+
and Codex `item.completed` events. Only successful `view_images` attachments or
|
| 114 |
+
API-player image inputs become displayed observations. Robot-produced files alone
|
| 115 |
+
do not establish that the Agent saw them. Matching embedded images from native
|
| 116 |
+
Codex events take precedence over file references; potentially overwritten files
|
| 117 |
+
are marked unavailable. The current view displays the latest observation batch,
|
| 118 |
+
not continuous video, and explicitly labels its age. Recorded summaries are shown
|
| 119 |
+
when the relevant stream provides them. It does not expose `session.json` tokens,
|
| 120 |
+
server-side hidden task parameters, or send any robot commands.
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
python -m unittest discover -s tests -p test_live_viewer.py -v
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
### Clearer terminal images
|
| 127 |
+
|
| 128 |
+
The old character preview was limited to 20 rows (at most ~40 vertical pixels).
|
| 129 |
+
It now uses available terminal height and width. `--camera main` or `--camera wrist`
|
| 130 |
+
selects a larger single view. Character mode is still a low-resolution preview.
|
| 131 |
+
|
| 132 |
+
For actual image pixels, use `--renderer iterm` (iTerm2 / WezTerm / VS Code with
|
| 133 |
+
`terminal.integrated.enableImages: true`) or `--renderer kitty`. Native mode
|
| 134 |
+
encodes original-resolution pixels as PNG; the terminal fits the display without
|
| 135 |
+
reducing the transmitted image to text-cell resolution. `auto` recognizes iTerm2,
|
| 136 |
+
WezTerm and Kitty environment markers; unknown terminals and multiplexers retain
|
| 137 |
+
the ANSI fallback. VS Code needs an explicit `--renderer iterm` after its setting
|
| 138 |
+
is enabled. Native protocol encoding is tested; visual compatibility still needs
|
| 139 |
+
to be checked in the user's terminal. Use a direct terminal outside tmux/screen
|
| 140 |
+
if image passthrough has not been configured. Redirected output always stays text.
|
| 141 |
+
|
| 142 |
+
Existing CLI processes keep their original interval and renderer: exit with Ctrl+C
|
| 143 |
+
and restart to pick up changes. Evaluation processes need no restart.
|
| 144 |
+
|
| 145 |
+
The user's Claude development terminal (`TERM_PROGRAM=claude-desktop`) displayed
|
| 146 |
+
an empty image area with the iTerm transport. In that environment, even an explicit
|
| 147 |
+
`--renderer iterm` now falls back to ANSI with a visible explanation. This avoids
|
| 148 |
+
blank frames but does not provide native image detail. Use `--camera main` for a
|
| 149 |
+
larger single-camera preview; original-resolution viewing needs an image-capable
|
| 150 |
+
viewer. No Claude terminal setting enabling inline images has been verified.
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_viewer/export.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export saved API-player runs as a portable, offline Agent Viewer.
|
| 2 |
+
|
| 3 |
+
No simulator/model calls are made. Original image bytes are embedded once.
|
| 4 |
+
Supports transcript.jsonl and gpt_transcript.jsonl (API-player event schema).
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import base64
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def read_jsonl(path):
|
| 17 |
+
rows = []
|
| 18 |
+
for number, line in enumerate(path.read_text().splitlines(), 1):
|
| 19 |
+
if line.strip():
|
| 20 |
+
try:
|
| 21 |
+
rows.append(json.loads(line))
|
| 22 |
+
except json.JSONDecodeError as exc:
|
| 23 |
+
raise ValueError(f"{path.name}:{number}: malformed JSON; export a completed log") from exc
|
| 24 |
+
return rows
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_output(value):
|
| 28 |
+
if isinstance(value, dict):
|
| 29 |
+
return value
|
| 30 |
+
try:
|
| 31 |
+
parsed = json.loads(value)
|
| 32 |
+
return parsed if isinstance(parsed, dict) else {}
|
| 33 |
+
except (ValueError, TypeError):
|
| 34 |
+
return {}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_run(folder, assets, sandbox_override=None):
|
| 38 |
+
folder = Path(folder)
|
| 39 |
+
transcript = next((folder / name for name in ('transcript.jsonl', 'gpt_transcript.jsonl')
|
| 40 |
+
if (folder / name).exists()), None)
|
| 41 |
+
if not transcript:
|
| 42 |
+
raise ValueError(f"No supported API-player transcript in {folder}")
|
| 43 |
+
rows = read_jsonl(transcript)
|
| 44 |
+
if not any(row.get('ev') == 'assistant' for row in rows):
|
| 45 |
+
raise ValueError(f"No API-player assistant events in {transcript}")
|
| 46 |
+
session = json.loads((folder / 'session.json').read_text())
|
| 47 |
+
events = read_jsonl(folder / 'events.jsonl') if (folder / 'events.jsonl').exists() else []
|
| 48 |
+
start = next((r for r in rows if r.get('ev') == 'start'), {})
|
| 49 |
+
server = next((r for r in events if r.get('ev') == 'session_start'), {})
|
| 50 |
+
sandbox = Path(sandbox_override or session.get('sandbox', folder))
|
| 51 |
+
warnings, cache = [], {}
|
| 52 |
+
|
| 53 |
+
def images(refs, source, timestamp):
|
| 54 |
+
result = []
|
| 55 |
+
for ref in refs:
|
| 56 |
+
if not isinstance(ref, str):
|
| 57 |
+
raise ValueError('Expected image path strings in API-player transcript')
|
| 58 |
+
if ref not in cache:
|
| 59 |
+
relative = Path(ref)
|
| 60 |
+
roots = [folder, sandbox]
|
| 61 |
+
candidates = []
|
| 62 |
+
# Only export images within the explicitly selected run/sandbox.
|
| 63 |
+
for root in roots:
|
| 64 |
+
candidate = (root / relative).resolve()
|
| 65 |
+
if candidate.is_relative_to(root.resolve()):
|
| 66 |
+
candidates.append(candidate)
|
| 67 |
+
path = next((p for p in candidates if p.is_file()), None)
|
| 68 |
+
key = None
|
| 69 |
+
if path:
|
| 70 |
+
raw = path.read_bytes()
|
| 71 |
+
if raw.startswith(b'\xff\xd8\xff'):
|
| 72 |
+
mime = 'image/jpeg'
|
| 73 |
+
elif raw.startswith(b'\x89PNG\r\n\x1a\n'):
|
| 74 |
+
mime = 'image/png'
|
| 75 |
+
elif raw[:6] in (b'GIF87a', b'GIF89a'):
|
| 76 |
+
mime = 'image/gif'
|
| 77 |
+
elif raw[:4] == b'RIFF' and raw[8:12] == b'WEBP':
|
| 78 |
+
mime = 'image/webp'
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f'Unsupported image bytes: {ref}')
|
| 81 |
+
key = hashlib.sha256(raw).hexdigest()[:24]
|
| 82 |
+
assets[key] = f'data:{mime};base64,' + base64.b64encode(raw).decode()
|
| 83 |
+
else:
|
| 84 |
+
warnings.append(f'图片缺失:{ref}')
|
| 85 |
+
name = relative.stem
|
| 86 |
+
camera = 'agentview' if 'agentview' in name else 'wrist' if 'wrist' in name else name
|
| 87 |
+
cache[ref] = {'asset': key, 'path': ref, 'camera': camera}
|
| 88 |
+
result.append({**cache[ref], 'source': source, 'at': timestamp})
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
outcomes = [{'attempt': e.get('attempt'), 'success': e.get('success'),
|
| 92 |
+
'feedback': e.get('feedback', ''), 'at': e.get('t')}
|
| 93 |
+
for e in events if e.get('ev') == 'done']
|
| 94 |
+
steps, pending, latest, latest_text = [], [], [], ''
|
| 95 |
+
attempt, origin, active, task_text = 1, rows[0].get('t', 0), None, ''
|
| 96 |
+
for line, row in enumerate(rows, 1):
|
| 97 |
+
kind = row.get('ev')
|
| 98 |
+
if kind == 'user':
|
| 99 |
+
latest_text = row.get('text', '')
|
| 100 |
+
if not task_text:
|
| 101 |
+
match = re.search(r'\{.*\}', latest_text, re.S)
|
| 102 |
+
task_text = parse_output(match.group() if match else '').get('task', latest_text)
|
| 103 |
+
if row.get('images'):
|
| 104 |
+
latest = images(row['images'], line, row.get('t'))
|
| 105 |
+
elif kind in ('api_error', 'abort'):
|
| 106 |
+
pending.append({'kind': kind, 'text': row.get('error', ''), 'at': row.get('t')})
|
| 107 |
+
elif kind == 'assistant':
|
| 108 |
+
calls = row.get('tool_calls', [])
|
| 109 |
+
active = {
|
| 110 |
+
'index': len(steps), 'turn': row.get('turn'), 'attempt': attempt,
|
| 111 |
+
'at': row.get('t'), 'elapsed': max(0, row.get('t', origin) - origin),
|
| 112 |
+
'latency': row.get('latency_s'), 'before': list(latest),
|
| 113 |
+
'inputText': latest_text, 'text': row.get('text') or '',
|
| 114 |
+
'decisionSummary': row.get('reasoning_summary') or None,
|
| 115 |
+
'decisionSummaryStatus': row.get('reasoning_summary_status', 'not_recorded'),
|
| 116 |
+
'decisionSourceLine': line,
|
| 117 |
+
'actions': [{'id': c.get('id'), 'name': c.get('name', 'tool'),
|
| 118 |
+
'arguments': c.get('arguments', {}), 'result': None,
|
| 119 |
+
'after': []} for c in calls],
|
| 120 |
+
'notices': pending, 'verdict': None,
|
| 121 |
+
'requestImages': row.get('request_stats', {}).get('n_images'),
|
| 122 |
+
}
|
| 123 |
+
pending = []
|
| 124 |
+
steps.append(active)
|
| 125 |
+
elif kind == 'tool':
|
| 126 |
+
if active is None:
|
| 127 |
+
warnings.append(f'第 {line} 行工具结果缺少前置调用')
|
| 128 |
+
continue
|
| 129 |
+
if row.get('turn') is not None and row.get('turn') != active['turn']:
|
| 130 |
+
raise ValueError(f'Tool turn mismatch at transcript line {line}')
|
| 131 |
+
unresolved = [a for a in active['actions'] if a['result'] is None]
|
| 132 |
+
call_id = row.get('call_id') or row.get('tool_call_id')
|
| 133 |
+
action = next((a for a in unresolved if call_id and a['id'] == call_id), None)
|
| 134 |
+
if call_id and action is None:
|
| 135 |
+
raise ValueError(f'Unknown tool call id at transcript line {line}')
|
| 136 |
+
if action is None:
|
| 137 |
+
action = next((a for a in unresolved if isinstance(a['arguments'], dict)
|
| 138 |
+
and a['arguments'].get('command') == row.get('command')), None)
|
| 139 |
+
if action is None and len(unresolved) == 1:
|
| 140 |
+
action = unresolved[0]
|
| 141 |
+
if action is None:
|
| 142 |
+
raise ValueError(f'Ambiguous tool result at transcript line {line}')
|
| 143 |
+
output = row.get('output', '')
|
| 144 |
+
action['result'] = output
|
| 145 |
+
action['at'] = row.get('t')
|
| 146 |
+
action['after'] = images(row.get('images', []), line, row.get('t'))
|
| 147 |
+
parsed = parse_output(output)
|
| 148 |
+
action['ok'] = parsed.get('ok')
|
| 149 |
+
latest_text = output if isinstance(output, str) else json.dumps(output, ensure_ascii=False)
|
| 150 |
+
if action['after']:
|
| 151 |
+
latest = list(action['after'])
|
| 152 |
+
command = row.get('command') or (action['arguments'].get('command', '')
|
| 153 |
+
if isinstance(action['arguments'], dict) else '')
|
| 154 |
+
if command.split(' ', 1)[0] == 'done':
|
| 155 |
+
verdict = next((o for o in outcomes if o['attempt'] == attempt), None)
|
| 156 |
+
if verdict:
|
| 157 |
+
active['verdict'] = verdict
|
| 158 |
+
# A failed done may immediately return RESET images for the next attempt.
|
| 159 |
+
message = parsed.get('message', '')
|
| 160 |
+
next_attempt = re.search(r'Attempt\s+(\d+)\s+of', message)
|
| 161 |
+
if next_attempt:
|
| 162 |
+
attempt = int(next_attempt.group(1))
|
| 163 |
+
action['resetToAttempt'] = attempt
|
| 164 |
+
if pending:
|
| 165 |
+
steps[-1]['noticesAfter'] = pending
|
| 166 |
+
for step in steps:
|
| 167 |
+
step['incomplete'] = any(a['result'] is None for a in step['actions'])
|
| 168 |
+
status = 'success' if any(o['success'] is True for o in outcomes) else (
|
| 169 |
+
'failed' if outcomes and any(r.get('ev') == 'end' and r.get('finished') is True for r in rows) else 'incomplete')
|
| 170 |
+
video = None
|
| 171 |
+
video_path = folder / 'rollout.mp4'
|
| 172 |
+
if video_path.is_file():
|
| 173 |
+
raw = video_path.read_bytes()
|
| 174 |
+
if len(raw) < 12 or raw[4:8] != b'ftyp':
|
| 175 |
+
raise ValueError('rollout.mp4 is not an MP4 container')
|
| 176 |
+
key = 'video-' + hashlib.sha256(raw).hexdigest()[:24]
|
| 177 |
+
assets[key] = 'data:video/mp4;base64,' + base64.b64encode(raw).decode()
|
| 178 |
+
video = {'asset': key, 'name': 'rollout.mp4'}
|
| 179 |
+
return {'id': folder.name, 'video': video, 'task': server.get('task', folder.name),
|
| 180 |
+
'taskText': task_text, 'seed': server.get('seed'), 'model': start.get('model', '未记录'),
|
| 181 |
+
'perception': server.get('perception', '未记录'), 'feedback': server.get('feedback', '未记录'),
|
| 182 |
+
'status': status, 'steps': steps, 'outcomes': outcomes,
|
| 183 |
+
'warnings': sorted(set(warnings)), 'source': transcript.name,
|
| 184 |
+
'actionCount': sum(len(s['actions']) for s in steps)}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def render(folders, output, sandbox_override=None):
|
| 188 |
+
assets = {}
|
| 189 |
+
runs = [build_run(folder, assets, sandbox_override) for folder in folders]
|
| 190 |
+
payload = json.dumps({'version': 1, 'runs': runs, 'assets': assets}, ensure_ascii=False)
|
| 191 |
+
# Logs are untrusted text, including strings containing HTML/script terminators.
|
| 192 |
+
payload = payload.replace('&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e')
|
| 193 |
+
template = Path(__file__).with_name('viewer.html').read_text()
|
| 194 |
+
output = Path(output)
|
| 195 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
output.write_text(template.replace('/*__PAYLOAD__*/null', payload))
|
| 197 |
+
return runs
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def main():
|
| 201 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 202 |
+
parser.add_argument('--run', type=Path, action='append', required=True, help='Repeat to include multiple runs')
|
| 203 |
+
parser.add_argument('--out', type=Path, required=True)
|
| 204 |
+
parser.add_argument('--sandbox', type=Path, help='Relocated image directory for a single run')
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
if args.sandbox and len(args.run) != 1:
|
| 207 |
+
parser.error('--sandbox requires exactly one --run')
|
| 208 |
+
try:
|
| 209 |
+
runs = render(args.run, args.out, args.sandbox)
|
| 210 |
+
except (ValueError, OSError, KeyError) as exc:
|
| 211 |
+
parser.exit(1, f'Export failed: {exc}\n')
|
| 212 |
+
print(json.dumps({'output': str(args.out.resolve()), 'runs': [
|
| 213 |
+
{'task': r['task'], 'steps': len(r['steps']), 'actions': r['actionCount'],
|
| 214 |
+
'outcomes': [o['success'] for o in r['outcomes']], 'warnings': r['warnings']} for r in runs
|
| 215 |
+
]}, ensure_ascii=False, indent=2))
|
| 216 |
+
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Read-only terminal viewer for active LFF-Bench runs (ANSI images or ASCII)."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import argparse
|
| 5 |
+
import base64
|
| 6 |
+
import io
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import shutil
|
| 11 |
+
import sys
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
# Strip terminal controls from untrusted logged text; only this program emits ANSI.
|
| 16 |
+
def clean(value):
|
| 17 |
+
return re.sub(r'[\x00-\x1f\x7f-\x9f]', ' ', str(value))
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def read_json(path):
|
| 21 |
+
try:
|
| 22 |
+
return json.loads(Path(path).read_text())
|
| 23 |
+
except (OSError, ValueError):
|
| 24 |
+
return None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class Tail:
|
| 28 |
+
"""Only consume complete JSONL records; tolerate concurrent append and rotation."""
|
| 29 |
+
def __init__(self, path):
|
| 30 |
+
self.path, self.offset, self.pending, self.identity = Path(path), 0, b'', None
|
| 31 |
+
self.errors = 0
|
| 32 |
+
self.generation = 0
|
| 33 |
+
|
| 34 |
+
def read(self):
|
| 35 |
+
try:
|
| 36 |
+
with self.path.open('rb') as stream:
|
| 37 |
+
stat = os.fstat(stream.fileno())
|
| 38 |
+
identity = (stat.st_dev, stat.st_ino)
|
| 39 |
+
if self.identity is not None and (identity != self.identity or stat.st_size < self.offset):
|
| 40 |
+
self.offset, self.pending = 0, b''
|
| 41 |
+
self.generation += 1
|
| 42 |
+
self.identity = identity
|
| 43 |
+
stream.seek(self.offset)
|
| 44 |
+
chunk = stream.read()
|
| 45 |
+
self.offset = stream.tell()
|
| 46 |
+
except OSError:
|
| 47 |
+
return []
|
| 48 |
+
lines = (self.pending + chunk).split(b'\n')
|
| 49 |
+
self.pending = lines.pop()
|
| 50 |
+
out = []
|
| 51 |
+
for line in lines:
|
| 52 |
+
if not line.strip():
|
| 53 |
+
continue
|
| 54 |
+
try:
|
| 55 |
+
row = json.loads(line)
|
| 56 |
+
if isinstance(row, dict):
|
| 57 |
+
out.append(row)
|
| 58 |
+
else:
|
| 59 |
+
self.errors += 1
|
| 60 |
+
except (ValueError, UnicodeDecodeError):
|
| 61 |
+
self.errors += 1
|
| 62 |
+
return out
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class Run:
|
| 66 |
+
def __init__(self, path):
|
| 67 |
+
self.path = Path(path)
|
| 68 |
+
self.task = self.path.name
|
| 69 |
+
self.calls = 0
|
| 70 |
+
self.attempt = 1
|
| 71 |
+
self.outcomes = []
|
| 72 |
+
self.command = '等待工具调用'
|
| 73 |
+
self.command_at = None
|
| 74 |
+
self.view_paths = []
|
| 75 |
+
self.view_at = None
|
| 76 |
+
self.view_sequence = 0
|
| 77 |
+
self.embedded_sequence = 0
|
| 78 |
+
self.embedded_paths = []
|
| 79 |
+
self.embedded = []
|
| 80 |
+
self.summary = ''
|
| 81 |
+
self.status = '等待日志'
|
| 82 |
+
self.notice = ''
|
| 83 |
+
self.last_activity = None
|
| 84 |
+
names = ['events.jsonl', 'gateway_transcript.jsonl', 'mcp_transcript.jsonl',
|
| 85 |
+
'transcript.jsonl', 'gpt_transcript.jsonl', 'codex_events.jsonl']
|
| 86 |
+
self.tails = {n: Tail(self.path / n) for n in names}
|
| 87 |
+
self.image_cache = {}
|
| 88 |
+
|
| 89 |
+
def update(self):
|
| 90 |
+
gateway = 'gateway_transcript.jsonl' if (self.path/'gateway_transcript.jsonl').exists() else 'mcp_transcript.jsonl'
|
| 91 |
+
api = 'transcript.jsonl' if (self.path/'transcript.jsonl').exists() else 'gpt_transcript.jsonl'
|
| 92 |
+
for name in ['events.jsonl', gateway, api, 'codex_events.jsonl']:
|
| 93 |
+
tail = self.tails[name]
|
| 94 |
+
generation = tail.generation
|
| 95 |
+
rows = tail.read()
|
| 96 |
+
if tail.generation != generation:
|
| 97 |
+
# Avoid mixing observations and counts across replaced/truncated runs.
|
| 98 |
+
self.__init__(self.path)
|
| 99 |
+
self.notice = '日志已轮转,重新读取'
|
| 100 |
+
return self.update()
|
| 101 |
+
for row in rows:
|
| 102 |
+
if row.get('t') is not None:
|
| 103 |
+
self.last_activity = max(self.last_activity or 0, row['t'])
|
| 104 |
+
if name == 'events.jsonl':
|
| 105 |
+
if row.get('ev') == 'session_start':
|
| 106 |
+
self.task = row.get('task', self.task)
|
| 107 |
+
self.status = '运行中'
|
| 108 |
+
elif row.get('ev') == 'call':
|
| 109 |
+
self.calls += 1
|
| 110 |
+
self.attempt = row.get('attempt', self.attempt)
|
| 111 |
+
self.command = row.get('cmd', '') + ' ' + json.dumps(row.get('args', {}), ensure_ascii=False)
|
| 112 |
+
self.command_at = row.get('t')
|
| 113 |
+
elif row.get('ev') == 'done':
|
| 114 |
+
self.outcomes.append((row.get('attempt'), row.get('success')))
|
| 115 |
+
elif name == gateway:
|
| 116 |
+
if row.get('ev') != 'tool':
|
| 117 |
+
continue
|
| 118 |
+
if row.get('finished'):
|
| 119 |
+
self.status = '任务已结束'
|
| 120 |
+
if row.get('name') == 'view_images' and not row.get('is_error') and row.get('images', 0) > 0:
|
| 121 |
+
paths = []
|
| 122 |
+
for output in row.get('output', []):
|
| 123 |
+
try:
|
| 124 |
+
obj = json.loads(output)
|
| 125 |
+
paths.extend(obj.get('attached', []))
|
| 126 |
+
except (ValueError, TypeError, AttributeError):
|
| 127 |
+
pass
|
| 128 |
+
# Only mark confirmed attachments as observed, not requested files.
|
| 129 |
+
if paths:
|
| 130 |
+
self.view_paths, self.view_at = paths, row.get('t')
|
| 131 |
+
self.view_sequence += 1
|
| 132 |
+
if row.get('name') == 'robot':
|
| 133 |
+
self.command = row.get('arguments', {}).get('command', self.command)
|
| 134 |
+
self.command_at = row.get('t')
|
| 135 |
+
elif name == api:
|
| 136 |
+
if row.get('ev') in ('user', 'tool') and row.get('images'):
|
| 137 |
+
self.view_paths, self.view_at = row['images'], row.get('t')
|
| 138 |
+
self.view_sequence += 1
|
| 139 |
+
if row.get('ev') == 'assistant':
|
| 140 |
+
self.summary = row.get('reasoning_summary') or row.get('text') or ''
|
| 141 |
+
if row.get('ev') in ('end', 'abort'):
|
| 142 |
+
self.status = '已结束' if row['ev'] == 'end' else '已中断'
|
| 143 |
+
elif name == 'codex_events.jsonl' and row.get('type') == 'item.completed':
|
| 144 |
+
item = row.get('item', {})
|
| 145 |
+
if item.get('type') in ('reasoning', 'agent_message'):
|
| 146 |
+
self.summary = item.get('text', '')
|
| 147 |
+
if item.get('type') == 'mcp_tool_call' and item.get('tool') == 'view_images' and not item.get('error'):
|
| 148 |
+
content = (item.get('result') or {}).get('content', [])
|
| 149 |
+
paths, raw = [], []
|
| 150 |
+
for c in content:
|
| 151 |
+
if c.get('type') == 'text':
|
| 152 |
+
try:
|
| 153 |
+
paths.extend(json.loads(c.get('text', '')).get('attached', []))
|
| 154 |
+
except (ValueError, AttributeError):
|
| 155 |
+
pass
|
| 156 |
+
elif c.get('type') == 'image':
|
| 157 |
+
try:
|
| 158 |
+
raw.append(base64.b64decode(c['data'], validate=True))
|
| 159 |
+
except (ValueError, KeyError):
|
| 160 |
+
pass
|
| 161 |
+
if raw and len(raw) == len(paths):
|
| 162 |
+
self.embedded_paths, self.embedded = paths, raw
|
| 163 |
+
self.embedded_sequence += 1
|
| 164 |
+
if not (self.path/gateway).exists():
|
| 165 |
+
self.view_paths = paths
|
| 166 |
+
self.view_sequence = self.embedded_sequence
|
| 167 |
+
self.notice = f'跳过 {sum(t.errors for t in self.tails.values())} 条损坏日志' if any(t.errors for t in self.tails.values()) else self.notice
|
| 168 |
+
|
| 169 |
+
def frames(self):
|
| 170 |
+
session = read_json(self.path/'session.json') or {}
|
| 171 |
+
roots = [self.path]
|
| 172 |
+
if session.get('sandbox'):
|
| 173 |
+
roots.append(Path(session['sandbox']))
|
| 174 |
+
result = []
|
| 175 |
+
for index, ref in enumerate(self.view_paths):
|
| 176 |
+
if not isinstance(ref, str):
|
| 177 |
+
continue
|
| 178 |
+
if self.embedded_sequence == self.view_sequence and self.embedded_paths == self.view_paths and index < len(self.embedded):
|
| 179 |
+
result.append((ref, self.embedded[index], '工具响应内嵌图片'))
|
| 180 |
+
continue
|
| 181 |
+
for root in roots:
|
| 182 |
+
target = (root/ref).resolve()
|
| 183 |
+
if not target.is_relative_to(root.resolve()) or not target.is_file():
|
| 184 |
+
continue
|
| 185 |
+
stat = target.stat()
|
| 186 |
+
if self.view_at is not None and stat.st_mtime > self.view_at + 0.1:
|
| 187 |
+
result.append((ref, None, '文件在观察后已修改,不能确认原图'))
|
| 188 |
+
break
|
| 189 |
+
key = (str(target), stat.st_mtime_ns, stat.st_size)
|
| 190 |
+
if key not in self.image_cache:
|
| 191 |
+
self.image_cache = {key: target.read_bytes()}
|
| 192 |
+
result.append((ref, self.image_cache[key], '日志引用文件(未校验原始字节)'))
|
| 193 |
+
break
|
| 194 |
+
else:
|
| 195 |
+
result.append((ref, None, '图片文件不可用'))
|
| 196 |
+
return result
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def choose_run(batch):
|
| 200 |
+
data = read_json(Path(batch)/'manifest.json')
|
| 201 |
+
if not data:
|
| 202 |
+
return None, '批次清单暂不可读'
|
| 203 |
+
rows = data.get('runs', [])
|
| 204 |
+
counts = {key: sum(r.get('status') == key for r in rows) for key in ['done', 'running', 'pending']}
|
| 205 |
+
active = [r for r in rows if r.get('status') == 'running' and r.get('log')]
|
| 206 |
+
completed = [r for r in rows if r.get('log')]
|
| 207 |
+
row = active[0] if active else completed[-1] if completed else None
|
| 208 |
+
summary = ' / '.join(f'{key} {count}' for key, count in counts.items())
|
| 209 |
+
return row, summary
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def image_lines(raw, columns, rows, color):
|
| 213 |
+
from PIL import Image, ImageOps
|
| 214 |
+
image = Image.open(io.BytesIO(raw)).convert('RGB')
|
| 215 |
+
width, height = columns, rows * 2
|
| 216 |
+
image = ImageOps.contain(image, (width, height))
|
| 217 |
+
pixels = image.load()
|
| 218 |
+
lines = []
|
| 219 |
+
ramp = ' .:-=+*#%@'
|
| 220 |
+
for y in range(0, image.height, 2):
|
| 221 |
+
line = ''
|
| 222 |
+
for x in range(image.width):
|
| 223 |
+
upper, lower = pixels[x,y], pixels[x,min(y+1,image.height-1)]
|
| 224 |
+
if color:
|
| 225 |
+
line += '\033[38;2;%d;%d;%dm\033[48;2;%d;%d;%dm▀' % (*upper, *lower)
|
| 226 |
+
else:
|
| 227 |
+
value = (sum(upper) + sum(lower)) / 6
|
| 228 |
+
line += ramp[min(9, int(value/256*10))]
|
| 229 |
+
lines.append(line + ('\033[0m' if color else ''))
|
| 230 |
+
return lines
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# Native image transports keep source pixels rather than quantizing to text cells.
|
| 234 |
+
KITTY_IMAGE_ID = 1987000000 + os.getpid() % 100000
|
| 235 |
+
|
| 236 |
+
def choose_renderer(requested, environ=None, tty=True):
|
| 237 |
+
env = os.environ if environ is None else environ
|
| 238 |
+
if not tty:
|
| 239 |
+
return 'ansi'
|
| 240 |
+
# This embedded terminal was observed to swallow OSC 1337 images, leaving
|
| 241 |
+
# the reserved rectangle blank. Keep a visible preview even for old commands.
|
| 242 |
+
if env.get('TERM_PROGRAM') == 'claude-desktop' and requested == 'iterm':
|
| 243 |
+
return 'ansi'
|
| 244 |
+
if requested != 'auto':
|
| 245 |
+
return requested
|
| 246 |
+
# Multiplexers need terminal-specific passthrough setup; keep auto conservative.
|
| 247 |
+
if env.get('TMUX') or env.get('STY'):
|
| 248 |
+
return 'ansi'
|
| 249 |
+
if env.get('KITTY_WINDOW_ID') or env.get('TERM') == 'xterm-kitty':
|
| 250 |
+
return 'kitty'
|
| 251 |
+
if env.get('TERM_PROGRAM') in ('iTerm.app', 'WezTerm'):
|
| 252 |
+
return 'iterm'
|
| 253 |
+
return 'ansi'
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def native_image(raw_images, columns, rows, renderer):
|
| 257 |
+
from PIL import Image
|
| 258 |
+
decoded = [Image.open(io.BytesIO(raw)).convert('RGB') for raw in raw_images]
|
| 259 |
+
# Place full-resolution views side by side without resampling source pixels.
|
| 260 |
+
canvas = Image.new('RGB', (sum(im.width for im in decoded), max(im.height for im in decoded)))
|
| 261 |
+
x = 0
|
| 262 |
+
for im in decoded:
|
| 263 |
+
canvas.paste(im, (x, 0))
|
| 264 |
+
x += im.width
|
| 265 |
+
buf = io.BytesIO()
|
| 266 |
+
canvas.save(buf, format='PNG')
|
| 267 |
+
data = base64.b64encode(buf.getvalue()).decode()
|
| 268 |
+
if renderer == 'iterm':
|
| 269 |
+
sequence = f'\033]1337;File=inline=1;width={columns};height={rows};preserveAspectRatio=1:{data}\a'
|
| 270 |
+
else:
|
| 271 |
+
# Preserve aspect in the usual 1:2 text cells; don't stretch square inputs.
|
| 272 |
+
w = max(1, min(columns, int(rows * 2 * canvas.width / canvas.height)))
|
| 273 |
+
h = max(1, min(rows, round(w * canvas.height / canvas.width / 2)))
|
| 274 |
+
chunks = [data[i:i+4096] for i in range(0, len(data), 4096)]
|
| 275 |
+
sequence = ''
|
| 276 |
+
for n, chunk in enumerate(chunks):
|
| 277 |
+
meta = f'a=T,f=100,t=d,i={KITTY_IMAGE_ID},q=2,C=1,c={w},r={h},' if n == 0 else ''
|
| 278 |
+
sequence += f'\033_G{meta}m={int(n < len(chunks)-1)};{chunk}\033\\'
|
| 279 |
+
# Both protocols are given a reserved rectangle; restore before advancing.
|
| 280 |
+
return '\0337' + sequence + '\0338' + '\n' * (rows - 1)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def clear_native(renderer):
|
| 284 |
+
return f'\033_Ga=d,d=I,i={KITTY_IMAGE_ID},q=2\033\\' if renderer == 'kitty' else ''
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def age(timestamp):
|
| 288 |
+
return f'{max(0,int(time.time()-timestamp))} 秒前' if timestamp else '时间未记录'
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def render(run, label, width, rows, color, images, renderer="ansi", camera="all"):
|
| 292 |
+
lines = [clean(label)[:width], f'{clean(run.task)} | {clean(run.status)} | 尝试 {run.attempt} | 机器人动作 {run.calls}',
|
| 293 |
+
f'最近动作 ({age(run.command_at)}): {clean(run.command)[:max(15,width-22)]}',
|
| 294 |
+
f'最近返回给 Agent 的图片 ({age(run.view_at)}):按观察事件更新,不是连续视频']
|
| 295 |
+
frames = run.frames()
|
| 296 |
+
if camera != "all":
|
| 297 |
+
keyword = "agentview" if camera == "main" else "wrist"
|
| 298 |
+
frames = [f for f in frames if keyword in f[0]][-1:]
|
| 299 |
+
if not frames:
|
| 300 |
+
lines.append('尚未发现已返回给 Agent 的图片。')
|
| 301 |
+
if images and frames:
|
| 302 |
+
shown = frames[-2:]
|
| 303 |
+
cell = max(12,(width-3*(len(shown)-1))//len(shown))
|
| 304 |
+
columns = []
|
| 305 |
+
for ref, raw, source in shown:
|
| 306 |
+
display = ('字符缩略图' if renderer == 'ansi' else '原图像素') if raw else '不可用'
|
| 307 |
+
lines.append(f' {clean(ref)} · 来源:{source} · 显示:{display}')
|
| 308 |
+
try:
|
| 309 |
+
columns.append(image_lines(raw, cell, rows, color) if raw else ['[原图不可用]'])
|
| 310 |
+
except Exception as exc:
|
| 311 |
+
columns.append([f'[无法解码图片: {type(exc).__name__}]'])
|
| 312 |
+
if renderer in ('iterm', 'kitty') and any(raw for _, raw, _ in shown):
|
| 313 |
+
try:
|
| 314 |
+
lines.append(native_image([raw for _, raw, _ in shown if raw], width, rows, renderer))
|
| 315 |
+
columns = []
|
| 316 |
+
except Exception as exc:
|
| 317 |
+
lines.append(f'原图显示编码失败,使用字符预览: {type(exc).__name__}')
|
| 318 |
+
for y in range(max(map(len, columns), default=0)):
|
| 319 |
+
parts=[]
|
| 320 |
+
for c in columns:
|
| 321 |
+
part=c[y] if y<len(c) else ''
|
| 322 |
+
visible=len(re.sub(r'\033\[[0-9;]*m','',part))
|
| 323 |
+
parts.append(part+' '*max(0,cell-visible))
|
| 324 |
+
lines.append(' '.join(parts))
|
| 325 |
+
elif frames:
|
| 326 |
+
lines.extend('图片: '+clean(f[0]) for f in frames)
|
| 327 |
+
if run.summary:
|
| 328 |
+
lines.append('最近记录的摘要/说明: '+clean(run.summary)[:max(20,width-20)])
|
| 329 |
+
if run.outcomes:
|
| 330 |
+
lines.append('已提交结果: '+' · '.join(f'尝试 {a}: '+('成功' if ok else '失败') for a,ok in run.outcomes))
|
| 331 |
+
if run.notice:
|
| 332 |
+
lines.append(run.notice)
|
| 333 |
+
lines.append('最近日志活动: '+age(run.last_activity))
|
| 334 |
+
return '\n'.join(lines)
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
def main(argv=None):
|
| 338 |
+
parser=argparse.ArgumentParser(description=__doc__)
|
| 339 |
+
group=parser.add_mutually_exclusive_group(required=True)
|
| 340 |
+
group.add_argument('--batch',type=Path,help='Batch directory; follows the running task then the next one')
|
| 341 |
+
group.add_argument('--run',type=Path,help='One run directory')
|
| 342 |
+
parser.add_argument('--interval',type=float,default=6,help="Refresh interval in seconds (default: 6)")
|
| 343 |
+
parser.add_argument('--once',action='store_true')
|
| 344 |
+
parser.add_argument('--duration',type=float,help='Stop after N seconds (useful for verification)')
|
| 345 |
+
parser.add_argument('--ascii',action='store_true',help='Portable monochrome preview instead of truecolor blocks')
|
| 346 |
+
parser.add_argument('--no-images',action='store_true')
|
| 347 |
+
parser.add_argument('--renderer',choices=['auto','ansi','iterm','kitty'],default='auto',help='Native pixels: iterm (also VS Code with enableImages) or kitty; auto detects known terminals')
|
| 348 |
+
parser.add_argument('--camera',choices=['all','main','wrist'],default='all',help='Select one camera for a larger view')
|
| 349 |
+
parser.add_argument('--width',type=int,default=None)
|
| 350 |
+
parser.add_argument('--image-rows',type=int,default=None)
|
| 351 |
+
a=parser.parse_args(argv)
|
| 352 |
+
if a.interval<0.5:parser.error('--interval must be >= 0.5 seconds')
|
| 353 |
+
if a.width is not None and a.width<24:parser.error('--width must be >= 24')
|
| 354 |
+
if a.image_rows is not None and a.image_rows<2:parser.error('--image-rows must be >= 2')
|
| 355 |
+
if a.duration is not None and a.duration<=0:parser.error('--duration must be positive')
|
| 356 |
+
if not a.no_images:
|
| 357 |
+
try:import PIL
|
| 358 |
+
except ImportError:parser.error('Image preview needs Pillow; use the evaluation Python or --no-images')
|
| 359 |
+
renderer=choose_renderer('ansi' if a.ascii else a.renderer,tty=sys.stdout.isatty())
|
| 360 |
+
if a.no_images:renderer='ansi'
|
| 361 |
+
compatibility_notice = (
|
| 362 |
+
'Claude 内置终端的 iTerm 图片模式未能显示;已切换为字符预览(非原图清晰度)。'
|
| 363 |
+
if os.environ.get('TERM_PROGRAM') == 'claude-desktop'
|
| 364 |
+
and a.renderer == 'iterm' and renderer == 'ansi'
|
| 365 |
+
and not a.ascii and not a.no_images and sys.stdout.isatty() else ''
|
| 366 |
+
)
|
| 367 |
+
interactive=sys.stdout.isatty() and not a.once
|
| 368 |
+
current=None
|
| 369 |
+
started=time.monotonic()
|
| 370 |
+
previous=None
|
| 371 |
+
try:
|
| 372 |
+
if interactive:print('\033[?1049h\033[?25l',end='',flush=True)
|
| 373 |
+
while True:
|
| 374 |
+
label='Agent Viewer · LIVE · Ctrl+C 退出'
|
| 375 |
+
path=a.run
|
| 376 |
+
if a.batch:
|
| 377 |
+
selected,summary=choose_run(a.batch)
|
| 378 |
+
path=Path(selected['log']) if selected else None
|
| 379 |
+
label=f'{a.batch.name} | {summary}'
|
| 380 |
+
if path is not None:
|
| 381 |
+
if current is None or current.path!=path:current=Run(path)
|
| 382 |
+
current.update()
|
| 383 |
+
if a.batch and selected:current.status=selected.get('status',current.status)
|
| 384 |
+
size=shutil.get_terminal_size((100,36))
|
| 385 |
+
width=a.width or max(24,size.columns-1)
|
| 386 |
+
rows=a.image_rows or max(3,size.lines-12-bool(compatibility_notice))
|
| 387 |
+
label += f' | 刷新 {a.interval:g}s · {renderer}'
|
| 388 |
+
output=render(current,label,width,rows,sys.stdout.isatty() and not a.ascii,not a.no_images,renderer,a.camera)
|
| 389 |
+
if compatibility_notice:
|
| 390 |
+
header, _, body = output.partition('\n')
|
| 391 |
+
output = header + '\n' + compatibility_notice + '\n' + body
|
| 392 |
+
else:output=label+'\n等待批次启动下一任务…'
|
| 393 |
+
if output!=previous:
|
| 394 |
+
if interactive:print(clear_native(renderer)+'\033[H\033[J'+output,end='',flush=True)
|
| 395 |
+
else:print(output,flush=True)
|
| 396 |
+
previous=output
|
| 397 |
+
if a.once or a.duration and time.monotonic()-started>=a.duration:break
|
| 398 |
+
delay=a.interval if a.duration is None else min(a.interval,max(0,a.duration-(time.monotonic()-started)))
|
| 399 |
+
time.sleep(delay)
|
| 400 |
+
except KeyboardInterrupt:
|
| 401 |
+
pass
|
| 402 |
+
finally:
|
| 403 |
+
if interactive:print(clear_native(renderer)+'\033[0m\033[?25h\033[?1049l',end='',flush=True)
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/agent_viewer/viewer.html
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!doctype html>
|
| 2 |
+
<html lang="zh-CN">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
| 5 |
+
<title>Agent Viewer · 历史回放</title>
|
| 6 |
+
<style>
|
| 7 |
+
:root{color-scheme:light;--bg:#f6f7f6;--paper:#fff;--text:#192b31;--muted:#62747a;--border:#dfe7e6;--teal:#087f79;--soft:#e9f5f1;--orange:#b56624;--red:#af4545;--mono:ui-monospace,SFMono-Regular,Consolas,monospace;font-family:Inter,-apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif;color:var(--text);background:var(--bg)}
|
| 8 |
+
*{box-sizing:border-box}body{margin:0}button,input,select{font:inherit}button,select{cursor:pointer}button{border:1px solid var(--border);background:var(--paper);color:var(--text);border-radius:7px;padding:9px 13px;font-size:13px}button:hover{background:var(--soft)}button:disabled{opacity:.4;cursor:default}button:focus-visible,input:focus-visible,select:focus-visible{outline:3px solid #55bbb1;outline-offset:2px}button.active,button[aria-pressed="true"]{border-color:var(--teal);color:var(--teal);background:var(--soft)}.primary{background:var(--teal);border-color:var(--teal);color:white}.primary:hover{background:#076762}.muted{color:var(--muted)}.mono,code{font-family:var(--mono)}.eyebrow{font-size:10px;text-transform:uppercase;letter-spacing:1.7px;font-weight:700;color:var(--muted)}
|
| 9 |
+
header{height:72px;padding:0 28px;display:flex;align-items:center;gap:18px;border-bottom:1px solid var(--border);background:var(--paper)}.brand{font-size:21px;font-weight:750;letter-spacing:-.6px;display:flex;align-items:center;gap:11px}.brandmark{background:var(--teal);color:#fff;border-radius:9px;padding:4px 8px;font-size:20px}.divider{height:23px;width:1px;background:var(--border)}.mode{margin-left:auto;font-size:12px;color:var(--teal);background:var(--soft);padding:7px 12px;border-radius:6px}.shell{display:grid;grid-template-columns:235px minmax(0,1fr);min-height:calc(100vh - 72px)}aside{padding:27px 18px;border-right:1px solid var(--border);background:#f9faf9}.aside-title{display:flex;justify-content:space-between;align-items:center;margin-bottom:21px;font-size:13px}.run{display:block;text-align:left;width:100%;padding:15px 13px;border-radius:9px;margin-bottom:9px}.run strong{display:block;font-size:13px;line-height:1.6;overflow-wrap:anywhere}.run small{display:block;line-height:1.9;color:var(--muted);font-size:11px}.run .state{font-size:11px;color:var(--teal);margin-bottom:9px;display:block}.aside-section{border-top:1px solid var(--border);margin-top:27px;padding-top:22px}.attempt{display:block;width:100%;text-align:left;margin-top:9px;font-size:12px}.attempt span{float:right}.success{color:var(--teal)}.failed{color:var(--red)}.aside-note{font-size:11px;line-height:1.9;margin-top:25px;color:var(--muted)}
|
| 10 |
+
main{min-width:0;padding:28px 30px}.heading{display:flex;justify-content:space-between;gap:20px;align-items:flex-start;margin-bottom:22px}h1{font-size:26px;letter-spacing:-.8px;line-height:1.3;margin:7px 0 9px}h2{font-size:15px;margin:0}h3{font-size:13px;margin:0}.subtitle{font-size:12px;line-height:1.8;color:var(--muted)}.pill{display:inline-block;white-space:nowrap;font-size:11px;padding:6px 10px;border-radius:20px;background:var(--soft);color:var(--teal)}.workspace{display:grid;grid-template-columns:minmax(320px,1.5fr) minmax(280px,1fr);gap:22px}.panel{background:var(--paper);border:1px solid var(--border);border-radius:12px;overflow:hidden}.panel-top{display:flex;align-items:center;justify-content:space-between;padding:17px 19px;border-bottom:1px solid var(--border);gap:10px}.panel-top small{font-size:11px;color:var(--muted)}.switches{padding:14px 18px;display:flex;gap:7px;flex-wrap:wrap}.switches button{font-size:11px;padding:7px 10px}.image-stage{background:#e9eeec;margin:0 18px;min-height:230px;display:grid;place-items:center;position:relative;border-radius:7px;overflow:hidden}.image-stage img{display:block;width:100%;height:clamp(290px,36vw,480px);object-fit:contain}.image-stage .empty{padding:45px;text-align:center;color:var(--muted);line-height:1.8}.caption{padding:12px 19px;font-size:11px;color:var(--muted);line-height:1.7;overflow-wrap:anywhere}.camera-strip{display:flex;gap:12px;padding:0 18px 18px;flex-wrap:wrap}.camera{display:grid;grid-template-columns:58px 1fr;align-items:center;gap:9px;text-align:left;padding:5px 10px 5px 5px;min-width:140px}.camera img{width:58px;height:46px;object-fit:contain;background:#e9eeec;border-radius:4px}.camera span{font-size:11px}.task{margin:0 18px 18px;padding:14px 0 0;border-top:1px solid var(--border);font-size:12px;line-height:1.8}.task p{margin:6px 0 0}.step-title{display:flex;align-items:center;justify-content:space-between;margin-bottom:15px}.step-title small{font-size:11px;color:var(--muted)}.flowcard{background:var(--paper);border:1px solid var(--border);border-radius:10px;margin-bottom:12px;padding:16px}.cardtitle{display:flex;align-items:center;gap:9px;margin-bottom:12px;font-size:12px;font-weight:650}.number{color:var(--muted);background:var(--bg);border:1px solid var(--border);border-radius:5px;padding:4px;font:10px var(--mono)}.flowcard p{font-size:12px;line-height:1.8;margin:7px 0;color:var(--muted)}pre{margin:9px 0 0;font:11px/1.7 var(--mono);white-space:pre-wrap;overflow-wrap:anywhere;background:var(--bg);border:1px solid var(--border);padding:12px;border-radius:6px;max-height:230px;overflow:auto}details{margin-top:9px}summary{font-size:11px;color:var(--muted);cursor:pointer;padding:5px 0}.result-message{font-size:13px;line-height:1.8}.notice{border:1px solid #e9cfab;background:#fff8ec;color:#89541d;padding:10px 12px;border-radius:7px;margin-top:10px;font-size:11px;line-height:1.8}.statement{border-left:2px solid var(--teal);padding-left:10px;font-size:12px;line-height:1.8;margin:12px 0}.subtle{font-size:11px;line-height:1.8;color:var(--muted)}
|
| 11 |
+
.timeline{margin-top:22px;padding:18px 20px}.controls{display:flex;align-items:center;gap:9px;flex-wrap:wrap}.controls .count{font:12px var(--mono);margin:0 8px}.controls select{padding:7px;border:1px solid var(--border);background:var(--paper);border-radius:6px;font-size:11px}.controls small{margin-left:auto;font-size:11px;color:var(--muted)}input[type=range]{width:100%;accent-color:var(--teal);margin:18px 0 10px;cursor:pointer}.filmstrip{display:flex;gap:9px;overflow-x:auto;padding:3px 0 7px;scroll-behavior:smooth}.frame{flex:0 0 95px;padding:4px;position:relative}.frame img,.frame .placeholder{display:block;width:85px;height:64px;object-fit:contain;background:#e9eeec;border-radius:4px}.frame .label{display:block;font-size:10px;margin:7px 0 3px}.frame .dot{position:absolute;top:8px;right:8px;border:2px solid white;width:10px;height:10px;border-radius:50%;background:var(--teal)}.frame .dot.bad{background:var(--orange)}.timeline-foot{display:flex;justify-content:space-between;gap:15px;font-size:10px;color:var(--muted);margin-top:10px;line-height:1.8}footer{display:flex;justify-content:space-between;font-size:10px;color:var(--muted);margin-top:18px;gap:15px;line-height:1.8}.warning-list{font-size:11px;color:var(--orange)}
|
| 12 |
+
@media(min-width:1600px){main{max-width:1600px;width:100%;margin:auto}}@media(max-width:1100px){.shell{grid-template-columns:185px minmax(0,1fr)}main{padding:23px 20px}.workspace{gap:15px;grid-template-columns:minmax(250px,1.2fr) minmax(250px,1fr)}aside{padding:25px 12px}.image-stage img{height:320px}}@media(max-width:850px){.shell{display:block}aside{border-right:0;border-bottom:1px solid var(--border);padding:15px 20px}.aside-title,.aside-note,.aside-section .eyebrow{display:none}#runs{display:flex;gap:10px}.run{width:auto;min-width:190px;margin:0}.aside-section{margin:12px 0 0;padding:0;border:0;display:flex;gap:8px}.attempt{width:auto}.attempt span{float:none;margin-left:10px}.workspace{grid-template-columns:minmax(0,1fr)}.image-stage img{height:400px}header{padding:0 18px;height:63px}.heading{margin-bottom:17px}main{padding:22px 18px}.details-col{display:grid;grid-template-columns:1fr 1fr;gap:12px}.step-title{grid-column:1/-1;margin-bottom:0}.flowcard{margin:0}.flowcard:last-child{grid-column:1/-1}}@media(max-width:480px){header .divider,header>.muted{display:none}header{gap:8px}.brand{font-size:18px}.mode{font-size:10px;padding:6px 8px}.heading{display:block}h1{font-size:23px}.heading>.pill{margin-top:9px}.details-col{display:block}.flowcard{margin-top:12px}.image-stage{margin:0 10px}.image-stage img{height:280px}.panel-top{padding:14px}.camera-strip{padding:0 10px 12px;gap:6px}.camera{min-width:120px;padding-right:6px;grid-template-columns:42px 1fr}.camera img{width:42px;height:38px}.timeline{padding:14px 10px}.controls{gap:5px}.controls .count{margin:0 3px;font-size:10px}.controls small{display:none}.controls button{padding:9px 10px}.timeline-foot,footer{flex-direction:column;gap:3px}}
|
| 13 |
+
[hidden]{display:none!important}.view-tabs{display:flex;gap:8px;margin-bottom:18px}.video-panel{margin-bottom:22px}.video-stage{background:#101817;padding:16px;text-align:center}.video-stage video{display:block;width:100%;max-height:68vh;min-height:200px;margin:auto;aspect-ratio:640/376;background:#101817}.video-toolbar{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:14px 19px}.video-toolbar label{font-size:12px}.video-toolbar select{padding:6px;border:1px solid var(--border);border-radius:6px;background:var(--paper);color:var(--text)}.video-toolbar .subtle{margin-left:auto}.video-note{padding:0 19px 16px;font-size:12px;line-height:1.8;color:var(--muted)}
|
| 14 |
+
.reason-copy{white-space:pre-wrap;font-size:12px;line-height:1.8;background:var(--soft);border-radius:7px;padding:12px;margin:9px 0}.reason-empty{background:none;color:var(--muted);padding:0}.reason-public{white-space:pre-wrap;font-size:12px;line-height:1.8;border-left:2px solid var(--teal);padding-left:10px;margin:9px 0}.view-tabs{flex-wrap:wrap}
|
| 15 |
+
</style>
|
| 16 |
+
</head>
|
| 17 |
+
<body>
|
| 18 |
+
<header><div class="brand"><span class="brandmark">⌘</span>Agent Viewer</div><span class="divider"></span><span class="muted" style="font-size:12px">LFF-Bench</span><span class="mode">◷ 历史回放</span></header>
|
| 19 |
+
<div class="shell">
|
| 20 |
+
<aside><div class="aside-title"><strong>运行记录</strong><span id="run-count" class="muted"></span></div><nav id="runs" aria-label="运行记录"></nav><div class="aside-section" id="attempts"></div><div class="aside-note">回放已保存的观察与工具记录。<br>画面来自模型输入的历史图片文件。<br>视频支持连续播放与全屏。<br>逐步视图:← → 切换,空格播放。</div></aside>
|
| 21 |
+
<main>
|
| 22 |
+
<div class="heading"><div><div class="eyebrow">OBSERVE / ACT / REVIEW</div><h1 id="title"></h1><div class="subtitle" id="subtitle"></div></div><span id="status" class="pill"></span></div>
|
| 23 |
+
<div class="view-tabs" aria-label="回放视图"><button id="video-tab" aria-pressed="false">▶ 完整执行视频</button><button id="steps-tab" aria-pressed="false">逐步输入与日志</button></div>
|
| 24 |
+
<section id="video-view" class="panel video-panel" hidden><div class="panel-top"><h2>完整执行录像</h2><small>主相机 + 腕部相机</small></div><div class="video-stage"><video id="execution-video" controls playsinline preload="metadata" aria-label="任务完整执行录像">浏览器不支持视频播放。</video></div><div class="video-toolbar"><label for="video-rate">播放速度</label><select id="video-rate"><option value="0.3333333333333333">⅓×</option><option value="0.5">0.5×</option><option value="1" selected>1× 原录像</option><option value="2">2×</option></select><span class="subtle">连续播放 · 拖动进度 · 全屏查看</span></div><div class="video-note">播放原始执行录像,保留尝试切换与结果画面。录像时间不等于日志中的等待时间;查看单步输入与工具返回可切换到“逐步输入与日志”。</div><div id="video-error" class="notice" hidden role="alert"></div></section>
|
| 25 |
+
<div id="step-view"><div class="workspace">
|
| 26 |
+
<section class="panel"><div class="panel-top"><h2>Agent 看到的画面</h2><small id="attempt-label"></small></div><div class="switches"><button id="before" aria-pressed="true">决策前 · 最近观察</button><button id="after" aria-pressed="false">执行后 · 返回图片</button></div><div class="image-stage" id="stage"></div><div class="caption" id="caption"></div><div class="camera-strip" id="cameras"></div><div class="task"><span class="eyebrow">TASK</span><p id="task"></p></div></section>
|
| 27 |
+
<section class="details-col" aria-label="当前步骤"><div class="step-title"><h2 id="step-title"></h2><small id="time"></small></div><div class="flowcard"><div class="cardtitle"><span class="number">01</span>观察输入</div><div id="observation-note" class="subtle"></div><details><summary>查看最近输入文本</summary><pre id="input-text"></pre></details></div><div class="flowcard"><div class="cardtitle"><span class="number">02</span>步骤间思考</div><div id="reason-transition" class="subtle"></div><div id="reason-summary" class="reason-copy"></div><div id="reason-public-wrap"><span class="subtle">Agent 文字说明</span><div id="reason-public" class="reason-public"></div></div><details><summary>前一步反馈与记录来源</summary><pre id="reason-feedback"></pre><p id="reason-source" class="subtle"></p><p class="subtle">显示已记录的模型摘要与文字回复,不代表完整内部 CoT。</p></details></div><div class="flowcard"><div class="cardtitle"><span class="number">03</span>执行动作</div><div id="actions"></div></div><div class="flowcard"><div class="cardtitle"><span class="number">04</span>执行反馈</div><div id="results"></div><div id="notices"></div></div></section>
|
| 28 |
+
</div>
|
| 29 |
+
<section class="panel timeline" aria-label="回放时间轴"><div class="controls"><button id="prev" aria-label="上一步">←</button><button id="play" class="primary" aria-label="播放回放">▶ 播放</button><button id="next" aria-label="下一步">→</button><span class="count" id="count" aria-live="polite"></span><select id="speed" aria-label="每步播放时长"><option value="2000">2 秒 / 步</option><option value="1000">1 秒 / 步</option><option value="4000">4 秒 / 步</option></select><small>按步骤播放 · 不按实际等待时间</small></div><input id="scrubber" type="range" min="0" value="0" aria-label="选择回放步骤"><div class="filmstrip" id="filmstrip"></div><div class="timeline-foot"><span>● 绿色:尝试成功 ● 橙色:失败 / API 重试</span><span id="step-meta"></span></div></section>
|
| 30 |
+
</div>
|
| 31 |
+
<div id="warnings" class="warning-list"></div><footer><span>真实历史记录 · 原始执行录像与输入图片 · 离线可用</span><span>逐步视图展示最近观察;模型上下文可能包含更早图片。</span></footer>
|
| 32 |
+
</main></div>
|
| 33 |
+
<script id="viewer-data" type="application/json">/*__PAYLOAD__*/null</script>
|
| 34 |
+
<script>
|
| 35 |
+
'use strict';
|
| 36 |
+
const DATA=JSON.parse(document.getElementById('viewer-data').textContent);
|
| 37 |
+
const $=id=>document.getElementById(id);
|
| 38 |
+
const names={l5_slide_to_target:'把红色方块滑入目标区',l1_bias_place:'校准偏差下的抓取放置'};
|
| 39 |
+
let runIndex=0, index=0, phase='before', camera='agentview', selectedFrameKey=null, timer=null, viewMode='steps';
|
| 40 |
+
const run=()=>DATA.runs[runIndex];
|
| 41 |
+
const step=()=>run().steps[index];
|
| 42 |
+
function el(tag,text,cls){const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e;}
|
| 43 |
+
function fmt(value){return typeof value==='string'?value:JSON.stringify(value,null,2);}
|
| 44 |
+
function clock(seconds){const s=Math.max(0,Math.round(seconds||0));return `${Math.floor(s/60)}:${String(s%60).padStart(2,'0')}`;}
|
| 45 |
+
function cameraName(name){return name==='agentview'?'主相机':name==='wrist'?'腕部相机':name;}
|
| 46 |
+
function stop(){if(timer)clearInterval(timer);timer=null;$('play').textContent='▶ 播放';$('play').setAttribute('aria-label','播放回放');}
|
| 47 |
+
function setMode(mode){stop();viewMode=mode==='video'&&run().video?'video':'steps';$('video-view').hidden=viewMode!=='video';$('step-view').hidden=viewMode!=='steps';$('video-tab').setAttribute('aria-pressed',String(viewMode==='video'));$('steps-tab').setAttribute('aria-pressed',String(viewMode==='steps'));if(viewMode!=='video')$('execution-video').pause();}
|
| 48 |
+
function setupVideo(){const v=$('execution-video');v.pause();v.removeAttribute('src');$('video-error').hidden=true;$('video-tab').disabled=!run().video;if(run().video)v.src=DATA.assets[run().video.asset];v.load();$('video-rate').value='1';v.playbackRate=1;setMode(run().video?'video':'steps');}
|
| 49 |
+
function move(value,manual=true){if(manual)stop();index=Math.max(0,Math.min(run().steps.length-1,value));render();}
|
| 50 |
+
function img(frame){const image=el('img');image.alt=`${cameraName(frame.camera)} · ${frame.path}`;image.src=DATA.assets[frame.asset];return image;}
|
| 51 |
+
function allAfter(s){return s.actions.flatMap(a=>a.after||[]);}
|
| 52 |
+
function renderRun(){
|
| 53 |
+
const r=run();$('title').textContent=names[r.task]||r.task;$('subtitle').textContent=`${r.model} / seed ${r.seed??'—'} / ${r.actionCount} 次工具调用 / ${r.feedback} · ${r.perception}`;
|
| 54 |
+
$('task').textContent=r.taskText;$('status').textContent=r.status==='success'?'● 最终成功':r.status==='failed'?'● 尝试未成功':'◌ 记录未完成';
|
| 55 |
+
$('status').style.color=r.status==='failed'?'var(--red)':'';$('run-count').textContent=DATA.runs.length;
|
| 56 |
+
$('runs').replaceChildren(...DATA.runs.map((item,n)=>{const b=el('button',undefined,'run'+(n===runIndex?' active':''));b.setAttribute('aria-pressed',String(n===runIndex));b.append(el('span',item.status==='success'?'● 已完成 · 成功':'◌ '+(item.status==='failed'?'未成功':'未完成'),'state'),el('strong',names[item.task]||item.task),el('small',`${item.model} · seed ${item.seed??'—'}`),el('small',`${item.steps.length} 步决策 · ${item.outcomes.length} 次提交`));b.onclick=()=>{stop();runIndex=n;index=0;phase='before';renderRun();render();};return b;}));
|
| 57 |
+
$('attempts').replaceChildren(el('div','ATTEMPTS','eyebrow'),...r.outcomes.map(o=>{const b=el('button',`第 ${o.attempt} 次尝试`,'attempt');b.append(el('span',o.success?'成功 ↗':'失败 ↗',o.success?'success':'failed'));b.title=o.feedback;b.onclick=()=>{setMode('steps');phase='before';move(r.steps.findIndex(s=>s.verdict?.attempt===o.attempt));};return b;}));
|
| 58 |
+
$('scrubber').max=r.steps.length-1;
|
| 59 |
+
$('warnings').replaceChildren(...r.warnings.map(w=>el('p',w)));
|
| 60 |
+
$('filmstrip').replaceChildren(...r.steps.map((s,n)=>{const b=el('button',undefined,'frame');b.setAttribute('aria-label',`第 ${n+1} 步,尝试 ${s.attempt}`);const f=s.before.find(f=>f.camera==='agentview')||s.before[0];b.append(f?.asset?img(f):el('span','无图片','placeholder'));b.append(el('span',`${String(n+1).padStart(2,'0')} · 尝试 ${s.attempt}`,'label'));if(s.verdict||s.notices.length)b.append(el('span',undefined,'dot'+(s.verdict?.success?'':' bad')));b.onclick=()=>move(n);return b;}));
|
| 61 |
+
setupVideo();
|
| 62 |
+
}
|
| 63 |
+
function renderReason(){
|
| 64 |
+
const s=step(),previous=run().steps[index-1];
|
| 65 |
+
$('reason-transition').textContent=index===0?'任务输入 → 第 1 步':`第 ${index} 步反馈 → 第 ${index+1} 步决策`;
|
| 66 |
+
$('reason-feedback').textContent=previous?previous.actions.map(a=>a.result===null?'结果未记录':fmt(a.result)).join('\n\n')||previous.text||'没有工具反馈':s.inputText||'初始输入未记录';
|
| 67 |
+
$('reason-summary').textContent=s.decisionSummary||(s.decisionSummaryStatus==='not_returned'?'模型未返回摘要。':'本步未记录摘要。');
|
| 68 |
+
$('reason-summary').classList.toggle('reason-empty',!s.decisionSummary);
|
| 69 |
+
$('reason-public-wrap').hidden=!s.text;$('reason-public').textContent=s.text||'';
|
| 70 |
+
$('reason-source').textContent=`来源:${run().source} 第 ${s.decisionSourceLine} 行 · turn ${s.turn??'—'}`;
|
| 71 |
+
}
|
| 72 |
+
function render(){
|
| 73 |
+
renderReason();
|
| 74 |
+
const r=run(),s=step(),after=allAfter(s),frames=phase==='before'?s.before:after;
|
| 75 |
+
const selected=frames.find(f=>`${f.path}@${f.source}`===selectedFrameKey)||frames.find(f=>f.camera===camera)||frames[0];if(selected)camera=selected.camera;
|
| 76 |
+
$('before').setAttribute('aria-pressed',String(phase==='before'));$('after').setAttribute('aria-pressed',String(phase==='after'));
|
| 77 |
+
$('attempt-label').textContent=`尝试 ${s.attempt} · 步骤 ${index+1}`;$('step-title').textContent=`Step ${String(index+1).padStart(2,'0')}`;
|
| 78 |
+
$('time').textContent=`+${clock(s.elapsed)}${s.latency==null?'':` · 模型耗时 ${s.latency.toFixed(1)}s`}`;
|
| 79 |
+
$('stage').replaceChildren(selected?.asset?img(selected):el('div',selected?'该图片文件缺失':'此步骤没有返回新图片','empty'));
|
| 80 |
+
const reset=s.actions.find(a=>a.resetToAttempt);
|
| 81 |
+
$('caption').textContent=selected?`${cameraName(selected.camera)} · ${selected.path} · 来源:transcript 第 ${selected.source} 行${phase==='after'&&reset?` · 已重置为尝试 ${reset.resetToAttempt}`:''}`:'日志未记录新图片;切换“决策前”查看最近观察。';
|
| 82 |
+
$('cameras').replaceChildren(...frames.map((f,n)=>{const b=el('button',undefined,'camera');b.setAttribute('aria-pressed',String(f===selected));if(f.asset)b.append(img(f));b.append(el('span',cameraName(f.camera)));b.onclick=()=>{camera=f.camera;selectedFrameKey=`${f.path}@${f.source}`;render();};return b;}));
|
| 83 |
+
$('observation-note').textContent=`最近一次收到 ${s.before.length} 张图片${s.requestImages==null?'':`;本次请求记录共 ${s.requestImages} 张图片(含历史)`}。`;
|
| 84 |
+
$('input-text').textContent=s.inputText||'没有记录输入文本。';
|
| 85 |
+
$('actions').replaceChildren(...s.actions.map(a=>{const box=el('div');box.append(el('div',a.name,'subtle'),el('pre',fmt(a.arguments)));return box;}));
|
| 86 |
+
if(!s.actions.length)$('actions').append(el('p','本步没有工具调用,Agent 输出最终报告。'));
|
| 87 |
+
$('results').replaceChildren();
|
| 88 |
+
if(s.verdict){$('results').append(el('div',s.verdict.success?'✓ 本次尝试成功':'↻ 本次尝试失败',`result-message ${s.verdict.success?'success':'failed'}`),el('p',s.verdict.feedback));}
|
| 89 |
+
for(const a of s.actions){
|
| 90 |
+
if(!s.verdict)$('results').append(el('div',a.result===null?'等待结果 / 日志缺失':a.ok===false?'工具返回错误':'工具已返回',`result-message ${a.ok===false?'failed':''}`));
|
| 91 |
+
if(a.resetToAttempt)$('results').append(el('div',`场景已重置:返回图片属于第 ${a.resetToAttempt} 次尝试。`,'notice'));
|
| 92 |
+
const d=el('details');d.append(el('summary',`${a.name} · 完整返回`),el('pre',a.result===null?'未记录':fmt(a.result)));$('results').append(d);
|
| 93 |
+
}
|
| 94 |
+
if(!s.actions.length)$('results').append(el('p','最终文字报告;结果以尝试判定为准。'));
|
| 95 |
+
const notices=[...s.notices,...(s.noticesAfter||[])];$('notices').replaceChildren(...notices.map(n=>el('div',`${n.kind==='api_error'?'API 重试':'运行中断'} · ${n.text}`,'notice')));
|
| 96 |
+
$('count').textContent=`${String(index+1).padStart(2,'0')} / ${r.steps.length}`;$('scrubber').value=index;$('prev').disabled=index===0;$('next').disabled=index===r.steps.length-1;
|
| 97 |
+
$('step-meta').textContent=`turn ${s.turn??'—'} · ${s.actions.length} 次工具调用${s.incomplete?' · 结果不完整':''}`;
|
| 98 |
+
[...$('filmstrip').children].forEach((b,n)=>b.setAttribute('aria-pressed',String(n===index)));
|
| 99 |
+
const selectedButton=$('filmstrip').children[index];if(selectedButton){const strip=$('filmstrip'),a=selectedButton.getBoundingClientRect(),b=strip.getBoundingClientRect();if(a.left<b.left||a.right>b.right)strip.scrollLeft+=a.left-b.left-strip.clientWidth/2+selectedButton.offsetWidth/2;}
|
| 100 |
+
}
|
| 101 |
+
$('prev').onclick=()=>move(index-1);$('next').onclick=()=>move(index+1);$('scrubber').oninput=e=>move(Number(e.target.value));
|
| 102 |
+
$('before').onclick=()=>{phase='before';render();};$('after').onclick=()=>{phase='after';render();};
|
| 103 |
+
$('play').onclick=()=>{if(timer){stop();return;}if(index===run().steps.length-1)move(0);$('play').textContent='Ⅱ 暂停';$('play').setAttribute('aria-label','暂停回放');timer=setInterval(()=>{if(index>=run().steps.length-1){stop();return;}move(index+1,false);if(index===run().steps.length-1)stop();},Number($('speed').value));};
|
| 104 |
+
$('speed').onchange=()=>{if(timer){stop();$('play').click();}};
|
| 105 |
+
$('video-tab').onclick=()=>setMode('video');$('steps-tab').onclick=()=>setMode('steps');
|
| 106 |
+
$('video-rate').onchange=e=>{$('execution-video').playbackRate=Number(e.target.value);};
|
| 107 |
+
$('execution-video').onerror=()=>{if(!run().video)return;$('video-error').textContent='视频加载失败,请刷新重试;仍可查看逐步输入与日志。';$('video-error').hidden=false;};
|
| 108 |
+
document.addEventListener('keydown',e=>{if(viewMode==='video')return;if(e.target.closest('input,select,textarea,button,summary'))return;if(e.key==='ArrowLeft'){e.preventDefault();move(index-1);}if(e.key==='ArrowRight'){e.preventDefault();move(index+1);}if(e.code==='Space'&&viewMode==='steps'){e.preventDefault();$('play').click();}});
|
| 109 |
+
renderRun();render();
|
| 110 |
+
</script>
|
| 111 |
+
</body></html>
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/claude_batch.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch bookkeeping for Claude-subagent policy runs.
|
| 2 |
+
|
| 3 |
+
start python scripts/claude_batch.py start --batch exp1 --model sonnet --tasks t1:s1,s2 t2:s1 --k 3 --port0 9000
|
| 4 |
+
-> starts one server per (task, seed, condition) run and writes runs/claude/<batch>/manifest.json
|
| 5 |
+
conditions: harness = memory full + feedback (default F1) + k attempts in one agent;
|
| 6 |
+
noharness = k independent single-attempt agents (memory none, k=1)
|
| 7 |
+
usage python scripts/claude_batch.py usage --batch exp1 --run <run> --agent <agentId> --tokens N --ms N --tools N
|
| 8 |
+
audit python scripts/claude_batch.py audit --batch exp1 (runs audit_subagent on every recorded agent)
|
| 9 |
+
table python scripts/claude_batch.py table --batch exp1 [--batch exp2 ...]
|
| 10 |
+
stop python scripts/claude_batch.py stop --batch exp1
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import glob
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
|
| 19 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 20 |
+
RUNS = os.path.join(ROOT, "runs", "claude")
|
| 21 |
+
RUNS_DIR_DEFAULT = RUNS
|
| 22 |
+
TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (<agentId>.output files)
|
| 23 |
+
|
| 24 |
+
PLAYER_PROMPT = """You are controlling a simulated robot arm. Everything you need is in the directory {sb}
|
| 25 |
+
|
| 26 |
+
Rules (strict):
|
| 27 |
+
- First read {sb}/README.md — it explains the robot, the coordinate frames, the cameras, the commands and your task.
|
| 28 |
+
- Control the robot only by running shell commands of the form:
|
| 29 |
+
cd {sb} && ./robot <command> key=value ...
|
| 30 |
+
Run one robot command per shell call.
|
| 31 |
+
- Look at camera images only with your file-reading tool on the image paths the robot prints (they are inside that directory's obs/ folder).
|
| 32 |
+
- Do not read, list, search or execute anything else on this machine: no other files or directories, no other programs, no scripts of your own, no web access. Only README.md, the obs/ images and ./robot.
|
| 33 |
+
- Keep going until a robot command tells you to stop or that the episode is over.
|
| 34 |
+
|
| 35 |
+
When you are told to stop, reply with a short report: what you did (key commands and parameter values), what you observed, any feedback you got, and how you changed your approach."""
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
PLAYER_PROMPT_LA = """You are controlling a simulated robot arm. Your workspace is the directory {sb}
|
| 39 |
+
|
| 40 |
+
Rules (strict):
|
| 41 |
+
- First read {sb}/README.md: it explains the robot, the commands, the observation files and your task.
|
| 42 |
+
- Every shell call must be exactly one of these forms, with nothing chained before or after it:
|
| 43 |
+
cd {sb} && ./robot <command> key=value ...
|
| 44 |
+
cd {sb} && ./shell '<bash command>'
|
| 45 |
+
cd {sb} && ./shell <<'EOF'
|
| 46 |
+
<multi-line bash command, e.g. a python3 heredoc>
|
| 47 |
+
EOF
|
| 48 |
+
./robot runs one robot command. ./shell runs your command inside the workspace (ls, python3 with numpy / scipy /
|
| 49 |
+
Pillow / OpenCV, writing your own notes or scripts, ...); it has no network and cannot control the robot.
|
| 50 |
+
- Use your file-reading tool to look at images and other files, and your file-writing tools if you want, but only on
|
| 51 |
+
files inside {sb}.
|
| 52 |
+
- Do not read, list, search or execute anything else on this machine, do not use any other tool, no web access.
|
| 53 |
+
- Keep going until a robot command tells you to stop or that the episode is over.
|
| 54 |
+
|
| 55 |
+
When you are told to stop, reply with a short report: what you did (key commands and parameter values), what you
|
| 56 |
+
observed, any feedback you got, and how you changed your approach."""
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
THINK_ALOUD = """
|
| 60 |
+
|
| 61 |
+
Think aloud (for the experiment log): before every ./robot command, first write one to three plain sentences as
|
| 62 |
+
normal text (not inside a tool call): what you currently see or know, what you conclude from it, and what the next
|
| 63 |
+
command is meant to achieve. After each attempt ends, also write what you think went wrong (or right) and what you
|
| 64 |
+
will change. Keep these notes short and factual."""
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def manifest_path(batch):
|
| 68 |
+
return os.path.join(RUNS, batch, "manifest.json")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def load(batch):
|
| 72 |
+
with open(manifest_path(batch)) as f:
|
| 73 |
+
return json.load(f)
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def save(batch, m):
|
| 77 |
+
os.makedirs(os.path.dirname(manifest_path(batch)), exist_ok=True)
|
| 78 |
+
with open(manifest_path(batch), "w") as f:
|
| 79 |
+
json.dump(m, f, indent=1)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def port_free(port):
|
| 83 |
+
import socket
|
| 84 |
+
with socket.socket() as so:
|
| 85 |
+
try:
|
| 86 |
+
so.bind(("127.0.0.1", port))
|
| 87 |
+
return True
|
| 88 |
+
except OSError:
|
| 89 |
+
return False
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def start_one(task, seed, mem, k, port, tag, perception="depth", video=False, style="v1", extra="", feedback="F1"):
|
| 93 |
+
env = dict(os.environ, LFF_RUNS_DIR=os.environ.get("LFF_RUNS_DIR", RUNS_DIR_DEFAULT), LFF_STYLE=style, LFF_EXTRA_ARGS=extra)
|
| 94 |
+
out = subprocess.run(["bash", os.path.join(ROOT, "scripts", "start_robot_session.sh"), task, str(seed), mem, feedback,
|
| 95 |
+
str(port), "direct", str(k), tag, perception, "1" if video else "0"], capture_output=True, text=True,
|
| 96 |
+
env=env)
|
| 97 |
+
kv = dict(line.split("=", 1) for line in out.stdout.strip().splitlines() if "=" in line and line.split("=")[0] in ("SANDBOX", "LOG"))
|
| 98 |
+
if "SANDBOX" not in kv:
|
| 99 |
+
raise RuntimeError(out.stdout + out.stderr)
|
| 100 |
+
return kv["SANDBOX"], kv["LOG"]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def cmd_start(a):
|
| 104 |
+
m = load(a.batch) if os.path.exists(manifest_path(a.batch)) else dict(batch=a.batch, runs=[])
|
| 105 |
+
port = a.port0
|
| 106 |
+
used = {r["port"] for r in m["runs"]}
|
| 107 |
+
for spec in a.tasks:
|
| 108 |
+
task, seeds = spec.split(":")
|
| 109 |
+
for seed in seeds.split(","):
|
| 110 |
+
conds = [("harness", "full", a.k, 0)] + [("noharness", "none", 1, i) for i in range(a.k)]
|
| 111 |
+
for cond, mem, k, rep in conds:
|
| 112 |
+
if a.only and cond != a.only:
|
| 113 |
+
continue
|
| 114 |
+
while port in used or not port_free(port):
|
| 115 |
+
port += 1
|
| 116 |
+
hide_k = bool(a.hide_k and cond == "harness")
|
| 117 |
+
tag = (f"{a.batch}-{a.model}-{cond}{rep if cond == 'noharness' else ''}" + ("-nominal" if a.nominal else "")
|
| 118 |
+
+ ("-hidek" if hide_k else "") + (f"-arm{a.arm}" if a.arm != "none" else "")
|
| 119 |
+
+ ("-dossier" if a.dossier else ""))
|
| 120 |
+
extra = (("--agent-iface cli" if a.style == "la" else "") + (" --nominal" if a.nominal else "")
|
| 121 |
+
+ (" --hide-k" if hide_k else "") + (f" --arm {a.arm}" if a.arm != "none" else "")
|
| 122 |
+
+ (f" --dossier {os.path.abspath(a.dossier)}" if a.dossier else ""))
|
| 123 |
+
os.environ["LFF_RUNS_DIR"] = os.path.join(RUNS, a.batch)
|
| 124 |
+
sb, log = start_one(task, int(seed), mem, k, port, tag, a.perception, a.video, a.style, extra.strip(), a.feedback)
|
| 125 |
+
used.add(port)
|
| 126 |
+
r = dict(run=os.path.basename(log), task=task, seed=int(seed), model=a.model, cond=cond, rep=rep, k=k,
|
| 127 |
+
port=port, sandbox=sb, log=log, perception=a.perception, video=a.video, style=a.style,
|
| 128 |
+
nominal=a.nominal, feedback=a.feedback, think_aloud=a.think_aloud, hide_k=hide_k,
|
| 129 |
+
arm=a.arm, dossier=os.path.abspath(a.dossier) if a.dossier else "",
|
| 130 |
+
prompt=(PLAYER_PROMPT_LA if a.style == "la" else PLAYER_PROMPT).format(sb=sb)
|
| 131 |
+
+ (THINK_ALOUD if a.think_aloud else ""))
|
| 132 |
+
m["runs"].append(r)
|
| 133 |
+
print(json.dumps({k_: r[k_] for k_ in ("run", "sandbox")}), flush=True)
|
| 134 |
+
save(a.batch, m)
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def cmd_usage(a):
|
| 138 |
+
m = load(a.batch)
|
| 139 |
+
for r in m["runs"]:
|
| 140 |
+
if r["run"] == a.run or r["sandbox"] == a.run:
|
| 141 |
+
r.update(agent=a.agent, tokens=a.tokens, ms=a.ms, tool_uses=a.tools)
|
| 142 |
+
save(a.batch, m)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def cmd_audit(a):
|
| 146 |
+
m = load(a.batch)
|
| 147 |
+
for r in m["runs"]:
|
| 148 |
+
if not r.get("agent"):
|
| 149 |
+
continue
|
| 150 |
+
tr = os.path.join(TRANSCRIPTS, f"{r['agent']}.output")
|
| 151 |
+
if not os.path.exists(tr):
|
| 152 |
+
r["audit"] = "transcript missing"
|
| 153 |
+
continue
|
| 154 |
+
out = subprocess.run([sys.executable, os.path.join(ROOT, "scripts", "audit_subagent.py"), tr, r["sandbox"],
|
| 155 |
+
"--out", os.path.join(r["log"], "audit.json")] + (["--la"] if r.get("style") == "la" else []),
|
| 156 |
+
capture_output=True, text=True)
|
| 157 |
+
res = json.loads(out.stdout)
|
| 158 |
+
r["audit"] = dict(n_calls=res["n_calls"], n_violations=res["n_violations"])
|
| 159 |
+
if res["n_violations"]:
|
| 160 |
+
print(r["run"], res["violations"][:3])
|
| 161 |
+
save(a.batch, m)
|
| 162 |
+
print("audited", sum(1 for r in m["runs"] if r.get("audit")))
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def run_stats(r):
|
| 166 |
+
ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
|
| 167 |
+
if r.get("only_attempt"): # one attempt of a run (api_batch --memfree followup: attempt 1 of a history run)
|
| 168 |
+
ev = [e for e in ev if e.get("attempt") == r["only_attempt"]]
|
| 169 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 170 |
+
http = [e for e in ev if e["ev"] == "http"]
|
| 171 |
+
calls = [e for e in ev if e["ev"] == "call"]
|
| 172 |
+
first = next((d["attempt"] for d in dones if d["success"]), None)
|
| 173 |
+
think = [h["think_s"] for h in http if h.get("think_s") is not None]
|
| 174 |
+
srv = [h["server_s"] for h in http]
|
| 175 |
+
t0 = http[0]["t_recv"] if http else None
|
| 176 |
+
t1 = http[-1]["t_send"] if http else None
|
| 177 |
+
return dict(attempts=len(dones), first_success=first, n_calls=len(calls), n_http=len(http),
|
| 178 |
+
think_s=sum(think), server_s=sum(srv), wall_s=(t1 - t0) if t0 else None,
|
| 179 |
+
think_per_cmd=(sum(think) / len(think)) if think else None,
|
| 180 |
+
outcomes=[(d["attempt"], d["success"], d.get("feedback", "")) for d in dones])
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def cmd_table(a):
|
| 184 |
+
rows = []
|
| 185 |
+
for b in a.batch:
|
| 186 |
+
for r in load(b)["runs"]:
|
| 187 |
+
try:
|
| 188 |
+
st = run_stats(r)
|
| 189 |
+
except FileNotFoundError:
|
| 190 |
+
continue
|
| 191 |
+
rows.append(dict(r, **st))
|
| 192 |
+
import collections
|
| 193 |
+
# group: (task, model) -> harness runs / noharness groups by seed
|
| 194 |
+
g = collections.defaultdict(lambda: dict(h=[], n=collections.defaultdict(list)))
|
| 195 |
+
for x in rows:
|
| 196 |
+
key = (x["task"], x["model"])
|
| 197 |
+
if x["cond"] == "harness":
|
| 198 |
+
g[key]["h"].append(x)
|
| 199 |
+
else:
|
| 200 |
+
g[key]["n"][x["seed"]].append(x)
|
| 201 |
+
lines = ["| task | model | n | harness @1 | harness @k | no-harness @1 | no-harness @k (k indep.) | think s/cmd | cmds/attempt | wall min/run (harness) |",
|
| 202 |
+
"|---|---|---|---|---|---|---|---|---|---|"]
|
| 203 |
+
tot = collections.defaultdict(lambda: [0, 0, 0, 0, 0])
|
| 204 |
+
for (task, model), d in sorted(g.items()):
|
| 205 |
+
H = [x for x in d["h"] if x["attempts"] > 0]
|
| 206 |
+
K = max([x["k"] for x in H] or [3])
|
| 207 |
+
h1 = sum(1 for x in H if x["first_success"] == 1)
|
| 208 |
+
hk = sum(1 for x in H if x["first_success"] is not None)
|
| 209 |
+
seeds = [s for s, xs in d["n"].items() if all(x["attempts"] > 0 for x in xs)]
|
| 210 |
+
n1 = sum(1 for s in seeds if sorted(d["n"][s], key=lambda x: x["rep"])[0]["first_success"])
|
| 211 |
+
nk = sum(1 for s in seeds if any(x["first_success"] for x in d["n"][s]))
|
| 212 |
+
allx = H + [x for s in seeds for x in d["n"][s] if not x.get("only_attempt")] # attempt 1 counted in H
|
| 213 |
+
th = [x["think_per_cmd"] for x in allx if x["think_per_cmd"]]
|
| 214 |
+
cpa = [x["n_calls"] / max(x["attempts"], 1) for x in allx]
|
| 215 |
+
wall = [x["wall_s"] / 60 for x in H if x["wall_s"]]
|
| 216 |
+
f = lambda v: f"{sum(v) / len(v):.1f}" if v else "—"
|
| 217 |
+
lines.append(f"| {task} | {model} | {len(H)}/{len(seeds)} | {h1}/{len(H)} | {hk}/{len(H)} | {n1}/{len(seeds)} | "
|
| 218 |
+
f"{nk}/{len(seeds)} | {f(th)} | {f(cpa)} | {f(wall)} |")
|
| 219 |
+
t = tot[model]
|
| 220 |
+
t[0] += h1; t[1] += hk; t[2] += len(H); t[3] += nk; t[4] += len(seeds)
|
| 221 |
+
for model, t in tot.items():
|
| 222 |
+
lines.append(f"| **all** | {model} | | {t[0]}/{t[2]} | {t[1]}/{t[2]} | | {t[3]}/{t[4]} | | | |")
|
| 223 |
+
print("\n".join(lines))
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def cmd_restart(a):
|
| 227 |
+
"""Re-run interrupted runs from scratch: stop the old server, start a fresh one (new sandbox, new port),
|
| 228 |
+
keep the old entry under 'superseded'."""
|
| 229 |
+
m = load(a.batch)
|
| 230 |
+
used = {r["port"] for r in m["runs"]}
|
| 231 |
+
port = a.port0
|
| 232 |
+
for i, r in enumerate(list(m["runs"])):
|
| 233 |
+
if r["run"] not in a.runs:
|
| 234 |
+
continue
|
| 235 |
+
try:
|
| 236 |
+
os.kill(int(open(os.path.join(r["log"], "server.pid")).read()), 15)
|
| 237 |
+
except (ProcessLookupError, FileNotFoundError):
|
| 238 |
+
pass
|
| 239 |
+
while port in used or not port_free(port):
|
| 240 |
+
port += 1
|
| 241 |
+
mem = "full" if r["cond"] == "harness" else "none"
|
| 242 |
+
tag = f"{a.batch}-{r['model']}-{r['cond']}{r['rep'] if r['cond'] == 'noharness' else ''}"
|
| 243 |
+
if r.get("style") == "la":
|
| 244 |
+
os.environ["LFF_RUNS_DIR"] = os.path.dirname(r["log"])
|
| 245 |
+
extra = (("--agent-iface cli" if r.get("style") == "la" else "") + (" --nominal" if r.get("nominal") else "")
|
| 246 |
+
+ (" --hide-k" if r.get("hide_k") else "")
|
| 247 |
+
+ (f" --arm {r['arm']}" if r.get("arm", "none") != "none" else "")
|
| 248 |
+
+ (f" --dossier {r['dossier']}" if r.get("dossier") else ""))
|
| 249 |
+
tag += ("-hidek" if r.get("hide_k") else "") + (f"-arm{r['arm']}" if r.get("arm", "none") != "none" else "") \
|
| 250 |
+
+ ("-dossier" if r.get("dossier") else "")
|
| 251 |
+
sb, log = start_one(r["task"], r["seed"], mem, r["k"], port, tag, r.get("perception", "depth"), r.get("video", False),
|
| 252 |
+
r.get("style", "v1"), extra.strip(), r.get("feedback", "F2"))
|
| 253 |
+
used.add(port)
|
| 254 |
+
new = {k: v for k, v in r.items() if k not in ("agent", "tokens", "ms", "tool_uses", "audit")}
|
| 255 |
+
new.update(run=os.path.basename(log), port=port, sandbox=sb, log=log,
|
| 256 |
+
prompt=(PLAYER_PROMPT_LA if r.get("style") == "la" else PLAYER_PROMPT).format(sb=sb))
|
| 257 |
+
m.setdefault("superseded", []).append(dict(r, reason=a.reason))
|
| 258 |
+
m["runs"][i] = new
|
| 259 |
+
print(json.dumps(dict(run=new["run"], sandbox=sb)))
|
| 260 |
+
save(a.batch, m)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def cmd_stop(a):
|
| 264 |
+
for r in load(a.batch)["runs"]:
|
| 265 |
+
pid = os.path.join(r["log"], "server.pid")
|
| 266 |
+
if os.path.exists(pid):
|
| 267 |
+
try:
|
| 268 |
+
os.kill(int(open(pid).read()), 15)
|
| 269 |
+
except ProcessLookupError:
|
| 270 |
+
pass
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def main():
|
| 274 |
+
ap = argparse.ArgumentParser()
|
| 275 |
+
sub = ap.add_subparsers(dest="cmd")
|
| 276 |
+
s = sub.add_parser("start"); s.add_argument("--batch", required=True); s.add_argument("--model", required=True)
|
| 277 |
+
s.add_argument("--tasks", nargs="+", required=True); s.add_argument("--k", type=int, default=3)
|
| 278 |
+
s.add_argument("--port0", type=int, default=9000); s.add_argument("--only", choices=["harness", "noharness"])
|
| 279 |
+
s.add_argument("--perception", default="depth", choices=["depth", "rgb", "rgbd"]); s.add_argument("--video", action="store_true")
|
| 280 |
+
s.add_argument("--style", default="v1", choices=["v1", "v2", "la"])
|
| 281 |
+
s.add_argument("--nominal", action="store_true", help="L1 control: hidden calibration error removed")
|
| 282 |
+
s.add_argument("--arm", default="none", choices=["none", "h0", "hplus", "twin"],
|
| 283 |
+
help="full5 controlled arm (lffbench/arm_specs/<task>.py), passed to every run of this call")
|
| 284 |
+
s.add_argument("--dossier", default="",
|
| 285 |
+
help="la, single task:seed per call: earlier-attempt record (scripts/make_dossier.py) copied to history/")
|
| 286 |
+
s.add_argument("--hide-k", action="store_true",
|
| 287 |
+
help="harness runs: README says 1 attempt (same as the independent run); the other k-1 attempts are "
|
| 288 |
+
"announced only after a failure")
|
| 289 |
+
s.add_argument("--think-aloud", action="store_true",
|
| 290 |
+
help="append a request to write 1-3 plain sentences before every robot command (the transcript keeps no "
|
| 291 |
+
"thinking text, so this is the only way to record the agent's reasoning); changes the prompt")
|
| 292 |
+
s.add_argument("--feedback", default="F1", choices=["F0", "F1", "F2"],
|
| 293 |
+
help="after a failed attempt: F1 = success/failure only (default since 2026-10-08); F2 = measured error "
|
| 294 |
+
"(privileged; neither LIBERO-Agent nor RoboDojo gives it), ablation only")
|
| 295 |
+
u = sub.add_parser("usage"); u.add_argument("--batch", required=True); u.add_argument("--run", required=True)
|
| 296 |
+
u.add_argument("--agent", required=True); u.add_argument("--tokens", type=int); u.add_argument("--ms", type=int)
|
| 297 |
+
u.add_argument("--tools", type=int)
|
| 298 |
+
au = sub.add_parser("audit"); au.add_argument("--batch", required=True)
|
| 299 |
+
t = sub.add_parser("table"); t.add_argument("--batch", nargs="+", required=True)
|
| 300 |
+
st = sub.add_parser("stop"); st.add_argument("--batch", required=True)
|
| 301 |
+
rs = sub.add_parser("restart"); rs.add_argument("--batch", required=True); rs.add_argument("--runs", nargs="+", required=True)
|
| 302 |
+
rs.add_argument("--port0", type=int, default=9300)
|
| 303 |
+
rs.add_argument("--reason", default="interrupted (rate limit)")
|
| 304 |
+
a = ap.parse_args()
|
| 305 |
+
dict(start=cmd_start, usage=cmd_usage, audit=cmd_audit, table=cmd_table, stop=cmd_stop, restart=cmd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| 3 |
+
|
| 4 |
+
Input: the unified LeRobot v3 release named by /mnt/cpfs/shared/datasets/lffbench_agent_replays/CURRENT.json, plus any
|
| 5 |
+
package it does not hold yet (--extra-source). Output: one LeRobot v2.1 dataset with the feature names of openpi's LIBERO
|
| 6 |
+
config (image, wrist_image, state, actions), one episode per successful attempt:
|
| 7 |
+
|
| 8 |
+
- only frames of attempts judged successful, without the evaluator's outcome check (annotation.phase == 2);
|
| 9 |
+
- a multi-attempt `within` episode gives one clip per successful attempt, so action chunks never cross attempts;
|
| 10 |
+
- the safety routine of l6_sequence_resume's emergency stop drives the arm without the agent, so it is cut out;
|
| 11 |
+
- one instance per task is held out by (task, seed) and written to a separate dataset, never to the training one;
|
| 12 |
+
- videos are remuxed packet by packet from the published files: the pixels are the validated ones, nothing is re-encoded.
|
| 13 |
+
|
| 14 |
+
python scripts/lerobot_sft_dataset.py build --out DIR --repo-id lff_sft_vX --holdout sets/main_v2_3inst.txt [--holdout-seed task:seed ...]
|
| 15 |
+
python scripts/lerobot_sft_dataset.py verify DIR/<repo-id> # in the OpenPI environment: reads through its LeRobot
|
| 16 |
+
python scripts/lerobot_sft_dataset.py norm DIR/<repo-id> --assets <assets_base_dir>/pi05_lff/<repo-id>
|
| 17 |
+
|
| 18 |
+
Run with an environment that has av and pyarrow (shared/envs/openpi-ppu20).
|
| 19 |
+
"""
|
| 20 |
+
import argparse
|
| 21 |
+
import collections
|
| 22 |
+
import functools
|
| 23 |
+
import glob
|
| 24 |
+
import json
|
| 25 |
+
import multiprocessing
|
| 26 |
+
import os
|
| 27 |
+
import random
|
| 28 |
+
import time
|
| 29 |
+
from concurrent.futures import ProcessPoolExecutor
|
| 30 |
+
|
| 31 |
+
import av
|
| 32 |
+
import numpy as np
|
| 33 |
+
import pyarrow as pa
|
| 34 |
+
import pyarrow.parquet as pq
|
| 35 |
+
|
| 36 |
+
DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays"
|
| 37 |
+
FPS = 20
|
| 38 |
+
CAMERAS = {"image": "observation.images.image", "wrist_image": "observation.images.wrist_image"}
|
| 39 |
+
CHUNK = 1000
|
| 40 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def sources(extra):
|
| 44 |
+
"""The canonical release, which already merges the earlier packages, and what it does not hold yet."""
|
| 45 |
+
return [json.load(open(os.path.join(DATA, "CURRENT.json")))["dataset"]] + list(extra or [])
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def read_holdout(path, extra):
|
| 49 |
+
out = {}
|
| 50 |
+
if path:
|
| 51 |
+
for line in open(path):
|
| 52 |
+
if line.strip() and not line.startswith("#"):
|
| 53 |
+
t, s = line.strip().split(":")
|
| 54 |
+
out[t] = {int(x) for x in s.split(",")}
|
| 55 |
+
for item in extra or []:
|
| 56 |
+
t, s = item.split(":")
|
| 57 |
+
out[t] = {int(x) for x in s.split(",")}
|
| 58 |
+
return out
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def plan_source(name, only_task=None):
|
| 62 |
+
"""Successful attempts of one published dataset, as frame ranges inside its episodes."""
|
| 63 |
+
p = os.path.join(DATA, name)
|
| 64 |
+
rows = {}
|
| 65 |
+
for line in open(os.path.join(p, "lff/episodes.jsonl")):
|
| 66 |
+
r = json.loads(line)
|
| 67 |
+
if any(r["success"]) and (not only_task or r["task"] in only_task):
|
| 68 |
+
rows[r["episode_index"]] = r
|
| 69 |
+
if not rows:
|
| 70 |
+
return [], collections.Counter()
|
| 71 |
+
meta = []
|
| 72 |
+
for f in sorted(glob.glob(os.path.join(p, "meta/episodes/chunk-*/file-*.parquet"))):
|
| 73 |
+
keep = ["episode_index", "length", "dataset_from_index"]
|
| 74 |
+
for key in CAMERAS.values():
|
| 75 |
+
keep += [f"videos/{key}/chunk_index", f"videos/{key}/file_index", f"videos/{key}/from_timestamp"]
|
| 76 |
+
meta += pq.read_table(f, columns=keep).to_pylist()
|
| 77 |
+
meta = {m["episode_index"]: m for m in meta}
|
| 78 |
+
cols = ["index", "episode_index", "frame_index", "annotation.attempt_index", "annotation.phase", "annotation.attempt_success",
|
| 79 |
+
"annotation.command_index", "action"]
|
| 80 |
+
keep, located, stops = {}, {}, {}
|
| 81 |
+
for f in sorted(glob.glob(os.path.join(p, "data/chunk-*/file-*.parquet"))):
|
| 82 |
+
t = pq.read_table(f, columns=cols)
|
| 83 |
+
ep = t["episode_index"].to_numpy().reshape(-1)
|
| 84 |
+
fr = t["frame_index"].to_numpy().reshape(-1)
|
| 85 |
+
att = t["annotation.attempt_index"].to_numpy().reshape(-1)
|
| 86 |
+
ph = t["annotation.phase"].to_numpy().reshape(-1)
|
| 87 |
+
su = t["annotation.attempt_success"].to_numpy().reshape(-1)
|
| 88 |
+
cmd = t["annotation.command_index"].to_numpy().reshape(-1)
|
| 89 |
+
grip = np.stack(t["action"].to_numpy(zero_copy_only=False))[:, 6]
|
| 90 |
+
first_index = int(t["index"][0].as_py())
|
| 91 |
+
for e in np.unique(ep):
|
| 92 |
+
if int(e) not in rows:
|
| 93 |
+
continue
|
| 94 |
+
located[int(e)] = (f, first_index)
|
| 95 |
+
m = (ep == e) & (su == 1) & (ph != 2)
|
| 96 |
+
for a in np.unique(att[m]):
|
| 97 |
+
ix = np.sort(fr[m & (att == a)])
|
| 98 |
+
keep[(int(e), int(a))] = ix
|
| 99 |
+
if rows[int(e)]["task"] == "l6_sequence_resume":
|
| 100 |
+
o = np.flatnonzero(ep == e)
|
| 101 |
+
o = o[np.argsort(fr[o])]
|
| 102 |
+
stops[int(e)] = emergency_stops(fr[o], att[o], cmd[o], ph[o], grip[o])
|
| 103 |
+
clips, stats = [], collections.Counter()
|
| 104 |
+
for (e, a), ix in sorted(keep.items()):
|
| 105 |
+
r = rows[e]
|
| 106 |
+
spans = [(int(ix[0]), int(ix[-1]) + 1)]
|
| 107 |
+
if not (np.diff(ix) == 1).all():
|
| 108 |
+
raise ValueError(f"{name} episode {e} attempt {a}: frames are not contiguous")
|
| 109 |
+
for s_att, cut0, cut1 in stops.get(e, []):
|
| 110 |
+
if s_att == a:
|
| 111 |
+
stats["emergency_frames_cut"] += cut1 - cut0
|
| 112 |
+
spans = [x for x in ((spans[0][0], cut0), (cut1, spans[0][1])) if x[1] > x[0]]
|
| 113 |
+
for s0, s1 in spans:
|
| 114 |
+
clips.append(dict(source=name, episode=e, attempt=a, start=s0, stop=s1, task=r["task"], seed=r["seed"], run=r["run"], batch=r["batch"],
|
| 115 |
+
model=r["model"], condition=r["condition"], protocol=r["protocol"], instruction=r["instruction"], cause=r["paper_cause"],
|
| 116 |
+
first_attempt=a == 1, run_outcome_class=r.get("run_outcome_class"),
|
| 117 |
+
videos={cam: dict(chunk=meta[e][f"videos/{key}/chunk_index"], file=meta[e][f"videos/{key}/file_index"],
|
| 118 |
+
t0=meta[e][f"videos/{key}/from_timestamp"]) for cam, key in CAMERAS.items()},
|
| 119 |
+
ep_from=meta[e]["dataset_from_index"], data_file=located[e][0], data_first_index=located[e][1]))
|
| 120 |
+
return clips, stats
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def emergency_stops(frame, attempt, command, phase, grip):
|
| 124 |
+
"""l6_sequence_resume's emergency stop opens the jaws in the middle of a move and then drives the arm home until that
|
| 125 |
+
command returns; an agent's move never changes the gripper while it moves. So the stop is where the gripper action
|
| 126 |
+
turns from close to open inside one motion command, and the routine is the rest of that command.
|
| 127 |
+
Returns [(attempt, first frame of the routine, end of the command)]."""
|
| 128 |
+
out = []
|
| 129 |
+
for i in range(1, len(frame)):
|
| 130 |
+
if phase[i] == 0 == phase[i - 1] and command[i] == command[i - 1] and attempt[i] == attempt[i - 1] \
|
| 131 |
+
and grip[i - 1] > 0 > grip[i]:
|
| 132 |
+
end = i
|
| 133 |
+
while end < len(frame) and command[end] == command[i] and attempt[end] == attempt[i]:
|
| 134 |
+
end += 1
|
| 135 |
+
out.append((int(attempt[i]), int(frame[i]), int(frame[end - 1]) + 1))
|
| 136 |
+
return out
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def remux(src, dst, f0, n, t0):
|
| 140 |
+
"""Copy n frames starting at file time t0 + f0/FPS without re-encoding. Returns (frames written, first frame kept):
|
| 141 |
+
a clip must start on a key frame, so a start between key frames moves to the next one."""
|
| 142 |
+
os.makedirs(os.path.dirname(dst), exist_ok=True)
|
| 143 |
+
tmp = dst + ".tmp.mp4"
|
| 144 |
+
with av.open(src) as ic:
|
| 145 |
+
s = ic.streams.video[0]
|
| 146 |
+
tb = s.time_base
|
| 147 |
+
first = int(round((t0 + f0 / FPS) / tb))
|
| 148 |
+
frame_pts = int(round(1 / (FPS * tb)))
|
| 149 |
+
ic.seek(first, stream=s, backward=True, any_frame=False)
|
| 150 |
+
with av.open(tmp, "w", format="mp4") as oc:
|
| 151 |
+
o = oc.add_stream_from_template(s, opaque=True) # packets are copied, so no encoder is involved
|
| 152 |
+
base, written = None, 0
|
| 153 |
+
for pkt in ic.demux(s):
|
| 154 |
+
if pkt.pts is None or pkt.pts < first:
|
| 155 |
+
continue
|
| 156 |
+
idx = int(round((pkt.pts - first) / frame_pts))
|
| 157 |
+
if idx >= n:
|
| 158 |
+
break
|
| 159 |
+
if base is None:
|
| 160 |
+
if not pkt.is_keyframe:
|
| 161 |
+
continue
|
| 162 |
+
base, kept = pkt.pts, idx
|
| 163 |
+
pkt.pts = pkt.pts - base
|
| 164 |
+
pkt.dts = pkt.dts - base
|
| 165 |
+
pkt.stream = o
|
| 166 |
+
oc.mux(pkt)
|
| 167 |
+
written += 1
|
| 168 |
+
os.replace(tmp, dst)
|
| 169 |
+
return written, kept
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@functools.lru_cache(maxsize=2)
|
| 173 |
+
def read_data_file(path):
|
| 174 |
+
return pq.read_table(path, columns=["observation.state", "action", "index", "episode_index", "annotation.attempt_success", "annotation.phase"])
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def write_clip(job):
|
| 178 |
+
"""One output episode: both videos, then the parquet of exactly the frames they hold."""
|
| 179 |
+
clip, ep, out = job
|
| 180 |
+
n = clip["stop"] - clip["start"]
|
| 181 |
+
chunk = ep // CHUNK
|
| 182 |
+
src = os.path.join(DATA, clip["source"])
|
| 183 |
+
results = {}
|
| 184 |
+
for cam, v in clip["videos"].items():
|
| 185 |
+
path = os.path.join(src, f"videos/{CAMERAS[cam]}/chunk-{v['chunk']:03d}/file-{v['file']:03d}.mp4")
|
| 186 |
+
results[cam] = remux(path, os.path.join(out, f"videos/chunk-{chunk:03d}/{cam}/episode_{ep:06d}.mp4"), clip["start"], n, v["t0"])
|
| 187 |
+
kept = {r[1] for r in results.values()}
|
| 188 |
+
if len(kept) != 1:
|
| 189 |
+
raise ValueError(f"cameras disagree on the first key frame: {results} ({clip['source']} {clip['episode']})")
|
| 190 |
+
skip = kept.pop()
|
| 191 |
+
length = results["image"][0]
|
| 192 |
+
if results["wrist_image"][0] != length or length != n - skip:
|
| 193 |
+
raise ValueError(f"frame count {results} != {n - skip} ({clip['source']} {clip['episode']})")
|
| 194 |
+
i0 = clip["ep_from"] + clip["start"] + skip
|
| 195 |
+
t = read_data_file(clip["data_file"]).slice(i0 - clip["data_first_index"], length)
|
| 196 |
+
if t.num_rows != length or int(t["index"][0].as_py()) != i0 or set(t["episode_index"].to_pylist()) != {clip["episode"]}:
|
| 197 |
+
raise ValueError(f"parquet slice mismatch ({clip['source']} {clip['episode']})")
|
| 198 |
+
if set(t["annotation.attempt_success"].to_pylist()) != {1} or 2 in set(t["annotation.phase"].to_pylist()):
|
| 199 |
+
raise ValueError(f"unexpected frame labels ({clip['source']} {clip['episode']})")
|
| 200 |
+
state = np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float32)
|
| 201 |
+
action = np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float32)
|
| 202 |
+
chunk_dir = os.path.join(out, f"videos/chunk-{chunk:03d}")
|
| 203 |
+
images = {cam: image_stats(os.path.join(chunk_dir, f"{cam}/episode_{ep:06d}.mp4"), length) for cam in CAMERAS}
|
| 204 |
+
return dict(ep=ep, length=length, skip=skip, state=state, action=action, image_stats=images)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def stats_of(a):
|
| 208 |
+
return dict(min=a.min(0).tolist(), max=a.max(0).tolist(), mean=a.mean(0).tolist(), std=a.std(0).tolist(), count=[len(a)])
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def image_stats(path, length, n=5):
|
| 212 |
+
"""Sampled image statistics for meta/episodes_stats.jsonl (LeRobot requires them, openpi does not use them)."""
|
| 213 |
+
frames = []
|
| 214 |
+
with av.open(path) as c:
|
| 215 |
+
s = c.streams.video[0]
|
| 216 |
+
for i in np.linspace(0, length - 1, min(n, length)).astype(int):
|
| 217 |
+
pts = int(round(i / FPS / s.time_base))
|
| 218 |
+
c.seek(pts, stream=s, backward=True)
|
| 219 |
+
for fr in c.decode(s):
|
| 220 |
+
if fr.pts >= pts:
|
| 221 |
+
frames.append(fr.to_ndarray(format="rgb24").astype(np.float32) / 255.0)
|
| 222 |
+
break
|
| 223 |
+
x = np.stack(frames).transpose(0, 3, 1, 2)
|
| 224 |
+
fmt = lambda v: [[[float(q)]] for q in v]
|
| 225 |
+
return dict(min=fmt(x.min((0, 2, 3))), max=fmt(x.max((0, 2, 3))), mean=fmt(x.mean((0, 2, 3))), std=fmt(x.std((0, 2, 3))), count=[len(frames)])
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def pool(workers):
|
| 229 |
+
"""Fresh interpreters: a forked worker inherits FFmpeg's state from a parent that decoded video and can deadlock."""
|
| 230 |
+
return ProcessPoolExecutor(workers, mp_context=multiprocessing.get_context("spawn"))
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def write_dataset(out, clips, workers):
|
| 234 |
+
os.makedirs(os.path.join(out, "meta"), exist_ok=True)
|
| 235 |
+
os.makedirs(os.path.join(out, "lff"), exist_ok=True)
|
| 236 |
+
tasks = sorted({c["instruction"] for c in clips})
|
| 237 |
+
task_index = {t: i for i, t in enumerate(tasks)}
|
| 238 |
+
clips = sorted(clips, key=lambda c: (c["task"], c["seed"], c["source"], c["episode"], c["start"]))
|
| 239 |
+
with pool(workers) as ex:
|
| 240 |
+
results = list(ex.map(write_clip, [(c, i, out) for i, c in enumerate(clips)], chunksize=4))
|
| 241 |
+
index, eps, ep_stats, prov = 0, [], [], []
|
| 242 |
+
for c, r in zip(clips, results):
|
| 243 |
+
ep, n = r["ep"], r["length"]
|
| 244 |
+
chunk = ep // CHUNK
|
| 245 |
+
ts = np.arange(n, dtype=np.float32) / FPS
|
| 246 |
+
table = pa.table({"state": list(r["state"]), "actions": list(r["action"]), "timestamp": ts, "frame_index": np.arange(n),
|
| 247 |
+
"episode_index": np.full(n, ep), "index": np.arange(index, index + n),
|
| 248 |
+
"task_index": np.full(n, task_index[c["instruction"]])})
|
| 249 |
+
p = os.path.join(out, f"data/chunk-{chunk:03d}/episode_{ep:06d}.parquet")
|
| 250 |
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
| 251 |
+
pq.write_table(table, p)
|
| 252 |
+
eps.append(dict(episode_index=ep, tasks=[c["instruction"]], length=n))
|
| 253 |
+
st = dict(state=stats_of(r["state"]), actions=stats_of(r["action"]),
|
| 254 |
+
timestamp=stats_of(ts[:, None]), frame_index=stats_of(np.arange(n)[:, None]),
|
| 255 |
+
episode_index=stats_of(np.full((n, 1), ep)), index=stats_of(np.arange(index, index + n)[:, None]),
|
| 256 |
+
task_index=stats_of(np.full((n, 1), task_index[c["instruction"]])))
|
| 257 |
+
st.update(r["image_stats"])
|
| 258 |
+
ep_stats.append(dict(episode_index=ep, stats=st))
|
| 259 |
+
prov.append(dict(episode_index=ep, index_from=index, length=n, source=c["source"], source_episode=c["episode"], attempt=c["attempt"],
|
| 260 |
+
source_frame_start=c["start"] + r["skip"], task=c["task"], seed=c["seed"], cause=c["cause"], model=c["model"],
|
| 261 |
+
run=c["run"], batch=c["batch"], condition=c["condition"], protocol=c["protocol"], first_attempt=c["first_attempt"],
|
| 262 |
+
run_outcome_class=c["run_outcome_class"]))
|
| 263 |
+
index += n
|
| 264 |
+
feat = lambda dtype, shape, names=None: dict(dtype=dtype, shape=shape, names=names)
|
| 265 |
+
video = dict(dtype="video", shape=[256, 256, 3], names=["height", "width", "channels"],
|
| 266 |
+
info={"video.height": 256, "video.width": 256, "video.codec": "av1", "video.pix_fmt": "yuv420p", "video.is_depth_map": False,
|
| 267 |
+
"video.fps": FPS, "video.channels": 3, "has_audio": False})
|
| 268 |
+
info = dict(codebase_version="v2.1", robot_type="franka_panda", total_episodes=len(clips), total_frames=index, total_tasks=len(tasks),
|
| 269 |
+
total_videos=2 * len(clips), total_chunks=(len(clips) - 1) // CHUNK + 1, chunks_size=CHUNK, fps=FPS, splits={"train": f"0:{len(clips)}"},
|
| 270 |
+
data_path="data/chunk-{episode_chunk:03d}/episode_{episode_index:06d}.parquet",
|
| 271 |
+
video_path="videos/chunk-{episode_chunk:03d}/{video_key}/episode_{episode_index:06d}.mp4",
|
| 272 |
+
features=dict(image=video, wrist_image=video,
|
| 273 |
+
state=feat("float32", [8], ["eef_x", "eef_y", "eef_z", "eef_rot_aa_x", "eef_rot_aa_y", "eef_rot_aa_z", "finger_qpos_left", "finger_qpos_right"]),
|
| 274 |
+
actions=feat("float32", [7], ["eef_delta_x", "eef_delta_y", "eef_delta_z", "eef_delta_rot_aa_x", "eef_delta_rot_aa_y", "eef_delta_rot_aa_z", "gripper_close"]),
|
| 275 |
+
timestamp=feat("float32", [1]), frame_index=feat("int64", [1]), episode_index=feat("int64", [1]), index=feat("int64", [1]),
|
| 276 |
+
task_index=feat("int64", [1])))
|
| 277 |
+
json.dump(info, open(os.path.join(out, "meta/info.json"), "w"), indent=1)
|
| 278 |
+
jsonl = lambda name, rows: open(os.path.join(out, name), "w").write("".join(json.dumps(r) + "\n" for r in rows))
|
| 279 |
+
jsonl("meta/tasks.jsonl", [dict(task_index=i, task=t) for i, t in enumerate(tasks)])
|
| 280 |
+
jsonl("meta/episodes.jsonl", eps)
|
| 281 |
+
jsonl("meta/episodes_stats.jsonl", ep_stats)
|
| 282 |
+
jsonl("lff/provenance.jsonl", prov)
|
| 283 |
+
return prov
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def summarize(prov):
|
| 287 |
+
per = collections.defaultdict(lambda: dict(episodes=0, frames=0, seeds=set()))
|
| 288 |
+
for p in prov:
|
| 289 |
+
d = per[p["task"]]
|
| 290 |
+
d["episodes"] += 1
|
| 291 |
+
d["frames"] += p["length"]
|
| 292 |
+
d["seeds"].add(p["seed"])
|
| 293 |
+
return {t: dict(episodes=d["episodes"], frames=d["frames"], seeds=sorted(d["seeds"])) for t, d in sorted(per.items())}
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def cmd_build(a):
|
| 297 |
+
holdout = read_holdout(a.holdout, a.holdout_seed)
|
| 298 |
+
names = sources(a.extra_source)
|
| 299 |
+
clips, stats = [], collections.Counter()
|
| 300 |
+
with pool(a.workers) as ex:
|
| 301 |
+
for c, s in ex.map(functools.partial(plan_source, only_task=a.only_task), names):
|
| 302 |
+
clips += c
|
| 303 |
+
stats.update(s)
|
| 304 |
+
seen =collections.Counter((c["run"], c["attempt"], c["start"]) for c in clips)
|
| 305 |
+
dups = [k for k, v in seen.items() if v > 1]
|
| 306 |
+
if dups:
|
| 307 |
+
raise SystemExit(f"{len(dups)} duplicate clips, e.g. {dups[:3]}")
|
| 308 |
+
no_holdout = sorted({c["task"] for c in clips} - set(holdout))
|
| 309 |
+
if no_holdout:
|
| 310 |
+
raise SystemExit(f"tasks without a held-out instance: {no_holdout}")
|
| 311 |
+
train = [c for c in clips if c["seed"] not in holdout[c["task"]]]
|
| 312 |
+
test = [c for c in clips if c["seed"] in holdout[c["task"]]]
|
| 313 |
+
report = dict(built_utc=time.strftime("%FT%TZ", time.gmtime()), sources=names, holdout={t: sorted(s) for t, s in holdout.items()},
|
| 314 |
+
emergency_frames_cut=stats["emergency_frames_cut"])
|
| 315 |
+
for split, group, repo in (("train", train, a.repo_id), ("heldout", test, a.repo_id + "_heldout")):
|
| 316 |
+
if split not in a.splits:
|
| 317 |
+
continue
|
| 318 |
+
out = os.path.join(a.out, repo)
|
| 319 |
+
if os.path.exists(os.path.join(out, "meta/info.json")):
|
| 320 |
+
raise SystemExit(f"{out} exists: datasets are not rewritten in place")
|
| 321 |
+
prov = write_dataset(out, group, a.workers)
|
| 322 |
+
report[split] = dict(repo_id=repo, episodes=len(prov), frames=sum(p["length"] for p in prov), tasks=len({p["task"] for p in prov}),
|
| 323 |
+
first_attempt=sum(p["first_attempt"] for p in prov), per_task=summarize(prov))
|
| 324 |
+
json.dump(report, open(os.path.join(out, "lff/build_report.json"), "w"), indent=1)
|
| 325 |
+
print(split, report[split]["episodes"], "episodes", report[split]["frames"], "frames", report[split]["tasks"], "tasks", flush=True)
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@functools.lru_cache(maxsize=64)
|
| 329 |
+
def source_meta(src):
|
| 330 |
+
"""Per episode metadata of one release, and (first index, path) of each of its data files."""
|
| 331 |
+
meta = {}
|
| 332 |
+
for mf in sorted(glob.glob(os.path.join(src, "meta/episodes/chunk-*/file-*.parquet"))):
|
| 333 |
+
keep = [c for c in pq.read_schema(mf).names if not c.startswith("stats/")]
|
| 334 |
+
for m in pq.read_table(mf, columns=keep).to_pylist():
|
| 335 |
+
meta[m["episode_index"]] = m
|
| 336 |
+
files = []
|
| 337 |
+
for df in sorted(glob.glob(os.path.join(src, "data/chunk-*/file-*.parquet"))):
|
| 338 |
+
files.append((int(pq.read_table(df, columns=["index"])["index"][0].as_py()), df))
|
| 339 |
+
return meta, files
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def source_frame(prov, t):
|
| 343 |
+
"""State, action and both camera frames of one output frame, read directly from the published release."""
|
| 344 |
+
src = os.path.join(DATA, prov["source"])
|
| 345 |
+
f = prov["source_frame_start"] + t
|
| 346 |
+
metas, files = source_meta(src)
|
| 347 |
+
meta = metas[prov["source_episode"]]
|
| 348 |
+
i = meta["dataset_from_index"] + f
|
| 349 |
+
first, df = [x for x in files if x[0] <= i][-1]
|
| 350 |
+
row = read_data_file(df).slice(i - first, 1).to_pylist()[0]
|
| 351 |
+
if row["index"] != i:
|
| 352 |
+
raise SystemExit(f"source row lookup failed: {prov['source']} {i}")
|
| 353 |
+
imgs = {}
|
| 354 |
+
for cam, key in CAMERAS.items():
|
| 355 |
+
path = os.path.join(src, f"videos/{key}/chunk-{meta[f'videos/{key}/chunk_index']:03d}/file-{meta[f'videos/{key}/file_index']:03d}.mp4")
|
| 356 |
+
ts = meta[f"videos/{key}/from_timestamp"] + f / FPS
|
| 357 |
+
with av.open(path) as c:
|
| 358 |
+
s = c.streams.video[0]
|
| 359 |
+
c.seek(int(ts / s.time_base), stream=s, backward=True)
|
| 360 |
+
for fr in c.decode(s):
|
| 361 |
+
if abs(float(fr.pts * s.time_base) - ts) < 1e-3:
|
| 362 |
+
imgs[cam] = fr.to_ndarray(format="rgb24")
|
| 363 |
+
break
|
| 364 |
+
return row, imgs
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
def cmd_verify(a):
|
| 368 |
+
"""Reads the dataset through openpi's LeRobot exactly as training does and compares it with the published releases."""
|
| 369 |
+
import lerobot.common.datasets.lerobot_dataset as ld
|
| 370 |
+
out = a.dir.rstrip("/")
|
| 371 |
+
root, repo = os.path.dirname(out), os.path.basename(out)
|
| 372 |
+
prov = [json.loads(x) for x in open(os.path.join(out, "lff/provenance.jsonl"))]
|
| 373 |
+
report = json.load(open(os.path.join(out, "lff/build_report.json")))
|
| 374 |
+
meta = ld.LeRobotDatasetMetadata(repo, root=out)
|
| 375 |
+
H = 10
|
| 376 |
+
ds = ld.LeRobotDataset(repo, root=out, delta_timestamps={"actions": [t / meta.fps for t in range(H)]}, video_backend="pyav")
|
| 377 |
+
checks = dict(n_frames=len(ds), n_episodes=meta.total_episodes, fps=meta.fps)
|
| 378 |
+
if len(ds) != sum(p["length"] for p in prov):
|
| 379 |
+
raise SystemExit("frame count differs from the provenance")
|
| 380 |
+
holdout = {t: set(s) for t, s in report["holdout"].items()}
|
| 381 |
+
leaked = [p for p in prov if (p["seed"] in holdout.get(p["task"], ())) != repo.endswith("_heldout")]
|
| 382 |
+
checks["instances_in_wrong_split"] = len(leaked)
|
| 383 |
+
rng = random.Random(0)
|
| 384 |
+
by_task = collections.defaultdict(list)
|
| 385 |
+
for p in prov:
|
| 386 |
+
by_task[p["task"]].append(p)
|
| 387 |
+
samples = []
|
| 388 |
+
for t, ps in sorted(by_task.items()):
|
| 389 |
+
for j in range(a.per_task):
|
| 390 |
+
p = rng.choice(ps)
|
| 391 |
+
near_end = j % 2 == 1 and p["length"] > H # half of the samples test the chunks that reach the clip's end
|
| 392 |
+
samples.append((p, p["length"] - rng.randint(1, H - 1) if near_end else rng.randrange(p["length"])))
|
| 393 |
+
state_err, act_err, img_err, chunk_err, pad_bad, prompts = [], [], [], [], 0, set()
|
| 394 |
+
tasks = {t["task_index"]: t["task"] for t in (json.loads(x) for x in open(os.path.join(out, "meta/tasks.jsonl")))}
|
| 395 |
+
for p, t in samples:
|
| 396 |
+
item = ds[p["index_from"] + t]
|
| 397 |
+
row, imgs = source_frame(p, t)
|
| 398 |
+
state_err.append(float(np.abs(item["state"].numpy() - np.asarray(row["observation.state"])).max()))
|
| 399 |
+
chunk = item["actions"].numpy()
|
| 400 |
+
act_err.append(float(np.abs(chunk[0] - np.asarray(row["action"])).max()))
|
| 401 |
+
if row["annotation.attempt_success"] != 1 or row["annotation.phase"] == 2:
|
| 402 |
+
raise SystemExit(f"frame with the wrong label in the dataset: {p['source']} {p['source_episode']} {t}")
|
| 403 |
+
for j in range(1, H):
|
| 404 |
+
if t + j >= p["length"]: # past the clip's end the loader must repeat the last action, not read the next clip
|
| 405 |
+
last = ds.hf_dataset[p["index_from"] + p["length"] - 1]["actions"].numpy()
|
| 406 |
+
chunk_err.append(float(np.abs(chunk[j] - last).max()))
|
| 407 |
+
pad_bad += int(not item["actions_is_pad"][j])
|
| 408 |
+
for cam in CAMERAS:
|
| 409 |
+
got = (item[cam].numpy().transpose(1, 2, 0) * 255).round()
|
| 410 |
+
img_err.append(float(np.abs(got - imgs[cam].astype(float)).mean()))
|
| 411 |
+
prompts.add(tasks[int(item["task_index"])] == item["task"])
|
| 412 |
+
checks.update(samples=len(samples), max_state_err=max(state_err), max_action_err=max(act_err), max_image_mae=max(img_err),
|
| 413 |
+
chunk_end_checks=len(chunk_err), max_chunk_end_err=max(chunk_err or [0.0]), chunk_end_not_padded=pad_bad, prompts_ok=prompts == {True})
|
| 414 |
+
actions = np.concatenate([np.asarray(ds.hf_dataset[p["index_from"]]["actions"])[None] for p in prov[:50]])
|
| 415 |
+
checks["first_actions_range"] = [float(actions.min()), float(actions.max())]
|
| 416 |
+
checks["pass"] = bool(not leaked and max(state_err) < 1e-6 and max(act_err) < 1e-6 and max(img_err) < 1.0 and max(chunk_err or [0.0]) < 1e-6
|
| 417 |
+
and not pad_bad and prompts == {True})
|
| 418 |
+
json.dump(checks, open(os.path.join(out, "lff/verify_report.json"), "w"), indent=1)
|
| 419 |
+
print(json.dumps(checks, indent=1))
|
| 420 |
+
if not checks["pass"]:
|
| 421 |
+
raise SystemExit("VERIFY FAILED")
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def cmd_norm(a):
|
| 425 |
+
"""openpi's scripts/compute_norm_stats.py computes state and action-chunk statistics, decoding every video frame on
|
| 426 |
+
the way. This feeds the same RunningStats the same arrays from the parquet files, so it takes seconds."""
|
| 427 |
+
from openpi.shared import normalize
|
| 428 |
+
out = a.dir.rstrip("/")
|
| 429 |
+
stats = {key: normalize.RunningStats() for key in ("state", "actions")}
|
| 430 |
+
eps = [json.loads(x) for x in open(os.path.join(out, "meta/episodes.jsonl"))]
|
| 431 |
+
for e in eps:
|
| 432 |
+
i = e["episode_index"]
|
| 433 |
+
t = pq.read_table(os.path.join(out, f"data/chunk-{i // CHUNK:03d}/episode_{i:06d}.parquet"), columns=["state", "actions"])
|
| 434 |
+
state = np.stack(t["state"].to_numpy(zero_copy_only=False))
|
| 435 |
+
act = np.stack(t["actions"].to_numpy(zero_copy_only=False))
|
| 436 |
+
idx = np.minimum(np.arange(len(act))[:, None] + np.arange(a.horizon)[None, :], len(act) - 1) # the loader's clamping
|
| 437 |
+
stats["state"].update(state)
|
| 438 |
+
stats["actions"].update(act[idx])
|
| 439 |
+
norm = {key: s.get_statistics() for key, s in stats.items()}
|
| 440 |
+
normalize.save(a.assets, norm)
|
| 441 |
+
print(f"wrote {a.assets}/norm_stats.json from {len(eps)} episodes")
|
| 442 |
+
for key, n in norm.items():
|
| 443 |
+
print(key, "q01", np.round(n.q01, 4).tolist(), "q99", np.round(n.q99, 4).tolist())
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def main():
|
| 447 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 448 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 449 |
+
n = sub.add_parser("norm")
|
| 450 |
+
n.add_argument("dir")
|
| 451 |
+
n.add_argument("--assets", required=True, help="<assets_base_dir>/<config name>/<repo id>")
|
| 452 |
+
n.add_argument("--horizon", type=int, default=10)
|
| 453 |
+
n.set_defaults(fn=cmd_norm)
|
| 454 |
+
b = sub.add_parser("build")
|
| 455 |
+
b.add_argument("--out", required=True)
|
| 456 |
+
b.add_argument("--repo-id", required=True)
|
| 457 |
+
b.add_argument("--holdout", help="sets/ file naming the held-out instance of each task")
|
| 458 |
+
b.add_argument("--holdout-seed", nargs="*", help="task:seed items for tasks not in that file")
|
| 459 |
+
b.add_argument("--extra-source", nargs="*", help="packages not in the canonical release yet")
|
| 460 |
+
b.add_argument("--splits", nargs="*", default=["train", "heldout"])
|
| 461 |
+
b.add_argument("--only-task", nargs="*", help="keep only these tasks (development datasets)")
|
| 462 |
+
b.add_argument("--workers", type=int, default=6)
|
| 463 |
+
b.set_defaults(fn=cmd_build)
|
| 464 |
+
v = sub.add_parser("verify")
|
| 465 |
+
v.add_argument("dir")
|
| 466 |
+
v.add_argument("--per-task", type=int, default=3)
|
| 467 |
+
v.set_defaults(fn=cmd_verify)
|
| 468 |
+
a = ap.parse_args()
|
| 469 |
+
a.fn(a)
|
| 470 |
+
|
| 471 |
+
|
| 472 |
+
if __name__ == "__main__":
|
| 473 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/outcomes.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-instance outcomes of api_batch.py --memfree followup batches, in the paper's terms (paper/01 §4 3.6):
|
| 2 |
+
|
| 3 |
+
CS attempt 1 succeeded with no error event in it IR attempt 1 succeeded after an error event (repaired
|
| 4 |
+
XR attempt 1 failed, a later attempt succeeded within the attempt)
|
| 5 |
+
F no attempt succeeded S? attempt 1 succeeded, but the task logs no error events
|
| 6 |
+
(CS or IR cannot be told apart)
|
| 7 |
+
A1 = CS + IR (+ S?), A3 = A1 + XR (history condition); pass@k = the memory-free chain (attempt 1 shared with the
|
| 8 |
+
history run, then fresh agents) succeeded; delta = A3 - pass@k, paired per instance. Tasks whose scene persists
|
| 9 |
+
between attempts (protocol "within") have no memory-free chain and are listed apart (user 2026-10-20).
|
| 10 |
+
|
| 11 |
+
python scripts/outcomes.py --batch cx_main1 [--batch ...] [--json out.json]
|
| 12 |
+
|
| 13 |
+
An error event is read from the task's outcome dict of the successful attempt: trap_fired / recovered_in_attempt
|
| 14 |
+
true, or one of the n_* counters of mistakes (n_bad_pushes, n_wrong_way, n_regressions, n_load_falls, ...) above 0.
|
| 15 |
+
The finish reason of every failed attempt is printed so that false success claims can be judged (not judged here).
|
| 16 |
+
"""
|
| 17 |
+
import argparse
|
| 18 |
+
import ast
|
| 19 |
+
import json
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
|
| 23 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 24 |
+
import api_batch # noqa: E402
|
| 25 |
+
|
| 26 |
+
ERROR_FLAGS = ("trap_fired", "recovered_in_attempt")
|
| 27 |
+
ERROR_COUNTS = ("n_bad_pushes", "n_turned_pushes", "n_wrong_way", "n_regressions", "n_load_falls", "n_trap_events",
|
| 28 |
+
"n_missed_strikes", "n_open_gripper_pushes")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def attempts(log):
|
| 32 |
+
"""[(attempt, success, outcome dict, finish reason)] from the robot server log."""
|
| 33 |
+
out = []
|
| 34 |
+
p = os.path.join(log or "", "events.jsonl")
|
| 35 |
+
if not os.path.exists(p):
|
| 36 |
+
return out
|
| 37 |
+
for line in open(p):
|
| 38 |
+
e = json.loads(line)
|
| 39 |
+
if e.get("ev") != "done":
|
| 40 |
+
continue
|
| 41 |
+
o = e.get("outcome") or {}
|
| 42 |
+
if isinstance(o, str):
|
| 43 |
+
try:
|
| 44 |
+
o = ast.literal_eval(o)
|
| 45 |
+
except (ValueError, SyntaxError):
|
| 46 |
+
o = {}
|
| 47 |
+
out.append((int(e["attempt"]), e["success"] in (True, "True"), o, e.get("reason") or ""))
|
| 48 |
+
return sorted(out, key=lambda x: x[0])
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def error_event(o):
|
| 52 |
+
"""True / False if the outcome dict says whether an error happened, None if the task logs no error events."""
|
| 53 |
+
keys = [k for k in ERROR_FLAGS + ERROR_COUNTS if k in o]
|
| 54 |
+
if not keys:
|
| 55 |
+
return None
|
| 56 |
+
return any(bool(o[k]) for k in ERROR_FLAGS if k in o) or any((o.get(k) or 0) > 0 for k in ERROR_COUNTS if k in o)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def instance_rows(m, audit=None, batch=None):
|
| 60 |
+
rows = []
|
| 61 |
+
for r in m["runs"]:
|
| 62 |
+
if not (r["cond"] == "harness" and r.get("followup")) or r["status"] != "done":
|
| 63 |
+
continue
|
| 64 |
+
att = attempts(r.get("log"))
|
| 65 |
+
if not att:
|
| 66 |
+
continue
|
| 67 |
+
if audit is not None and att[0][0] != 1:
|
| 68 |
+
raise ValueError(f"Cannot audit {r['task']}: first-attempt record is missing")
|
| 69 |
+
hist = "".join("S" if s else "F" for _, s, _, _ in att)
|
| 70 |
+
if att[0][1]:
|
| 71 |
+
ev = error_event(att[0][2])
|
| 72 |
+
cls = "S?" if ev is None else ("IR" if ev else "CS")
|
| 73 |
+
else:
|
| 74 |
+
cls = "XR" if any(s for _, s, _, _ in att) else "F"
|
| 75 |
+
legacy_cls = cls
|
| 76 |
+
audit_basis = None
|
| 77 |
+
if audit is not None and att[0][1]:
|
| 78 |
+
from outcome_audit import adjudicate
|
| 79 |
+
cls, audit_basis = adjudicate(audit, batch, r, True)
|
| 80 |
+
within = api_batch.episode_protocol(r.get("log")) == "within"
|
| 81 |
+
chain = sorted((x for x in m["runs"] if x.get("chain") == r["id"]), key=lambda x: x["rep"])
|
| 82 |
+
mf = None
|
| 83 |
+
if not within:
|
| 84 |
+
mf = hist[0] + "".join("S" if any(api_batch.attempt_results(x.get("log"))) else
|
| 85 |
+
("F" if x["status"] == "done" else "?") for x in chain)
|
| 86 |
+
failed = [(a, reason) for a, s, _, reason in att if not s]
|
| 87 |
+
failed += [(f"mf{x['rep'] + 1}", rr) for x in chain for _, s, _, rr in attempts(x.get("log")) if not s]
|
| 88 |
+
rows.append(dict(task=r["task"], seed=r["seed"], cls=cls, legacy_cls=legacy_cls,
|
| 89 |
+
batch=batch, run_id=r["id"], audit_basis=audit_basis,
|
| 90 |
+
history=hist, memfree=mf, within=within,
|
| 91 |
+
a1=att[0][1], a3=any(s for _, s, _, _ in att),
|
| 92 |
+
passk=None if mf is None else ("S" in mf), failed_reasons=failed))
|
| 93 |
+
return rows
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def summary(rows):
|
| 97 |
+
n = len(rows)
|
| 98 |
+
paired = [x for x in rows if x["passk"] is not None and "?" not in (x["memfree"] or "")]
|
| 99 |
+
cnt = {c: sum(1 for x in rows if x["cls"] == c) for c in ("CS", "IR", "S?", "XR", "F")}
|
| 100 |
+
return dict(n=n, **cnt, A1=sum(x["a1"] for x in rows), A3=sum(x["a3"] for x in rows), n_paired=len(paired),
|
| 101 |
+
A3_paired=sum(x["a3"] for x in paired), passk_paired=sum(x["passk"] for x in paired),
|
| 102 |
+
delta_paired=(sum(x["a3"] for x in paired) - sum(x["passk"] for x in paired)) / max(1, len(paired)))
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def main():
|
| 106 |
+
ap = argparse.ArgumentParser()
|
| 107 |
+
ap.add_argument("--batch", action="append", required=True)
|
| 108 |
+
ap.add_argument("--json", default=None)
|
| 109 |
+
ap.add_argument("--runs-root", help="read manifests from another checkout's runs/api directory")
|
| 110 |
+
ap.add_argument("--audit", help="hash-bound reviewed classifications (unreviewed first successes remain S?)")
|
| 111 |
+
a = ap.parse_args()
|
| 112 |
+
if a.runs_root:
|
| 113 |
+
api_batch.RUNS = os.path.abspath(a.runs_root)
|
| 114 |
+
audit = None
|
| 115 |
+
if a.audit:
|
| 116 |
+
from outcome_audit import load_audit
|
| 117 |
+
audit = load_audit(a.audit)
|
| 118 |
+
rows = []
|
| 119 |
+
for b in a.batch:
|
| 120 |
+
rows += instance_rows(api_batch.load(b), audit=audit, batch=b)
|
| 121 |
+
print("Classification: " + ("reviewed evidence (see audit sources)" if audit is not None else
|
| 122 |
+
"legacy task-counter heuristic; CS/IR coverage is task-dependent"))
|
| 123 |
+
print("| task | seed | outcome | history | memory-free | note |\n|---|---|---|---|---|---|")
|
| 124 |
+
for x in rows:
|
| 125 |
+
print(f"| {x['task']} | {x['seed']} | {x['cls']} | {x['history']} | {x['memfree'] or '—'} | "
|
| 126 |
+
f"{'scene persists: no memory-free chain' if x['within'] else ''} |")
|
| 127 |
+
s = summary(rows)
|
| 128 |
+
print(f"\nn={s['n']} CS={s['CS']} IR={s['IR']} S?={s['S?']} XR={s['XR']} F={s['F']} A1={s['A1']}/{s['n']} "
|
| 129 |
+
f"A3={s['A3']}/{s['n']} paired (no persisting scene, chain finished): n={s['n_paired']} "
|
| 130 |
+
f"A3={s['A3_paired']} pass@k={s['passk_paired']} delta={s['delta_paired']:+.3f}")
|
| 131 |
+
print("\nfinish reasons of failed attempts (for judging false success claims):")
|
| 132 |
+
for x in rows:
|
| 133 |
+
for att, reason in x["failed_reasons"]:
|
| 134 |
+
print(f" {x['task']} {att}: {reason[:160]}")
|
| 135 |
+
if a.json:
|
| 136 |
+
with open(a.json, "w") as f:
|
| 137 |
+
json.dump(dict(rows=rows, summary=s), f, indent=1, ensure_ascii=False)
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/qwen_vl_server.sh
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Launch the Qwen3-VL OpenAI-compatible server on the local PPU.
|
| 3 |
+
# Usage: bash scripts/qwen_vl_server.sh [--port 8765] [--host 127.0.0.1] [other qwen_vl_server.py args]
|
| 4 |
+
# Uses the system python3.12 (torch 2.6 PPU build) + a private overlay dir that only
|
| 5 |
+
# holds transformers==4.57.6 / tokenizers==0.22.1 / huggingface_hub==0.36.0; the
|
| 6 |
+
# overlay is put on PYTHONPATH for this process only.
|
| 7 |
+
set -eo pipefail
|
| 8 |
+
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
| 9 |
+
# PPU runtime libs (libhggcrt1.so etc.); without this torch spins printing load errors.
|
| 10 |
+
source /usr/local/PPU_SDK/envsetup.sh cuda >/dev/null
|
| 11 |
+
[ -n "${QWEN_OVERLAY:-}" ] && export PYTHONPATH="${QWEN_OVERLAY}${PYTHONPATH:+:${PYTHONPATH}}"
|
| 12 |
+
export OMP_NUM_THREADS="${OMP_NUM_THREADS:-1}"
|
| 13 |
+
export MKL_NUM_THREADS="${MKL_NUM_THREADS:-1}"
|
| 14 |
+
export TOKENIZERS_PARALLELISM=false
|
| 15 |
+
export HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1
|
| 16 |
+
export PYTHONUNBUFFERED=1
|
| 17 |
+
exec /usr/local/bin/python3.12 "${HERE}/qwen_vl_server.py" "$@"
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/replay_la.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Replay the robot commands of a logged agent attempt on a fresh task instance (current task code) and print the
|
| 2 |
+
outcome next to the logged one -- e.g. to check a rule change against old runs without re-running the agent.
|
| 3 |
+
|
| 4 |
+
usage: python scripts/replay_la.py <run_dir> <attempt> [--seg] [--fb]
|
| 5 |
+
LA `move_eef` calls mirror robot_server._handle_v2 (missing axes default to the current pose, move_to then gripper);
|
| 6 |
+
v1 tool calls (move_to / open_gripper / close_gripper / push, world frame) are passed to the ToolExecutor as logged.
|
| 7 |
+
--seg prints the per-command board / cube motion (tasks whose Skills keep `segments`), --fb the F2 text.
|
| 8 |
+
"""
|
| 9 |
+
import importlib
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import pkgutil
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from lffbench.agent.tools import WS_HI, WS_LO, ToolExecutor
|
| 18 |
+
from lffbench import tasks as task_pkg
|
| 19 |
+
from lffbench.task_base import TASKS
|
| 20 |
+
|
| 21 |
+
for _m in pkgutil.iter_modules(task_pkg.__path__):
|
| 22 |
+
importlib.import_module(f"lffbench.tasks.{_m.name}")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
run_dir, attempt = sys.argv[1], int(sys.argv[2])
|
| 27 |
+
ev = [json.loads(l) for l in open(os.path.join(run_dir, "events.jsonl")) if l.strip()]
|
| 28 |
+
start = next(e for e in ev if e["ev"] == "session_start")
|
| 29 |
+
task = TASKS[start["task"]](cam_res=128)
|
| 30 |
+
inst = task.sample_instance(start["seed"])
|
| 31 |
+
task.reset_instance(inst)
|
| 32 |
+
sim = task.env.sim
|
| 33 |
+
off = np.array(sim.data.body_xpos[sim.model.body_name2id("robot0_base")], float).copy()
|
| 34 |
+
ex = ToolExecutor(task, inst, image_res=128, cams=("agentview",))
|
| 35 |
+
logged = None
|
| 36 |
+
for e in ev:
|
| 37 |
+
if e.get("attempt") != attempt:
|
| 38 |
+
continue
|
| 39 |
+
if e["ev"] == "done":
|
| 40 |
+
logged = e
|
| 41 |
+
break
|
| 42 |
+
if e["ev"] == "call" and e["cmd"] in ("move_to", "open_gripper", "close_gripper", "push"): # v1 tools
|
| 43 |
+
ex.call(e["cmd"], e["args"])
|
| 44 |
+
print(f" s{e['step']:>2} {e['cmd']} {e['args']} [seg {len(getattr(task.sk, 'segments', []))}]")
|
| 45 |
+
continue
|
| 46 |
+
if e["ev"] != "call" or e["cmd"] != "move_eef":
|
| 47 |
+
continue
|
| 48 |
+
args = e["args"]
|
| 49 |
+
p = ex.proprio()
|
| 50 |
+
cur = np.asarray(p["eef_pos"], float) - off
|
| 51 |
+
tgt = [float(args.get(k, cur[i])) for i, k in enumerate("xyz")]
|
| 52 |
+
yaw = float(args.get("yaw", p["eef_yaw_deg"]))
|
| 53 |
+
speed = None if args.get("speed") in (None, "") else float(args["speed"])
|
| 54 |
+
moving = any(k in args for k in ("x", "y", "z", "yaw"))
|
| 55 |
+
tgt_w = np.asarray(tgt) + off
|
| 56 |
+
if moving and not (np.all(tgt_w >= WS_LO) and np.all(tgt_w <= WS_HI)):
|
| 57 |
+
print(f" s{e['step']:>2} rejected")
|
| 58 |
+
continue
|
| 59 |
+
if moving:
|
| 60 |
+
mv = dict(x=float(tgt_w[0]), y=float(tgt_w[1]), z=float(tgt_w[2]), yaw=yaw)
|
| 61 |
+
if speed is not None:
|
| 62 |
+
mv["speed"] = speed
|
| 63 |
+
ex.call("move_to", mv)
|
| 64 |
+
if args.get("gripper"):
|
| 65 |
+
ex.call("open_gripper" if args["gripper"] == "open" else "close_gripper", {})
|
| 66 |
+
print(f" s{e['step']:>2} {' '.join(f'{k}={v}' for k, v in args.items())} [seg {len(getattr(task.sk, 'segments', []))}]")
|
| 67 |
+
if "--seg" in sys.argv and hasattr(task.sk, "segments"):
|
| 68 |
+
for g in task.sk.segments:
|
| 69 |
+
if g["path"] > 0.0005 or g["touch"]:
|
| 70 |
+
print(f" seg@{g['step0']:>4} {g['kind']:<5} steps={g['steps']:>3} path={100*g['path']:.2f}cm "
|
| 71 |
+
f"driven={100*g['driven']:.2f}cm touch={g['touch']:>3} board_dxy={g['board_dxy']} "
|
| 72 |
+
f"cube_dxy={g['cube_dxy']} cube_from_start={g['cube_from_start']}")
|
| 73 |
+
out = task.outcome(inst)
|
| 74 |
+
keys = ("moved_toward_robot", "n_pulls", "pulls_cm", "pre_pull_cube_cm", "stray_cm", "n_pushes", "max_advance",
|
| 75 |
+
"n_turns", "n_wrong_way", "n_strikes", "n_missed_strikes", "free_slide_cm", "n_bad_pushes",
|
| 76 |
+
"first_push_yaw_deg", "n_open_gripper_pushes", "irrecoverable", "trap_fired", "recovered_in_attempt")
|
| 77 |
+
print("REPLAY :", "S" if out["success"] else "F", out.get("failure"), {k: out[k] for k in keys if k in out})
|
| 78 |
+
if "--fb" in sys.argv:
|
| 79 |
+
print("F2 :", task.feedback(inst, out, "F2"))
|
| 80 |
+
if logged:
|
| 81 |
+
print("LOGGED :", "S" if logged["success"] else "F", logged["outcome"].get("failure"))
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/tool_gateway.py
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Per-episode tool gateway (docs/18 §6.1): the one implementation of the three LA tools for every access path.
|
| 2 |
+
|
| 3 |
+
`robot` (forwarded to robot_server), `shell` (jailed, in the episode workspace) and `view_images` (workspace image files),
|
| 4 |
+
with the per-attempt tool-call budget counted here once for the whole episode: when it is used up the attempt is
|
| 5 |
+
finished automatically and the result is appended to that call's output. The MCP server (scripts/mcp_robot_server.py)
|
| 6 |
+
and the Python SDK (client/lffbench_client) are thin clients of this process, so a native harness (Codex, Claude Code)
|
| 7 |
+
and a robot harness framework (RPent, ...) get the same tools, outputs and limits. The gateway runs outside the harness
|
| 8 |
+
jail next to robot_server; harness processes only see its HTTP port and token, never robot_server's token, the
|
| 9 |
+
workspace files or a shell of their own.
|
| 10 |
+
|
| 11 |
+
python scripts/tool_gateway.py --session runs/<...>/session.json
|
| 12 |
+
writes <log dir>/gateway.json {url, port, pid, token} (mode 600) once it listens and logs every call to
|
| 13 |
+
<log dir>/gateway_transcript.jsonl. HTTP on 127.0.0.1, header "Authorization: Bearer <token>":
|
| 14 |
+
POST /tool {"name": ..., "arguments": {...}} -> {"content": [...], "is_error", "finished", "calls_in_attempt"}
|
| 15 |
+
content items: {"type": "text", "text"} / {"type": "image", "mimeType", "data" (base64)}
|
| 16 |
+
GET /tool_specs?style=raw|mcp|anthropic|openai_responses|openai_chat the three tool schemas, descriptions verbatim
|
| 17 |
+
GET /readme README.md of the episode workspace
|
| 18 |
+
GET /first_message preamble + README + first status report, byte-identical to the native harnesses' first
|
| 19 |
+
message (taken from <log dir>/first_message.txt when the launcher already rendered it)
|
| 20 |
+
GET /health
|
| 21 |
+
GET /status robot_server's `status`, for a framework's own loop (e.g. the reference driver's "Continue ..."
|
| 22 |
+
nudge, which needs the attempt number): not a tool call, not counted in the per-attempt budget,
|
| 23 |
+
logged as ev=status; the native harnesses' launcher makes the same call directly
|
| 24 |
+
(scripts/harness_run.py continue_episode)
|
| 25 |
+
Header "X-LFF-Face" labels the access path in the transcript (mcp, sdk, ...). Contract: like mcp_robot_server.py and
|
| 26 |
+
api_player.py the gateway is an access path, not part of contract_sha256 (docs/15 §8.4); the "oracle through every
|
| 27 |
+
access path" self-check keeps the paths equal.
|
| 28 |
+
"""
|
| 29 |
+
import argparse
|
| 30 |
+
import base64
|
| 31 |
+
import hmac
|
| 32 |
+
import json
|
| 33 |
+
import os
|
| 34 |
+
import secrets
|
| 35 |
+
import subprocess
|
| 36 |
+
import sys
|
| 37 |
+
import threading
|
| 38 |
+
import time
|
| 39 |
+
import traceback
|
| 40 |
+
import urllib.parse
|
| 41 |
+
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
| 42 |
+
|
| 43 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 44 |
+
from api_player import (SHELL_TOOL, TOOL_LA, VIEW_TOOL_LA, call_server, parse_command, run_shell, # noqa: E402
|
| 45 |
+
workspace_image)
|
| 46 |
+
|
| 47 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 48 |
+
TOOLS = [TOOL_LA, SHELL_TOOL, VIEW_TOOL_LA]
|
| 49 |
+
GATEWAY_FILE = "gateway.json"
|
| 50 |
+
TRANSCRIPT = "gateway_transcript.jsonl"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def tool_specs(style="raw"):
|
| 54 |
+
"""The three tool schemas in the format a framework registers them in; names, descriptions and parameter schemas
|
| 55 |
+
are the reference driver's, verbatim."""
|
| 56 |
+
if style == "raw":
|
| 57 |
+
return [dict(t) for t in TOOLS]
|
| 58 |
+
if style == "mcp":
|
| 59 |
+
return [dict(name=t["name"], description=t["description"], inputSchema=t["parameters"]) for t in TOOLS]
|
| 60 |
+
if style == "anthropic":
|
| 61 |
+
return [dict(name=t["name"], description=t["description"], input_schema=t["parameters"]) for t in TOOLS]
|
| 62 |
+
if style == "openai_responses":
|
| 63 |
+
return [dict(type="function", name=t["name"], description=t["description"], parameters=t["parameters"])
|
| 64 |
+
for t in TOOLS]
|
| 65 |
+
if style == "openai_chat":
|
| 66 |
+
return [dict(type="function", function=dict(name=t["name"], description=t["description"],
|
| 67 |
+
parameters=t["parameters"])) for t in TOOLS]
|
| 68 |
+
raise ValueError(f"unknown style {style!r}: raw, mcp, anthropic, openai_responses or openai_chat")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class ToolCore:
|
| 72 |
+
"""The three tools on one robot_server session, with the per-attempt tool-call budget. Same semantics and output
|
| 73 |
+
text as the reference driver's LA tools (and, before the gateway, mcp_robot_server.Session)."""
|
| 74 |
+
|
| 75 |
+
def __init__(self, session_path, carry_from=None):
|
| 76 |
+
"""carry_from: a transcript (jsonl with ev=tool, calls_in_attempt, finished) to continue the budget from, for an
|
| 77 |
+
in-process host that is restarted within one episode (mcp_robot_server without a gateway)."""
|
| 78 |
+
sess = json.load(open(session_path))
|
| 79 |
+
self.session_path = os.path.abspath(session_path)
|
| 80 |
+
self.sb, self.port = sess["sandbox"], sess["port"]
|
| 81 |
+
self.log_dir = os.path.dirname(self.session_path)
|
| 82 |
+
iface = json.load(open(os.path.join(self.log_dir, "agent_iface.json")))
|
| 83 |
+
self.token, self.max_tool_calls = iface["token"], int(iface["max_tool_calls"])
|
| 84 |
+
self.calls_in_attempt, self.finished = 0, False
|
| 85 |
+
if carry_from and os.path.exists(carry_from):
|
| 86 |
+
for line in open(carry_from):
|
| 87 |
+
try:
|
| 88 |
+
d = json.loads(line)
|
| 89 |
+
except ValueError:
|
| 90 |
+
continue
|
| 91 |
+
if d.get("ev") == "tool" and d.get("calls_in_attempt") is not None:
|
| 92 |
+
self.calls_in_attempt, self.finished = int(d["calls_in_attempt"]), bool(d.get("finished"))
|
| 93 |
+
|
| 94 |
+
def robot(self, cmdline):
|
| 95 |
+
cmd, args = parse_command(cmdline)
|
| 96 |
+
if cmd is None:
|
| 97 |
+
return json.dumps(dict(ok=False, error=args))
|
| 98 |
+
raw = call_server(self.port, self.token, cmd, args)
|
| 99 |
+
try:
|
| 100 |
+
rep = json.loads(raw)
|
| 101 |
+
except ValueError: # help text
|
| 102 |
+
return raw
|
| 103 |
+
msg = (rep.get("message", "") + " " + rep.get("error", "")) if isinstance(rep, dict) else ""
|
| 104 |
+
if isinstance(rep, dict) and isinstance(rep.get("attempt_ended"), dict):
|
| 105 |
+
msg += " " + rep["attempt_ended"].get("message", "")
|
| 106 |
+
if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
|
| 107 |
+
self.finished = True
|
| 108 |
+
if isinstance(rep, dict) and (rep.get("ended") or isinstance(rep.get("attempt_ended"), dict)):
|
| 109 |
+
self.calls_in_attempt = 0
|
| 110 |
+
return json.dumps(rep)
|
| 111 |
+
|
| 112 |
+
def call(self, name, args):
|
| 113 |
+
"""-> (content list, is_error); content items as in MCP (text / image with base64 data)."""
|
| 114 |
+
args = args if isinstance(args, dict) else {}
|
| 115 |
+
if not self.finished:
|
| 116 |
+
self.calls_in_attempt += 1
|
| 117 |
+
if name == "robot":
|
| 118 |
+
content, err = [dict(type="text", text=self.robot(str(args.get("command", ""))))], False
|
| 119 |
+
elif name == "shell":
|
| 120 |
+
code, out, dt = run_shell(self.sb, str(args.get("command", "")))
|
| 121 |
+
content, err = [dict(type="text", text=json.dumps(dict(exit_code=code, output=out)))], False
|
| 122 |
+
elif name == "view_images":
|
| 123 |
+
paths = [str(x) for x in (args.get("paths") or [])][:8]
|
| 124 |
+
full = [(x, workspace_image(self.sb, x)) for x in paths]
|
| 125 |
+
ok = [x for x, f in full if f]
|
| 126 |
+
out = dict(ok=bool(ok), attached=ok)
|
| 127 |
+
if len(ok) < len(paths):
|
| 128 |
+
out["not_viewable"] = [x for x, f in full if not f]
|
| 129 |
+
content, err = [dict(type="text", text=json.dumps(out))], False
|
| 130 |
+
for x, f in full:
|
| 131 |
+
if f:
|
| 132 |
+
mime = "image/png" if f.lower().endswith(".png") else "image/jpeg"
|
| 133 |
+
content.append(dict(type="image", mimeType=mime, data=base64.b64encode(open(f, "rb").read()).decode()))
|
| 134 |
+
else:
|
| 135 |
+
return [dict(type="text", text=f"unknown tool {name!r}")], True
|
| 136 |
+
if not self.finished and self.calls_in_attempt >= self.max_tool_calls:
|
| 137 |
+
raw = call_server(self.port, self.token, "finish", dict(reason="tool-call budget used up (automatic)"))
|
| 138 |
+
try:
|
| 139 |
+
rep = json.loads(raw)
|
| 140 |
+
except ValueError:
|
| 141 |
+
rep = dict(raw=raw)
|
| 142 |
+
msg = rep.get("message", "") + " " + rep.get("error", "")
|
| 143 |
+
if "episode is over" in msg or "No attempts left" in msg or "Stop now" in msg:
|
| 144 |
+
self.finished = True
|
| 145 |
+
self.calls_in_attempt = 0
|
| 146 |
+
content.append(dict(type="text", text=(f"The budget of {self.max_tool_calls} tool calls for this attempt was "
|
| 147 |
+
f"used up, so the attempt was finished automatically. Result: "
|
| 148 |
+
+ json.dumps(rep))))
|
| 149 |
+
return content, err
|
| 150 |
+
|
| 151 |
+
def readme(self):
|
| 152 |
+
return open(os.path.join(self.sb, "README.md"), encoding="utf-8").read()
|
| 153 |
+
|
| 154 |
+
def first_message(self):
|
| 155 |
+
"""The native harnesses' first user message. Rendered by the launcher (harness_run.py) into first_message.txt;
|
| 156 |
+
otherwise rendered here once, with the same single `status` call, and saved there."""
|
| 157 |
+
path = os.path.join(self.log_dir, "first_message.txt")
|
| 158 |
+
if os.path.exists(path):
|
| 159 |
+
return open(path, encoding="utf-8").read()
|
| 160 |
+
sys.path.insert(0, ROOT)
|
| 161 |
+
from lffbench.harnesses.base import first_message_text
|
| 162 |
+
status_json = json.dumps(json.loads(call_server(self.port, self.token, "status", {})))
|
| 163 |
+
text = first_message_text(self.readme(), status_json)
|
| 164 |
+
with open(path, "w", encoding="utf-8") as f:
|
| 165 |
+
f.write(text)
|
| 166 |
+
return text
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def log_line(f, d):
|
| 170 |
+
d["t"] = time.time()
|
| 171 |
+
f.write(json.dumps(d, ensure_ascii=False) + "\n")
|
| 172 |
+
f.flush()
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def serve(core, port=0, gateway_file=None, watch_parent=True):
|
| 176 |
+
token = secrets.token_hex(16)
|
| 177 |
+
lock = threading.Lock()
|
| 178 |
+
tlog = open(os.path.join(core.log_dir, TRANSCRIPT), "a")
|
| 179 |
+
fm_cache = {}
|
| 180 |
+
|
| 181 |
+
class H(BaseHTTPRequestHandler):
|
| 182 |
+
protocol_version = "HTTP/1.1"
|
| 183 |
+
|
| 184 |
+
def log_message(self, *a):
|
| 185 |
+
pass
|
| 186 |
+
|
| 187 |
+
def _send(self, code, body, ctype="application/json"):
|
| 188 |
+
data = body if isinstance(body, bytes) else (body if isinstance(body, str) else json.dumps(body)).encode()
|
| 189 |
+
self.send_response(code)
|
| 190 |
+
self.send_header("Content-Type", ctype + ("; charset=utf-8" if ctype.startswith("text") or
|
| 191 |
+
ctype == "application/json" else ""))
|
| 192 |
+
self.send_header("Content-Length", str(len(data)))
|
| 193 |
+
self.end_headers()
|
| 194 |
+
self.wfile.write(data)
|
| 195 |
+
|
| 196 |
+
def _authorized(self):
|
| 197 |
+
got = self.headers.get("Authorization", "")
|
| 198 |
+
return hmac.compare_digest(got.encode(), f"Bearer {token}".encode())
|
| 199 |
+
|
| 200 |
+
def do_GET(self):
|
| 201 |
+
u = urllib.parse.urlparse(self.path)
|
| 202 |
+
if u.path == "/health":
|
| 203 |
+
return self._send(200, dict(ok=True))
|
| 204 |
+
if not self._authorized():
|
| 205 |
+
return self._send(401, dict(error="unauthorized"))
|
| 206 |
+
try:
|
| 207 |
+
if u.path == "/tool_specs":
|
| 208 |
+
style = (urllib.parse.parse_qs(u.query).get("style") or ["raw"])[0]
|
| 209 |
+
return self._send(200, dict(style=style, tools=tool_specs(style)))
|
| 210 |
+
if u.path == "/readme":
|
| 211 |
+
return self._send(200, core.readme(), "text/markdown")
|
| 212 |
+
if u.path == "/first_message":
|
| 213 |
+
with lock:
|
| 214 |
+
if "text" not in fm_cache:
|
| 215 |
+
fm_cache["text"] = core.first_message()
|
| 216 |
+
return self._send(200, fm_cache["text"], "text/plain")
|
| 217 |
+
if u.path == "/status": # a framework's own status call (not the model's): not counted
|
| 218 |
+
face = (self.headers.get("X-LFF-Face") or "http")[:32]
|
| 219 |
+
with lock:
|
| 220 |
+
raw = call_server(core.port, core.token, "status", {})
|
| 221 |
+
log_line(tlog, dict(ev="status", face=face))
|
| 222 |
+
status = json.loads(raw)
|
| 223 |
+
return self._send(200, {k: status.get(k) for k in ("attempt", "max_attempts", "finished")})
|
| 224 |
+
except ValueError as e:
|
| 225 |
+
return self._send(400, dict(error=str(e)))
|
| 226 |
+
except Exception as e:
|
| 227 |
+
log_line(tlog, dict(ev="error", path=u.path, error=traceback.format_exc()[-2000:]))
|
| 228 |
+
return self._send(500, dict(error=f"{type(e).__name__}: {e}"))
|
| 229 |
+
return self._send(404, dict(error=f"no such path {u.path}"))
|
| 230 |
+
|
| 231 |
+
def do_POST(self):
|
| 232 |
+
u = urllib.parse.urlparse(self.path)
|
| 233 |
+
if not self._authorized():
|
| 234 |
+
return self._send(401, dict(error="unauthorized"))
|
| 235 |
+
if u.path != "/tool":
|
| 236 |
+
return self._send(404, dict(error=f"no such path {u.path}"))
|
| 237 |
+
try:
|
| 238 |
+
req = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0) or 0)) or b"{}")
|
| 239 |
+
name, args = req.get("name"), req.get("arguments") or {}
|
| 240 |
+
except (ValueError, AttributeError):
|
| 241 |
+
return self._send(400, dict(error="body must be JSON {name, arguments}"))
|
| 242 |
+
face = (self.headers.get("X-LFF-Face") or "http")[:32]
|
| 243 |
+
try:
|
| 244 |
+
with lock: # one tool call at a time per episode, as in the MCP server and the reference driver
|
| 245 |
+
t0 = time.time()
|
| 246 |
+
content, err = core.call(name, args)
|
| 247 |
+
out = dict(content=content, is_error=err, finished=core.finished,
|
| 248 |
+
calls_in_attempt=core.calls_in_attempt)
|
| 249 |
+
log_line(tlog, dict(ev="tool", face=face, name=name, arguments=args, dt=round(time.time() - t0, 2),
|
| 250 |
+
is_error=err, output=[c["text"] for c in content if c["type"] == "text"],
|
| 251 |
+
images=sum(1 for c in content if c["type"] == "image"),
|
| 252 |
+
finished=core.finished, calls_in_attempt=core.calls_in_attempt))
|
| 253 |
+
except Exception as e:
|
| 254 |
+
log_line(tlog, dict(ev="error", face=face, name=name, error=traceback.format_exc()[-2000:]))
|
| 255 |
+
return self._send(500, dict(error=f"{type(e).__name__}: {e}"))
|
| 256 |
+
return self._send(200, out)
|
| 257 |
+
|
| 258 |
+
srv = ThreadingHTTPServer(("127.0.0.1", port), H)
|
| 259 |
+
srv.daemon_threads = True
|
| 260 |
+
port = srv.server_address[1]
|
| 261 |
+
info = dict(url=f"http://127.0.0.1:{port}", port=port, pid=os.getpid(), token=token)
|
| 262 |
+
gateway_file = gateway_file or os.path.join(core.log_dir, GATEWAY_FILE)
|
| 263 |
+
tmp = gateway_file + ".tmp"
|
| 264 |
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
| 265 |
+
with os.fdopen(fd, "w") as f:
|
| 266 |
+
json.dump(info, f)
|
| 267 |
+
os.replace(tmp, gateway_file)
|
| 268 |
+
log_line(tlog, dict(ev="start", pid=os.getpid(), port=port, session=core.session_path,
|
| 269 |
+
max_tool_calls=core.max_tool_calls))
|
| 270 |
+
import signal
|
| 271 |
+
signal.signal(signal.SIGTERM, lambda *_: threading.Thread(target=srv.shutdown, daemon=True).start())
|
| 272 |
+
if watch_parent: # exit with the launcher, also when it is killed without cleaning up
|
| 273 |
+
ppid = os.getppid()
|
| 274 |
+
|
| 275 |
+
def watch():
|
| 276 |
+
while os.getppid() == ppid:
|
| 277 |
+
time.sleep(2)
|
| 278 |
+
srv.shutdown()
|
| 279 |
+
threading.Thread(target=watch, daemon=True).start()
|
| 280 |
+
try:
|
| 281 |
+
srv.serve_forever(poll_interval=0.5)
|
| 282 |
+
finally:
|
| 283 |
+
log_line(tlog, dict(ev="stop"))
|
| 284 |
+
srv.server_close()
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# ------------------------------------------------------------------------------------------------ launcher helpers
|
| 288 |
+
def start_gateway(session_path, python=None, timeout_s=30, env=None):
|
| 289 |
+
"""Start a gateway for one episode (child of the caller) and wait until it listens. -> (Popen, info dict with url,
|
| 290 |
+
port, pid, token). The caller stops it with stop_gateway()."""
|
| 291 |
+
log_dir = os.path.dirname(os.path.abspath(session_path))
|
| 292 |
+
gfile = os.path.join(log_dir, GATEWAY_FILE)
|
| 293 |
+
if os.path.exists(gfile):
|
| 294 |
+
os.remove(gfile)
|
| 295 |
+
err = open(os.path.join(log_dir, "gateway_stderr.txt"), "ab")
|
| 296 |
+
p = subprocess.Popen([python or sys.executable, os.path.abspath(__file__), "--session", os.path.abspath(session_path)],
|
| 297 |
+
stdin=subprocess.DEVNULL, stdout=err, stderr=err, env=env)
|
| 298 |
+
deadline = time.time() + timeout_s
|
| 299 |
+
while time.time() < deadline:
|
| 300 |
+
if p.poll() is not None:
|
| 301 |
+
raise RuntimeError(f"tool gateway exited with code {p.returncode}; see {log_dir}/gateway_stderr.txt")
|
| 302 |
+
if os.path.exists(gfile):
|
| 303 |
+
return p, json.load(open(gfile))
|
| 304 |
+
time.sleep(0.05)
|
| 305 |
+
stop_gateway(p)
|
| 306 |
+
raise RuntimeError(f"tool gateway did not start within {timeout_s} s")
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def stop_gateway(p):
|
| 310 |
+
if p is None or p.poll() is not None:
|
| 311 |
+
return
|
| 312 |
+
p.terminate()
|
| 313 |
+
try:
|
| 314 |
+
p.wait(timeout=10)
|
| 315 |
+
except subprocess.TimeoutExpired:
|
| 316 |
+
p.kill()
|
| 317 |
+
p.wait()
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
def main():
|
| 321 |
+
ap = argparse.ArgumentParser()
|
| 322 |
+
ap.add_argument("--session", required=True, help="session.json written by start_robot_session.sh (la style)")
|
| 323 |
+
ap.add_argument("--port", type=int, default=0, help="0 = pick a free port")
|
| 324 |
+
ap.add_argument("--gateway-file", default=None, help=f"default <log dir>/{GATEWAY_FILE}")
|
| 325 |
+
ap.add_argument("--no-watch-parent", action="store_true", help="keep running when the launcher exits")
|
| 326 |
+
a = ap.parse_args()
|
| 327 |
+
serve(ToolCore(a.session), port=a.port, gateway_file=a.gateway_file, watch_parent=not a.no_watch_parent)
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
if __name__ == "__main__":
|
| 331 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/trace_html.py
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Render one player-subagent run as a self-contained HTML trace: everything the agent received,
|
| 2 |
+
every command it ran, every result and image it saw, its own text, plus the server-side ground truth.
|
| 3 |
+
|
| 4 |
+
python scripts/trace_html.py --batch exp1 --sandbox <hex> --out traces/<name>.html
|
| 5 |
+
"""
|
| 6 |
+
import argparse
|
| 7 |
+
import base64
|
| 8 |
+
import html
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
|
| 13 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 14 |
+
TRANSCRIPTS = os.environ.get("CLAUDE_TASKS_DIR", "") # the Claude Code session's tasks/ dir (<agentId>.output files)
|
| 15 |
+
|
| 16 |
+
CSS = """
|
| 17 |
+
:root{--bg:#fafaf9;--fg:#1c1917;--mut:#57534e;--card:#fff;--bd:#e7e5e4;--acc:#2563eb;--tool:#f5f5f4;--ok:#15803d;--bad:#b91c1c;--th:#7c3aed}
|
| 18 |
+
@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){--bg:#1c1917;--fg:#e7e5e4;--mut:#a8a29e;--card:#292524;--bd:#44403c;--acc:#60a5fa;--tool:#231f1d;--ok:#4ade80;--bad:#f87171;--th:#c4b5fd}}
|
| 19 |
+
body{background:var(--bg);color:var(--fg);font:14px/1.55 system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;margin:0;padding:16px;max-width:1100px;margin:auto}
|
| 20 |
+
h1{font-size:20px}h2{font-size:17px;margin-top:28px;border-bottom:1px solid var(--bd);padding-bottom:4px}
|
| 21 |
+
.card{background:var(--card);border:1px solid var(--bd);border-radius:8px;padding:10px 12px;margin:8px 0}
|
| 22 |
+
pre{white-space:pre-wrap;word-break:break-word;background:var(--tool);border:1px solid var(--bd);border-radius:6px;padding:8px;font:12px/1.45 ui-monospace,Menlo,monospace;margin:4px 0;max-height:420px;overflow:auto}
|
| 23 |
+
.lbl{font-size:12px;color:var(--mut);font-weight:600;text-transform:uppercase;letter-spacing:.03em}
|
| 24 |
+
.cmd{color:var(--acc)}.think{color:var(--th)}.ok{color:var(--ok);font-weight:600}.bad{color:var(--bad);font-weight:600}
|
| 25 |
+
img{max-width:256px;border-radius:4px;border:1px solid var(--bd);margin:2px}
|
| 26 |
+
details>summary{cursor:pointer;color:var(--mut)}
|
| 27 |
+
table{border-collapse:collapse}td,th{border:1px solid var(--bd);padding:3px 8px;text-align:left;font-size:13px}
|
| 28 |
+
.step{display:flex;gap:8px}.n{color:var(--mut);min-width:34px;font-variant-numeric:tabular-nums}
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def esc(s):
|
| 33 |
+
return html.escape(str(s))
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def ts(x):
|
| 37 |
+
return datetime.fromisoformat(x.replace("Z", "+00:00")).timestamp()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def main():
|
| 41 |
+
ap = argparse.ArgumentParser()
|
| 42 |
+
ap.add_argument("--batch", default="exp1")
|
| 43 |
+
ap.add_argument("--sandbox", required=True, help="sandbox hex id")
|
| 44 |
+
ap.add_argument("--out", required=True)
|
| 45 |
+
ap.add_argument("--title", default="")
|
| 46 |
+
a = ap.parse_args()
|
| 47 |
+
m = json.load(open(os.path.join(ROOT, "runs", "claude", a.batch, "manifest.json")))
|
| 48 |
+
run = next(r for r in m["runs"] if r["sandbox"].endswith(a.sandbox))
|
| 49 |
+
tr = [json.loads(l) for l in open(os.path.join(TRANSCRIPTS, f"{run['agent']}.output"))]
|
| 50 |
+
ev = [json.loads(l) for l in open(os.path.join(run["log"], "events.jsonl"))]
|
| 51 |
+
start = next(e for e in ev if e["ev"] == "session_start")
|
| 52 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 53 |
+
http = [e for e in ev if e["ev"] == "http"]
|
| 54 |
+
think = [h["think_s"] for h in http if h.get("think_s")]
|
| 55 |
+
srv = [h["server_s"] for h in http]
|
| 56 |
+
|
| 57 |
+
out = [f"<!doctype html><html lang='zh'><head><meta charset='utf-8'><meta name='viewport' content='width=device-width,initial-scale=1'><title>{esc(a.title or 'Agent trace')}</title><style>{CSS}</style></head><body>"]
|
| 58 |
+
out.append(f"<h1>{esc(a.title or run['run'])}</h1>")
|
| 59 |
+
out.append("<div class='card'><table>")
|
| 60 |
+
rows = [("任务", run["task"]), ("种子", run["seed"]), ("模型", run["model"]), ("条件", run["cond"] + f"(k={run['k']})"),
|
| 61 |
+
("沙箱", run["sandbox"]), ("服务端 run 名", run["run"]),
|
| 62 |
+
("结果", ";".join(f"第{d['attempt']}次 {'成功' if d['success'] else '失败'}" for d in dones)),
|
| 63 |
+
("命令数 / 模型思考总时长 / 仿真执行总时长", f"{sum(1 for e in ev if e['ev']=='call')} / {sum(think):.0f} s / {sum(srv):.0f} s"),
|
| 64 |
+
("子代理墙钟", f"{(ts(tr[-1]['timestamp']) - ts(tr[0]['timestamp'])) / 60:.1f} min")]
|
| 65 |
+
for k, v in rows:
|
| 66 |
+
out.append(f"<tr><th>{esc(k)}</th><td>{esc(v)}</td></tr>")
|
| 67 |
+
out.append("</table></div>")
|
| 68 |
+
inst = {k: v for k, v in start["inst"].items()}
|
| 69 |
+
out.append("<div class='card'><div class='lbl'>服务端真值(agent 从未看到)</div><pre>" + esc(json.dumps(inst, indent=1, ensure_ascii=False)[:3000]) + "</pre></div>")
|
| 70 |
+
|
| 71 |
+
# ---------------------------------------------------------------- what the agent received
|
| 72 |
+
out.append("<h2>1. agent 收到的上下文</h2>")
|
| 73 |
+
out.append("<div class='card'>Claude Code 内置的系统提示和工具定义不在对话记录里(由 Claude Code 注入,这里看不到原文)。下面是记录里能看到的全部注入内容和我的提示。</div>")
|
| 74 |
+
for d in tr:
|
| 75 |
+
if d["type"] != "attachment":
|
| 76 |
+
continue
|
| 77 |
+
at = d["attachment"]
|
| 78 |
+
t = at.get("type")
|
| 79 |
+
if t == "instructions":
|
| 80 |
+
for f in at.get("files", []):
|
| 81 |
+
out.append(f"<details class='card'><summary>注入附���:{esc(f.get('type'))} — {esc(f.get('path'))}({len(f.get('content',''))} 字符)</summary><pre>{esc(f.get('content',''))}</pre></details>")
|
| 82 |
+
elif t in ("environment", "model", "date", "session_context", "skill_listing", "deferred_tools_delta", "credential_org"):
|
| 83 |
+
body = json.dumps({k: v for k, v in at.items() if k != "type"}, ensure_ascii=False, indent=1)
|
| 84 |
+
out.append(f"<details class='card'><summary>注入附件:{esc(t)}({len(body)} 字符)</summary><pre>{esc(body[:6000])}</pre></details>")
|
| 85 |
+
first_user = next(d for d in tr if d["type"] == "user")
|
| 86 |
+
out.append("<div class='card'><div class='lbl'>我给 agent 的提示(原文)</div><pre>" + esc(first_user["message"]["content"]) + "</pre></div>")
|
| 87 |
+
|
| 88 |
+
# ---------------------------------------------------------------- timeline
|
| 89 |
+
out.append("<h2>2. 逐步过程(agent 的文字、执行的命令、收到的结果和图像)</h2>")
|
| 90 |
+
n = 0
|
| 91 |
+
results = {}
|
| 92 |
+
for d in tr:
|
| 93 |
+
if d["type"] == "user" and isinstance(d["message"].get("content"), list):
|
| 94 |
+
for c in d["message"]["content"]:
|
| 95 |
+
if c.get("type") == "tool_result":
|
| 96 |
+
results[c["tool_use_id"]] = c
|
| 97 |
+
t0 = ts(tr[0]["timestamp"])
|
| 98 |
+
for d in tr:
|
| 99 |
+
if d["type"] != "assistant":
|
| 100 |
+
continue
|
| 101 |
+
for c in d["message"].get("content", []):
|
| 102 |
+
ct = c.get("type")
|
| 103 |
+
tt = f"+{ts(d['timestamp']) - t0:6.0f}s"
|
| 104 |
+
if ct == "thinking" and c.get("thinking"):
|
| 105 |
+
out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl think'>思考</span><pre class='think'>{esc(c['thinking'])}</pre></div>")
|
| 106 |
+
elif ct == "text" and c.get("text", "").strip():
|
| 107 |
+
out.append(f"<div class='card'><span class='n'>{tt}</span> <span class='lbl'>agent 文字</span><pre>{esc(c['text'])}</pre></div>")
|
| 108 |
+
elif ct == "tool_use":
|
| 109 |
+
n += 1
|
| 110 |
+
inp = c.get("input", {})
|
| 111 |
+
if c["name"] == "Bash":
|
| 112 |
+
head = f"Bash: <span class='cmd'>{esc(inp.get('command',''))}</span>"
|
| 113 |
+
elif c["name"] == "Read":
|
| 114 |
+
head = f"Read: <span class='cmd'>{esc(inp.get('file_path',''))}</span>"
|
| 115 |
+
elif c["name"] == "SubagentHandback":
|
| 116 |
+
head = "最终报告(SubagentHandback)"
|
| 117 |
+
else:
|
| 118 |
+
head = f"{esc(c['name'])}: {esc(json.dumps(inp, ensure_ascii=False)[:300])}"
|
| 119 |
+
block = [f"<div class='card'><span class='n'>{tt} #{n}</span> <span class='lbl'>工具调用</span> {head}"]
|
| 120 |
+
if c["name"] == "SubagentHandback":
|
| 121 |
+
block.append(f"<pre>{esc(inp.get('message',''))}</pre>")
|
| 122 |
+
r = results.get(c["id"])
|
| 123 |
+
if r is not None:
|
| 124 |
+
rc = r.get("content")
|
| 125 |
+
if isinstance(rc, str):
|
| 126 |
+
rc = [{"type": "text", "text": rc}]
|
| 127 |
+
for part in rc or []:
|
| 128 |
+
if part.get("type") == "text":
|
| 129 |
+
txt = part["text"]
|
| 130 |
+
block.append(f"<details {'open' if len(txt) < 1500 else ''}><summary>返回({len(txt)} 字符)</summary><pre>{esc(txt)}</pre></details>")
|
| 131 |
+
elif part.get("type") == "image":
|
| 132 |
+
src = part.get("source", {})
|
| 133 |
+
if src.get("type") == "base64":
|
| 134 |
+
block.append(f"<img src='data:{src.get('media_type','image/jpeg')};base64,{src['data']}'>")
|
| 135 |
+
block.append("</div>")
|
| 136 |
+
out.extend(block)
|
| 137 |
+
out.append("<h2>3. 服务端每次 done 的判定</h2>")
|
| 138 |
+
for e in dones:
|
| 139 |
+
out.append(f"<div class='card'>第 {e['attempt']} 次:<span class='{'ok' if e['success'] else 'bad'}'>{'成功' if e['success'] else '失败'}</span><pre>{esc(e.get('feedback',''))}</pre></div>")
|
| 140 |
+
out.append("</body></html>")
|
| 141 |
+
os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
|
| 142 |
+
with open(a.out, "w") as f:
|
| 143 |
+
f.write("\n".join(out))
|
| 144 |
+
print(a.out, os.path.getsize(a.out), "bytes; tool calls", n)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
if __name__ == "__main__":
|
| 148 |
+
main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/validate_parts_cart.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Development physical validation; no model API, no pose injection after reset."""
|
| 2 |
+
import argparse,copy,json,time,hashlib
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from lffbench.tasks.lh_parts_cart import PartsCart
|
| 7 |
+
from lffbench import envs
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
p=argparse.ArgumentParser();p.add_argument('--seeds',nargs='+',type=int,default=[1000,1001,1002]);p.add_argument('--out',required=True);p.add_argument('--case',choices=['combined','oracle','l4','l2','l5'],default='combined');a=p.parse_args()
|
| 11 |
+
out=Path(a.out);out.mkdir(parents=True,exist_ok=True)
|
| 12 |
+
x=PartsCart(cam_res=512);rows=[]
|
| 13 |
+
def clean(obj):
|
| 14 |
+
if isinstance(obj,np.ndarray):return obj.tolist()
|
| 15 |
+
if isinstance(obj,np.generic):return obj.item()
|
| 16 |
+
raise TypeError(type(obj).__name__)
|
| 17 |
+
for seed in a.seeds:
|
| 18 |
+
i=x.sample_instance(seed)
|
| 19 |
+
if a.case in ['l4','l2','l5']:i['traps']={k:k==a.case.upper() for k in ['L4','L2','L5']}
|
| 20 |
+
x.reset_instance(i);r=dict(seed=seed,case=a.case,instance=i,checkpoints=[]);rows.append(r)
|
| 21 |
+
def snap(label):
|
| 22 |
+
o=copy.deepcopy(x.outcome(i));q=out/f's{seed}_{label}.png';Image.fromarray(x.snapshot(res=512)).save(q)
|
| 23 |
+
r['checkpoints'].append(dict(label=label,sim_step=x.sk.n_steps,commands=x.sk.robot_commands,outcome=o,image=str(q.resolve())))
|
| 24 |
+
(out/'results.json').write_text(json.dumps(rows,indent=2,default=clean))
|
| 25 |
+
print(seed,label,o['success'],o['traps'],o['stages'],flush=True)
|
| 26 |
+
snap('initial')
|
| 27 |
+
if a.case=='oracle':
|
| 28 |
+
x.execute(i,x.oracle_params(i));snap('oracle_final');continue
|
| 29 |
+
if a.case in ['combined','l4']:
|
| 30 |
+
x.tool_push_out();snap('L4_blocked')
|
| 31 |
+
x.tool_push_front();snap('L4_retrieved')
|
| 32 |
+
x.load(careful=a.case not in ['combined','l2']);snap('loaded')
|
| 33 |
+
if a.case in ['combined','l2']:
|
| 34 |
+
x.repair_load();snap('L2_restored')
|
| 35 |
+
if all(x.cargo_ok(j) for j in range(2)):
|
| 36 |
+
if a.case in ['combined','l5']:
|
| 37 |
+
# First full naive push, then reuse correction loop without its initial push.
|
| 38 |
+
x.transport(0.,False);snap('L5_naive_push')
|
| 39 |
+
x._transport_only=True
|
| 40 |
+
# Feed a no-op execute only for the corrector's initial call; subsequent _push_at are unchanged.
|
| 41 |
+
original=x.execute
|
| 42 |
+
x.execute=lambda inst,params:None
|
| 43 |
+
try:
|
| 44 |
+
from lffbench.tasks.l7_offcenter_push import OffcenterPush
|
| 45 |
+
OffcenterPush.adaptive_attempt(x,i,0.)
|
| 46 |
+
finally:x.execute=original;x._transport_only=False
|
| 47 |
+
snap('L5_corrected')
|
| 48 |
+
else:x.transport(i['com_offset'],False)
|
| 49 |
+
x.repair_load();x.sk.set_gripper(False,steps=10);e=x.sk.eef_pos();x.sk.move_to([e[0],e[1],envs.TABLE_Z+.24]);snap('final')
|
| 50 |
+
x.env.close()
|
| 51 |
+
(out/'manifest.json').write_text(json.dumps(dict(case=a.case,seeds=a.seeds,task_sha256=hashlib.sha256(Path(__file__).parents[1].joinpath('lffbench/tasks/lh_parts_cart.py').read_bytes()).hexdigest(),note='scripted development validation, not model runs'),indent=2))
|
| 52 |
+
if __name__=='__main__':main()
|
leaf/release/source_packages/breakfast-v2-20261103-breakfast_v2_20261103_opus/lff/source_closure/scripts/vla_acceptance.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Acceptance test of the VLA evaluator (lffbench/vla.py) against recorded agent attempts.
|
| 3 |
+
|
| 4 |
+
Replays recorded first attempts through the exact path a policy takes (vla.run_session) and checks
|
| 5 |
+
- the verdict: outcome() must give the recorded label, for successes AND failures;
|
| 6 |
+
- the observation: state and both cameras must equal what the LeRobot dataset holds for that frame, and the prompt
|
| 7 |
+
must be what the agent was told (first_message.txt; the proprioception frame is "true" here because the dataset
|
| 8 |
+
records the true pose; the evaluator's default applies the L1 calibration errors).
|
| 9 |
+
|
| 10 |
+
python3 scripts/vla_acceptance.py plan --out DIR [--per-label 2] # no simulator; any python with pyarrow
|
| 11 |
+
python scripts/vla_acceptance.py one DIR/cand/<stem>.json # one attempt, in the LFF environment
|
| 12 |
+
python3 scripts/vla_acceptance.py summary DIR
|
| 13 |
+
|
| 14 |
+
An open-loop replay is only meaningful when the recording is reproduced, so lossless float64 actions are used where the
|
| 15 |
+
intermediate recordings exist (published parquet actions are float32 and diverge on chaotic contacts). A candidate
|
| 16 |
+
whose replay leaves the recording is reported as `diverged`, not as a verdict error.
|
| 17 |
+
"""
|
| 18 |
+
import argparse
|
| 19 |
+
import collections
|
| 20 |
+
import glob
|
| 21 |
+
import hashlib
|
| 22 |
+
import json
|
| 23 |
+
import os
|
| 24 |
+
import sys
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
|
| 28 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 29 |
+
AR = os.path.dirname(ROOT)
|
| 30 |
+
DATA = "/mnt/cpfs/shared/datasets/lffbench_agent_replays"
|
| 31 |
+
CUMULATIVE = {"v1.0", "v1.1", "v1.2", "v1.3"}
|
| 32 |
+
DIVERGED_M = 0.005 # the replayed grasp point is this far from the recording
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _sha(path, memo={}):
|
| 36 |
+
if path not in memo:
|
| 37 |
+
memo[path] = hashlib.sha256(open(path, "rb").read()).hexdigest() if os.path.exists(path) else None
|
| 38 |
+
return memo[path]
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def code_matches(run_dir):
|
| 42 |
+
p = os.path.join(run_dir, "contract.json")
|
| 43 |
+
if not os.path.exists(p):
|
| 44 |
+
return False
|
| 45 |
+
files = json.load(open(p))["contract"].get("server_code_files") or {}
|
| 46 |
+
return bool(files) and all(_sha(os.path.join(ROOT, f)) == h for f, h in files.items())
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def raw_roots():
|
| 50 |
+
roots = [f"{AR}/lerobot_replay_raw_local", f"{AR}/lerobot_replay_raw_dlc"]
|
| 51 |
+
for pat in ("ops/lerobot_backfill_20261102/exports/*/raw", "ops/lerobot_backfill_20261102/dlc_parallel/exports/*/raw",
|
| 52 |
+
"ops/compound_lh_eval_20261102/exports/*/raw", "ops/codex_watch/*/exports/*/raw",
|
| 53 |
+
"ops/lerobot_deepseek_20261030/exports/*/raw"):
|
| 54 |
+
roots += glob.glob(os.path.join(AR, pat))
|
| 55 |
+
return roots
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def cmd_plan(a):
|
| 59 |
+
import pyarrow.dataset as ds
|
| 60 |
+
os.makedirs(os.path.join(a.out, "cand"), exist_ok=True)
|
| 61 |
+
roots = raw_roots()
|
| 62 |
+
pool = collections.defaultdict(list)
|
| 63 |
+
for name in sorted(os.listdir(DATA)):
|
| 64 |
+
p = os.path.join(DATA, name, "lff/episodes.jsonl")
|
| 65 |
+
if name in CUMULATIVE or not os.path.exists(p):
|
| 66 |
+
continue
|
| 67 |
+
for line in open(p):
|
| 68 |
+
r = json.loads(line)
|
| 69 |
+
if not r["attempts"] or r["attempts"][0] != 1 or r["success"][0] is None:
|
| 70 |
+
continue
|
| 71 |
+
if r.get("auto_ended") and r["auto_ended"][0]: # ended by a budget inside the server, not by `finish`
|
| 72 |
+
continue
|
| 73 |
+
pool[(r["task"], bool(r["success"][0]))].append((r["length"], name, r))
|
| 74 |
+
n, missing = 0, []
|
| 75 |
+
for (task, label), lst in sorted(pool.items()):
|
| 76 |
+
lst.sort(key=lambda x: x[0])
|
| 77 |
+
got, seeds = 0, set()
|
| 78 |
+
for need_raw in (True, False):
|
| 79 |
+
for length, name, r in lst:
|
| 80 |
+
if got >= a.per_label:
|
| 81 |
+
break
|
| 82 |
+
if r["seed"] in seeds:
|
| 83 |
+
continue
|
| 84 |
+
run_dir = os.path.join(ROOT, "runs/api", r["batch"], r["run"])
|
| 85 |
+
if not os.path.isdir(run_dir) or not code_matches(run_dir):
|
| 86 |
+
continue
|
| 87 |
+
raw = next((q for q in (f"{x}/{r['batch']}/{r['run']}/ep00/frames.npz" for x in roots) if os.path.exists(q)), None)
|
| 88 |
+
if need_raw and raw is None:
|
| 89 |
+
continue
|
| 90 |
+
stem = f"{task}__{'ok' if label else 'fail'}{got}"
|
| 91 |
+
cand = dict(stem=stem, task=task, seed=r["seed"], label=label, run_dir=run_dir, dataset=name, episode_index=r["episode_index"],
|
| 92 |
+
instruction=r["instruction"], protocol=r["protocol"], model=r["model"], raw=raw, length=r["length"])
|
| 93 |
+
if raw is None:
|
| 94 |
+
t = ds.dataset(os.path.join(DATA, name, "data"), format="parquet").to_table(
|
| 95 |
+
columns=["action", "annotation.phase", "annotation.attempt_index", "observation.state", "frame_index"],
|
| 96 |
+
filter=ds.field("episode_index") == r["episode_index"]).sort_by("frame_index")
|
| 97 |
+
np.savez(os.path.join(a.out, "cand", stem + ".npz"),
|
| 98 |
+
action=np.stack(t["action"].to_numpy(zero_copy_only=False)).astype(np.float64),
|
| 99 |
+
phase=t["annotation.phase"].to_numpy().astype(int).reshape(-1),
|
| 100 |
+
attempt=t["annotation.attempt_index"].to_numpy().astype(int).reshape(-1),
|
| 101 |
+
state=np.stack(t["observation.state"].to_numpy(zero_copy_only=False)).astype(np.float64))
|
| 102 |
+
json.dump(cand, open(os.path.join(a.out, "cand", stem + ".json"), "w"), indent=1)
|
| 103 |
+
got += 1
|
| 104 |
+
n += 1
|
| 105 |
+
seeds.add(r["seed"])
|
| 106 |
+
if got < a.per_label:
|
| 107 |
+
missing.append((task, label, got))
|
| 108 |
+
print(n, "candidates;", "short of the requested count:", missing)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def video_frame(path, t):
|
| 112 |
+
import cv2
|
| 113 |
+
cap = cv2.VideoCapture(path)
|
| 114 |
+
cap.set(cv2.CAP_PROP_POS_FRAMES, t)
|
| 115 |
+
ok, img = cap.read()
|
| 116 |
+
cap.release()
|
| 117 |
+
return img[:, :, ::-1] if ok else None
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def cmd_one(a):
|
| 121 |
+
sys.path.insert(0, ROOT)
|
| 122 |
+
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
| 123 |
+
import lerobot_replay as LR
|
| 124 |
+
from lffbench import vla
|
| 125 |
+
c = json.load(open(a.cand))
|
| 126 |
+
if c["raw"]:
|
| 127 |
+
z = np.load(c["raw"])
|
| 128 |
+
keep = (z["attempt"] == 1) & (z["phase"] != 2)
|
| 129 |
+
state = np.concatenate([z["eef_pos"], z["eef_axis_angle"], z["gripper_qpos"]], axis=1)
|
| 130 |
+
precision = "float64"
|
| 131 |
+
else:
|
| 132 |
+
z = np.load(a.cand[:-5] + ".npz")
|
| 133 |
+
keep = (z["attempt"] == 1) & (z["phase"] != 2)
|
| 134 |
+
state = z["state"]
|
| 135 |
+
precision = "float32"
|
| 136 |
+
idx = np.flatnonzero(keep)
|
| 137 |
+
assert (np.diff(idx) == 1).all() and idx[0] == 0, "attempt 1 must be one contiguous prefix"
|
| 138 |
+
actions = z["action"][idx]
|
| 139 |
+
s = LR.RunLog(c["run_dir"]).start
|
| 140 |
+
task = LR.TASKS[c["task"]](cam_res=256)
|
| 141 |
+
inst = task.sample_instance(s["seed"])
|
| 142 |
+
logged = s.get("inst") or {}
|
| 143 |
+
if s.get("arm", "none") not in (None, "none") or logged.get("nominal"):
|
| 144 |
+
inst.update(logged)
|
| 145 |
+
first_message = os.path.join(c["run_dir"], "first_message.txt")
|
| 146 |
+
prompt = vla.task_prompt(task, inst)
|
| 147 |
+
res = dict(stem=c["stem"], task=c["task"], seed=c["seed"], label=c["label"], precision=precision, n=len(actions), protocol=c["protocol"],
|
| 148 |
+
prompt_ok=prompt in open(first_message).read() if os.path.exists(first_message) else prompt == c["instruction"],
|
| 149 |
+
first_div=None, parity=[])
|
| 150 |
+
mid = (len(actions) // 2) // 5 * 5
|
| 151 |
+
raw_dir = os.path.dirname(c["raw"]) if c["raw"] else None
|
| 152 |
+
|
| 153 |
+
def on_obs(t, obs):
|
| 154 |
+
err = float(np.abs(obs["observation/state"] - state[t]).max())
|
| 155 |
+
if res["first_div"] is None and np.linalg.norm(obs["observation/state"][:3] - state[t][:3]) > DIVERGED_M:
|
| 156 |
+
res["first_div"] = t
|
| 157 |
+
if t in (0, mid) and res["first_div"] is None:
|
| 158 |
+
row = dict(t=t, state_err=err)
|
| 159 |
+
if raw_dir:
|
| 160 |
+
for key, f in (("observation/image", "agentview.mp4"), ("observation/wrist_image", "wrist.mp4")):
|
| 161 |
+
img = video_frame(os.path.join(raw_dir, f), t)
|
| 162 |
+
if img is not None:
|
| 163 |
+
row[f[:-4] + "_mae"] = float(np.abs(obs[key].astype(float) - img.astype(float)).mean())
|
| 164 |
+
res["parity"].append(row)
|
| 165 |
+
|
| 166 |
+
policy = vla.ReplayPolicy(actions, chunk=5, on_obs=on_obs)
|
| 167 |
+
rec = vla.run_session(task, inst, policy, k=1, max_steps=len(actions), replan=5, frame="true", idle_s=0, probe_every_s=0)[0]
|
| 168 |
+
res.update(verdict=rec["success"], end=rec["end"], n_steps=rec["n_steps"], detail=str(rec["detail"])[:240], failure=rec["failure"])
|
| 169 |
+
res["verdict_ok"] = rec["success"] == c["label"]
|
| 170 |
+
json.dump(res, open(a.cand.replace("/cand/", "/out/"), "w"), indent=1)
|
| 171 |
+
print(c["stem"], "verdict_ok", res["verdict_ok"], "first_div", res["first_div"], "parity", res["parity"][:1], flush=True)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def cmd_summary(a):
|
| 175 |
+
rows = [json.load(open(f)) for f in sorted(glob.glob(os.path.join(a.dir, "out/*.json")))]
|
| 176 |
+
tally = collections.Counter()
|
| 177 |
+
bad = []
|
| 178 |
+
for r in rows:
|
| 179 |
+
kind = "ok" if r["label"] else "fail"
|
| 180 |
+
if r["verdict_ok"]:
|
| 181 |
+
tally[kind + "_right"] += 1
|
| 182 |
+
elif r["first_div"] is not None:
|
| 183 |
+
tally[kind + "_diverged"] += 1
|
| 184 |
+
bad.append(r)
|
| 185 |
+
else:
|
| 186 |
+
tally[kind + "_WRONG"] += 1
|
| 187 |
+
bad.append(r)
|
| 188 |
+
per_task = collections.defaultdict(lambda: collections.Counter())
|
| 189 |
+
for r in rows:
|
| 190 |
+
key = "right" if r["verdict_ok"] else ("diverged" if r["first_div"] is not None else "WRONG")
|
| 191 |
+
per_task[r["task"]][("ok_" if r["label"] else "fail_") + key] += 1
|
| 192 |
+
t0 = [p for r in rows for p in r["parity"] if p["t"] == 0]
|
| 193 |
+
later = [p for r in rows for p in r["parity"] if p["t"] > 0]
|
| 194 |
+
|
| 195 |
+
def worst(ps, key):
|
| 196 |
+
vals = [p[key] for p in ps if key in p]
|
| 197 |
+
return (round(max(vals), 7), len(vals)) if vals else None
|
| 198 |
+
|
| 199 |
+
out = dict(n=len(rows), tally=dict(tally), n_tasks=len(per_task), per_task={t: dict(c) for t, c in sorted(per_task.items())},
|
| 200 |
+
prompt_mismatch=sorted({r["task"] for r in rows if not r["prompt_ok"]}),
|
| 201 |
+
parity_t0=dict(state=worst(t0, "state_err"), agentview=worst(t0, "agentview_mae"), wrist=worst(t0, "wrist_mae")),
|
| 202 |
+
parity_mid=dict(state=worst(later, "state_err"), agentview=worst(later, "agentview_mae"), wrist=worst(later, "wrist_mae")),
|
| 203 |
+
not_right=[{k: r[k] for k in ("stem", "seed", "precision", "first_div", "n", "detail")} for r in bad])
|
| 204 |
+
json.dump(out, open(os.path.join(a.dir, "summary.json"), "w"), indent=1)
|
| 205 |
+
print(json.dumps({k: v for k, v in out.items() if k not in ("per_task", "not_right")}, indent=1))
|
| 206 |
+
for r in out["not_right"]:
|
| 207 |
+
print(r["stem"], r["seed"], r["precision"], "first_div", r["first_div"], "/", r["n"], "|", r["detail"][:130])
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def main():
|
| 211 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 212 |
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
| 213 |
+
p = sub.add_parser("plan")
|
| 214 |
+
p.add_argument("--out", required=True)
|
| 215 |
+
p.add_argument("--per-label", type=int, default=2)
|
| 216 |
+
p.set_defaults(fn=cmd_plan)
|
| 217 |
+
o = sub.add_parser("one")
|
| 218 |
+
o.add_argument("cand")
|
| 219 |
+
o.set_defaults(fn=cmd_one)
|
| 220 |
+
s = sub.add_parser("summary")
|
| 221 |
+
s.add_argument("dir")
|
| 222 |
+
s.set_defaults(fn=cmd_summary)
|
| 223 |
+
a = ap.parse_args()
|
| 224 |
+
a.fn(a)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
if __name__ == "__main__":
|
| 228 |
+
main()
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/agent/backends/chat_completions.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""OpenAI-compatible Chat Completions backend (function calling), e.g. for a local open-source VLM served
|
| 2 |
+
by scripts/qwen_vl_server.py or any vLLM / SGLang endpoint. Same conversation, different wire format.
|
| 3 |
+
|
| 4 |
+
Reasoning models on this API (Kimi, DeepSeek, vLLM reasoning parsers) return their thinking as the non-standard
|
| 5 |
+
message field `reasoning_content`. It is logged as the reasoning summary and, with replay_reasoning (default), sent
|
| 6 |
+
back unchanged on that assistant message, so the model keeps its reasoning across tool calls like the Anthropic and
|
| 7 |
+
Responses backends do (Kimi's docs ask for this in multi-step tool use)."""
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import time
|
| 11 |
+
|
| 12 |
+
from ..context import ToolCall, prune_live_images
|
| 13 |
+
from .base import Backend, BackendResponse, import_openai
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def chat_tools(specs):
|
| 17 |
+
return [dict(type="function", function=dict(name=s["name"], description=s["description"],
|
| 18 |
+
parameters=s["parameters"])) for s in specs]
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ChatCompletionsBackend(Backend):
|
| 22 |
+
name = "chat"
|
| 23 |
+
|
| 24 |
+
def __init__(self, model="qwen3-vl-8b", base_url=None, api_key=None, temperature=0.0, max_tokens=1024,
|
| 25 |
+
max_live_images=4, jpeg_quality=90, timeout=600.0, client=None, extra_body=None,
|
| 26 |
+
replay_reasoning=True):
|
| 27 |
+
self.model = model
|
| 28 |
+
self.base_url = base_url or os.environ.get("LFF_CHAT_BASE_URL", "http://127.0.0.1:8765/v1")
|
| 29 |
+
self.api_key = api_key or os.environ.get("LFF_CHAT_API_KEY", "EMPTY")
|
| 30 |
+
self.temperature = temperature
|
| 31 |
+
self.max_tokens = max_tokens
|
| 32 |
+
self.max_live_images = max_live_images
|
| 33 |
+
self.jpeg_quality = jpeg_quality
|
| 34 |
+
self.timeout = timeout
|
| 35 |
+
self.extra_body = extra_body
|
| 36 |
+
self.replay_reasoning = replay_reasoning
|
| 37 |
+
self._client = client
|
| 38 |
+
|
| 39 |
+
def config(self):
|
| 40 |
+
return dict(name=self.name, model=self.model, base_url=self.base_url, temperature=self.temperature,
|
| 41 |
+
max_tokens=self.max_tokens, max_live_images=self.max_live_images,
|
| 42 |
+
replay_reasoning=self.replay_reasoning)
|
| 43 |
+
|
| 44 |
+
def client(self):
|
| 45 |
+
if self._client is None:
|
| 46 |
+
openai = import_openai()
|
| 47 |
+
kw = dict(api_key=self.api_key, base_url=self.base_url, timeout=self.timeout, max_retries=1)
|
| 48 |
+
if any(h in self.base_url for h in ("://127.0.0.1", "://localhost")):
|
| 49 |
+
# local server: ignore the machine's proxy variables (ALL_PROXY=socks5h://... is set here)
|
| 50 |
+
kw["http_client"] = openai.DefaultHttpxClient(trust_env=False, timeout=self.timeout)
|
| 51 |
+
self._client = openai.OpenAI(**kw)
|
| 52 |
+
return self._client
|
| 53 |
+
|
| 54 |
+
def build_request(self, conv, tools):
|
| 55 |
+
msgs = [dict(role="system", content=conv.system)]
|
| 56 |
+
for it in prune_live_images(conv.items, self.max_live_images):
|
| 57 |
+
if it["kind"] == "user":
|
| 58 |
+
content = []
|
| 59 |
+
for p in it["parts"]:
|
| 60 |
+
if p["type"] == "text":
|
| 61 |
+
content.append(dict(type="text", text=p["text"]))
|
| 62 |
+
else:
|
| 63 |
+
content.append(dict(type="image_url", image_url=dict(url=p["image"].data_url(self.jpeg_quality))))
|
| 64 |
+
msgs.append(dict(role="user", content=content))
|
| 65 |
+
elif it["kind"] == "assistant":
|
| 66 |
+
if not it.get("text") and not it["tool_calls"]:
|
| 67 |
+
# a reasoning-only turn (no text, no tool call; seen with DeepSeek at effort=max): the player still
|
| 68 |
+
# counts it and nudges, but OpenAI-compatible APIs reject an assistant message with neither content
|
| 69 |
+
# nor tool_calls (DeepSeek: 400 "content or tool_calls must be set"), so it is left out of the request
|
| 70 |
+
continue
|
| 71 |
+
m = dict(role="assistant", content=it.get("text") or None)
|
| 72 |
+
rc = (it.get("raw") or [{}])[0].get("reasoning_content") if it.get("backend") == self.name else None
|
| 73 |
+
if rc and self.replay_reasoning:
|
| 74 |
+
m["reasoning_content"] = rc
|
| 75 |
+
if it["tool_calls"]:
|
| 76 |
+
m["tool_calls"] = [dict(id=tc.id, type="function",
|
| 77 |
+
function=dict(name=tc.name,
|
| 78 |
+
arguments=tc.raw_arguments or json.dumps(tc.arguments)))
|
| 79 |
+
for tc in it["tool_calls"]]
|
| 80 |
+
msgs.append(m)
|
| 81 |
+
elif it["kind"] == "tool_output":
|
| 82 |
+
msgs.append(dict(role="tool", tool_call_id=it["call_id"], content=it["text"]))
|
| 83 |
+
req = dict(model=self.model, messages=tool_results_first(msgs), tools=chat_tools(tools), tool_choice="auto",
|
| 84 |
+
max_tokens=self.max_tokens)
|
| 85 |
+
if self.temperature is not None: # None: the endpoint's default (reasoning models may reject a temperature)
|
| 86 |
+
req["temperature"] = self.temperature
|
| 87 |
+
if self.extra_body:
|
| 88 |
+
req["extra_body"] = dict(self.extra_body)
|
| 89 |
+
return req
|
| 90 |
+
|
| 91 |
+
def act(self, conv, tools):
|
| 92 |
+
req = self.build_request(conv, tools)
|
| 93 |
+
n_img = sum(1 for m in req["messages"] if isinstance(m.get("content"), list)
|
| 94 |
+
for c in m["content"] if c.get("type") == "image_url")
|
| 95 |
+
t0 = time.time()
|
| 96 |
+
resp = self.client().chat.completions.create(**req)
|
| 97 |
+
lat = time.time() - t0
|
| 98 |
+
stats = dict(n_images=n_img, n_messages=len(req["messages"]))
|
| 99 |
+
if not getattr(resp, "choices", None): # gateway hiccup: nothing to append, the player asks again
|
| 100 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 101 |
+
error="empty response (no choices)")
|
| 102 |
+
msg = resp.choices[0].message
|
| 103 |
+
rc = getattr(msg, "reasoning_content", None) or (getattr(msg, "model_extra", None) or {}).get("reasoning_content")
|
| 104 |
+
calls = []
|
| 105 |
+
for i, tc in enumerate(msg.tool_calls or []):
|
| 106 |
+
raw = tc.function.arguments or ""
|
| 107 |
+
try:
|
| 108 |
+
args = json.loads(raw) if raw else {}
|
| 109 |
+
except json.JSONDecodeError:
|
| 110 |
+
args = {}
|
| 111 |
+
calls.append(ToolCall(id=tc.id or f"call_{i}", name=tc.function.name, arguments=args, raw_arguments=raw))
|
| 112 |
+
u = resp.usage
|
| 113 |
+
ctd = getattr(u, "completion_tokens_details", None) if u else None
|
| 114 |
+
usage = dict(input_tokens=getattr(u, "prompt_tokens", 0) or 0, cached_tokens=0,
|
| 115 |
+
output_tokens=getattr(u, "completion_tokens", 0) or 0,
|
| 116 |
+
reasoning_tokens=(getattr(ctd, "reasoning_tokens", 0) or 0) if ctd else 0) if u else {}
|
| 117 |
+
if not calls and not msg.content and not rc and not u:
|
| 118 |
+
return BackendResponse(latency_s=lat, request_stats=stats, status="incomplete",
|
| 119 |
+
error="empty response (no output, no usage)")
|
| 120 |
+
return BackendResponse(tool_calls=calls, text=msg.content or None, reasoning_summary=rc or None, usage=usage,
|
| 121 |
+
latency_s=lat, raw=[dict(reasoning_content=rc)] if rc else None, request_stats=stats)
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def tool_results_first(msgs):
|
| 125 |
+
"""OpenAI-compatible APIs require every tool_call of an assistant message to be answered by tool messages directly
|
| 126 |
+
after it. The player adds the images a tool returned (view_images, robot) as a user message right after that tool's
|
| 127 |
+
output, so a turn with several tool calls (e.g. view_images then shell) would put a user message between the tool
|
| 128 |
+
messages (DeepSeek: 400 "insufficient tool messages following tool_calls message"). Move such user messages after
|
| 129 |
+
the last tool message of the turn; nothing else changes order."""
|
| 130 |
+
out, i = [], 0
|
| 131 |
+
while i < len(msgs):
|
| 132 |
+
m = msgs[i]
|
| 133 |
+
out.append(m)
|
| 134 |
+
i += 1
|
| 135 |
+
if m["role"] != "assistant" or not m.get("tool_calls"):
|
| 136 |
+
continue
|
| 137 |
+
need = {tc["id"] for tc in m["tool_calls"]}
|
| 138 |
+
held = []
|
| 139 |
+
while i < len(msgs) and need:
|
| 140 |
+
n = msgs[i]
|
| 141 |
+
if n["role"] == "tool" and n.get("tool_call_id") in need:
|
| 142 |
+
out.append(n)
|
| 143 |
+
need.discard(n["tool_call_id"])
|
| 144 |
+
elif n["role"] == "user":
|
| 145 |
+
held.append(n)
|
| 146 |
+
else:
|
| 147 |
+
break
|
| 148 |
+
i += 1
|
| 149 |
+
out.extend(held)
|
| 150 |
+
return out
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/codex-chatgpt-generic_0.163.0_399ff69c431c066e_gpt-6-astra_high.json
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex-chatgpt-generic|0.163.0|399ff69c431c066e|gpt-6-astra|high",
|
| 3 |
+
"fingerprint_sha256": "41fecee198c38459b5fae54c29ebf99c368e60381b3f11418dea02590bba5222",
|
| 4 |
+
"written": "2026-10-20 02:33:15",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 16979,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"list_mcp_resource_templates",
|
| 9 |
+
"list_mcp_resources",
|
| 10 |
+
"mcp__lff.robot",
|
| 11 |
+
"mcp__lff.shell",
|
| 12 |
+
"mcp__lff.view_images",
|
| 13 |
+
"read_mcp_resource",
|
| 14 |
+
"request_user_input"
|
| 15 |
+
],
|
| 16 |
+
"effort_in_request": "high",
|
| 17 |
+
"model_in_request": "gpt-6-astra",
|
| 18 |
+
"sandbox": {
|
| 19 |
+
"sandbox": "seccomp",
|
| 20 |
+
"sandbox_mode": "read-only"
|
| 21 |
+
}
|
| 22 |
+
}
|
| 23 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/lffbench/harnesses/pins/codex_0.156.0_78a11f06e0a2dda4_gpt-6-astra_medium.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "codex|0.156.0|78a11f06e0a2dda4|gpt-6-astra|medium",
|
| 3 |
+
"fingerprint_sha256": "cdffdbedeb4b110f1f29227ee9459940be8175df4ca71546690ff6db0cccbd6a",
|
| 4 |
+
"written": "2026-10-13 04:13:35",
|
| 5 |
+
"summary": {
|
| 6 |
+
"developer_chars": 23961,
|
| 7 |
+
"top_tools": [
|
| 8 |
+
"collaboration.followup_task",
|
| 9 |
+
"collaboration.interrupt_agent",
|
| 10 |
+
"collaboration.list_agents",
|
| 11 |
+
"collaboration.send_message",
|
| 12 |
+
"collaboration.spawn_agent",
|
| 13 |
+
"collaboration.wait_agent",
|
| 14 |
+
"functions.exec",
|
| 15 |
+
"functions.request_user_input",
|
| 16 |
+
"functions.request_user_input_async",
|
| 17 |
+
"functions.wait"
|
| 18 |
+
],
|
| 19 |
+
"all_tools": [
|
| 20 |
+
"apply_patch",
|
| 21 |
+
"clock__curr_time",
|
| 22 |
+
"list_mcp_resource_templates",
|
| 23 |
+
"list_mcp_resources",
|
| 24 |
+
"mcp__lff__robot",
|
| 25 |
+
"mcp__lff__shell",
|
| 26 |
+
"mcp__lff__view_images",
|
| 27 |
+
"read_mcp_resource"
|
| 28 |
+
],
|
| 29 |
+
"effort_in_request": "medium",
|
| 30 |
+
"model_in_request": "gpt-6-astra",
|
| 31 |
+
"sandbox": {
|
| 32 |
+
"sandbox": "seccomp",
|
| 33 |
+
"sandbox_mode": "read-only"
|
| 34 |
+
}
|
| 35 |
+
}
|
| 36 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/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_opus/lff/source_closure/lffbench/harnesses/pins/sensenova_codex-generic-2c45c1ca7b3b_0.163.0_399ff69c431c066e_gpt-6.1-sol_high.json
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"key": "sensenova_codex-generic-2c45c1ca7b3b|0.163.0|399ff69c431c066e|gpt-6.1-sol|high",
|
| 3 |
+
"fingerprint_sha256": "4a741aa5b9ff4e51ead5f08944f6bd44f4bfbb79731098fb24d37d32a43fcba9",
|
| 4 |
+
"written": "2026-10-25 04:38:49",
|
| 5 |
+
"summary": {
|
| 6 |
+
"report": "reports/robot_harness_integration_20261025/selfcheck_final/selfcheck.json",
|
| 7 |
+
"checks": 10,
|
| 8 |
+
"framework": {
|
| 9 |
+
"commit": "b513a1c7289ab11eb844856588b64c378705c405",
|
| 10 |
+
"patch_sha256": "70b46c683ddd7e18593c9340da272ffb29d7f60708477aea5eed9f021bc9e823",
|
| 11 |
+
"tree_sha256": "2c45c1ca7b3bf6182adebd373f7ff15bd6db5f0dd583f5c8113a87a88afee350",
|
| 12 |
+
"untracked": [
|
| 13 |
+
"lff_integration/__init__.py",
|
| 14 |
+
"lff_integration/run.py"
|
| 15 |
+
]
|
| 16 |
+
}
|
| 17 |
+
}
|
| 18 |
+
}
|
leaf/release/source_packages/compound-lh-20261102-clh_20261102_opus/lff/source_closure/scripts/agent_viewer/export.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Export saved API-player runs as a portable, offline Agent Viewer.
|
| 2 |
+
|
| 3 |
+
No simulator/model calls are made. Original image bytes are embedded once.
|
| 4 |
+
Supports transcript.jsonl and gpt_transcript.jsonl (API-player event schema).
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import base64
|
| 10 |
+
import hashlib
|
| 11 |
+
import json
|
| 12 |
+
import re
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def read_jsonl(path):
|
| 17 |
+
rows = []
|
| 18 |
+
for number, line in enumerate(path.read_text().splitlines(), 1):
|
| 19 |
+
if line.strip():
|
| 20 |
+
try:
|
| 21 |
+
rows.append(json.loads(line))
|
| 22 |
+
except json.JSONDecodeError as exc:
|
| 23 |
+
raise ValueError(f"{path.name}:{number}: malformed JSON; export a completed log") from exc
|
| 24 |
+
return rows
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def parse_output(value):
|
| 28 |
+
if isinstance(value, dict):
|
| 29 |
+
return value
|
| 30 |
+
try:
|
| 31 |
+
parsed = json.loads(value)
|
| 32 |
+
return parsed if isinstance(parsed, dict) else {}
|
| 33 |
+
except (ValueError, TypeError):
|
| 34 |
+
return {}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def build_run(folder, assets, sandbox_override=None):
|
| 38 |
+
folder = Path(folder)
|
| 39 |
+
transcript = next((folder / name for name in ('transcript.jsonl', 'gpt_transcript.jsonl')
|
| 40 |
+
if (folder / name).exists()), None)
|
| 41 |
+
if not transcript:
|
| 42 |
+
raise ValueError(f"No supported API-player transcript in {folder}")
|
| 43 |
+
rows = read_jsonl(transcript)
|
| 44 |
+
if not any(row.get('ev') == 'assistant' for row in rows):
|
| 45 |
+
raise ValueError(f"No API-player assistant events in {transcript}")
|
| 46 |
+
session = json.loads((folder / 'session.json').read_text())
|
| 47 |
+
events = read_jsonl(folder / 'events.jsonl') if (folder / 'events.jsonl').exists() else []
|
| 48 |
+
start = next((r for r in rows if r.get('ev') == 'start'), {})
|
| 49 |
+
server = next((r for r in events if r.get('ev') == 'session_start'), {})
|
| 50 |
+
sandbox = Path(sandbox_override or session.get('sandbox', folder))
|
| 51 |
+
warnings, cache = [], {}
|
| 52 |
+
|
| 53 |
+
def images(refs, source, timestamp):
|
| 54 |
+
result = []
|
| 55 |
+
for ref in refs:
|
| 56 |
+
if not isinstance(ref, str):
|
| 57 |
+
raise ValueError('Expected image path strings in API-player transcript')
|
| 58 |
+
if ref not in cache:
|
| 59 |
+
relative = Path(ref)
|
| 60 |
+
roots = [folder, sandbox]
|
| 61 |
+
candidates = []
|
| 62 |
+
# Only export images within the explicitly selected run/sandbox.
|
| 63 |
+
for root in roots:
|
| 64 |
+
candidate = (root / relative).resolve()
|
| 65 |
+
if candidate.is_relative_to(root.resolve()):
|
| 66 |
+
candidates.append(candidate)
|
| 67 |
+
path = next((p for p in candidates if p.is_file()), None)
|
| 68 |
+
key = None
|
| 69 |
+
if path:
|
| 70 |
+
raw = path.read_bytes()
|
| 71 |
+
if raw.startswith(b'\xff\xd8\xff'):
|
| 72 |
+
mime = 'image/jpeg'
|
| 73 |
+
elif raw.startswith(b'\x89PNG\r\n\x1a\n'):
|
| 74 |
+
mime = 'image/png'
|
| 75 |
+
elif raw[:6] in (b'GIF87a', b'GIF89a'):
|
| 76 |
+
mime = 'image/gif'
|
| 77 |
+
elif raw[:4] == b'RIFF' and raw[8:12] == b'WEBP':
|
| 78 |
+
mime = 'image/webp'
|
| 79 |
+
else:
|
| 80 |
+
raise ValueError(f'Unsupported image bytes: {ref}')
|
| 81 |
+
key = hashlib.sha256(raw).hexdigest()[:24]
|
| 82 |
+
assets[key] = f'data:{mime};base64,' + base64.b64encode(raw).decode()
|
| 83 |
+
else:
|
| 84 |
+
warnings.append(f'图片缺失:{ref}')
|
| 85 |
+
name = relative.stem
|
| 86 |
+
camera = 'agentview' if 'agentview' in name else 'wrist' if 'wrist' in name else name
|
| 87 |
+
cache[ref] = {'asset': key, 'path': ref, 'camera': camera}
|
| 88 |
+
result.append({**cache[ref], 'source': source, 'at': timestamp})
|
| 89 |
+
return result
|
| 90 |
+
|
| 91 |
+
outcomes = [{'attempt': e.get('attempt'), 'success': e.get('success'),
|
| 92 |
+
'feedback': e.get('feedback', ''), 'at': e.get('t')}
|
| 93 |
+
for e in events if e.get('ev') == 'done']
|
| 94 |
+
steps, pending, latest, latest_text = [], [], [], ''
|
| 95 |
+
attempt, origin, active, task_text = 1, rows[0].get('t', 0), None, ''
|
| 96 |
+
for line, row in enumerate(rows, 1):
|
| 97 |
+
kind = row.get('ev')
|
| 98 |
+
if kind == 'user':
|
| 99 |
+
latest_text = row.get('text', '')
|
| 100 |
+
if not task_text:
|
| 101 |
+
match = re.search(r'\{.*\}', latest_text, re.S)
|
| 102 |
+
task_text = parse_output(match.group() if match else '').get('task', latest_text)
|
| 103 |
+
if row.get('images'):
|
| 104 |
+
latest = images(row['images'], line, row.get('t'))
|
| 105 |
+
elif kind in ('api_error', 'abort'):
|
| 106 |
+
pending.append({'kind': kind, 'text': row.get('error', ''), 'at': row.get('t')})
|
| 107 |
+
elif kind == 'assistant':
|
| 108 |
+
calls = row.get('tool_calls', [])
|
| 109 |
+
active = {
|
| 110 |
+
'index': len(steps), 'turn': row.get('turn'), 'attempt': attempt,
|
| 111 |
+
'at': row.get('t'), 'elapsed': max(0, row.get('t', origin) - origin),
|
| 112 |
+
'latency': row.get('latency_s'), 'before': list(latest),
|
| 113 |
+
'inputText': latest_text, 'text': row.get('text') or '',
|
| 114 |
+
'decisionSummary': row.get('reasoning_summary') or None,
|
| 115 |
+
'decisionSummaryStatus': row.get('reasoning_summary_status', 'not_recorded'),
|
| 116 |
+
'decisionSourceLine': line,
|
| 117 |
+
'actions': [{'id': c.get('id'), 'name': c.get('name', 'tool'),
|
| 118 |
+
'arguments': c.get('arguments', {}), 'result': None,
|
| 119 |
+
'after': []} for c in calls],
|
| 120 |
+
'notices': pending, 'verdict': None,
|
| 121 |
+
'requestImages': row.get('request_stats', {}).get('n_images'),
|
| 122 |
+
}
|
| 123 |
+
pending = []
|
| 124 |
+
steps.append(active)
|
| 125 |
+
elif kind == 'tool':
|
| 126 |
+
if active is None:
|
| 127 |
+
warnings.append(f'第 {line} 行工具结果缺少前置调用')
|
| 128 |
+
continue
|
| 129 |
+
if row.get('turn') is not None and row.get('turn') != active['turn']:
|
| 130 |
+
raise ValueError(f'Tool turn mismatch at transcript line {line}')
|
| 131 |
+
unresolved = [a for a in active['actions'] if a['result'] is None]
|
| 132 |
+
call_id = row.get('call_id') or row.get('tool_call_id')
|
| 133 |
+
action = next((a for a in unresolved if call_id and a['id'] == call_id), None)
|
| 134 |
+
if call_id and action is None:
|
| 135 |
+
raise ValueError(f'Unknown tool call id at transcript line {line}')
|
| 136 |
+
if action is None:
|
| 137 |
+
action = next((a for a in unresolved if isinstance(a['arguments'], dict)
|
| 138 |
+
and a['arguments'].get('command') == row.get('command')), None)
|
| 139 |
+
if action is None and len(unresolved) == 1:
|
| 140 |
+
action = unresolved[0]
|
| 141 |
+
if action is None:
|
| 142 |
+
raise ValueError(f'Ambiguous tool result at transcript line {line}')
|
| 143 |
+
output = row.get('output', '')
|
| 144 |
+
action['result'] = output
|
| 145 |
+
action['at'] = row.get('t')
|
| 146 |
+
action['after'] = images(row.get('images', []), line, row.get('t'))
|
| 147 |
+
parsed = parse_output(output)
|
| 148 |
+
action['ok'] = parsed.get('ok')
|
| 149 |
+
latest_text = output if isinstance(output, str) else json.dumps(output, ensure_ascii=False)
|
| 150 |
+
if action['after']:
|
| 151 |
+
latest = list(action['after'])
|
| 152 |
+
command = row.get('command') or (action['arguments'].get('command', '')
|
| 153 |
+
if isinstance(action['arguments'], dict) else '')
|
| 154 |
+
if command.split(' ', 1)[0] == 'done':
|
| 155 |
+
verdict = next((o for o in outcomes if o['attempt'] == attempt), None)
|
| 156 |
+
if verdict:
|
| 157 |
+
active['verdict'] = verdict
|
| 158 |
+
# A failed done may immediately return RESET images for the next attempt.
|
| 159 |
+
message = parsed.get('message', '')
|
| 160 |
+
next_attempt = re.search(r'Attempt\s+(\d+)\s+of', message)
|
| 161 |
+
if next_attempt:
|
| 162 |
+
attempt = int(next_attempt.group(1))
|
| 163 |
+
action['resetToAttempt'] = attempt
|
| 164 |
+
if pending:
|
| 165 |
+
steps[-1]['noticesAfter'] = pending
|
| 166 |
+
for step in steps:
|
| 167 |
+
step['incomplete'] = any(a['result'] is None for a in step['actions'])
|
| 168 |
+
status = 'success' if any(o['success'] is True for o in outcomes) else (
|
| 169 |
+
'failed' if outcomes and any(r.get('ev') == 'end' and r.get('finished') is True for r in rows) else 'incomplete')
|
| 170 |
+
video = None
|
| 171 |
+
video_path = folder / 'rollout.mp4'
|
| 172 |
+
if video_path.is_file():
|
| 173 |
+
raw = video_path.read_bytes()
|
| 174 |
+
if len(raw) < 12 or raw[4:8] != b'ftyp':
|
| 175 |
+
raise ValueError('rollout.mp4 is not an MP4 container')
|
| 176 |
+
key = 'video-' + hashlib.sha256(raw).hexdigest()[:24]
|
| 177 |
+
assets[key] = 'data:video/mp4;base64,' + base64.b64encode(raw).decode()
|
| 178 |
+
video = {'asset': key, 'name': 'rollout.mp4'}
|
| 179 |
+
return {'id': folder.name, 'video': video, 'task': server.get('task', folder.name),
|
| 180 |
+
'taskText': task_text, 'seed': server.get('seed'), 'model': start.get('model', '未记录'),
|
| 181 |
+
'perception': server.get('perception', '未记录'), 'feedback': server.get('feedback', '未记录'),
|
| 182 |
+
'status': status, 'steps': steps, 'outcomes': outcomes,
|
| 183 |
+
'warnings': sorted(set(warnings)), 'source': transcript.name,
|
| 184 |
+
'actionCount': sum(len(s['actions']) for s in steps)}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def render(folders, output, sandbox_override=None):
|
| 188 |
+
assets = {}
|
| 189 |
+
runs = [build_run(folder, assets, sandbox_override) for folder in folders]
|
| 190 |
+
payload = json.dumps({'version': 1, 'runs': runs, 'assets': assets}, ensure_ascii=False)
|
| 191 |
+
# Logs are untrusted text, including strings containing HTML/script terminators.
|
| 192 |
+
payload = payload.replace('&', '\\u0026').replace('<', '\\u003c').replace('>', '\\u003e')
|
| 193 |
+
template = Path(__file__).with_name('viewer.html').read_text()
|
| 194 |
+
output = Path(output)
|
| 195 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 196 |
+
output.write_text(template.replace('/*__PAYLOAD__*/null', payload))
|
| 197 |
+
return runs
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def main():
|
| 201 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 202 |
+
parser.add_argument('--run', type=Path, action='append', required=True, help='Repeat to include multiple runs')
|
| 203 |
+
parser.add_argument('--out', type=Path, required=True)
|
| 204 |
+
parser.add_argument('--sandbox', type=Path, help='Relocated image directory for a single run')
|
| 205 |
+
args = parser.parse_args()
|
| 206 |
+
if args.sandbox and len(args.run) != 1:
|
| 207 |
+
parser.error('--sandbox requires exactly one --run')
|
| 208 |
+
try:
|
| 209 |
+
runs = render(args.run, args.out, args.sandbox)
|
| 210 |
+
except (ValueError, OSError, KeyError) as exc:
|
| 211 |
+
parser.exit(1, f'Export failed: {exc}\n')
|
| 212 |
+
print(json.dumps({'output': str(args.out.resolve()), 'runs': [
|
| 213 |
+
{'task': r['task'], 'steps': len(r['steps']), 'actions': r['actionCount'],
|
| 214 |
+
'outcomes': [o['success'] for o in r['outcomes']], 'warnings': r['warnings']} for r in runs
|
| 215 |
+
]}, ensure_ascii=False, indent=2))
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
if __name__ == '__main__':
|
| 219 |
+
main()
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/batches.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"g56sol_canary_20261114": {
|
| 3 |
+
"source_manifest": "/mnt/cpfs/workspace/agentic-robotics/ops/new_model_exports_20261115/sources/gpt56/original34/runs/api/g56sol_canary_20261114/manifest.json",
|
| 4 |
+
"supplement": true,
|
| 5 |
+
"selected_runs": 1,
|
| 6 |
+
"exported_runs": 1,
|
| 7 |
+
"note": "Original condition and feedback dossier are in each episode annotation source.evaluation_config."
|
| 8 |
+
}
|
| 9 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/workspace_isolation_patch.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"changes": [
|
| 3 |
+
{
|
| 4 |
+
"group": "original34",
|
| 5 |
+
"path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/original34/jail/jail_inner.sh",
|
| 6 |
+
"applied_utc": "2026-11-14T21:05:01.896083+00:00",
|
| 7 |
+
"old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
|
| 8 |
+
"new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"group": "compound2",
|
| 12 |
+
"path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/jail/jail_inner.sh",
|
| 13 |
+
"applied_utc": "2026-11-14T21:05:01.930531+00:00",
|
| 14 |
+
"old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
|
| 15 |
+
"new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"group": "breakfast1",
|
| 19 |
+
"path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/breakfast1/jail/jail_inner.sh",
|
| 20 |
+
"applied_utc": "2026-11-14T21:05:01.961630+00:00",
|
| 21 |
+
"old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
|
| 22 |
+
"new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"group": "remaining3",
|
| 26 |
+
"path": "/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/remaining3/jail/jail_inner.sh",
|
| 27 |
+
"applied_utc": "2026-11-14T21:05:01.994096+00:00",
|
| 28 |
+
"old_sha256": "609b51bb346302c335ed58bfd18d660d3e3a6d2d78154afd15232b8c3b072f49",
|
| 29 |
+
"new_sha256": "e5311a8044b8366ce268cfa9b6f57d7615de566fcfbe4d1a7f66eee1acd50089"
|
| 30 |
+
}
|
| 31 |
+
],
|
| 32 |
+
"upstream_patch": "/mnt/cpfs/workspace/agentic-robotics/ops/minimax_glm_go_smoke_20261114/workspace_jail_fix.patch",
|
| 33 |
+
"active_tool_calls": "api_player.run_shell invokes repository-local jail file anew per call; running agent context unchanged",
|
| 34 |
+
"completed_runs": "retained: full transcript inspected; no shared workspace access observed",
|
| 35 |
+
"mixed_runtime_runs": [
|
| 36 |
+
"/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_lid_box_s3000_full_F1_direct_k3_1114-204823_p31114",
|
| 37 |
+
"/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_bridge_s3001_full_F1_direct_k3_1114-205050_p31111",
|
| 38 |
+
"/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_tray_delivery_s3000_full_F1_direct_k3_1114-205403_p31112",
|
| 39 |
+
"/mnt/cpfs/workspace/agentic-robotics/ops/gpt56sol_high_40_20261114/sources/compound2/runs/api/g56sol_compound2_20261114/g56sol_compound2_20261114-gpt-5.6-sol-codex-harness-hidek_lh_parts_cart_s3000_full_F1_direct_k3_1114-205125_p31201"
|
| 40 |
+
]
|
| 41 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/evaluation_evidence/workspace_isolation_regression.json
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checks": [
|
| 3 |
+
{
|
| 4 |
+
"group": "original34",
|
| 5 |
+
"result": {
|
| 6 |
+
"old_camera_visible": false,
|
| 7 |
+
"shared_entries": 0,
|
| 8 |
+
"episode_read_write": true
|
| 9 |
+
},
|
| 10 |
+
"via": "api_player.run_shell (same function used by MCP ToolCore)",
|
| 11 |
+
"seconds": 0.06228327751159668
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"group": "compound2",
|
| 15 |
+
"result": {
|
| 16 |
+
"old_camera_visible": false,
|
| 17 |
+
"shared_entries": 0,
|
| 18 |
+
"episode_read_write": true
|
| 19 |
+
},
|
| 20 |
+
"via": "api_player.run_shell (same function used by MCP ToolCore)",
|
| 21 |
+
"seconds": 0.05967354774475098
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"group": "breakfast1",
|
| 25 |
+
"result": {
|
| 26 |
+
"old_camera_visible": false,
|
| 27 |
+
"shared_entries": 0,
|
| 28 |
+
"episode_read_write": true
|
| 29 |
+
},
|
| 30 |
+
"via": "api_player.run_shell (same function used by MCP ToolCore)",
|
| 31 |
+
"seconds": 0.05977678298950195
|
| 32 |
+
},
|
| 33 |
+
{
|
| 34 |
+
"group": "remaining3",
|
| 35 |
+
"result": {
|
| 36 |
+
"old_camera_visible": false,
|
| 37 |
+
"shared_entries": 0,
|
| 38 |
+
"episode_read_write": true
|
| 39 |
+
},
|
| 40 |
+
"via": "api_player.run_shell (same function used by MCP ToolCore)",
|
| 41 |
+
"seconds": 0.06399154663085938
|
| 42 |
+
}
|
| 43 |
+
],
|
| 44 |
+
"host_legacy_unchanged": true,
|
| 45 |
+
"passed": true
|
| 46 |
+
}
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/rejected.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[]
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/release/image_stats.json
ADDED
|
@@ -0,0 +1,703 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"status": "pass",
|
| 3 |
+
"created": "2026-11-15T07:04:11.086269+00:00",
|
| 4 |
+
"method": "Full RGB pixel histograms from distinct floor(n/4), floor(n/2), floor(3n/4) frames per episode; float64 moments and exact histogram quantiles. Samples are stratified by episode, not a full-frame census.",
|
| 5 |
+
"sample_frames_per_camera": {
|
| 6 |
+
"observation.images.image": 9,
|
| 7 |
+
"observation.images.wrist_image": 9
|
| 8 |
+
},
|
| 9 |
+
"old_zero_std_episode_camera_pairs": 6,
|
| 10 |
+
"old_global_image_stats": {
|
| 11 |
+
"observation.images.image": {
|
| 12 |
+
"min": [
|
| 13 |
+
[
|
| 14 |
+
[
|
| 15 |
+
0.023529411764705882
|
| 16 |
+
]
|
| 17 |
+
],
|
| 18 |
+
[
|
| 19 |
+
[
|
| 20 |
+
0.023529411764705882
|
| 21 |
+
]
|
| 22 |
+
],
|
| 23 |
+
[
|
| 24 |
+
[
|
| 25 |
+
0.023529411764705882
|
| 26 |
+
]
|
| 27 |
+
]
|
| 28 |
+
],
|
| 29 |
+
"max": [
|
| 30 |
+
[
|
| 31 |
+
[
|
| 32 |
+
1.0
|
| 33 |
+
]
|
| 34 |
+
],
|
| 35 |
+
[
|
| 36 |
+
[
|
| 37 |
+
1.0
|
| 38 |
+
]
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
[
|
| 42 |
+
1.0
|
| 43 |
+
]
|
| 44 |
+
]
|
| 45 |
+
],
|
| 46 |
+
"mean": [
|
| 47 |
+
[
|
| 48 |
+
[
|
| 49 |
+
0.5724476251759791
|
| 50 |
+
]
|
| 51 |
+
],
|
| 52 |
+
[
|
| 53 |
+
[
|
| 54 |
+
0.5380949804182761
|
| 55 |
+
]
|
| 56 |
+
],
|
| 57 |
+
[
|
| 58 |
+
[
|
| 59 |
+
0.4921313251309835
|
| 60 |
+
]
|
| 61 |
+
]
|
| 62 |
+
],
|
| 63 |
+
"std": [
|
| 64 |
+
[
|
| 65 |
+
[
|
| 66 |
+
0.00027417786766923183
|
| 67 |
+
]
|
| 68 |
+
],
|
| 69 |
+
[
|
| 70 |
+
[
|
| 71 |
+
0.0013719812971569433
|
| 72 |
+
]
|
| 73 |
+
],
|
| 74 |
+
[
|
| 75 |
+
[
|
| 76 |
+
0.001925627743290284
|
| 77 |
+
]
|
| 78 |
+
]
|
| 79 |
+
],
|
| 80 |
+
"count": [
|
| 81 |
+
662
|
| 82 |
+
],
|
| 83 |
+
"q01": [
|
| 84 |
+
[
|
| 85 |
+
[
|
| 86 |
+
0.10330811336635237
|
| 87 |
+
]
|
| 88 |
+
],
|
| 89 |
+
[
|
| 90 |
+
[
|
| 91 |
+
0.10918879170507718
|
| 92 |
+
]
|
| 93 |
+
],
|
| 94 |
+
[
|
| 95 |
+
[
|
| 96 |
+
0.10720904334745103
|
| 97 |
+
]
|
| 98 |
+
]
|
| 99 |
+
],
|
| 100 |
+
"q10": [
|
| 101 |
+
[
|
| 102 |
+
[
|
| 103 |
+
0.4236171036001957
|
| 104 |
+
]
|
| 105 |
+
],
|
| 106 |
+
[
|
| 107 |
+
[
|
| 108 |
+
0.41513650829417753
|
| 109 |
+
]
|
| 110 |
+
],
|
| 111 |
+
[
|
| 112 |
+
[
|
| 113 |
+
0.4019094679539349
|
| 114 |
+
]
|
| 115 |
+
]
|
| 116 |
+
],
|
| 117 |
+
"q50": [
|
| 118 |
+
[
|
| 119 |
+
[
|
| 120 |
+
0.5921843548834195
|
| 121 |
+
]
|
| 122 |
+
],
|
| 123 |
+
[
|
| 124 |
+
[
|
| 125 |
+
0.5548762580062345
|
| 126 |
+
]
|
| 127 |
+
],
|
| 128 |
+
[
|
| 129 |
+
[
|
| 130 |
+
0.5039093048879485
|
| 131 |
+
]
|
| 132 |
+
]
|
| 133 |
+
],
|
| 134 |
+
"q90": [
|
| 135 |
+
[
|
| 136 |
+
[
|
| 137 |
+
0.7528608977327463
|
| 138 |
+
]
|
| 139 |
+
],
|
| 140 |
+
[
|
| 141 |
+
[
|
| 142 |
+
0.6895305153879344
|
| 143 |
+
]
|
| 144 |
+
],
|
| 145 |
+
[
|
| 146 |
+
[
|
| 147 |
+
0.6197205409602238
|
| 148 |
+
]
|
| 149 |
+
]
|
| 150 |
+
],
|
| 151 |
+
"q99": [
|
| 152 |
+
[
|
| 153 |
+
[
|
| 154 |
+
0.7895371391890743
|
| 155 |
+
]
|
| 156 |
+
],
|
| 157 |
+
[
|
| 158 |
+
[
|
| 159 |
+
0.7309023979966346
|
| 160 |
+
]
|
| 161 |
+
],
|
| 162 |
+
[
|
| 163 |
+
[
|
| 164 |
+
0.7019681879617495
|
| 165 |
+
]
|
| 166 |
+
]
|
| 167 |
+
]
|
| 168 |
+
},
|
| 169 |
+
"observation.images.wrist_image": {
|
| 170 |
+
"min": [
|
| 171 |
+
[
|
| 172 |
+
[
|
| 173 |
+
0.0392156862745098
|
| 174 |
+
]
|
| 175 |
+
],
|
| 176 |
+
[
|
| 177 |
+
[
|
| 178 |
+
0.0392156862745098
|
| 179 |
+
]
|
| 180 |
+
],
|
| 181 |
+
[
|
| 182 |
+
[
|
| 183 |
+
0.03137254901960784
|
| 184 |
+
]
|
| 185 |
+
]
|
| 186 |
+
],
|
| 187 |
+
"max": [
|
| 188 |
+
[
|
| 189 |
+
[
|
| 190 |
+
1.0
|
| 191 |
+
]
|
| 192 |
+
],
|
| 193 |
+
[
|
| 194 |
+
[
|
| 195 |
+
1.0
|
| 196 |
+
]
|
| 197 |
+
],
|
| 198 |
+
[
|
| 199 |
+
[
|
| 200 |
+
0.9372549019607843
|
| 201 |
+
]
|
| 202 |
+
]
|
| 203 |
+
],
|
| 204 |
+
"mean": [
|
| 205 |
+
[
|
| 206 |
+
[
|
| 207 |
+
0.6186158786699336
|
| 208 |
+
]
|
| 209 |
+
],
|
| 210 |
+
[
|
| 211 |
+
[
|
| 212 |
+
0.6000395921330113
|
| 213 |
+
]
|
| 214 |
+
],
|
| 215 |
+
[
|
| 216 |
+
[
|
| 217 |
+
0.4985415645617669
|
| 218 |
+
]
|
| 219 |
+
]
|
| 220 |
+
],
|
| 221 |
+
"std": [
|
| 222 |
+
[
|
| 223 |
+
[
|
| 224 |
+
0.004224488963831252
|
| 225 |
+
]
|
| 226 |
+
],
|
| 227 |
+
[
|
| 228 |
+
[
|
| 229 |
+
0.03180308912061847
|
| 230 |
+
]
|
| 231 |
+
],
|
| 232 |
+
[
|
| 233 |
+
[
|
| 234 |
+
0.03912741562642721
|
| 235 |
+
]
|
| 236 |
+
]
|
| 237 |
+
],
|
| 238 |
+
"count": [
|
| 239 |
+
662
|
| 240 |
+
],
|
| 241 |
+
"q01": [
|
| 242 |
+
[
|
| 243 |
+
[
|
| 244 |
+
0.09397557496460453
|
| 245 |
+
]
|
| 246 |
+
],
|
| 247 |
+
[
|
| 248 |
+
[
|
| 249 |
+
0.09786038850109556
|
| 250 |
+
]
|
| 251 |
+
],
|
| 252 |
+
[
|
| 253 |
+
[
|
| 254 |
+
0.08073933439230596
|
| 255 |
+
]
|
| 256 |
+
]
|
| 257 |
+
],
|
| 258 |
+
"q10": [
|
| 259 |
+
[
|
| 260 |
+
[
|
| 261 |
+
0.20197669351471703
|
| 262 |
+
]
|
| 263 |
+
],
|
| 264 |
+
[
|
| 265 |
+
[
|
| 266 |
+
0.20456524065567516
|
| 267 |
+
]
|
| 268 |
+
],
|
| 269 |
+
[
|
| 270 |
+
[
|
| 271 |
+
0.2025492333968704
|
| 272 |
+
]
|
| 273 |
+
]
|
| 274 |
+
],
|
| 275 |
+
"q50": [
|
| 276 |
+
[
|
| 277 |
+
[
|
| 278 |
+
0.7282935574975211
|
| 279 |
+
]
|
| 280 |
+
],
|
| 281 |
+
[
|
| 282 |
+
[
|
| 283 |
+
0.6505025147682957
|
| 284 |
+
]
|
| 285 |
+
],
|
| 286 |
+
[
|
| 287 |
+
[
|
| 288 |
+
0.5308794907569632
|
| 289 |
+
]
|
| 290 |
+
]
|
| 291 |
+
],
|
| 292 |
+
"q90": [
|
| 293 |
+
[
|
| 294 |
+
[
|
| 295 |
+
0.7878391630847865
|
| 296 |
+
]
|
| 297 |
+
],
|
| 298 |
+
[
|
| 299 |
+
[
|
| 300 |
+
0.8666685534039836
|
| 301 |
+
]
|
| 302 |
+
],
|
| 303 |
+
[
|
| 304 |
+
[
|
| 305 |
+
0.7308799027799128
|
| 306 |
+
]
|
| 307 |
+
]
|
| 308 |
+
],
|
| 309 |
+
"q99": [
|
| 310 |
+
[
|
| 311 |
+
[
|
| 312 |
+
0.8820232074850729
|
| 313 |
+
]
|
| 314 |
+
],
|
| 315 |
+
[
|
| 316 |
+
[
|
| 317 |
+
0.9781071266032694
|
| 318 |
+
]
|
| 319 |
+
],
|
| 320 |
+
[
|
| 321 |
+
[
|
| 322 |
+
0.8573683854132182
|
| 323 |
+
]
|
| 324 |
+
]
|
| 325 |
+
]
|
| 326 |
+
}
|
| 327 |
+
},
|
| 328 |
+
"new_global_image_stats": {
|
| 329 |
+
"observation.images.image": {
|
| 330 |
+
"count": [
|
| 331 |
+
9
|
| 332 |
+
],
|
| 333 |
+
"mean": [
|
| 334 |
+
[
|
| 335 |
+
[
|
| 336 |
+
0.5720239510463474
|
| 337 |
+
]
|
| 338 |
+
],
|
| 339 |
+
[
|
| 340 |
+
[
|
| 341 |
+
0.5370516376038263
|
| 342 |
+
]
|
| 343 |
+
],
|
| 344 |
+
[
|
| 345 |
+
[
|
| 346 |
+
0.49072072147543916
|
| 347 |
+
]
|
| 348 |
+
]
|
| 349 |
+
],
|
| 350 |
+
"std": [
|
| 351 |
+
[
|
| 352 |
+
[
|
| 353 |
+
0.15137633564235153
|
| 354 |
+
]
|
| 355 |
+
],
|
| 356 |
+
[
|
| 357 |
+
[
|
| 358 |
+
0.13093388433028796
|
| 359 |
+
]
|
| 360 |
+
],
|
| 361 |
+
[
|
| 362 |
+
[
|
| 363 |
+
0.11600448252015728
|
| 364 |
+
]
|
| 365 |
+
]
|
| 366 |
+
],
|
| 367 |
+
"min": [
|
| 368 |
+
[
|
| 369 |
+
[
|
| 370 |
+
0.023529411764705882
|
| 371 |
+
]
|
| 372 |
+
],
|
| 373 |
+
[
|
| 374 |
+
[
|
| 375 |
+
0.023529411764705882
|
| 376 |
+
]
|
| 377 |
+
],
|
| 378 |
+
[
|
| 379 |
+
[
|
| 380 |
+
0.023529411764705882
|
| 381 |
+
]
|
| 382 |
+
]
|
| 383 |
+
],
|
| 384 |
+
"max": [
|
| 385 |
+
[
|
| 386 |
+
[
|
| 387 |
+
1.0
|
| 388 |
+
]
|
| 389 |
+
],
|
| 390 |
+
[
|
| 391 |
+
[
|
| 392 |
+
1.0
|
| 393 |
+
]
|
| 394 |
+
],
|
| 395 |
+
[
|
| 396 |
+
[
|
| 397 |
+
1.0
|
| 398 |
+
]
|
| 399 |
+
]
|
| 400 |
+
],
|
| 401 |
+
"q01": [
|
| 402 |
+
[
|
| 403 |
+
[
|
| 404 |
+
0.10588235294117647
|
| 405 |
+
]
|
| 406 |
+
],
|
| 407 |
+
[
|
| 408 |
+
[
|
| 409 |
+
0.10980392156862745
|
| 410 |
+
]
|
| 411 |
+
],
|
| 412 |
+
[
|
| 413 |
+
[
|
| 414 |
+
0.10588235294117647
|
| 415 |
+
]
|
| 416 |
+
]
|
| 417 |
+
],
|
| 418 |
+
"q10": [
|
| 419 |
+
[
|
| 420 |
+
[
|
| 421 |
+
0.4235294117647059
|
| 422 |
+
]
|
| 423 |
+
],
|
| 424 |
+
[
|
| 425 |
+
[
|
| 426 |
+
0.41568627450980394
|
| 427 |
+
]
|
| 428 |
+
],
|
| 429 |
+
[
|
| 430 |
+
[
|
| 431 |
+
0.4
|
| 432 |
+
]
|
| 433 |
+
]
|
| 434 |
+
],
|
| 435 |
+
"q50": [
|
| 436 |
+
[
|
| 437 |
+
[
|
| 438 |
+
0.592156862745098
|
| 439 |
+
]
|
| 440 |
+
],
|
| 441 |
+
[
|
| 442 |
+
[
|
| 443 |
+
0.5529411764705883
|
| 444 |
+
]
|
| 445 |
+
],
|
| 446 |
+
[
|
| 447 |
+
[
|
| 448 |
+
0.5019607843137255
|
| 449 |
+
]
|
| 450 |
+
]
|
| 451 |
+
],
|
| 452 |
+
"q90": [
|
| 453 |
+
[
|
| 454 |
+
[
|
| 455 |
+
0.7529411764705882
|
| 456 |
+
]
|
| 457 |
+
],
|
| 458 |
+
[
|
| 459 |
+
[
|
| 460 |
+
0.6862745098039216
|
| 461 |
+
]
|
| 462 |
+
],
|
| 463 |
+
[
|
| 464 |
+
[
|
| 465 |
+
0.6196078431372549
|
| 466 |
+
]
|
| 467 |
+
]
|
| 468 |
+
],
|
| 469 |
+
"q99": [
|
| 470 |
+
[
|
| 471 |
+
[
|
| 472 |
+
0.788235294117647
|
| 473 |
+
]
|
| 474 |
+
],
|
| 475 |
+
[
|
| 476 |
+
[
|
| 477 |
+
0.7254901960784313
|
| 478 |
+
]
|
| 479 |
+
],
|
| 480 |
+
[
|
| 481 |
+
[
|
| 482 |
+
0.6705882352941176
|
| 483 |
+
]
|
| 484 |
+
]
|
| 485 |
+
]
|
| 486 |
+
},
|
| 487 |
+
"observation.images.wrist_image": {
|
| 488 |
+
"count": [
|
| 489 |
+
9
|
| 490 |
+
],
|
| 491 |
+
"mean": [
|
| 492 |
+
[
|
| 493 |
+
[
|
| 494 |
+
0.6076160771654582
|
| 495 |
+
]
|
| 496 |
+
],
|
| 497 |
+
[
|
| 498 |
+
[
|
| 499 |
+
0.566811209618396
|
| 500 |
+
]
|
| 501 |
+
],
|
| 502 |
+
[
|
| 503 |
+
[
|
| 504 |
+
0.46072409636054945
|
| 505 |
+
]
|
| 506 |
+
]
|
| 507 |
+
],
|
| 508 |
+
"std": [
|
| 509 |
+
[
|
| 510 |
+
[
|
| 511 |
+
0.22932417206704866
|
| 512 |
+
]
|
| 513 |
+
],
|
| 514 |
+
[
|
| 515 |
+
[
|
| 516 |
+
0.23032292273571484
|
| 517 |
+
]
|
| 518 |
+
],
|
| 519 |
+
[
|
| 520 |
+
[
|
| 521 |
+
0.2065260769782005
|
| 522 |
+
]
|
| 523 |
+
]
|
| 524 |
+
],
|
| 525 |
+
"min": [
|
| 526 |
+
[
|
| 527 |
+
[
|
| 528 |
+
0.050980392156862744
|
| 529 |
+
]
|
| 530 |
+
],
|
| 531 |
+
[
|
| 532 |
+
[
|
| 533 |
+
0.050980392156862744
|
| 534 |
+
]
|
| 535 |
+
],
|
| 536 |
+
[
|
| 537 |
+
[
|
| 538 |
+
0.03137254901960784
|
| 539 |
+
]
|
| 540 |
+
]
|
| 541 |
+
],
|
| 542 |
+
"max": [
|
| 543 |
+
[
|
| 544 |
+
[
|
| 545 |
+
0.996078431372549
|
| 546 |
+
]
|
| 547 |
+
],
|
| 548 |
+
[
|
| 549 |
+
[
|
| 550 |
+
1.0
|
| 551 |
+
]
|
| 552 |
+
],
|
| 553 |
+
[
|
| 554 |
+
[
|
| 555 |
+
0.9098039215686274
|
| 556 |
+
]
|
| 557 |
+
]
|
| 558 |
+
],
|
| 559 |
+
"q01": [
|
| 560 |
+
[
|
| 561 |
+
[
|
| 562 |
+
0.09019607843137255
|
| 563 |
+
]
|
| 564 |
+
],
|
| 565 |
+
[
|
| 566 |
+
[
|
| 567 |
+
0.09019607843137255
|
| 568 |
+
]
|
| 569 |
+
],
|
| 570 |
+
[
|
| 571 |
+
[
|
| 572 |
+
0.0784313725490196
|
| 573 |
+
]
|
| 574 |
+
]
|
| 575 |
+
],
|
| 576 |
+
"q10": [
|
| 577 |
+
[
|
| 578 |
+
[
|
| 579 |
+
0.20392156862745098
|
| 580 |
+
]
|
| 581 |
+
],
|
| 582 |
+
[
|
| 583 |
+
[
|
| 584 |
+
0.20392156862745098
|
| 585 |
+
]
|
| 586 |
+
],
|
| 587 |
+
[
|
| 588 |
+
[
|
| 589 |
+
0.20392156862745098
|
| 590 |
+
]
|
| 591 |
+
]
|
| 592 |
+
],
|
| 593 |
+
"q50": [
|
| 594 |
+
[
|
| 595 |
+
[
|
| 596 |
+
0.7019607843137254
|
| 597 |
+
]
|
| 598 |
+
],
|
| 599 |
+
[
|
| 600 |
+
[
|
| 601 |
+
0.6
|
| 602 |
+
]
|
| 603 |
+
],
|
| 604 |
+
[
|
| 605 |
+
[
|
| 606 |
+
0.43529411764705883
|
| 607 |
+
]
|
| 608 |
+
]
|
| 609 |
+
],
|
| 610 |
+
"q90": [
|
| 611 |
+
[
|
| 612 |
+
[
|
| 613 |
+
0.7843137254901961
|
| 614 |
+
]
|
| 615 |
+
],
|
| 616 |
+
[
|
| 617 |
+
[
|
| 618 |
+
0.8627450980392157
|
| 619 |
+
]
|
| 620 |
+
],
|
| 621 |
+
[
|
| 622 |
+
[
|
| 623 |
+
0.7176470588235294
|
| 624 |
+
]
|
| 625 |
+
]
|
| 626 |
+
],
|
| 627 |
+
"q99": [
|
| 628 |
+
[
|
| 629 |
+
[
|
| 630 |
+
0.9137254901960784
|
| 631 |
+
]
|
| 632 |
+
],
|
| 633 |
+
[
|
| 634 |
+
[
|
| 635 |
+
0.9686274509803922
|
| 636 |
+
]
|
| 637 |
+
],
|
| 638 |
+
[
|
| 639 |
+
[
|
| 640 |
+
0.8470588235294118
|
| 641 |
+
]
|
| 642 |
+
]
|
| 643 |
+
]
|
| 644 |
+
}
|
| 645 |
+
},
|
| 646 |
+
"samples": [
|
| 647 |
+
{
|
| 648 |
+
"camera": "observation.images.image",
|
| 649 |
+
"episode_index": 0,
|
| 650 |
+
"frame_indices": [
|
| 651 |
+
581,
|
| 652 |
+
1163,
|
| 653 |
+
1745
|
| 654 |
+
]
|
| 655 |
+
},
|
| 656 |
+
{
|
| 657 |
+
"camera": "observation.images.wrist_image",
|
| 658 |
+
"episode_index": 0,
|
| 659 |
+
"frame_indices": [
|
| 660 |
+
581,
|
| 661 |
+
1163,
|
| 662 |
+
1745
|
| 663 |
+
]
|
| 664 |
+
},
|
| 665 |
+
{
|
| 666 |
+
"camera": "observation.images.image",
|
| 667 |
+
"episode_index": 1,
|
| 668 |
+
"frame_indices": [
|
| 669 |
+
347,
|
| 670 |
+
694,
|
| 671 |
+
1041
|
| 672 |
+
]
|
| 673 |
+
},
|
| 674 |
+
{
|
| 675 |
+
"camera": "observation.images.wrist_image",
|
| 676 |
+
"episode_index": 1,
|
| 677 |
+
"frame_indices": [
|
| 678 |
+
347,
|
| 679 |
+
694,
|
| 680 |
+
1041
|
| 681 |
+
]
|
| 682 |
+
},
|
| 683 |
+
{
|
| 684 |
+
"camera": "observation.images.image",
|
| 685 |
+
"episode_index": 2,
|
| 686 |
+
"frame_indices": [
|
| 687 |
+
106,
|
| 688 |
+
213,
|
| 689 |
+
319
|
| 690 |
+
]
|
| 691 |
+
},
|
| 692 |
+
{
|
| 693 |
+
"camera": "observation.images.wrist_image",
|
| 694 |
+
"episode_index": 2,
|
| 695 |
+
"frame_indices": [
|
| 696 |
+
106,
|
| 697 |
+
213,
|
| 698 |
+
319
|
| 699 |
+
]
|
| 700 |
+
}
|
| 701 |
+
],
|
| 702 |
+
"wall_seconds": 1.6815614700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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Backend-neutral conversation, attempt records, memory selection and prompt text.
|
| 2 |
+
|
| 3 |
+
A conversation is a list of items (plain dicts):
|
| 4 |
+
{"kind": "user", "parts": [{"type": "text", "text": str} | {"type": "image", "image": ImageRef}], "live": bool}
|
| 5 |
+
{"kind": "assistant", "text": str|None, "tool_calls": [ToolCall], "raw": list|None, "backend": str}
|
| 6 |
+
{"kind": "tool_output", "call_id": str, "name": str, "text": str}
|
| 7 |
+
The system prompt is kept separately (Conversation.system). Backends convert this into their own wire
|
| 8 |
+
format (OpenAI Responses input items, Chat Completions messages, ...).
|
| 9 |
+
|
| 10 |
+
"live" user items are the current attempt's observations; old live images can be dropped to bound the
|
| 11 |
+
request size. History (earlier attempts) is packed into the attempt's first user item and never pruned,
|
| 12 |
+
so the request prefix stays byte-stable within an attempt and grows append-only across attempts
|
| 13 |
+
(prompt-cache friendly).
|
| 14 |
+
"""
|
| 15 |
+
import copy
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
from dataclasses import dataclass, field
|
| 19 |
+
from typing import Optional
|
| 20 |
+
|
| 21 |
+
from ..envs import TABLE_Z
|
| 22 |
+
|
| 23 |
+
MEMORY_MODES = ("none", "full", "last", "mismatched")
|
| 24 |
+
FEEDBACK_LEVELS = ("F0", "F1", "F2")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@dataclass
|
| 28 |
+
class ToolCall:
|
| 29 |
+
id: str
|
| 30 |
+
name: str
|
| 31 |
+
arguments: dict
|
| 32 |
+
raw_arguments: str = ""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass
|
| 36 |
+
class StepRecord:
|
| 37 |
+
step: int
|
| 38 |
+
name: str
|
| 39 |
+
args: dict
|
| 40 |
+
report: dict
|
| 41 |
+
ok: bool
|
| 42 |
+
wall_s: float = 0.0
|
| 43 |
+
sim_steps: int = 0
|
| 44 |
+
frame: object = None # ImageRef of the agentview after this step (for keyframes)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@dataclass
|
| 48 |
+
class AttemptRecord:
|
| 49 |
+
seed: int
|
| 50 |
+
attempt: int
|
| 51 |
+
steps: list = field(default_factory=list)
|
| 52 |
+
keyframes: list = field(default_factory=list) # [(caption, ImageRef)]
|
| 53 |
+
outcome: dict = field(default_factory=dict)
|
| 54 |
+
success: bool = False
|
| 55 |
+
feedback: str = ""
|
| 56 |
+
done_reason: Optional[str] = None
|
| 57 |
+
diagnosis: Optional[str] = None
|
| 58 |
+
ended_by: str = ""
|
| 59 |
+
backend_meta: dict = field(default_factory=dict)
|
| 60 |
+
|
| 61 |
+
def action_signature(self, nd=2):
|
| 62 |
+
"""Rounded action sequence (to compare consecutive attempts: 'same mistake again')."""
|
| 63 |
+
sig = []
|
| 64 |
+
for s in self.steps:
|
| 65 |
+
if s.name in ("get_observation", "pixel_to_world", "locate", "done"):
|
| 66 |
+
continue
|
| 67 |
+
sig.append((s.name, tuple(sorted((k, round(v, nd) if isinstance(v, (int, float)) and v is not None else v)
|
| 68 |
+
for k, v in s.args.items()))))
|
| 69 |
+
return tuple(sig)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def select_history(mode, own, donor=None):
|
| 73 |
+
"""Which earlier attempts the agent sees at the start of the next attempt."""
|
| 74 |
+
if mode == "none":
|
| 75 |
+
return []
|
| 76 |
+
if mode == "full":
|
| 77 |
+
return list(own)
|
| 78 |
+
if mode == "last":
|
| 79 |
+
return list(own[-1:])
|
| 80 |
+
if mode == "mismatched":
|
| 81 |
+
if donor is None:
|
| 82 |
+
raise ValueError("mismatched memory needs donor attempts from another instance")
|
| 83 |
+
return list(donor[:len(own)])
|
| 84 |
+
raise ValueError(mode)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class Conversation:
|
| 88 |
+
def __init__(self, system):
|
| 89 |
+
self.system = system
|
| 90 |
+
self.items = []
|
| 91 |
+
|
| 92 |
+
def add_user(self, parts, live=True):
|
| 93 |
+
self.items.append(dict(kind="user", parts=list(parts), live=live))
|
| 94 |
+
|
| 95 |
+
def add_assistant(self, text, tool_calls, raw=None, backend=""):
|
| 96 |
+
self.items.append(dict(kind="assistant", text=text, tool_calls=list(tool_calls), raw=raw, backend=backend))
|
| 97 |
+
|
| 98 |
+
def add_tool_output(self, call_id, name, text):
|
| 99 |
+
self.items.append(dict(kind="tool_output", call_id=call_id, name=name, text=text))
|
| 100 |
+
|
| 101 |
+
def n_images(self):
|
| 102 |
+
return sum(1 for it in self.items if it["kind"] == "user" for p in it["parts"] if p["type"] == "image")
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def prune_live_images(items, max_live):
|
| 106 |
+
"""Copy of `items` keeping only the newest `max_live` live images. Hysteresis: when the budget is
|
| 107 |
+
exceeded, prune down to half of it so the request prefix stays stable for several steps."""
|
| 108 |
+
if max_live is None or max_live < 0:
|
| 109 |
+
return items
|
| 110 |
+
live = [(i, j) for i, it in enumerate(items) if it["kind"] == "user" and it.get("live")
|
| 111 |
+
for j, p in enumerate(it["parts"]) if p["type"] == "image"]
|
| 112 |
+
if len(live) <= max_live:
|
| 113 |
+
return items
|
| 114 |
+
keep_n = max(max_live // 2, 1)
|
| 115 |
+
drop = set(live[:len(live) - keep_n])
|
| 116 |
+
out = []
|
| 117 |
+
for i, it in enumerate(items):
|
| 118 |
+
if it["kind"] == "user" and any((i, j) in drop for j in range(len(it["parts"]))):
|
| 119 |
+
it = dict(it)
|
| 120 |
+
parts = []
|
| 121 |
+
for j, p in enumerate(it["parts"]):
|
| 122 |
+
if (i, j) in drop:
|
| 123 |
+
parts.append(dict(type="text", text=f"[{p['image'].camera} image omitted to save context]"))
|
| 124 |
+
else:
|
| 125 |
+
parts.append(p)
|
| 126 |
+
it["parts"] = parts
|
| 127 |
+
out.append(it)
|
| 128 |
+
return out
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
# ---------------------------------------------------------------------------------------------- text
|
| 132 |
+
|
| 133 |
+
def fmt_num(v):
|
| 134 |
+
if v is None:
|
| 135 |
+
return "null"
|
| 136 |
+
if isinstance(v, bool):
|
| 137 |
+
return str(v).lower()
|
| 138 |
+
if isinstance(v, float):
|
| 139 |
+
return f"{v:.3f}".rstrip("0").rstrip(".") if abs(v) < 1e4 else f"{v:.4g}"
|
| 140 |
+
return json.dumps(v)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def fmt_call(name, args):
|
| 144 |
+
return f"{name}(" + ", ".join(f"{k}={fmt_num(v)}" for k, v in args.items()) + ")"
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def fmt_report(name, rep):
|
| 148 |
+
if not rep.get("ok", False):
|
| 149 |
+
return "ERROR: " + str(rep.get("error"))
|
| 150 |
+
bits = []
|
| 151 |
+
if "reached" in rep:
|
| 152 |
+
bits.append("reached" if rep["reached"] else "NOT reached")
|
| 153 |
+
if "sweep_reached" in rep:
|
| 154 |
+
bits.append("sweep completed" if rep["sweep_reached"] else "sweep NOT completed")
|
| 155 |
+
if "eef_pos" in rep and name in ("move_to", "push", "open_gripper", "close_gripper"):
|
| 156 |
+
bits.append("eef (" + ", ".join(f"{x:.3f}" for x in rep["eef_pos"]) + ")")
|
| 157 |
+
if name in ("open_gripper", "close_gripper"):
|
| 158 |
+
bits.append(f"width {rep.get('gripper_width_m', 0):.3f} m")
|
| 159 |
+
if rep.get("holding_object") not in (None, False):
|
| 160 |
+
bits.append(f"holding {rep['holding_object']}" if isinstance(rep["holding_object"], str) else "holding an object")
|
| 161 |
+
if rep.get("touched_object") or rep.get("touched_objects"):
|
| 162 |
+
t = rep.get("touched_objects")
|
| 163 |
+
bits.append("touched " + ", ".join(t) if t else "touched an object")
|
| 164 |
+
if name == "pixel_to_world":
|
| 165 |
+
bits.append("world (" + ", ".join(f"{x:.3f}" for x in rep["world_xyz"]) + ")")
|
| 166 |
+
if name == "locate":
|
| 167 |
+
bits.append("pos (" + ", ".join(f"{x:.3f}" for x in rep["position"]) + ")")
|
| 168 |
+
if "target_clipped_to" in rep or "start_clipped_to" in rep:
|
| 169 |
+
bits.append("target clipped to workspace")
|
| 170 |
+
if rep.get("events"):
|
| 171 |
+
bits.append("EVENT: " + " ".join(rep["events"]))
|
| 172 |
+
return "; ".join(bits) if bits else "ok"
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def summarize_actions(steps):
|
| 176 |
+
lines = []
|
| 177 |
+
for s in steps:
|
| 178 |
+
if s.name == "done":
|
| 179 |
+
lines.append(f"{s.step}. done(reason={json.dumps(s.args.get('reason', ''))})")
|
| 180 |
+
else:
|
| 181 |
+
lines.append(f"{s.step}. {fmt_call(s.name, s.args)} -> {fmt_report(s.name, s.report)}")
|
| 182 |
+
return "\n".join(lines) if lines else "(no actions)"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _text(t):
|
| 186 |
+
return dict(type="text", text=t)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _img(ref):
|
| 190 |
+
return dict(type="image", image=ref)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class PromptBuilder:
|
| 194 |
+
"""All text the agent sees. One instance per (task, config)."""
|
| 195 |
+
|
| 196 |
+
def __init__(self, task, protocol, k, memory, feedback, image_res, cam_axes, privileged_locate=False,
|
| 197 |
+
object_names=(), grasp_report="bool", cams=("agentview", "wrist"), depth_tool=True):
|
| 198 |
+
self.task, self.protocol, self.k = task, protocol, k
|
| 199 |
+
self.depth_tool = depth_tool
|
| 200 |
+
self.memory, self.feedback = memory, feedback
|
| 201 |
+
self.image_res, self.cam_axes = image_res, cam_axes
|
| 202 |
+
self.privileged_locate, self.object_names = privileged_locate, list(object_names)
|
| 203 |
+
self.grasp_report, self.cams = grasp_report, tuple(cams)
|
| 204 |
+
|
| 205 |
+
# ----------------------------------------------------------------------------- system prompt
|
| 206 |
+
def system_prompt(self):
|
| 207 |
+
ax = self.cam_axes.get("agentview") or {}
|
| 208 |
+
wx = self.cam_axes.get("wrist") or {}
|
| 209 |
+
lines = [
|
| 210 |
+
"You control a Franka Panda robot arm with a parallel-jaw gripper in a tabletop physics simulation. "
|
| 211 |
+
"You act only by calling the provided tools, exactly one tool call per turn. Every action tool returns an "
|
| 212 |
+
"execution report; after each action you also receive new camera images and the robot's proprioceptive "
|
| 213 |
+
"state.",
|
| 214 |
+
"",
|
| 215 |
+
"Coordinates (world frame, metres): the table top is at z = %.2f; the robot base is at x = -0.66, y = 0; "
|
| 216 |
+
"+x points away from the robot, +y to the robot's left, +z up. Positions given to move_to / push are for "
|
| 217 |
+
"the gripper's grasp point (midway between the fingertips). The gripper always points straight down; yaw "
|
| 218 |
+
"(degrees) turns it about the vertical axis: at yaw 0 the fingers close along the world y axis, at yaw 90 "
|
| 219 |
+
"along the world x axis; yaw is taken modulo 180 degrees because the gripper is symmetric." % TABLE_Z,
|
| 220 |
+
"",
|
| 221 |
+
"Direction words in every text you receive (task, reports, feedback) are robot-centric: forward = +x (away "
|
| 222 |
+
"from the robot), backward = -x (toward the robot), left = +y (the robot's left), right = -y (the robot's "
|
| 223 |
+
"right), up = +z. They never mean left/right in an image.",
|
| 224 |
+
"",
|
| 225 |
+
"Cameras (%dx%d images): 'agentview' looks at the table from the side opposite the robot, so the robot "
|
| 226 |
+
"appears at the top of that image; image-right is %s and image-down is %s in world coordinates (so the "
|
| 227 |
+
"robot's left appears on the right side of that image). 'wrist' is "
|
| 228 |
+
"mounted on the gripper and looks down between the fingers (at yaw 0, image-right is %s and image-down is "
|
| 229 |
+
"%s).%s"
|
| 230 |
+
% (self.image_res, self.image_res, ax.get("right", "?"), ax.get("down", "?"), wx.get("right", "?"),
|
| 231 |
+
wx.get("down", "?"),
|
| 232 |
+
" For pixel_to_world, u is the column counted from the left edge and v the row counted from the top "
|
| 233 |
+
"edge of the image as you received it." if self.depth_tool else ""),
|
| 234 |
+
"",
|
| 235 |
+
"Proprioception (end-effector position, yaw, gripper width%s) comes from the robot's own sensors."
|
| 236 |
+
% (", whether an object is held" if self.grasp_report != "none" else ""),
|
| 237 |
+
]
|
| 238 |
+
if self.privileged_locate:
|
| 239 |
+
lines += ["", "The locate tool is available and returns exact object positions. Objects: "
|
| 240 |
+
+ ", ".join(self.object_names) + "."]
|
| 241 |
+
else:
|
| 242 |
+
lines += ["", "Object positions are not given to you: localise objects from the images, e.g. by calling "
|
| 243 |
+
"pixel_to_world on the pixel where you see them." if self.depth_tool else
|
| 244 |
+
"Object positions are not given to you and there is no depth sensor: the cameras give colour "
|
| 245 |
+
"images only. Localise objects from the images."]
|
| 246 |
+
lines += ["", self._protocol_text(), "", self._feedback_text()]
|
| 247 |
+
if self.memory != "none":
|
| 248 |
+
lines += ["", "At the start of every attempt after the first, before your first tool call, write one to "
|
| 249 |
+
"three sentences assessing the earlier attempt(s): what happened and what you will keep or "
|
| 250 |
+
"change."]
|
| 251 |
+
lines += ["", "Finish by calling done(reason) when you believe the task is complete. Be precise: small errors "
|
| 252 |
+
"in position or speed matter."]
|
| 253 |
+
return "\n".join(lines)
|
| 254 |
+
|
| 255 |
+
def _protocol_text(self):
|
| 256 |
+
if self.memory == "none":
|
| 257 |
+
if self.protocol == "within":
|
| 258 |
+
return "Work on the task until you believe it is complete, then call done."
|
| 259 |
+
return "You have one attempt at the task; it ends when you call done."
|
| 260 |
+
if self.protocol == "within":
|
| 261 |
+
if self.feedback == "F0":
|
| 262 |
+
return (f"Everything happens in one continuous episode. After you call done you may be asked to "
|
| 263 |
+
f"continue from the current state; you may call done at most {self.k} times.")
|
| 264 |
+
return (f"Everything happens in one continuous episode. When you call done, the task is checked; if it is "
|
| 265 |
+
f"not complete you are told so and continue from the current state. You may call done at most "
|
| 266 |
+
f"{self.k} times.")
|
| 267 |
+
return (f"You get up to {self.k} attempts at the same task. Before every attempt the scene is reset to exactly "
|
| 268 |
+
f"the same initial state, with the same objects and the same physical properties. Each attempt ends "
|
| 269 |
+
f"when you call done; you will then see a summary of the attempt (key images, the actions you "
|
| 270 |
+
f"executed{'' if self.feedback == 'F0' else ' and outcome feedback'}).")
|
| 271 |
+
|
| 272 |
+
def _feedback_text(self):
|
| 273 |
+
if self.memory == "none":
|
| 274 |
+
return ""
|
| 275 |
+
if self.feedback == "F0":
|
| 276 |
+
return ("You will not be told whether an attempt succeeded; judge it from the images. "
|
| 277 |
+
+ ("Attempts continue until the budget is used up." if self.protocol == "cross" else ""))
|
| 278 |
+
if self.feedback == "F1":
|
| 279 |
+
return "After each attempt you are told only whether it succeeded."
|
| 280 |
+
return "After each attempt you are told whether it succeeded and, if not, a measurement of what went wrong."
|
| 281 |
+
|
| 282 |
+
# ----------------------------------------------------------------------------- per attempt
|
| 283 |
+
def history_parts(self, instruction, history):
|
| 284 |
+
"""First user item of an attempt (not pruned): task + packed earlier attempts. The header carries no
|
| 285 |
+
count so that the item grows append-only from one attempt to the next (prompt-cache friendly)."""
|
| 286 |
+
parts = [_text("TASK: " + instruction)]
|
| 287 |
+
if history:
|
| 288 |
+
parts.append(_text("\n=== Your earlier attempts ==="))
|
| 289 |
+
for i, rec in enumerate(history, 1):
|
| 290 |
+
parts += self.history_block(rec, i)
|
| 291 |
+
parts.append(_text("=== End of earlier attempts ==="))
|
| 292 |
+
return parts
|
| 293 |
+
|
| 294 |
+
def current_parts(self, attempt, obs_images, proprio, continuing=False):
|
| 295 |
+
"""Second user item of an attempt (live): attempt counter + current observation."""
|
| 296 |
+
parts = []
|
| 297 |
+
if self.memory != "none":
|
| 298 |
+
if self.protocol == "within" and continuing:
|
| 299 |
+
if self.feedback == "F0":
|
| 300 |
+
parts.append(_text(f"You called done. Continue from the current state (this is segment "
|
| 301 |
+
f"{attempt}; you may call done at most {self.k} times in total)."))
|
| 302 |
+
else:
|
| 303 |
+
parts.append(_text(f"You called done, but the task is not complete. Continue from the current "
|
| 304 |
+
f"state (this is segment {attempt}; you may call done at most {self.k} times "
|
| 305 |
+
f"in total)."))
|
| 306 |
+
elif self.protocol == "cross":
|
| 307 |
+
parts.append(_text(f"This is attempt {attempt} of at most {self.k}. The scene has been reset."))
|
| 308 |
+
parts += self.observation_parts("Current observation", obs_images, proprio)
|
| 309 |
+
return parts
|
| 310 |
+
|
| 311 |
+
def history_block(self, rec, idx):
|
| 312 |
+
head = f"\n--- Attempt {idx} ---" if self.protocol == "cross" else f"\n--- Segment {idx} (until done call {idx}) ---"
|
| 313 |
+
parts = [_text(head + "\nActions executed:\n" + summarize_actions(rec.steps))]
|
| 314 |
+
fb = (rec.feedback or "").strip()
|
| 315 |
+
if self.feedback != "F0" and fb:
|
| 316 |
+
parts.append(_text("Outcome feedback: " + fb))
|
| 317 |
+
if rec.keyframes:
|
| 318 |
+
parts.append(_text("Key images (" + ", ".join(c for c, _ in rec.keyframes) + "):"))
|
| 319 |
+
for cap, ref in rec.keyframes:
|
| 320 |
+
parts.append(_text(f"[{cap}]"))
|
| 321 |
+
parts.append(_img(ref))
|
| 322 |
+
return parts
|
| 323 |
+
|
| 324 |
+
def observation_parts(self, title, images, proprio):
|
| 325 |
+
parts = [_text(f"\n{title}:")]
|
| 326 |
+
for ref in images:
|
| 327 |
+
parts.append(_text(f"{ref.camera} camera:"))
|
| 328 |
+
parts.append(_img(ref))
|
| 329 |
+
parts.append(_text("Proprioception: " + json.dumps(proprio)))
|
| 330 |
+
return parts
|
| 331 |
+
|
| 332 |
+
def step_observation(self, step, tool_name, images, proprio):
|
| 333 |
+
return self.observation_parts(f"Observation after step {step} ({tool_name})", images, proprio)
|
| 334 |
+
|
| 335 |
+
@staticmethod
|
| 336 |
+
def nudge():
|
| 337 |
+
return [_text("Please continue by calling exactly one tool (call done if you are finished).")]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def pick_keyframes(steps, initial, final, n=4):
|
| 341 |
+
"""<= n agentview keyframes: start, up to n-2 informative intermediate frames, end (after settling)."""
|
| 342 |
+
out = [("start of attempt", initial)] if initial is not None and n >= 2 else []
|
| 343 |
+
budget = n - len(out) - (1 if final is not None else 0)
|
| 344 |
+
cands = [s for s in steps if s.frame is not None]
|
| 345 |
+
if budget > 0 and cands:
|
| 346 |
+
events = [s for s in cands if s.name in ("push", "close_gripper", "open_gripper")
|
| 347 |
+
or s.report.get("touched_object") or s.report.get("touched_objects")]
|
| 348 |
+
pool = events if len(events) >= budget else cands
|
| 349 |
+
if len(pool) > budget:
|
| 350 |
+
idx = [round(i * (len(pool) - 1) / max(budget - 1, 1)) for i in range(budget)] if budget > 1 \
|
| 351 |
+
else [len(pool) - 1]
|
| 352 |
+
pool = [pool[i] for i in sorted(set(idx))]
|
| 353 |
+
for s in sorted(pool, key=lambda s: s.step)[:budget]:
|
| 354 |
+
out.append((f"after step {s.step} ({s.name})", s.frame))
|
| 355 |
+
if final is not None:
|
| 356 |
+
out.append(("end of attempt, after objects settled", final))
|
| 357 |
+
return out[:n]
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
def wilson(k, n, z=1.96):
|
| 361 |
+
if n == 0:
|
| 362 |
+
return (float("nan"), float("nan"))
|
| 363 |
+
p = k / n
|
| 364 |
+
d = 1 + z * z / n
|
| 365 |
+
c = (p + z * z / (2 * n)) / d
|
| 366 |
+
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
|
| 367 |
+
return (max(0.0, c - h), min(1.0, c + h))
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def deep_strip_images(obj):
|
| 371 |
+
"""JSON-friendly copy of conversation items (images -> paths)."""
|
| 372 |
+
obj = copy.copy(obj)
|
| 373 |
+
if isinstance(obj, dict):
|
| 374 |
+
return {k: (v.path if k == "image" else deep_strip_images(v)) for k, v in obj.items()}
|
| 375 |
+
if isinstance(obj, list):
|
| 376 |
+
return [deep_strip_images(v) for v in obj]
|
| 377 |
+
return obj
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/agent/cost.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Token / cost accounting.
|
| 2 |
+
|
| 3 |
+
Prices (USD per 1M tokens) for gpt-6-astra from the OpenAI model page as recorded in
|
| 4 |
+
research_notes/.../seed_papers.md Q8 (2026-10): input 10, cached input 1, cache write 12.5, output 50;
|
| 5 |
+
prompts > 272K input tokens are billed 2x input/cached and 1.5x output. usage.input_tokens_details has
|
| 6 |
+
cached_tokens and (openai SDK >= 3.x) cache_write_tokens; both are priced separately when present.
|
| 7 |
+
Reasoning tokens are billed as output tokens (they are included in output_tokens).
|
| 8 |
+
"""
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
PRICES = {
|
| 12 |
+
"gpt-6-astra": dict(input=10.0, cached=1.0, cache_write=12.5, output=50.0, long_threshold=272_000, long_in=2.0, long_out=1.5),
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def call_cost(usage, model="gpt-6-astra"):
|
| 17 |
+
p = PRICES.get(model)
|
| 18 |
+
if p is None or not usage:
|
| 19 |
+
return None
|
| 20 |
+
inp = usage.get("input_tokens", 0) or 0
|
| 21 |
+
cached = usage.get("cached_tokens", 0) or 0
|
| 22 |
+
write = usage.get("cache_write_tokens", 0) or 0 # reported by newer SDKs / API versions
|
| 23 |
+
out = usage.get("output_tokens", 0) or 0
|
| 24 |
+
li, lo = (p["long_in"], p["long_out"]) if inp > p["long_threshold"] else (1.0, 1.0)
|
| 25 |
+
plain = max(inp - cached - write, 0)
|
| 26 |
+
return ((plain * p["input"] + write * p["cache_write"] + cached * p["cached"]) * li + out * p["output"] * lo) / 1e6
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def image_tokens(w, h, patch=32, per_patch=1.0, overhead=0):
|
| 30 |
+
"""ASSUMPTION (not verified for gpt-6-astra): patch-based image accounting as for the GPT-5 family,
|
| 31 |
+
one token per 32x32 patch (~256 tokens for 512x512). Real numbers come from response.usage."""
|
| 32 |
+
return int(math.ceil(w / patch) * math.ceil(h / patch) * per_patch + overhead)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def estimate_request_tokens(stats, image_res=512):
|
| 36 |
+
"""Rough input-token estimate of one request from OpenAIResponsesBackend.request_stats()."""
|
| 37 |
+
return int(stats.get("text_chars", 0) / 4 + stats.get("n_images", 0) * image_tokens(image_res, image_res))
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l3_card_edge.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L3 card_edge: a thin card lying flat on a board cannot be pinched; slide it over the board's edge, then grasp it.
|
| 2 |
+
|
| 3 |
+
Category: strategy_switching ("this way of doing it cannot work"), the user's taxonomy L3 example verbatim:
|
| 4 |
+
"卡片贴着桌面捏不起来 -> 先把卡片滑到桌沿,再夹起来".
|
| 5 |
+
|
| 6 |
+
Scene: a wooden board (22 x 26 x 5 cm) on the table with a thin red card (9.0 x 5.6 x 0.2 cm, 10 g) lying flat on it,
|
| 7 |
+
long side roughly along x or along y (+-10 deg); a grey bin (16 x 16 cm inside) stands on the table beside the board.
|
| 8 |
+
The board stands in for the table edge of the user's example: the real table edge is out of reach (near edge 16 cm
|
| 9 |
+
from the robot base, side edges at |y| = 0.6 m) and the harness does not let the grasp point go below the table top.
|
| 10 |
+
|
| 11 |
+
Why the prior fails (measured): a top-down grasp across the card's short side. The Panda fingertips land on the
|
| 12 |
+
board on either side of the card, but when they close on its 2 mm edge the contact flips to "slide over the top" and
|
| 13 |
+
both fingertips ride up over the card and close above it: 0/36 lifts for 1.5 / 2 / 3 mm cards, grasp-point height
|
| 14 |
+
-6..+3 mm, xy jitter 5 mm, yaw jitter 0.1 rad (prototype, 2026-10-08). Retrying with small variations fails the same
|
| 15 |
+
way. (A 4 mm card could be pinched -- the reason the earlier `l3_flat_card_edge` was dropped.)
|
| 16 |
+
|
| 17 |
+
What must be learned from the failure: the card cannot be picked up while it lies flat -> change the strategy: press
|
| 18 |
+
the closed fingertips onto the card and slide it (move_to with the fingertips pressing on it) until part of it hangs
|
| 19 |
+
over the board's edge, then grasp the overhanging part with the fingertips below the card: then the fingers close on
|
| 20 |
+
the card's full edge and it lifts (18/18 for 2.5-3.5 cm of overhang in the prototype). More than half the card's
|
| 21 |
+
length over the edge and it tips off the board.
|
| 22 |
+
|
| 23 |
+
Protocol: cross (reset to the same instance before every attempt), k = 5.
|
| 24 |
+
"""
|
| 25 |
+
import numpy as np
|
| 26 |
+
|
| 27 |
+
from .. import envs
|
| 28 |
+
from ..bddl import write_bddl
|
| 29 |
+
from ..objects import _SOLID, _fmt, _wrap, bin_xml, box_xml, register_generated
|
| 30 |
+
from ..skills import Skills
|
| 31 |
+
from ..task_base import LFFTask, register_task
|
| 32 |
+
|
| 33 |
+
CARD_HALF = (0.045, 0.028, 0.001) # 9.0 x 5.6 x 0.2 cm
|
| 34 |
+
CARD_MASS = 0.010
|
| 35 |
+
MU = 0.3 # card and board sliding friction (the fingers' 1.0 / 2.0 win in finger contacts: MuJoCo takes the max)
|
| 36 |
+
BOARD_HALF = (0.11, 0.13, 0.025)
|
| 37 |
+
BOARD_TOP = envs.TABLE_Z + 2 * BOARD_HALF[2]
|
| 38 |
+
BIN_IN = 0.08 # inner half width
|
| 39 |
+
BIN_WALL_H = 0.05
|
| 40 |
+
BIN_GAP = 0.06 # board edge to bin outer wall
|
| 41 |
+
BIN_T = 0.006
|
| 42 |
+
BIN_HALF_OUT = BIN_IN + BIN_T
|
| 43 |
+
TIP_BELOW_SITE = envs.FINGERTIP_BELOW_SITE
|
| 44 |
+
LOW_CLOSE = 0.02 # a close counts as a grasp try when the fingertips are at most this far above the card
|
| 45 |
+
OVERHANG = 0.03 # scripted target overhang (the grasp works for ~2.5-4.0 cm; the card tips off past ~4.5 cm)
|
| 46 |
+
GRASP_OUT = 0.022 # scripted grasp point: this far beyond the board edge (fingers must clear the edge)
|
| 47 |
+
DRAG_SPEED = 0.08
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def card_xml(name, rgba=(0.85, 0.15, 0.12, 1.0)):
|
| 51 |
+
g = (f' <geom name="{name}_g0" type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" mass="{CARD_MASS}" '
|
| 52 |
+
f'friction="{MU} 0.005 0.0001" {_SOLID} group="0" condim="4"/>\n'
|
| 53 |
+
f' <geom type="box" size="{_fmt(CARD_HALF)}" rgba="{_fmt(rgba)}" contype="0" conaffinity="0" group="1"/>')
|
| 54 |
+
return _wrap(name, g, CARD_HALF[2], float(np.hypot(CARD_HALF[0], CARD_HALF[1])))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _yaw_of(quat_wxyz):
|
| 58 |
+
w, x, y, z = quat_wxyz
|
| 59 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
EDGES = ("forward", "backward", "left", "right") # board edges in robot-centric words (+x, -x, +y, -y)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class CardSkills(Skills):
|
| 66 |
+
"""Skills that feed the task's per-step monitor and log every close of the gripper."""
|
| 67 |
+
|
| 68 |
+
def __init__(self, env, task, recorder=None):
|
| 69 |
+
super().__init__(env, recorder=recorder)
|
| 70 |
+
self.task = task
|
| 71 |
+
self.closes = []
|
| 72 |
+
|
| 73 |
+
def _act(self, dpos, drot, grip):
|
| 74 |
+
super()._act(dpos, drot, grip)
|
| 75 |
+
self.task.monitor_step()
|
| 76 |
+
|
| 77 |
+
def set_gripper(self, close, steps=15):
|
| 78 |
+
was_open = self.grip < 0
|
| 79 |
+
before = self.task.close_context() if (close and was_open) else None
|
| 80 |
+
rep = super().set_gripper(close, steps)
|
| 81 |
+
if before is not None:
|
| 82 |
+
before.update(held=self.holding("card_1"), width=round(self.gripper_width(), 4))
|
| 83 |
+
self.closes.append(before)
|
| 84 |
+
return rep
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
@register_task
|
| 88 |
+
class CardEdge(LFFTask):
|
| 89 |
+
name = "l3_card_edge"
|
| 90 |
+
level = "L3"
|
| 91 |
+
category = "strategy_switching"
|
| 92 |
+
capabilities = ("Perceive", "Reason", "Plan")
|
| 93 |
+
protocol = "cross"
|
| 94 |
+
instruction = "Pick up the thin red card lying on the wooden board and put it into the grey bin."
|
| 95 |
+
instruction_indirect = "Put the flat red rectangle that lies on the wooden block into the grey container."
|
| 96 |
+
|
| 97 |
+
# ------------------------------------------------------------ scene
|
| 98 |
+
def make_bddl(self):
|
| 99 |
+
card = register_generated("LffThinCard", card_xml("lff_thin_card"))
|
| 100 |
+
board = register_generated("LffCardBoard", box_xml("lff_card_board", BOARD_HALF, (0.62, 0.45, 0.27, 1.0),
|
| 101 |
+
friction=(MU, 0.005, 0.0001)), free=False)
|
| 102 |
+
bin_ = register_generated("LffCardBin", bin_xml("lff_card_bin", (BIN_IN, BIN_IN), BIN_WALL_H, wall_t=BIN_T,
|
| 103 |
+
rgba=(0.55, 0.56, 0.60, 1.0)), free=False)
|
| 104 |
+
objs = [("card_1", card, "card_region", (0.10, 0.20, 0.12, 0.22))]
|
| 105 |
+
fx = [("board_1", board, "board_region", (-0.11, -0.01, -0.09, 0.01)),
|
| 106 |
+
("bin_1", bin_, "bin_region", (-0.11, -0.31, -0.09, -0.29))]
|
| 107 |
+
return write_bddl(self.name, self.instruction, objs, fx)
|
| 108 |
+
|
| 109 |
+
def __init__(self, cam_res=None):
|
| 110 |
+
super().__init__(cam_res)
|
| 111 |
+
m = self.env.sim.model
|
| 112 |
+
self.board_bid = m.body_name2id(self.env.fixtures_dict["board_1"].root_body)
|
| 113 |
+
self.bin_bid = m.body_name2id(self.env.fixtures_dict["bin_1"].root_body)
|
| 114 |
+
self.inst = None
|
| 115 |
+
self.mon = None
|
| 116 |
+
|
| 117 |
+
def sample_instance(self, seed):
|
| 118 |
+
rng = np.random.default_rng(seed)
|
| 119 |
+
bx, by = float(rng.uniform(-0.14, -0.06)), float(rng.uniform(-0.08, 0.08))
|
| 120 |
+
along = str(rng.choice(["x", "y"]))
|
| 121 |
+
yaw = (0.0 if along == "x" else np.pi / 2) + float(rng.uniform(-np.radians(10), np.radians(10)))
|
| 122 |
+
if along == "x": # keep the whole card >= 3 cm (long axis) / 2 cm (short axis) inside the board
|
| 123 |
+
off = [rng.uniform(-0.03, 0.03), rng.uniform(-0.07, 0.07)]
|
| 124 |
+
else:
|
| 125 |
+
off = [rng.uniform(-0.055, 0.055), rng.uniform(-0.05, 0.05)]
|
| 126 |
+
side = 1.0 if rng.random() < 0.5 else -1.0
|
| 127 |
+
bin_xy = [bx + float(rng.uniform(-0.04, 0.04)), by + side * (BOARD_HALF[1] + BIN_GAP + BIN_HALF_OUT)]
|
| 128 |
+
return dict(seed=int(seed), board_xy=[bx, by], card_xy=[bx + float(off[0]), by + float(off[1])],
|
| 129 |
+
card_yaw=float(yaw), card_along=along, bin_xy=bin_xy, bin_side="left" if side > 0 else "right")
|
| 130 |
+
|
| 131 |
+
def apply_instance(self, inst):
|
| 132 |
+
self.inst = inst
|
| 133 |
+
m = self.env.sim.model
|
| 134 |
+
bx, by = inst["board_xy"]
|
| 135 |
+
m.body_pos[self.board_bid] = [bx, by, envs.TABLE_Z + BOARD_HALF[2]]
|
| 136 |
+
m.body_quat[self.board_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 137 |
+
cx, cy = inst["bin_xy"]
|
| 138 |
+
m.body_pos[self.bin_bid] = [cx, cy, envs.TABLE_Z + (BIN_WALL_H + BIN_T) / 2]
|
| 139 |
+
m.body_quat[self.bin_bid] = [1.0, 0.0, 0.0, 0.0]
|
| 140 |
+
x, y = inst["card_xy"]
|
| 141 |
+
envs.set_obj_pose(self.env, "card_1", [x, y, BOARD_TOP + CARD_HALF[2] + 0.0003], yaw=inst["card_yaw"])
|
| 142 |
+
|
| 143 |
+
def reset_instance(self, inst, recorder=None):
|
| 144 |
+
self.env.reset()
|
| 145 |
+
self.apply_instance(inst)
|
| 146 |
+
self.env.sim.forward()
|
| 147 |
+
envs.settle(self.env, 15)
|
| 148 |
+
self.sk = CardSkills(self.env, self, recorder=recorder)
|
| 149 |
+
p = self.card_pose()
|
| 150 |
+
self.mon = dict(start_xy=p["xy"].copy(), max_lift=0.0, max_overhang=0.0, fell=False)
|
| 151 |
+
return self.sk
|
| 152 |
+
|
| 153 |
+
# ------------------------------------------------------------ geometry
|
| 154 |
+
def card_pose(self):
|
| 155 |
+
p = envs.obj_pos(self.env, "card_1")
|
| 156 |
+
return dict(xy=p[:2].copy(), z=float(p[2]), yaw=_yaw_of(envs.obj_quat(self.env, "card_1")))
|
| 157 |
+
|
| 158 |
+
def card_corners(self):
|
| 159 |
+
d = self.env.sim.data
|
| 160 |
+
bid = envs.body_id(self.env, "card_1")
|
| 161 |
+
R = d.body_xmat[bid].reshape(3, 3)
|
| 162 |
+
h = np.array(CARD_HALF)
|
| 163 |
+
return np.array([d.body_xpos[bid] + R @ (h * [sx, sy, 0.0]) for sx in (-1, 1) for sy in (-1, 1)])
|
| 164 |
+
|
| 165 |
+
def overhang(self):
|
| 166 |
+
"""(how far the card sticks out beyond the board's edges (m, max over its corners), edge word)"""
|
| 167 |
+
c = self.card_corners()[:, :2] - np.asarray(self.inst["board_xy"])
|
| 168 |
+
prot = {"forward": c[:, 0].max() - BOARD_HALF[0], "backward": -c[:, 0].min() - BOARD_HALF[0],
|
| 169 |
+
"left": c[:, 1].max() - BOARD_HALF[1], "right": -c[:, 1].min() - BOARD_HALF[1]}
|
| 170 |
+
e = max(prot, key=prot.get)
|
| 171 |
+
return float(prot[e]), e
|
| 172 |
+
|
| 173 |
+
def on_board(self):
|
| 174 |
+
p = self.card_pose()
|
| 175 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["board_xy"]))
|
| 176 |
+
return bool(rel[0] <= BOARD_HALF[0] and rel[1] <= BOARD_HALF[1] and abs(p["z"] - BOARD_TOP) < 0.012)
|
| 177 |
+
|
| 178 |
+
def in_bin(self):
|
| 179 |
+
p = self.card_pose()
|
| 180 |
+
rel = np.abs(p["xy"] - np.asarray(self.inst["bin_xy"]))
|
| 181 |
+
return bool(rel[0] <= BIN_IN and rel[1] <= BIN_IN and p["z"] < envs.TABLE_Z + BIN_T + BIN_WALL_H)
|
| 182 |
+
|
| 183 |
+
# ------------------------------------------------------------ monitor
|
| 184 |
+
def monitor_step(self):
|
| 185 |
+
mon = self.mon
|
| 186 |
+
if mon is None:
|
| 187 |
+
return
|
| 188 |
+
zmin = float(self.card_corners()[:, 2].min())
|
| 189 |
+
mon["max_lift"] = max(mon["max_lift"], zmin - BOARD_TOP)
|
| 190 |
+
if self.on_board() or abs(self.card_pose()["z"] - BOARD_TOP) < 0.012:
|
| 191 |
+
mon["max_overhang"] = max(mon["max_overhang"], self.overhang()[0])
|
| 192 |
+
if self.card_pose()["z"] < BOARD_TOP - 0.02 and not self.sk.holding("card_1"):
|
| 193 |
+
mon["fell"] = True
|
| 194 |
+
|
| 195 |
+
def close_context(self):
|
| 196 |
+
"""Where the gripper is relative to the card and the board just before it closes."""
|
| 197 |
+
sk, p = self.sk, self.card_pose()
|
| 198 |
+
e = sk.eef_pos()
|
| 199 |
+
c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
|
| 200 |
+
rel = e[:2] - p["xy"]
|
| 201 |
+
local = [float(rel @ [c, s]), float(rel @ [-s, c])] # along the card's long / short side
|
| 202 |
+
b = e[:2] - np.asarray(self.inst["board_xy"])
|
| 203 |
+
beyond = {"forward": b[0] - BOARD_HALF[0], "backward": -b[0] - BOARD_HALF[0],
|
| 204 |
+
"left": b[1] - BOARD_HALF[1], "right": -b[1] - BOARD_HALF[1]}
|
| 205 |
+
edge = max(beyond, key=beyond.get)
|
| 206 |
+
ov, ov_edge = self.overhang()
|
| 207 |
+
return dict(step=sk.n_steps, local=[round(v, 4) for v in local],
|
| 208 |
+
tips_above_card=round(float(e[2] - TIP_BELOW_SITE - (p["z"] + CARD_HALF[2])), 4),
|
| 209 |
+
beyond_edge=round(float(beyond[edge]), 4), beyond_edge_name=edge,
|
| 210 |
+
card_on_board=self.on_board(), overhang=round(ov, 4), overhang_edge=ov_edge,
|
| 211 |
+
width_before=round(sk.gripper_width(), 4))
|
| 212 |
+
|
| 213 |
+
# ------------------------------------------------------------ outcome / F2
|
| 214 |
+
def outcome(self, inst):
|
| 215 |
+
envs.settle(self.env, 30)
|
| 216 |
+
sk, mon = self.sk, self.mon
|
| 217 |
+
p = self.card_pose()
|
| 218 |
+
held = bool(sk.holding("card_1"))
|
| 219 |
+
in_bin = self.in_bin() and not held
|
| 220 |
+
success = bool(in_bin)
|
| 221 |
+
moved = float(np.linalg.norm(p["xy"] - mon["start_xy"]))
|
| 222 |
+
lifted = mon["max_lift"] > 0.02
|
| 223 |
+
tries = [c for c in sk.closes if c["tips_above_card"] <= LOW_CLOSE and c["width_before"] > 0.02]
|
| 224 |
+
parts, mode = [], "success"
|
| 225 |
+
if success:
|
| 226 |
+
parts.append("The card is in the bin.")
|
| 227 |
+
else:
|
| 228 |
+
rel = p["xy"] - np.asarray(inst["bin_xy"])
|
| 229 |
+
where = (f"{100 * abs(rel[0]):.1f} cm {'forward' if rel[0] > 0 else 'backward'} and "
|
| 230 |
+
f"{100 * abs(rel[1]):.1f} cm {'left' if rel[1] > 0 else 'right'} of the bin's centre")
|
| 231 |
+
if held:
|
| 232 |
+
mode = "held"
|
| 233 |
+
parts.append(f"The card is still held by the gripper, {where}.")
|
| 234 |
+
elif lifted:
|
| 235 |
+
mode = "dropped"
|
| 236 |
+
loc = "on the board" if self.on_board() else ("on the table" if p["z"] < BOARD_TOP - 0.02 else
|
| 237 |
+
"partly on the board")
|
| 238 |
+
parts.append(f"The card was lifted {100 * mon['max_lift']:.1f} cm above the board but is not in the "
|
| 239 |
+
f"bin: it lies {loc}, its centre {where}.")
|
| 240 |
+
elif mon["fell"]:
|
| 241 |
+
mode = "fell_off"
|
| 242 |
+
parts.append("The card was never lifted; it fell off the board and lies flat on the table.")
|
| 243 |
+
else:
|
| 244 |
+
mode = "not_lifted"
|
| 245 |
+
parts.append("The card was never lifted; it still lies flat on the board"
|
| 246 |
+
+ (f" (it was slid {100 * moved:.1f} cm" + (f" and stuck out up to "
|
| 247 |
+
f"{100 * mon['max_overhang']:.1f} cm beyond the board's edge)" if mon["max_overhang"] > 0.003
|
| 248 |
+
else ")") if moved > 0.005 else "") + ".")
|
| 249 |
+
if not lifted:
|
| 250 |
+
if not tries:
|
| 251 |
+
parts.append("The gripper never closed with its fingertips down at the card.")
|
| 252 |
+
else:
|
| 253 |
+
c = tries[-1]
|
| 254 |
+
n = f"{len(tries)} grasp tries; in the last one, " if len(tries) > 1 else ""
|
| 255 |
+
if c["card_on_board"] and c["overhang"] <= 0.0 and c["beyond_edge"] < 0.0:
|
| 256 |
+
txt = ("when the gripper closed on the card lying flat on the board, its fingertips were on "
|
| 257 |
+
"either side of the card, at board level")
|
| 258 |
+
else:
|
| 259 |
+
if c["beyond_edge"] >= 0.0:
|
| 260 |
+
pos = f"{100 * c['beyond_edge']:.1f} cm beyond the board's {c['beyond_edge_name']} edge"
|
| 261 |
+
else:
|
| 262 |
+
pos = f"over the board, {100 * -c['beyond_edge']:.1f} cm inside its {c['beyond_edge_name']} edge"
|
| 263 |
+
txt = (f"when the gripper closed, the card stuck out {100 * max(c['overhang'], 0.0):.1f} cm "
|
| 264 |
+
f"beyond the board's {c['overhang_edge']} edge and the gripper's centre was {pos}")
|
| 265 |
+
txt += (f" ({100 * c['tips_above_card']:+.1f} cm from the fingertips to the top of the card); the "
|
| 266 |
+
"fingers closed ")
|
| 267 |
+
txt += ("fully, sliding over the top of the card instead of gripping its edges."
|
| 268 |
+
if c["width"] < 2 * CARD_HALF[1] - 0.01 and not c["held"] else
|
| 269 |
+
("on the card." if c["held"] else f"to {100 * c['width']:.1f} cm without holding the card."))
|
| 270 |
+
parts.append(n + txt if n else txt[0].upper() + txt[1:])
|
| 271 |
+
out = dict(success=success, mode=mode, held=held, lifted=bool(lifted), max_lift=round(mon["max_lift"], 4),
|
| 272 |
+
max_overhang=round(mon["max_overhang"], 4), moved=round(moved, 4), fell=bool(mon["fell"]),
|
| 273 |
+
grasp_tries=tries, closes=sk.closes, detail=" ".join(parts))
|
| 274 |
+
return out
|
| 275 |
+
|
| 276 |
+
# ------------------------------------------------------------ scripted policies (move_to + gripper only)
|
| 277 |
+
def _edge_plan(self, inst):
|
| 278 |
+
"""the board edge the card is slid to: along its long side; the near (backward) edge for x-cards,
|
| 279 |
+
the closer side edge for y-cards"""
|
| 280 |
+
if inst["card_along"] == "x":
|
| 281 |
+
return "backward"
|
| 282 |
+
return "left" if inst["card_xy"][1] >= inst["board_xy"][1] else "right"
|
| 283 |
+
|
| 284 |
+
def grasp_and_bin(self, xy, yaw, z_site, lift=0.12):
|
| 285 |
+
sk = self.sk
|
| 286 |
+
sk.set_gripper(False, steps=8)
|
| 287 |
+
sk.move_to([xy[0], xy[1], z_site + 0.08], yaw=yaw)
|
| 288 |
+
sk.move_to([xy[0], xy[1], z_site], tol=0.003, max_steps=120)
|
| 289 |
+
sk.set_gripper(True, steps=15)
|
| 290 |
+
sk.move_to([xy[0], xy[1], z_site + lift], speed=0.2)
|
| 291 |
+
if not sk.holding("card_1"):
|
| 292 |
+
sk.set_gripper(False, steps=8)
|
| 293 |
+
return False
|
| 294 |
+
bx, by = self.inst["bin_xy"]
|
| 295 |
+
hi = envs.TABLE_Z + BIN_WALL_H + 0.12
|
| 296 |
+
sk.move_to([bx, by, hi])
|
| 297 |
+
sk.move_to([bx, by, envs.TABLE_Z + BIN_WALL_H + 0.05], speed=0.2)
|
| 298 |
+
sk.set_gripper(False, steps=12)
|
| 299 |
+
sk.move_to([bx, by, hi])
|
| 300 |
+
return True
|
| 301 |
+
|
| 302 |
+
def slide_card(self, delta, press=0.004):
|
| 303 |
+
"""closed fingertips pressed on the card's centre, straight move by `delta` (xy), lift"""
|
| 304 |
+
sk, p = self.sk, self.card_pose()
|
| 305 |
+
z = p["z"] + CARD_HALF[2] + TIP_BELOW_SITE - press
|
| 306 |
+
sk.set_gripper(True, steps=8)
|
| 307 |
+
sk.move_to([p["xy"][0], p["xy"][1], z + 0.06], yaw=p["yaw"])
|
| 308 |
+
sk.move_to([p["xy"][0], p["xy"][1], z], tol=0.003, max_steps=100)
|
| 309 |
+
e = p["xy"] + np.asarray(delta, float)
|
| 310 |
+
sk.move_to([e[0], e[1], z], speed=DRAG_SPEED, tol=0.004, max_steps=300)
|
| 311 |
+
sk.move_to([e[0], e[1], z + 0.06], speed=0.2)
|
| 312 |
+
sk.hold(5)
|
| 313 |
+
|
| 314 |
+
def execute(self, inst, params):
|
| 315 |
+
p = self.card_pose()
|
| 316 |
+
if params["mode"] == "grasp":
|
| 317 |
+
xy = p["xy"] + np.asarray(params.get("dxy", (0.0, 0.0)))
|
| 318 |
+
self.grasp_and_bin(xy, p["yaw"] + params.get("dyaw", 0.0), BOARD_TOP + params.get("dz", 0.0))
|
| 319 |
+
return
|
| 320 |
+
# edge: slide the card along its long side until `overhang` of it sticks out over the chosen edge
|
| 321 |
+
edge = params.get("edge") or self._edge_plan(inst)
|
| 322 |
+
u = {"forward": (1, 0), "backward": (-1, 0), "left": (0, 1), "right": (0, -1)}[edge]
|
| 323 |
+
u = np.asarray(u, float)
|
| 324 |
+
c, s = np.cos(p["yaw"]), np.sin(p["yaw"])
|
| 325 |
+
long_ax = np.array([c, s]) if abs(np.array([c, s]) @ u) >= abs(np.array([-s, c]) @ u) else np.array([-s, c])
|
| 326 |
+
long_ax = long_ax * np.sign(long_ax @ u)
|
| 327 |
+
b = np.asarray(inst["board_xy"])
|
| 328 |
+
half = BOARD_HALF[0] if edge in ("forward", "backward") else BOARD_HALF[1]
|
| 329 |
+
edge_pos = (b @ u) + half # coordinate of the edge along u
|
| 330 |
+
ext = CARD_HALF[0] * abs(long_ax @ u) + CARD_HALF[1] * abs(np.array([-long_ax[1], long_ax[0]]) @ u)
|
| 331 |
+
for short in (0.01, 0.0): # slide to 1 cm short, look again, slide the rest (one stroke overshoots ~0.7 cm)
|
| 332 |
+
p = self.card_pose()
|
| 333 |
+
need = edge_pos + float(params["overhang"]) - short - (p["xy"] @ u + ext) # travel still needed along u
|
| 334 |
+
if need > 0.003:
|
| 335 |
+
self.slide_card(long_ax * need / max(long_ax @ u, 1e-6))
|
| 336 |
+
q = self.card_pose()
|
| 337 |
+
cu = float(q["xy"] @ u)
|
| 338 |
+
tip_u = cu + CARD_HALF[0] * float(long_ax @ u) # centre of the card's far end, along u
|
| 339 |
+
target_u = min(tip_u - 0.008, edge_pos + GRASP_OUT)
|
| 340 |
+
g = q["xy"] + long_ax * (target_u - cu) / max(float(long_ax @ u), 1e-6)
|
| 341 |
+
self.grasp_and_bin(g, q["yaw"], BOARD_TOP - 0.003)
|
| 342 |
+
|
| 343 |
+
def default_params(self, inst):
|
| 344 |
+
return dict(mode="grasp")
|
| 345 |
+
|
| 346 |
+
def oracle_params(self, inst):
|
| 347 |
+
return dict(mode="edge", overhang=OVERHANG)
|
| 348 |
+
|
| 349 |
+
def blind_params(self, inst, attempt, rng):
|
| 350 |
+
return dict(mode="grasp", dxy=rng.normal(0.0, 0.006, 2).tolist(), dyaw=float(rng.normal(0.0, 0.12)),
|
| 351 |
+
dz=float(rng.uniform(-0.006, 0.003)))
|
| 352 |
+
|
| 353 |
+
def adapt_params(self, inst, history):
|
| 354 |
+
"""not lifted while flat on the board (fingers slid over it) -> slide it over the edge first, 3 cm.
|
| 355 |
+
Edge tried: card fell off -> 1 cm less; fingers closed without holding and < 4 cm overhang -> 1 cm more."""
|
| 356 |
+
out, prm = history[-1]["outcome"], history[-1]["params"]
|
| 357 |
+
if prm["mode"] == "grasp":
|
| 358 |
+
return dict(mode="edge", overhang=OVERHANG) if out["mode"] in ("not_lifted", "fell_off") else dict(prm)
|
| 359 |
+
h = float(prm["overhang"])
|
| 360 |
+
if out["mode"] == "fell_off":
|
| 361 |
+
h -= 0.01
|
| 362 |
+
elif out["mode"] == "not_lifted":
|
| 363 |
+
h += 0.01 if out["max_overhang"] < 0.04 else -0.005
|
| 364 |
+
return dict(mode="edge", overhang=float(np.clip(h, 0.025, 0.045)))
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l5_slide.py
ADDED
|
@@ -0,0 +1,577 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 1 |
+
"""L5-A slide_to_target: strike the cube so that it slides on its own and comes to rest inside the target zone.
|
| 2 |
+
|
| 3 |
+
Hidden variable: cube-table sliding friction mu (log-uniform in [0.035, 0.10]) -- the cube looks the
|
| 4 |
+
same for every mu. With the default push speed the cube overshoots on slippery instances and stops
|
| 5 |
+
short on grippy ones; the only way to get it right is to infer from where the cube stopped how hard
|
| 6 |
+
to push next time (cf. MemMimic push_cube, iterative pushing).
|
| 7 |
+
|
| 8 |
+
Strikes per attempt: not limited (2026-10-19, user). From 2026-10-08 the instruction allowed ONE strike per attempt
|
| 9 |
+
(one move command pushing the cube, the gripper advancing at most 4 cm after the first touch), to stop slow pushes that
|
| 10 |
+
carry the cube to the target so that friction never matters (exp1 / cla1 Claude, la2 GPT: 0.05 m/s pushes). That rule
|
| 11 |
+
also moved within-attempt correction (overshot -> fetch the cube back -> strike again) to the next attempt. The
|
| 12 |
+
loophole is now closed by the success rule instead:
|
| 13 |
+
|
| 14 |
+
Success: when the attempt ends the cube is at rest, on the table, in the square (see "Target" below), AND it got there
|
| 15 |
+
by a free slide of at least D_MIN: from the last moment the robot touched it (any robot or gripper geom, contacts
|
| 16 |
+
checked at every 2 ms physics substep; holding it counts as touching) to its final position the cube slid >= D_MIN with
|
| 17 |
+
nothing touching it. A touch that leaves a resting cube where it was (< 1 mm) is ignored. This fails a quasi-static push
|
| 18 |
+
into the square (free slide 0-1.2 cm measured), placing the cube there with the gripper (0 cm) and putting it just in
|
| 19 |
+
front of the square and tapping it (< D_MIN); see the task card for the adversarial checks and why D_MIN = 3 cm.
|
| 20 |
+
|
| 21 |
+
Error events: every strike (a robot contact that moved the cube followed by a free slide of >= STRIKE_MIN) is logged
|
| 22 |
+
when the cube comes to rest; it is "missed" if the cube then lies outside the square (past / short / beside).
|
| 23 |
+
`n_missed_strikes`, `trap_fired` (>= 1 missed strike) and `recovered_in_attempt` (trap fired and the attempt then
|
| 24 |
+
succeeded) are in the outcome, as in l7_key_turn; `irrecoverable` = the cube fell off the table or lies outside the
|
| 25 |
+
arm's reach (the attempt is not ended for it).
|
| 26 |
+
|
| 27 |
+
Observation fix (2026-10-19): a strike used to return while the cube was still sliding, and `observe` does not advance
|
| 28 |
+
the simulation, so agents saw the cube half-way (cla2: "2.2 cm short", it then slid to 7.0 cm past the centre).
|
| 29 |
+
SlideSkills.move_to / set_gripper now hold the arm still after the motion until the cube is at rest (or WAIT_MAX),
|
| 30 |
+
so every reply and image shows the cube where it stopped. The waiting time counts as simulated motion time.
|
| 31 |
+
|
| 32 |
+
Target (2026-10-19, user; before: completely inside the square on all four sides, centre within +-1 cm): the agentview
|
| 33 |
+
camera looks at the square from the far side (the cube is pushed towards it), and a cube that sticks out past the far
|
| 34 |
+
edge by up to ~1 cm covers the far green line but shows < 2 px of red beyond it in the 512 x 512 image, which looks like
|
| 35 |
+
"inside / on the line" (self-test: 0.8 cm past the inner edge looked inside). So on the far side the cube may now lie on
|
| 36 |
+
the far green line: the instruction says it must not stick out beyond that line; judged, its centre may be up to
|
| 37 |
+
TOL_PAST = 2.0 cm past the square's centre (front face <= 4 mm beyond the line's outer edge). From 2.0 cm on, every one
|
| 38 |
+
of 25 measured instances shows >= 2 px of red beyond the line (task card). The near side and the sides stay "completely
|
| 39 |
+
inside" (+-1 cm): the near-side band cannot be made visible in the agentview by any tolerance (the cube's own body hides
|
| 40 |
+
the near line), and relaxing it would let the 0.30 m/s strike pass on short-stopping instances (task card).
|
| 41 |
+
"""
|
| 42 |
+
import numpy as np
|
| 43 |
+
|
| 44 |
+
from .. import envs
|
| 45 |
+
from ..bddl import write_bddl
|
| 46 |
+
from ..objects import _fmt, _wrap, box_xml, register_generated
|
| 47 |
+
from ..skills import DT, Skills, _rot_err
|
| 48 |
+
from ..task_base import LFFTask, register_task
|
| 49 |
+
|
| 50 |
+
CUBE = "cube_1"
|
| 51 |
+
CUBE_HALF = 0.02
|
| 52 |
+
D_MIN = 0.03 # the cube's last free slide (after its last contact with the robot) must be at least this long
|
| 53 |
+
STRIKE_MIN = 0.01 # a contact that moved the cube, followed by a free slide of >= 1 cm, counts as a strike
|
| 54 |
+
TOUCH_MOVE = 0.001 # a contact episode moved the cube if the cube ends >= 1 mm (3-D) from where it was at its start
|
| 55 |
+
EP_GAP = 25 # physics substeps (one control step, 50 ms) without robot contact end a contact episode
|
| 56 |
+
V_REST, W_REST = 0.003, 0.05 # cube at rest: linear speed below 3 mm/s and angular speed below 0.05 rad/s ...
|
| 57 |
+
REST_SUB = 25 # ... for 25 consecutive substeps (50 ms)
|
| 58 |
+
WAIT_MAX = 100 # control steps (5 s) a command may hold the arm waiting for the cube to come to rest
|
| 59 |
+
ON_TABLE = 0.005 # cube resting on the table: centre within 5 mm of TABLE_Z + CUBE_HALF
|
| 60 |
+
OFF_TABLE_Z = envs.TABLE_Z - 0.05 # cube centre below this: it fell off the table
|
| 61 |
+
REACH_MARGIN = 0.03 # cube centre this close to the commanded-target limits (agent/tools.py WS_LO / WS_HI): unreachable
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class CubeWatch:
|
| 65 |
+
"""Follows the cube at every physics substep (installed on env.sim by reset_instance; outcome() reads it).
|
| 66 |
+
|
| 67 |
+
contact episode: substeps with a robot-cube contact, merged across gaps shorter than EP_GAP substeps. Closed
|
| 68 |
+
EP_GAP substeps after its last contact; it "moved" the cube if the cube is then >= TOUCH_MOVE from where it was
|
| 69 |
+
when the episode began, or still moving.
|
| 70 |
+
release: the cube's xy at the last contact of the last episode that moved it, i.e. where its current free slide
|
| 71 |
+
began (None while the robot has never moved the cube).
|
| 72 |
+
strike: an episode that moved the cube followed by a free slide of >= STRIKE_MIN, logged when the cube comes to
|
| 73 |
+
rest (or when the robot touches it again before that: result "interrupted")."""
|
| 74 |
+
|
| 75 |
+
def __init__(self, env, target_xy, tol_short, tol_past, tol_across):
|
| 76 |
+
m = env.sim.model
|
| 77 |
+
self.env = env
|
| 78 |
+
self.is_robot = np.zeros(m.ngeom, bool)
|
| 79 |
+
self.is_robot[envs.robot_geom_ids(env)] = True
|
| 80 |
+
self.is_cube = np.zeros(m.ngeom, bool)
|
| 81 |
+
self.is_cube[envs.obj_geom_ids(env, CUBE)] = True
|
| 82 |
+
self.qa, self.da = envs.free_joint_addr(env, CUBE)
|
| 83 |
+
self.target = np.asarray(target_xy, float)
|
| 84 |
+
self.tol = (float(tol_short), float(tol_past), float(tol_across)) # centre offsets: short of / past / beside
|
| 85 |
+
self.n_sub = 0
|
| 86 |
+
self.ep = None # open contact episode
|
| 87 |
+
self.gap = 0
|
| 88 |
+
self.quiet = 0 # consecutive substeps at rest
|
| 89 |
+
self.release = None
|
| 90 |
+
self.slide = None # free slide in progress: where it started (cube at the episode start) and was released
|
| 91 |
+
self.moves = [] # closed contact episodes that moved the cube
|
| 92 |
+
self.strikes = []
|
| 93 |
+
|
| 94 |
+
# ------------------------------------------------------------ state
|
| 95 |
+
def pos(self):
|
| 96 |
+
return self.env.sim.data.qpos[self.qa:self.qa + 3].copy()
|
| 97 |
+
|
| 98 |
+
def at_rest(self):
|
| 99 |
+
qv = self.env.sim.data.qvel[self.da:self.da + 6]
|
| 100 |
+
return bool(np.linalg.norm(qv[:3]) < V_REST and np.linalg.norm(qv[3:]) < W_REST)
|
| 101 |
+
|
| 102 |
+
def judge(self, p):
|
| 103 |
+
"""Where a cube at p lies relative to the square: (along, across, in / past / short / beside / off).
|
| 104 |
+
in = centre at most tol_short short of / tol_past past the square's centre and within tol_across beside it."""
|
| 105 |
+
along, across = float(p[0] - self.target[0]), float(p[1] - self.target[1])
|
| 106 |
+
if abs(p[2] - (envs.TABLE_Z + CUBE_HALF)) > ON_TABLE:
|
| 107 |
+
return along, across, "off"
|
| 108 |
+
short, past, beside = self.tol
|
| 109 |
+
if -short <= along <= past and abs(across) <= beside:
|
| 110 |
+
return along, across, "in"
|
| 111 |
+
if along > past:
|
| 112 |
+
return along, across, "past"
|
| 113 |
+
if along < -short:
|
| 114 |
+
return along, across, "short"
|
| 115 |
+
return along, across, "beside"
|
| 116 |
+
|
| 117 |
+
# ------------------------------------------------------------ per substep
|
| 118 |
+
def substep(self):
|
| 119 |
+
d = self.env.sim.data
|
| 120 |
+
n = d.ncon
|
| 121 |
+
touch = False
|
| 122 |
+
if n:
|
| 123 |
+
g1 = np.asarray(d.contact.geom1)[:n]
|
| 124 |
+
g2 = np.asarray(d.contact.geom2)[:n]
|
| 125 |
+
touch = bool(np.any((self.is_robot[g1] & self.is_cube[g2]) | (self.is_robot[g2] & self.is_cube[g1])))
|
| 126 |
+
self.n_sub += 1
|
| 127 |
+
p = self.pos()
|
| 128 |
+
rest = self.at_rest()
|
| 129 |
+
self.quiet = self.quiet + 1 if rest else 0
|
| 130 |
+
if touch:
|
| 131 |
+
if self.ep is None:
|
| 132 |
+
if self.slide is not None:
|
| 133 |
+
self._end_slide(p, interrupted=not rest)
|
| 134 |
+
self.ep = dict(start=p, sub0=self.n_sub)
|
| 135 |
+
self.ep["last"] = p
|
| 136 |
+
self.ep["sub1"] = self.n_sub
|
| 137 |
+
self.gap = 0
|
| 138 |
+
elif self.ep is not None:
|
| 139 |
+
self.gap += 1
|
| 140 |
+
if self.gap >= EP_GAP:
|
| 141 |
+
self._close(p, rest)
|
| 142 |
+
if self.ep is None and self.slide is not None and self.quiet >= REST_SUB:
|
| 143 |
+
self._end_slide(p, interrupted=False)
|
| 144 |
+
|
| 145 |
+
def _close(self, p, rest):
|
| 146 |
+
ep, self.ep = self.ep, None
|
| 147 |
+
if np.linalg.norm(p - ep["start"]) < TOUCH_MOVE and rest:
|
| 148 |
+
return # touched a resting cube and left it where it was
|
| 149 |
+
self.release = ep["last"][:2].copy()
|
| 150 |
+
self.moves.append(dict(sub0=ep["sub0"], sub1=ep["sub1"], start=ep["start"].round(4).tolist(),
|
| 151 |
+
release=ep["last"].round(4).tolist()))
|
| 152 |
+
self.slide = dict(start=ep["start"], release=ep["last"], sub=ep["sub1"])
|
| 153 |
+
|
| 154 |
+
def _end_slide(self, p, interrupted):
|
| 155 |
+
s, self.slide = self.slide, None
|
| 156 |
+
free = float(np.linalg.norm(p[:2] - s["release"][:2]))
|
| 157 |
+
if free < STRIKE_MIN:
|
| 158 |
+
return # a push or a put-down, not a strike
|
| 159 |
+
along, across, res = self.judge(p)
|
| 160 |
+
self.strikes.append(dict(sub=int(s["sub"]), start=s["start"].round(4).tolist(),
|
| 161 |
+
release=s["release"].round(4).tolist(), rest=p.round(4).tolist(),
|
| 162 |
+
pushed_cm=round(100 * float(np.linalg.norm(s["release"][:2] - s["start"][:2])), 2),
|
| 163 |
+
free_slide_cm=round(100 * free, 2), along_err_cm=round(100 * along, 2),
|
| 164 |
+
across_err_cm=round(100 * across, 2),
|
| 165 |
+
result="interrupted" if interrupted else res,
|
| 166 |
+
missed=bool(not interrupted and res != "in")))
|
| 167 |
+
|
| 168 |
+
def flush(self):
|
| 169 |
+
"""End of attempt: settle the bookkeeping. Returns True if the robot is touching the cube now and that contact
|
| 170 |
+
has moved it (then the cube's current free slide is 0)."""
|
| 171 |
+
p = self.pos()
|
| 172 |
+
if self.ep is not None:
|
| 173 |
+
if np.linalg.norm(p - self.ep["start"]) >= TOUCH_MOVE or not self.at_rest():
|
| 174 |
+
self.release = p[:2].copy()
|
| 175 |
+
self.slide = None
|
| 176 |
+
return True
|
| 177 |
+
return False
|
| 178 |
+
if self.slide is not None and self.at_rest():
|
| 179 |
+
self._end_slide(p, interrupted=False)
|
| 180 |
+
return False
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def _install_watch(sim, watch):
|
| 184 |
+
"""Call watch.substep() after every MuJoCo step of this sim (one wrapper per sim, like agent/tools.ContactTracker;
|
| 185 |
+
it only reads the state). A fast strike touches the cube for 3-16 substeps (6-32 ms, measured), less than one
|
| 186 |
+
control step, so contact checks at control steps alone would miss it."""
|
| 187 |
+
if not getattr(sim, "_lff_slide_wrapped", False):
|
| 188 |
+
orig = sim.step
|
| 189 |
+
|
| 190 |
+
def step(*a, **k):
|
| 191 |
+
orig(*a, **k)
|
| 192 |
+
w = getattr(sim, "_lff_slide_watch", None)
|
| 193 |
+
if w is not None:
|
| 194 |
+
w.substep()
|
| 195 |
+
sim.step = step
|
| 196 |
+
sim._lff_slide_wrapped = True
|
| 197 |
+
sim._lff_slide_watch = watch
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class SlideSkills(Skills):
|
| 201 |
+
"""Skills whose motion commands return only once the cube has come to rest (see the module docstring)."""
|
| 202 |
+
|
| 203 |
+
def __init__(self, env, bias=None, recorder=None):
|
| 204 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 205 |
+
self._qa, self._da = envs.free_joint_addr(env, CUBE)
|
| 206 |
+
self.waits = [] # (control step, steps waited) for every command that had to wait
|
| 207 |
+
|
| 208 |
+
def cube_moving(self):
|
| 209 |
+
qv = self.env.sim.data.qvel[self._da:self._da + 6]
|
| 210 |
+
return bool(np.linalg.norm(qv[:3]) >= V_REST or np.linalg.norm(qv[3:]) >= W_REST)
|
| 211 |
+
|
| 212 |
+
def wait_cube_rest(self):
|
| 213 |
+
"""Hold the arm where it is until the cube is at rest (two control steps in a row) or WAIT_MAX steps passed.
|
| 214 |
+
No wait if the cube is already at rest or is held (it then moves with the arm)."""
|
| 215 |
+
if not self.cube_moving() or self.holding(CUBE):
|
| 216 |
+
return 0
|
| 217 |
+
p, R = self.eef_pos(), self._R()
|
| 218 |
+
quiet = 0
|
| 219 |
+
for k in range(WAIT_MAX):
|
| 220 |
+
self._act(p - self.eef_pos(), _rot_err(R, self.eef_mat()), self.grip)
|
| 221 |
+
quiet = 0 if self.cube_moving() else quiet + 1
|
| 222 |
+
if quiet >= 2:
|
| 223 |
+
break
|
| 224 |
+
self.waits.append((self.n_steps, k + 1))
|
| 225 |
+
return k + 1
|
| 226 |
+
|
| 227 |
+
def move_to(self, target, *args, **kwargs):
|
| 228 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 229 |
+
n = self.wait_cube_rest()
|
| 230 |
+
if n:
|
| 231 |
+
rep["waited_s"] = round(n * DT, 2)
|
| 232 |
+
return rep
|
| 233 |
+
|
| 234 |
+
def set_gripper(self, close, steps=15):
|
| 235 |
+
rep = super().set_gripper(close, steps)
|
| 236 |
+
n = self.wait_cube_rest()
|
| 237 |
+
if n:
|
| 238 |
+
rep["waited_s"] = round(n * DT, 2)
|
| 239 |
+
return rep
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
INNER_HALF = 0.03 # 6 cm square target (inner edge of the outline): near side and sides, the cube's centre within 1 cm
|
| 243 |
+
LINE_W = 0.006
|
| 244 |
+
# Far side (away from the robot, facing the agentview camera): the cube may lie on the far line. Instruction: no part of
|
| 245 |
+
# it beyond the line's outer edge (centre <= INNER_HALF + LINE_W - CUBE_HALF = 1.6 cm past the centre); judged: centre
|
| 246 |
+
# <= 2.0 cm past it, i.e. the front face up to 4 mm beyond the line, which in the 512 x 512 agentview is < 2 px of red
|
| 247 |
+
# beyond the line (from 2.0 cm on >= 2 px on all 25 measured instances, task card 2026-10-19).
|
| 248 |
+
TOL_PAST = 0.020
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def square_frame_xml(model_name, inner_half=INNER_HALF, line_w=LINE_W,
|
| 252 |
+
line_rgba=(0.1, 0.55, 0.15, 1.0), fill_rgba=(0.75, 0.92, 0.75, 1.0)):
|
| 253 |
+
"""Flat, visual-only square drawn on the table: a light fill plus a dark outline (no collisions)."""
|
| 254 |
+
o = inner_half + line_w
|
| 255 |
+
parts = [((0, 0, 0.0004), (o, o, 0.0004), fill_rgba),
|
| 256 |
+
((0, inner_half + line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba),
|
| 257 |
+
((0, -inner_half - line_w / 2, 0.0010), (o, line_w / 2, 0.0002), line_rgba),
|
| 258 |
+
((inner_half + line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba),
|
| 259 |
+
((-inner_half - line_w / 2, 0, 0.0010), (line_w / 2, o, 0.0002), line_rgba)]
|
| 260 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 261 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 262 |
+
return _wrap(model_name, g, 0.0012, o)
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
Z_PUSH = envs.TABLE_Z + 0.02
|
| 266 |
+
V_MIN, V_MAX = 0.12, 0.60
|
| 267 |
+
Z_GRASP = envs.TABLE_Z + CUBE_HALF # grasp point at the cube's centre height (fingertips ~1 cm above the table)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
@register_task
|
| 271 |
+
class SlideToTarget(LFFTask):
|
| 272 |
+
name = "l5_slide_to_target"
|
| 273 |
+
level = "L5"
|
| 274 |
+
category = "dynamics_adaptation"
|
| 275 |
+
capabilities = ("Reason", "Utilize")
|
| 276 |
+
# no parentheses or semicolons: the instruction is also the BDDL :language string (';' starts a comment there)
|
| 277 |
+
instruction = ("Push the red cube straight away from the robot so that it slides and comes to rest in the green "
|
| 278 |
+
"square marked on the table. On the side of the square nearest the robot and on its left and "
|
| 279 |
+
"right, no part of the cube may lie on or beyond the green border line. On the far side, away from "
|
| 280 |
+
"the robot, the cube may lie on the border line, but no part of it may stick out beyond that line. "
|
| 281 |
+
"The cube must slide the last part of the way on its own: after it leaves the gripper it has to "
|
| 282 |
+
f"slide at least {100 * D_MIN:.0f} cm, with nothing touching it, before it comes to rest in the "
|
| 283 |
+
"square.")
|
| 284 |
+
instruction_indirect = instruction
|
| 285 |
+
tol_along = INNER_HALF - CUBE_HALF # short of the centre (near side): completely inside the square (1.0 cm)
|
| 286 |
+
tol_past = TOL_PAST # past the centre (far side): may lie on the far line (2.0 cm, see TOL_PAST)
|
| 287 |
+
runup = 0.22 # long run-up so the gripper reaches the commanded speed before contact
|
| 288 |
+
tol_across = INNER_HALF - CUBE_HALF
|
| 289 |
+
|
| 290 |
+
def make_bddl(self):
|
| 291 |
+
cube = register_generated("LffRedCube", box_xml("lff_red_cube", (CUBE_HALF,) * 3, (0.85, 0.15, 0.15, 1),
|
| 292 |
+
density=1000))
|
| 293 |
+
# static fixture (no joint): a free body without collisions would fall through the table
|
| 294 |
+
zone = register_generated("LffTargetSquare", square_frame_xml("lff_target_square"), free=False)
|
| 295 |
+
objs = [("cube_1", cube, "cube_region", (-0.21, -0.01, -0.19, 0.01))]
|
| 296 |
+
fixtures = [("zone_1", zone, "zone_region", (-0.11, -0.01, -0.09, 0.01))]
|
| 297 |
+
return write_bddl(self.name, self.instruction, objs, fixtures=fixtures)
|
| 298 |
+
|
| 299 |
+
def apply_instance(self, inst):
|
| 300 |
+
m = self.env.sim.model
|
| 301 |
+
zone = self.env.fixtures_dict["zone_1"]
|
| 302 |
+
# the target zone is a flat marker: no collisions
|
| 303 |
+
for g in range(m.ngeom):
|
| 304 |
+
if (m.geom_id2name(g) or "").startswith("zone_1_"):
|
| 305 |
+
m.geom_contype[g] = 0
|
| 306 |
+
m.geom_conaffinity[g] = 0
|
| 307 |
+
x0, y0 = inst["cube_xy"]
|
| 308 |
+
envs.set_obj_pose(self.env, "cube_1", [x0, y0, envs.TABLE_Z + CUBE_HALF + 0.001])
|
| 309 |
+
bid = m.body_name2id(zone.root_body)
|
| 310 |
+
m.body_pos[bid] = [x0 + inst["target_dist"], y0, envs.TABLE_Z + 0.0002]
|
| 311 |
+
m.body_quat[bid] = [1.0, 0.0, 0.0, 0.0]
|
| 312 |
+
envs.set_friction(self.env, "cube_1", inst["mu"])
|
| 313 |
+
|
| 314 |
+
def reset_instance(self, inst, recorder=None):
|
| 315 |
+
self.env.reset()
|
| 316 |
+
self.apply_instance(inst)
|
| 317 |
+
self.env.sim.forward()
|
| 318 |
+
envs.settle(self.env, 10)
|
| 319 |
+
x0, y0 = inst["cube_xy"]
|
| 320 |
+
self.watch = CubeWatch(self.env, (x0 + inst["target_dist"], y0), self.tol_along, self.tol_past,
|
| 321 |
+
self.tol_across)
|
| 322 |
+
_install_watch(self.env.sim, self.watch)
|
| 323 |
+
self.sk = SlideSkills(self.env, recorder=recorder)
|
| 324 |
+
return self.sk
|
| 325 |
+
|
| 326 |
+
@staticmethod
|
| 327 |
+
def max_reach(mu):
|
| 328 |
+
"""Approximate slide distance at the top speed, fitted to a sweep (runup 0.22 m):
|
| 329 |
+
mu 0.04 -> 20.8 cm, 0.06 -> 14.8, 0.08 -> 11.8, 0.10 -> 10.1 cm."""
|
| 330 |
+
return 0.0103 / mu ** 0.95
|
| 331 |
+
|
| 332 |
+
def sample_instance(self, seed):
|
| 333 |
+
rng = np.random.default_rng(seed)
|
| 334 |
+
while True: # reject instances the top speed cannot reach (keeps every instance solvable)
|
| 335 |
+
inst = dict(seed=int(seed),
|
| 336 |
+
cube_xy=[float(rng.uniform(-0.23, -0.17)), float(rng.uniform(-0.10, 0.10))],
|
| 337 |
+
target_dist=float(rng.uniform(0.05, 0.12)),
|
| 338 |
+
mu=float(np.exp(rng.uniform(np.log(0.035), np.log(0.10)))))
|
| 339 |
+
if inst["target_dist"] <= 0.85 * self.max_reach(inst["mu"]):
|
| 340 |
+
return inst
|
| 341 |
+
|
| 342 |
+
# ------------------------------------------------------------ outcome
|
| 343 |
+
def outcome(self, inst):
|
| 344 |
+
envs.settle(self.env, 40)
|
| 345 |
+
w = self.watch
|
| 346 |
+
for _ in range(12): # still moving (e.g. a budget ended the attempt mid-slide): let it come to rest
|
| 347 |
+
if w.at_rest():
|
| 348 |
+
break
|
| 349 |
+
envs.settle(self.env, 5)
|
| 350 |
+
touching = w.flush()
|
| 351 |
+
x0, y0 = inst["cube_xy"]
|
| 352 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 353 |
+
along = (c[0] - x0) - inst["target_dist"]
|
| 354 |
+
across = c[1] - y0
|
| 355 |
+
_, _, where = w.judge(w.pos())
|
| 356 |
+
inside = where == "in"
|
| 357 |
+
at_rest = w.at_rest()
|
| 358 |
+
free = float(np.linalg.norm(c[:2] - w.release)) if w.release is not None else 0.0
|
| 359 |
+
slid = bool(w.release is not None and not touching and free >= D_MIN)
|
| 360 |
+
success = bool(inside and at_rest and slid)
|
| 361 |
+
strikes = w.strikes
|
| 362 |
+
n_missed = sum(s["missed"] for s in strikes)
|
| 363 |
+
from ..agent.tools import WS_HI, WS_LO
|
| 364 |
+
reach = bool(np.all(c[:2] >= WS_LO[:2] + REACH_MARGIN) and np.all(c[:2] <= WS_HI[:2] - REACH_MARGIN))
|
| 365 |
+
irrecoverable = bool(c[2] < OFF_TABLE_Z or not reach)
|
| 366 |
+
|
| 367 |
+
parts = []
|
| 368 |
+
if w.release is None and np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < STRIKE_MIN:
|
| 369 |
+
parts.append("The cube was not pushed.")
|
| 370 |
+
if c[2] < OFF_TABLE_Z:
|
| 371 |
+
parts.append("The cube fell off the table.")
|
| 372 |
+
else:
|
| 373 |
+
state = {"in": "in the square", "past": "it sticks out beyond the far green line",
|
| 374 |
+
"short": "it sticks out past the edge of the square nearest the robot"}.get(where,
|
| 375 |
+
"not in the square")
|
| 376 |
+
if along > 0:
|
| 377 |
+
parts.append(f"The cube stopped {100 * along:.1f} cm past the centre of the green square ({state}).")
|
| 378 |
+
else:
|
| 379 |
+
parts.append(f"The cube stopped {100 * -along:.1f} cm short of the centre of the green square "
|
| 380 |
+
f"({state}).")
|
| 381 |
+
if abs(across) > self.tol_across:
|
| 382 |
+
parts.append(f"It also drifted {100 * abs(across):.1f} cm to the {'left' if across > 0 else 'right'} "
|
| 383 |
+
f"(robot's view).")
|
| 384 |
+
if where == "off" and c[2] > OFF_TABLE_Z:
|
| 385 |
+
parts.append("It is not resting on the table.")
|
| 386 |
+
if inside and not at_rest:
|
| 387 |
+
parts.append("It was still moving when the attempt ended.")
|
| 388 |
+
if touching:
|
| 389 |
+
parts.append("The gripper was still touching (or holding) the cube when the attempt ended.")
|
| 390 |
+
elif inside and w.release is not None and free < D_MIN:
|
| 391 |
+
parts.append(f"After it last left the gripper it slid only {100 * free:.1f} cm on its own; it has to slide "
|
| 392 |
+
f"at least {100 * D_MIN:.0f} cm.")
|
| 393 |
+
if success:
|
| 394 |
+
failure = None
|
| 395 |
+
elif w.release is None and not inside:
|
| 396 |
+
failure = "not_touched"
|
| 397 |
+
elif not inside:
|
| 398 |
+
failure = "position"
|
| 399 |
+
elif not at_rest:
|
| 400 |
+
failure = "not_at_rest"
|
| 401 |
+
else:
|
| 402 |
+
failure = "slide_too_short"
|
| 403 |
+
out = dict(success=success, along_err=float(along), across_err=float(across), detail=" ".join(parts),
|
| 404 |
+
inside=inside, at_rest=at_rest, free_slide_cm=round(100 * free, 2),
|
| 405 |
+
release_xy=None if w.release is None else w.release.round(4).tolist(),
|
| 406 |
+
touching_at_end=bool(touching), n_moves=len(w.moves), n_strikes=len(strikes),
|
| 407 |
+
n_missed_strikes=int(n_missed), trap_fired=n_missed > 0,
|
| 408 |
+
recovered_in_attempt=bool(n_missed and success), irrecoverable=irrecoverable,
|
| 409 |
+
strikes=strikes, waits=len(getattr(self.sk, "waits", [])), failure=failure)
|
| 410 |
+
return out
|
| 411 |
+
|
| 412 |
+
# ------------------------------------------------------------ execution
|
| 413 |
+
def execute(self, inst, params):
|
| 414 |
+
"""One straight strike from the cube's initial position: closed gripper, 22 cm run-up, stop 1.5 cm past the
|
| 415 |
+
point of contact, lift (the move returns once the cube has come to rest)."""
|
| 416 |
+
x0, y0 = inst["cube_xy"]
|
| 417 |
+
sk = self.sk
|
| 418 |
+
sk.set_gripper(True, steps=5)
|
| 419 |
+
sk.move_to([x0 - self.runup, y0, Z_PUSH + 0.10], yaw=0.0)
|
| 420 |
+
sk.move_to([x0 - self.runup, y0, Z_PUSH], tol=0.003)
|
| 421 |
+
sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH], speed=float(np.clip(params["speed"], V_MIN, V_MAX)),
|
| 422 |
+
tol=0.01, max_steps=80)
|
| 423 |
+
sk.move_to([x0 - CUBE_HALF + 0.015, y0, Z_PUSH + 0.08], speed=0.3)
|
| 424 |
+
|
| 425 |
+
def default_params(self, inst):
|
| 426 |
+
return dict(speed=0.30)
|
| 427 |
+
|
| 428 |
+
def blind_params(self, inst, attempt, rng):
|
| 429 |
+
return dict(speed=float(np.clip(0.30 + rng.normal(0, 0.05), V_MIN, V_MAX)))
|
| 430 |
+
|
| 431 |
+
def adapt_params(self, inst, history):
|
| 432 |
+
"""Cross-attempt learner (one strike per attempt; used by the scripted agent backend): bracketing secant search
|
| 433 |
+
on speed using the signed stopping error. validate.py's adaptive policy is run_scripted (within the attempt)."""
|
| 434 |
+
pts = sorted((h["params"]["speed"], h["outcome"]["along_err"]) for h in history)
|
| 435 |
+
lo = [p for p in pts if p[1] < 0]
|
| 436 |
+
hi = [p for p in pts if p[1] > 0]
|
| 437 |
+
if lo and hi:
|
| 438 |
+
(v0, e0), (v1, e1) = max(lo, key=lambda p: p[0]), min(hi, key=lambda p: p[0])
|
| 439 |
+
v = v0 + (v1 - v0) * (-e0) / (e1 - e0)
|
| 440 |
+
elif hi: # always overshooting: slow down
|
| 441 |
+
v = min(p[0] for p in hi) * 0.7
|
| 442 |
+
else: # always short: speed up
|
| 443 |
+
v = max(p[0] for p in lo) * 1.35
|
| 444 |
+
return dict(speed=float(np.clip(v, V_MIN, V_MAX)))
|
| 445 |
+
|
| 446 |
+
def oracle_params(self, inst):
|
| 447 |
+
"""Privileged: bisection on speed by simulating pushes (uses the true mu)."""
|
| 448 |
+
if "_oracle_speed" in inst:
|
| 449 |
+
return dict(speed=inst["_oracle_speed"])
|
| 450 |
+
lo, hi = V_MIN, V_MAX
|
| 451 |
+
best = None
|
| 452 |
+
for _ in range(9):
|
| 453 |
+
mid = 0.5 * (lo + hi)
|
| 454 |
+
self.reset_instance(inst)
|
| 455 |
+
self.execute(inst, dict(speed=mid))
|
| 456 |
+
e = self.outcome(inst)["along_err"]
|
| 457 |
+
if best is None or abs(e) < abs(best[1]):
|
| 458 |
+
best = (mid, e)
|
| 459 |
+
if e > 0:
|
| 460 |
+
hi = mid
|
| 461 |
+
else:
|
| 462 |
+
lo = mid
|
| 463 |
+
inst["_oracle_speed"] = best[0]
|
| 464 |
+
self.reset_instance(inst)
|
| 465 |
+
return dict(speed=best[0])
|
| 466 |
+
|
| 467 |
+
# ------------------------------------------------------------ scripted within-attempt correction
|
| 468 |
+
AGENT_CMDS = 40 # robot_server default per-attempt budget (no agent_max_steps here): 40 commands ...
|
| 469 |
+
AGENT_SIM_S = 3.0 * AGENT_CMDS # ... and 3 s of simulated motion per command
|
| 470 |
+
RESTRIKE_MARGIN = 0.02 # strike again from where the cube stopped only if it is >= D_MIN + this short
|
| 471 |
+
|
| 472 |
+
def _strike_here(self, speed):
|
| 473 |
+
"""Strike the cube where it lies (perfect perception), straight towards +x. 4 agent commands: above the run-up
|
| 474 |
+
point + close, down, strike (returns at rest), lift."""
|
| 475 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 476 |
+
sk = self.sk
|
| 477 |
+
sk.move_to([c[0] - self.runup, c[1], Z_PUSH + 0.10], yaw=0.0)
|
| 478 |
+
sk.set_gripper(True, steps=5)
|
| 479 |
+
sk.move_to([c[0] - self.runup, c[1], Z_PUSH], tol=0.003)
|
| 480 |
+
sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH], speed=float(np.clip(speed, V_MIN, V_MAX)), tol=0.01,
|
| 481 |
+
max_steps=80)
|
| 482 |
+
sk.move_to([c[0] - CUBE_HALF + 0.015, c[1], Z_PUSH + 0.08], speed=0.3)
|
| 483 |
+
return 4
|
| 484 |
+
|
| 485 |
+
def _carry_back(self, inst):
|
| 486 |
+
"""Grasp the cube from above, carry it back to its initial position and put it down. 6 agent commands:
|
| 487 |
+
above it + open, down + close, lift, carry, down + open, lift."""
|
| 488 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 489 |
+
x0, y0 = inst["cube_xy"]
|
| 490 |
+
sk = self.sk
|
| 491 |
+
sk.move_to([c[0], c[1], Z_GRASP + 0.10], yaw=0.0)
|
| 492 |
+
sk.set_gripper(False, steps=10)
|
| 493 |
+
sk.move_to([c[0], c[1], Z_GRASP], tol=0.003)
|
| 494 |
+
sk.set_gripper(True, steps=15)
|
| 495 |
+
sk.move_to([c[0], c[1], Z_GRASP + 0.06])
|
| 496 |
+
sk.move_to([x0, y0, Z_GRASP + 0.06])
|
| 497 |
+
sk.move_to([x0, y0, Z_GRASP + 0.003], tol=0.003)
|
| 498 |
+
sk.set_gripper(False, steps=12)
|
| 499 |
+
sk.move_to([x0, y0, Z_GRASP + 0.10])
|
| 500 |
+
return 6
|
| 501 |
+
|
| 502 |
+
@staticmethod
|
| 503 |
+
def _plan_speed(want, pts):
|
| 504 |
+
"""Speed for a slide of `want` m from strikes seen so far, pts = [(speed, slide)]: none -> the 0.30 m/s
|
| 505 |
+
prior; one -> slide ~ speed^2 through it; several -> log-log interpolation between the bracketing strikes
|
| 506 |
+
(or extrapolation from the two nearest, exponent clipped to [0.5, 3])."""
|
| 507 |
+
pts = sorted((v, d) for v, d in pts if d > 0.002)
|
| 508 |
+
if not pts:
|
| 509 |
+
return 0.30
|
| 510 |
+
if len(pts) == 1:
|
| 511 |
+
v, d = pts[0]
|
| 512 |
+
return float(np.clip(v * (want / d) ** 0.5, V_MIN, V_MAX))
|
| 513 |
+
lo = [p for p in pts if p[1] <= want]
|
| 514 |
+
hi = [p for p in pts if p[1] > want]
|
| 515 |
+
if lo and hi:
|
| 516 |
+
(v0, d0), (v1, d1) = max(lo, key=lambda p: p[1]), min(hi, key=lambda p: p[1])
|
| 517 |
+
else:
|
| 518 |
+
(v0, d0), (v1, d1) = sorted(pts, key=lambda p: abs(np.log(p[1] / want)))[:2]
|
| 519 |
+
if abs(np.log(d1 / d0)) < 1e-6 or abs(np.log(v1 / v0)) < 1e-6:
|
| 520 |
+
return float(np.clip(v0 * (want / d0) ** 0.5, V_MIN, V_MAX))
|
| 521 |
+
k = float(np.clip(np.log(d1 / d0) / np.log(v1 / v0), 0.5, 3.0))
|
| 522 |
+
return float(np.clip(v0 * (want / d0) ** (1.0 / k), V_MIN, V_MAX))
|
| 523 |
+
|
| 524 |
+
def _adaptive_attempt(self, inst, pts):
|
| 525 |
+
"""One attempt of the scripted within-attempt learner: strike; look where the cube stopped (perfect
|
| 526 |
+
perception, as on the images); if short by >= D_MIN + 2 cm strike again from there, otherwise (overshot,
|
| 527 |
+
a little short, or drifted sideways) carry it back to its initial position and strike again, with the speed
|
| 528 |
+
planned from every strike seen so far (`pts`, also from earlier attempts). Stops when the cube is in the square
|
| 529 |
+
or the next correction would not fit in the agent's command / motion budget."""
|
| 530 |
+
x0, y0 = inst["cube_xy"]
|
| 531 |
+
tx = x0 + inst["target_dist"]
|
| 532 |
+
sk = self.sk
|
| 533 |
+
n0 = sk.n_steps
|
| 534 |
+
n_cmd, speeds, path = 0, [], []
|
| 535 |
+
while True:
|
| 536 |
+
c = envs.obj_pos(self.env, CUBE)
|
| 537 |
+
want = tx - c[0]
|
| 538 |
+
near_start = np.linalg.norm(c[:2] - np.asarray(inst["cube_xy"])) < 0.01
|
| 539 |
+
local = [(v, d) for v, d, s in pts if s == near_start] or [(v, d) for v, d, _ in pts]
|
| 540 |
+
speed = self._plan_speed(want, local)
|
| 541 |
+
n_cmd += self._strike_here(speed)
|
| 542 |
+
c1 = envs.obj_pos(self.env, CUBE)
|
| 543 |
+
pts.append((speed, float(c1[0] - c[0]), near_start))
|
| 544 |
+
speeds.append(round(speed, 4))
|
| 545 |
+
err, across = float(c1[0] - tx), float(c1[1] - y0)
|
| 546 |
+
path.append("strike")
|
| 547 |
+
if -self.tol_along <= err <= self.tol_past and abs(across) <= self.tol_across:
|
| 548 |
+
break
|
| 549 |
+
used_s = (sk.n_steps - n0) * DT
|
| 550 |
+
if err < 0 and -err >= D_MIN + self.RESTRIKE_MARGIN and abs(across) < 0.005:
|
| 551 |
+
if n_cmd + 4 > self.AGENT_CMDS or used_s + 12.0 > self.AGENT_SIM_S:
|
| 552 |
+
break
|
| 553 |
+
continue
|
| 554 |
+
if n_cmd + 10 > self.AGENT_CMDS or used_s + 30.0 > self.AGENT_SIM_S:
|
| 555 |
+
break
|
| 556 |
+
n_cmd += self._carry_back(inst)
|
| 557 |
+
path.append("carry_back")
|
| 558 |
+
return dict(speed=speeds[0], speeds=speeds, path=path, n_commands=n_cmd,
|
| 559 |
+
sim_s=round((sk.n_steps - n0) * DT, 1))
|
| 560 |
+
|
| 561 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 562 |
+
"""oracle / naive / blind: one strike per attempt (LFFTask.run_scripted, cross protocol). adaptive: corrects
|
| 563 |
+
within the attempt (_adaptive_attempt) and carries what it saw into the next attempt."""
|
| 564 |
+
if kind != "adaptive":
|
| 565 |
+
return super().run_scripted(kind, inst, k=k, seed=seed, on_attempt=on_attempt)
|
| 566 |
+
k = k or self.max_attempts
|
| 567 |
+
history, pts = [], []
|
| 568 |
+
for a in range(k):
|
| 569 |
+
self.reset_instance(inst)
|
| 570 |
+
params = self._adaptive_attempt(inst, pts)
|
| 571 |
+
out = self.outcome(inst)
|
| 572 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 573 |
+
if on_attempt:
|
| 574 |
+
on_attempt(a, params, out)
|
| 575 |
+
if out["success"]:
|
| 576 |
+
break
|
| 577 |
+
return history
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/lff/source_closure/lffbench/tasks/l7_offcenter_push.py
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""L7 offcenter_push: push a long box straight forward into a marked rectangle.
|
| 2 |
+
|
| 3 |
+
Category: failed_interaction_inference ("why did this contact not do what I expected?"). The code keeps level "L7";
|
| 4 |
+
the paper files the task under L5 (misjudged physics).
|
| 5 |
+
|
| 6 |
+
Hidden variable: the box's centre of mass is shifted along its long axis by e (|e| ~ U[4.5, 7.5] cm, either
|
| 7 |
+
side; implemented by moving the body's inertial frame, `body_ipos`). The box looks exactly the same for
|
| 8 |
+
every e (uniform colour, a symmetric tape stripe across its middle).
|
| 9 |
+
|
| 10 |
+
Why the prior fails: the natural push is at the middle of the box's back face. On a table the friction
|
| 11 |
+
resultant acts below the centre of mass, so a push whose line does not pass near it turns the box: the
|
| 12 |
+
heavy end lags behind. Measured (closed gripper at yaw 0, 8 cm/s, mu 0.5): pushing at the middle turns the
|
| 13 |
+
box 17 to 41 deg; the rectangle (box + 2 cm margin per side) only holds the box up to FIT_ANGLE = 10.9 deg
|
| 14 |
+
(exact geometry, box centred in the rectangle). Pushing within ~2 cm of the centre of mass gives a straight
|
| 15 |
+
translation (< 1 deg); 3 cm off gives 5-14 deg.
|
| 16 |
+
|
| 17 |
+
What must be learned from the failure: the turning direction tells which end is heavy (the end that
|
| 18 |
+
lagged), the amount tells roughly how far off the push was; push closer to the heavy end. F2 reports the box's
|
| 19 |
+
turn (direction and size, plus how far one end lags the other), where the box's centre ended relative to the
|
| 20 |
+
rectangle's centre, and where on the back face the gripper first touched it -- all relative measurements, never
|
| 21 |
+
absolute coordinates or e itself.
|
| 22 |
+
|
| 23 |
+
Pushes per attempt: not limited (2026-10-19, user). Until then the instruction allowed one push per attempt (one
|
| 24 |
+
move command that moves the box) and an attempt with more failed, so that the agent could not steer the box inside
|
| 25 |
+
an attempt; that moved trial and error that belongs inside an attempt to the next attempt. The attempt now succeeds
|
| 26 |
+
when the box ends completely inside the rectangle and upright, however many pushes it took (and every push was made
|
| 27 |
+
with the closed gripper, see below).
|
| 28 |
+
|
| 29 |
+
Error events (logged; they never end the attempt). A "push" is a move_to that moves the box > 1 cm or turns it
|
| 30 |
+
> 3 deg (unchanged definition). After every push the box is classified against the rectangle (`box_fit`):
|
| 31 |
+
over_turned (|yaw| > FIT_ANGLE: it fits at no position), overshot (a corner past the far edge), sideways (a corner
|
| 32 |
+
past a side edge), short (a corner still in front of the near edge, i.e. not pushed far enough yet), inside. A push
|
| 33 |
+
is `bad` when it leaves the box over_turned, overshot or sideways (or tipped over: upright cos < 0.5) -- not inside,
|
| 34 |
+
and not merely short of the rectangle (pushing straight on can fix "short", so pushing the box in in several steps is
|
| 35 |
+
not an error).
|
| 36 |
+
Outcome: n_pushes, n_bad_pushes, n_turned_pushes (bad pushes that left the box over_turned), n_trap_events (pushes
|
| 37 |
+
that took the box from a good state -- inside or short -- into a bad one, i.e. how often the trap fired anew),
|
| 38 |
+
trap_fired = n_bad_pushes > 0, recovered_in_attempt = trap_fired and success, first_push (record of the first push)
|
| 39 |
+
with first_push_yaw_deg and first_interaction_ok (the first push left the box inside, or short and not turned out).
|
| 40 |
+
irrecoverable: the box tipped over (upright cos < 0.5 after a move, < 0.95 after the final settle), fell off the
|
| 41 |
+
table, or went out of reach (its centre beyond world x = X_LOST, where the gripper can no longer be put down in front
|
| 42 |
+
of it at pushing height to push it back, or beyond |y| = Y_LOST); logged with the control step, the attempt goes on.
|
| 43 |
+
|
| 44 |
+
Closed gripper (2026-10-19): the instruction says "with the closed gripper", and a push made with the fingers open
|
| 45 |
+
(> OPEN_W apart when the move starts) now makes the attempt fail (failure "open_gripper" if the box is otherwise
|
| 46 |
+
inside). Reason, measured: open fingers touch the back face at two points ~8 cm apart, so ONE push at the middle of
|
| 47 |
+
the back face goes straight unless |e| > ~7 cm -- 22 of 25 instances (validation seeds 1000-1019, main 3000-3004)
|
| 48 |
+
succeeded that way without the centre of mass ever mattering. The box cannot be grasped, lifted or dragged by
|
| 49 |
+
pressing on its top (9 cm deep, the gripper opens 8 cm; measured), so no rule is needed for that.
|
| 50 |
+
|
| 51 |
+
Correction cost (measured 2026-10-19, task card): after the natural first push (middle, whole distance) the box is
|
| 52 |
+
turned 17-41 deg and lies across the rectangle. What repairs it: get in front of the leading (light) end and push it
|
| 53 |
+
back -- the box turns back with little translation -- then push the box in near the heavy end. The scripted
|
| 54 |
+
corrector (adaptive) did that in attempt 1 on 19 of 20 instances, 7-15 extra commands (median 7: 2 more pushes).
|
| 55 |
+
What does not: pushing the lagging end forward from behind turns the box back only slowly and carries it past the
|
| 56 |
+
rectangle (0 of 25 instances repaired that way; 11 ended out of reach). Near the reach limit the fingers ride up onto
|
| 57 |
+
the box instead of pushing it back. A cautious first push of 3 cm at the middle turns the box only 6.5-10.9 deg (below
|
| 58 |
+
FIT_ANGLE, so no error event) and shows the heavy end; probe + turn back + push in succeeded on 25 of 25 instances in
|
| 59 |
+
11 commands. So the task does not meet design rule R3 (a cost >= 10 commands for the common-sense first interaction);
|
| 60 |
+
its signal is clean success vs. in-attempt recovery (trap_fired / recovered_in_attempt) and first_push_yaw_deg.
|
| 61 |
+
"""
|
| 62 |
+
import numpy as np
|
| 63 |
+
|
| 64 |
+
from .. import envs
|
| 65 |
+
from ..bddl import write_bddl
|
| 66 |
+
from ..objects import _SOLID, _fmt, _wrap, register_generated
|
| 67 |
+
from ..skills import Skills
|
| 68 |
+
from ..task_base import LFFTask, register_task
|
| 69 |
+
|
| 70 |
+
BOX = "box_1"
|
| 71 |
+
HALF = np.array([0.045, 0.11, 0.02]) # 9 (x) x 22 (y, long axis) x 4 cm: too wide for the 8 cm gripper
|
| 72 |
+
MASS = 0.6
|
| 73 |
+
MU = 0.5
|
| 74 |
+
MARGIN = 0.02 # target rectangle = box footprint + 2 cm on every side
|
| 75 |
+
RECT_HALF = HALF[:2] + MARGIN
|
| 76 |
+
E_MIN, E_MAX = 0.045, 0.075
|
| 77 |
+
Z_PUSH = envs.TABLE_Z + 0.02 # grasp-point height during the push (finger tips ~1 cm above the table)
|
| 78 |
+
Z_SAFE = envs.TABLE_Z + 0.12 # travel height of the scripted corrector (8 cm above the box top)
|
| 79 |
+
PUSH_SPEED = 0.08
|
| 80 |
+
FINGER_AHEAD = 0.009 # the closed fingers' front face is ~0.9 cm ahead of the grasp point (measured, yaw 0)
|
| 81 |
+
RUNUP = 0.04
|
| 82 |
+
MOVE_TOL = 0.01 # a command "moved the box" if its centre moved this much ...
|
| 83 |
+
TURN_TOL = np.radians(3.0) # ... or it turned this much
|
| 84 |
+
TOUCH_TOL = 0.002 # the box "started to move" in a command once its centre moved this much
|
| 85 |
+
OPEN_W = 0.01 # finger opening above which a push counts as made with the gripper open (closed on nothing: 0.002 m)
|
| 86 |
+
TABLE_HALF = (0.5, 0.6) # LIBERO main_table top, centred at the world origin (table_collision geom)
|
| 87 |
+
# Reach at pushing height (grasp point 2 cm above the table, yaw 0; measured 2026-10-19): the gripper gets to world
|
| 88 |
+
# x = 0.10 within 1 cm for |y| <= 0.15; asked for more it stops at x ~ 0.13-0.17, sagging to the table. Pushing a box
|
| 89 |
+
# back from in front of it (measured, box not turned): still works with the box's centre at x = 0.125 (far face at
|
| 90 |
+
# 0.17); with the centre at 0.135 the fingers ride up onto the box or push it further away. A box turned 25 deg with
|
| 91 |
+
# its centre at 0.113 (far corner at 0.20) was still pushed back. So a box whose centre is past X_LOST counts as out of
|
| 92 |
+
# reach. The rectangle's far edge lies at world x = -0.055 ... 0.055.
|
| 93 |
+
X_LOST = 0.13
|
| 94 |
+
Y_LOST = 0.40
|
| 95 |
+
X_DOWN = 0.14 # farthest x at which the scripted corrector puts the gripper down in front of the box
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _fit_angle(half=HALF[:2], rect=RECT_HALF):
|
| 99 |
+
"""Largest |yaw| at which the box's footprint still fits inside the rectangle (box centred in it): the
|
| 100 |
+
rotated footprint's half extents are (a cos t + b sin t, a sin t + b cos t)."""
|
| 101 |
+
t = np.radians(np.arange(0.0, 90.0, 0.01))
|
| 102 |
+
ok = (half[0] * np.cos(t) + half[1] * np.sin(t) <= rect[0]) & (half[0] * np.sin(t) + half[1] * np.cos(t) <= rect[1])
|
| 103 |
+
return float(t[np.argmin(ok)] - np.radians(0.01)) if not ok.all() else np.pi / 2
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
FIT_ANGLE = _fit_angle() # 10.9 deg
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def long_box_xml(name, half=HALF, mass=MASS, rgba=(0.72, 0.53, 0.33, 1.0), tape_rgba=(0.88, 0.80, 0.62, 1.0)):
|
| 110 |
+
"""Solid box with an explicit inertial whose position is offset from the body origin at compile time, so
|
| 111 |
+
MuJoCo keeps the inertial frame separate (sameframe would otherwise ignore later changes of body_ipos)."""
|
| 112 |
+
I = mass / 12 * np.array([4 * (half[1] ** 2 + half[2] ** 2), 4 * (half[0] ** 2 + half[2] ** 2),
|
| 113 |
+
4 * (half[0] ** 2 + half[1] ** 2)])
|
| 114 |
+
tape = (half[0] + 0.0005, 0.012, 0.0006)
|
| 115 |
+
g = (f' <inertial pos="0 0.001 0" mass="{mass}" diaginertia="{_fmt(I)}" />\n'
|
| 116 |
+
f' <geom name="{name}_g0" type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" '
|
| 117 |
+
f'friction="1.0 0.005 0.0001" {_SOLID} group="0" />\n'
|
| 118 |
+
f' <geom type="box" size="{_fmt(half)}" rgba="{_fmt(rgba)}" conaffinity="0" contype="0" group="1" />\n'
|
| 119 |
+
f' <geom type="box" pos="0 0 {half[2]:.5f}" size="{_fmt(tape)}" rgba="{_fmt(tape_rgba)}" '
|
| 120 |
+
f'conaffinity="0" contype="0" group="1" />')
|
| 121 |
+
return _wrap(name, g, half[2], float(np.hypot(half[0], half[1])))
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def rect_frame_xml(name, inner_half=RECT_HALF, line_w=0.006, line_rgba=(0.1, 0.55, 0.15, 1.0),
|
| 125 |
+
fill_rgba=(0.75, 0.92, 0.75, 1.0)):
|
| 126 |
+
"""Flat, visual-only rectangle drawn on the table (light fill + dark outline, no collisions)."""
|
| 127 |
+
hx, hy = inner_half
|
| 128 |
+
ox, oy = hx + line_w, hy + line_w
|
| 129 |
+
parts = [((0, 0, 0.0004), (ox, oy, 0.0004), fill_rgba),
|
| 130 |
+
((0, hy + line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba),
|
| 131 |
+
((0, -hy - line_w / 2, 0.0010), (ox, line_w / 2, 0.0002), line_rgba),
|
| 132 |
+
((hx + line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba),
|
| 133 |
+
((-hx - line_w / 2, 0, 0.0010), (line_w / 2, oy, 0.0002), line_rgba)]
|
| 134 |
+
g = "\n".join(f' <geom type="box" pos="{_fmt(p)}" size="{_fmt(sz)}" rgba="{_fmt(c)}" '
|
| 135 |
+
f'contype="0" conaffinity="0" group="1" />' for p, sz, c in parts)
|
| 136 |
+
return _wrap(name, g, 0.0012, float(np.hypot(ox, oy)))
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def _yaw(quat_wxyz):
|
| 140 |
+
w, x, y, z = quat_wxyz
|
| 141 |
+
return float(np.arctan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z)))
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _rot(a):
|
| 145 |
+
return np.array([[np.cos(a), -np.sin(a)], [np.sin(a), np.cos(a)]])
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def _wrap_pi(a):
|
| 149 |
+
return float((a + np.pi) % (2 * np.pi) - np.pi)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def box_corners(p_xy, yaw):
|
| 153 |
+
R = _rot(yaw)
|
| 154 |
+
return np.array([np.asarray(p_xy[:2], float) + R @ np.array([sx * HALF[0], sy * HALF[1]])
|
| 155 |
+
for sx in (-1, 1) for sy in (-1, 1)])
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def box_fit(p_xy, yaw, t_xy):
|
| 159 |
+
"""The box's footprint against the (axis-aligned) target rectangle centred at t_xy. bad = it cannot get into the
|
| 160 |
+
rectangle by being pushed straight on: turned beyond FIT_ANGLE, a corner past the far edge, or past a side edge."""
|
| 161 |
+
c = box_corners(p_xy, yaw) - np.asarray(t_xy, float)[:2]
|
| 162 |
+
eps = 1e-6
|
| 163 |
+
inside = bool(np.all(np.abs(c[:, 0]) <= RECT_HALF[0] + eps) and np.all(np.abs(c[:, 1]) <= RECT_HALF[1] + eps))
|
| 164 |
+
yw = (yaw + np.pi / 2) % np.pi - np.pi / 2 # the footprint is symmetric under a half turn
|
| 165 |
+
over = bool(abs(yw) > FIT_ANGLE)
|
| 166 |
+
overshot = bool(np.any(c[:, 0] > RECT_HALF[0] + eps))
|
| 167 |
+
sideways = bool(np.any(np.abs(c[:, 1]) > RECT_HALF[1] + eps))
|
| 168 |
+
short = bool(np.any(c[:, 0] < -RECT_HALF[0] - eps))
|
| 169 |
+
return dict(inside=inside, over_turned=over, overshot=overshot, sideways=sideways, short=short,
|
| 170 |
+
bad=bool(over or overshot or sideways))
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _lr(v, unit="cm"):
|
| 174 |
+
return f"{100 * abs(v):.1f} {unit} to the {'left' if v > 0 else 'right'}"
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _fb(v):
|
| 178 |
+
return f"{100 * abs(v):.1f} cm {'forward' if v > 0 else 'backward'}"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _turn_words(deg):
|
| 182 |
+
return f"{abs(deg):.0f} degrees {'counterclockwise' if deg > 0 else 'clockwise'}"
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class _Budget(Exception):
|
| 186 |
+
"""the scripted policy used up the agent command budget of the attempt"""
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class PushSkills(Skills):
|
| 190 |
+
"""Skills that log, for whoever drives them (scripted policy or agent), which move_to commands moved the
|
| 191 |
+
box (pushes), where the gripper touched it, the box's state after every push, and whether the box was lost."""
|
| 192 |
+
|
| 193 |
+
def __init__(self, env, bias=None, recorder=None, target=None):
|
| 194 |
+
super().__init__(env, bias=bias, recorder=recorder)
|
| 195 |
+
self.target = None if target is None else np.asarray(target, float)[:2]
|
| 196 |
+
self.first_touch = None # where the gripper's centre was (box frame) when the box first moved
|
| 197 |
+
self._p0, self._yaw0 = self._box_pose()
|
| 198 |
+
self.box_moves = [] # one entry per move_to that moved / turned the box (a "push")
|
| 199 |
+
self.n_moves = 0 # move_to commands (an agent's move_eef with a motion = one move_to)
|
| 200 |
+
self.lost = {} # irrecoverable condition -> control step at which it was first seen
|
| 201 |
+
self._mv = None # the move_to in progress: box pose at its start, first touch inside it
|
| 202 |
+
|
| 203 |
+
def _box_pose(self):
|
| 204 |
+
p = envs.obj_pos(self.env, BOX)
|
| 205 |
+
return p, _yaw(envs.obj_quat(self.env, BOX))
|
| 206 |
+
|
| 207 |
+
def _local(self, p0, yaw0):
|
| 208 |
+
"""gripper centre in the box frame given by (p0, yaw0): (u along the short side, v along the long side)"""
|
| 209 |
+
return (_rot(yaw0).T @ (self.eef_pos()[:2] - p0[:2])).tolist()
|
| 210 |
+
|
| 211 |
+
def _act(self, dpos, drot, grip):
|
| 212 |
+
super()._act(dpos, drot, grip)
|
| 213 |
+
if self.first_touch is None or (self._mv is not None and self._mv["touch"] is None):
|
| 214 |
+
# "touch" = the first control step at which the box has moved 2 mm. Detected from the box's motion,
|
| 215 |
+
# not from contacts: a stiff gripper pushing a box makes a stick-slip contact that is often absent at the
|
| 216 |
+
# control-step boundaries (measured), so contact polling misses pushes.
|
| 217 |
+
p, _ = self._box_pose()
|
| 218 |
+
if self.first_touch is None and np.linalg.norm(p[:2] - self._p0[:2]) > TOUCH_TOL:
|
| 219 |
+
self.first_touch = dict(local=self._local(self._p0, self._yaw0), step=self.n_steps)
|
| 220 |
+
if self._mv is not None and self._mv["touch"] is None and np.linalg.norm(p[:2] - self._mv["p0"][:2]) > TOUCH_TOL:
|
| 221 |
+
self._mv["touch"] = self._local(self._mv["p0"], self._mv["yaw0"])
|
| 222 |
+
|
| 223 |
+
def fit(self, p=None, yaw=None):
|
| 224 |
+
if p is None:
|
| 225 |
+
p, yaw = self._box_pose()
|
| 226 |
+
return box_fit(p[:2], yaw, self.target) if self.target is not None else None
|
| 227 |
+
|
| 228 |
+
def check_lost(self, final=False):
|
| 229 |
+
"""record irrecoverable box states (tipped, off the table, out of reach); returns the current ones"""
|
| 230 |
+
p, _ = self._box_pose()
|
| 231 |
+
up = envs.obj_upright_cos(self.env, BOX)
|
| 232 |
+
now = []
|
| 233 |
+
if up < (0.95 if final else 0.5):
|
| 234 |
+
now.append("tipped")
|
| 235 |
+
if p[2] < envs.TABLE_Z - 0.02 or abs(p[0]) > TABLE_HALF[0] or abs(p[1]) > TABLE_HALF[1]:
|
| 236 |
+
now.append("off_table")
|
| 237 |
+
elif p[0] > X_LOST or abs(p[1]) > Y_LOST:
|
| 238 |
+
now.append("out_of_reach")
|
| 239 |
+
for w in now:
|
| 240 |
+
self.lost.setdefault(w, self.n_steps)
|
| 241 |
+
return now
|
| 242 |
+
|
| 243 |
+
def move_to(self, target, *args, **kwargs):
|
| 244 |
+
p0, y0 = self._box_pose()
|
| 245 |
+
fit0 = self.fit(p0, y0)
|
| 246 |
+
bad0 = fit0 is not None and (fit0["bad"] or envs.obj_upright_cos(self.env, BOX) < 0.5)
|
| 247 |
+
self._mv = dict(p0=p0, yaw0=y0, touch=None)
|
| 248 |
+
width0 = self.gripper_width()
|
| 249 |
+
self.n_moves += 1
|
| 250 |
+
try:
|
| 251 |
+
rep = super().move_to(target, *args, **kwargs)
|
| 252 |
+
finally:
|
| 253 |
+
mv, self._mv = self._mv, None
|
| 254 |
+
p1, y1 = self._box_pose()
|
| 255 |
+
dturn = _wrap_pi(y1 - y0)
|
| 256 |
+
if np.linalg.norm(p1[:2] - p0[:2]) > MOVE_TOL or abs(dturn) > TURN_TOL:
|
| 257 |
+
rec = dict(step=self.n_steps, moved_cm=round(100 * float(np.linalg.norm(p1[:2] - p0[:2])), 1),
|
| 258 |
+
turned_deg=round(float(np.degrees(dturn)), 1), yaw_deg=round(float(np.degrees(y1)), 1),
|
| 259 |
+
gripper_open=bool(width0 > OPEN_W))
|
| 260 |
+
t = mv["touch"]
|
| 261 |
+
if t is not None:
|
| 262 |
+
u, v = t
|
| 263 |
+
face = ("back" if u < -HALF[0] + 0.005 else "front" if u > HALF[0] - 0.005 else
|
| 264 |
+
"left_end" if v > 0 else "right_end")
|
| 265 |
+
rec.update(touch_u=round(float(u), 4), touch_v=round(float(v), 4), face=face)
|
| 266 |
+
fit1 = self.fit(p1, y1)
|
| 267 |
+
if fit1 is not None:
|
| 268 |
+
tipped = envs.obj_upright_cos(self.env, BOX) < 0.5
|
| 269 |
+
bad = bool(fit1["bad"] or tipped)
|
| 270 |
+
rec.update(inside=fit1["inside"] and not tipped, over_turned=fit1["over_turned"],
|
| 271 |
+
overshot=fit1["overshot"], sideways=fit1["sideways"], tipped=bool(tipped), bad=bad,
|
| 272 |
+
new_trap=bool(bad and not bad0))
|
| 273 |
+
self.box_moves.append(rec)
|
| 274 |
+
self.check_lost()
|
| 275 |
+
return rep
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@register_task
|
| 279 |
+
class OffcenterPush(LFFTask):
|
| 280 |
+
name = "l7_offcenter_push"
|
| 281 |
+
level = "L7"
|
| 282 |
+
category = "failed_interaction_inference"
|
| 283 |
+
capabilities = ("Perceive", "Reason", "Utilize")
|
| 284 |
+
protocol = "cross"
|
| 285 |
+
# 2026-10-19 (wording): the instruction states only the end state. "straight forward ... without turning" read as
|
| 286 |
+
# a rule on the motion (no turning on the way, push only forward), but success is judged on the end state alone
|
| 287 |
+
# (completely inside the rectangle -- which bounds the turn to FIT_ANGLE -- upright, every push with the closed
|
| 288 |
+
# gripper), and the repair that works pushes the leading end back from in front of the box.
|
| 289 |
+
instruction = ("Slowly push the long brown box with the closed gripper so that it ends up completely inside the "
|
| 290 |
+
"green rectangle ahead of it (farther from the robot).")
|
| 291 |
+
instruction_indirect = ("Slowly push the long cardboard-coloured block with the closed gripper so that it ends up "
|
| 292 |
+
"completely inside the marked green area ahead of it (farther from the robot).")
|
| 293 |
+
|
| 294 |
+
# ------------------------------------------------------------ scene
|
| 295 |
+
def make_bddl(self):
|
| 296 |
+
box = register_generated("LffL7LongBox", long_box_xml("lff_l7_long_box"))
|
| 297 |
+
zone = register_generated("LffL7TargetRect", rect_frame_xml("lff_l7_target_rect"), free=False)
|
| 298 |
+
objs = [(BOX, box, "box_region", (-0.18, -0.01, -0.16, 0.01))]
|
| 299 |
+
fixtures = [("zone_1", zone, "zone_region", (-0.06, -0.01, -0.04, 0.01))]
|
| 300 |
+
return write_bddl(self.name, "push the long box into the green rectangle", objs, fixtures=fixtures)
|
| 301 |
+
|
| 302 |
+
def sample_instance(self, seed):
|
| 303 |
+
rng = np.random.default_rng(seed)
|
| 304 |
+
e = float(rng.choice([-1.0, 1.0]) * rng.uniform(E_MIN, E_MAX))
|
| 305 |
+
return dict(seed=int(seed), box_xy=[float(rng.uniform(-0.20, -0.14)), float(rng.uniform(-0.08, 0.08))],
|
| 306 |
+
target_dist=float(rng.uniform(0.08, 0.13)), com_offset=e)
|
| 307 |
+
|
| 308 |
+
def target_xy(self, inst):
|
| 309 |
+
return np.array([inst["box_xy"][0] + inst["target_dist"], inst["box_xy"][1]])
|
| 310 |
+
|
| 311 |
+
def apply_instance(self, inst):
|
| 312 |
+
m = self.env.sim.model
|
| 313 |
+
zone = self.env.fixtures_dict["zone_1"]
|
| 314 |
+
for g in range(m.ngeom): # the rectangle is a flat marker
|
| 315 |
+
if (m.geom_id2name(g) or "").startswith("zone_1_"):
|
| 316 |
+
m.geom_contype[g] = 0
|
| 317 |
+
m.geom_conaffinity[g] = 0
|
| 318 |
+
t = self.target_xy(inst)
|
| 319 |
+
zb = m.body_name2id(zone.root_body)
|
| 320 |
+
m.body_pos[zb] = [t[0], t[1], envs.TABLE_Z + 0.0002]
|
| 321 |
+
m.body_quat[zb] = [1.0, 0.0, 0.0, 0.0]
|
| 322 |
+
bid = envs.body_id(self.env, BOX)
|
| 323 |
+
m.body_mass[bid] = MASS
|
| 324 |
+
m.body_ipos[bid] = [0.0, inst["com_offset"], 0.0]
|
| 325 |
+
envs.refit_bounds(self.env, bid) # the collision BVH lives in the inertial frame (envs.refit_bounds)
|
| 326 |
+
envs.set_friction(self.env, BOX, MU)
|
| 327 |
+
x0, y0 = inst["box_xy"]
|
| 328 |
+
envs.set_obj_pose(self.env, BOX, [x0, y0, envs.TABLE_Z + HALF[2] + 0.001])
|
| 329 |
+
|
| 330 |
+
def reset_instance(self, inst, recorder=None):
|
| 331 |
+
self.env.reset()
|
| 332 |
+
self.apply_instance(inst)
|
| 333 |
+
self.env.sim.forward()
|
| 334 |
+
envs.settle(self.env, 10)
|
| 335 |
+
self.sk = PushSkills(self.env, recorder=recorder, target=self.target_xy(inst))
|
| 336 |
+
self.sim0 = self.sk.n_steps
|
| 337 |
+
return self.sk
|
| 338 |
+
|
| 339 |
+
# ------------------------------------------------------------ outcome
|
| 340 |
+
def outcome(self, inst):
|
| 341 |
+
envs.settle(self.env, 30)
|
| 342 |
+
sk = self.sk
|
| 343 |
+
p = envs.obj_pos(self.env, BOX)
|
| 344 |
+
yaw = _yaw(envs.obj_quat(self.env, BOX))
|
| 345 |
+
t = self.target_xy(inst)
|
| 346 |
+
fit = box_fit(p[:2], yaw, t)
|
| 347 |
+
inside = fit["inside"]
|
| 348 |
+
upright = envs.obj_upright_cos(self.env, BOX) > 0.95
|
| 349 |
+
sk.check_lost(final=True)
|
| 350 |
+
pushes = sk.box_moves
|
| 351 |
+
n_push = len(pushes)
|
| 352 |
+
n_bad = sum(bool(m.get("bad")) for m in pushes)
|
| 353 |
+
n_open = sum(bool(m.get("gripper_open")) for m in pushes)
|
| 354 |
+
off = p[:2] - t
|
| 355 |
+
lag = 2 * HALF[1] * np.sin(yaw) # how far the +y end is behind (+) the -y end along x
|
| 356 |
+
success = bool(inside and upright and n_open == 0)
|
| 357 |
+
first = pushes[0] if pushes else None
|
| 358 |
+
out = dict(success=success, inside=bool(inside), upright=bool(upright),
|
| 359 |
+
n_pushes=n_push, n_bad_pushes=n_bad,
|
| 360 |
+
n_turned_pushes=sum(bool(m.get("over_turned")) for m in pushes),
|
| 361 |
+
n_trap_events=sum(bool(m.get("new_trap")) for m in pushes),
|
| 362 |
+
trap_fired=n_bad > 0, recovered_in_attempt=bool(n_bad and success),
|
| 363 |
+
first_push=first, first_push_yaw_deg=None if first is None else first["yaw_deg"],
|
| 364 |
+
first_interaction_ok=None if first is None else bool(not first.get("bad")),
|
| 365 |
+
n_open_gripper_pushes=n_open,
|
| 366 |
+
irrecoverable=bool(sk.lost), irrecoverable_why=dict(sk.lost),
|
| 367 |
+
n_box_moving_commands=n_push, box_moves=pushes, n_move_commands=sk.n_moves,
|
| 368 |
+
sim_s=round((sk.n_steps - getattr(self, "sim0", 0)) * 0.05, 1),
|
| 369 |
+
yaw_deg=round(float(np.degrees(yaw)), 1),
|
| 370 |
+
centre_offset=[round(float(off[0]), 4), round(float(off[1]), 4)],
|
| 371 |
+
touch_offset=None)
|
| 372 |
+
parts = []
|
| 373 |
+
if sk.first_touch is None:
|
| 374 |
+
out["failure"] = "not_touched"
|
| 375 |
+
parts.append("The box did not move: the gripper never pushed it.")
|
| 376 |
+
else:
|
| 377 |
+
lt = sk.first_touch["local"]
|
| 378 |
+
out["touch_offset"] = round(float(lt[1]), 4)
|
| 379 |
+
if success:
|
| 380 |
+
parts.append("The box is completely inside the rectangle.")
|
| 381 |
+
elif not upright:
|
| 382 |
+
out["failure"] = "tipped"
|
| 383 |
+
parts.append("The box tipped over.")
|
| 384 |
+
elif inside:
|
| 385 |
+
out["failure"] = "open_gripper"
|
| 386 |
+
parts.append("The box is completely inside the rectangle, but it was pushed with the gripper open; "
|
| 387 |
+
"the task asks for pushing with the closed gripper.")
|
| 388 |
+
else:
|
| 389 |
+
out["failure"] = "turned" if abs(np.degrees(yaw)) > 6 else "position"
|
| 390 |
+
parts.append("The box is not completely inside the rectangle.")
|
| 391 |
+
if n_push > 1:
|
| 392 |
+
txt = f"It was moved by {n_push} separate move commands"
|
| 393 |
+
if abs(first["yaw_deg"]) >= 1.0:
|
| 394 |
+
txt += f"; after the first one it had turned {_turn_words(first['yaw_deg'])} (seen from above)"
|
| 395 |
+
parts.append(txt + ".")
|
| 396 |
+
if n_open and out.get("failure") != "open_gripper":
|
| 397 |
+
parts.append("The gripper was open during " + ("that push." if n_push == 1 else
|
| 398 |
+
f"{n_open} of the pushes."))
|
| 399 |
+
turn = np.degrees(yaw)
|
| 400 |
+
if abs(turn) >= 1.0:
|
| 401 |
+
parts.append(f"It {'ended up turned' if n_push > 1 else 'turned'} {_turn_words(turn)} (seen from "
|
| 402 |
+
f"above): its {'left' if lag > 0 else 'right'} end ended {100 * abs(lag):.1f} cm "
|
| 403 |
+
f"further back than its {'right' if lag > 0 else 'left'} end.")
|
| 404 |
+
else:
|
| 405 |
+
parts.append("It did not turn (less than 1 degree)." if n_push <= 1 else
|
| 406 |
+
"It ended up not turned (less than 1 degree).")
|
| 407 |
+
parts.append(f"Its centre ended {_fb(off[0])} and {_lr(off[1])} of the rectangle's centre.")
|
| 408 |
+
parts.append(f"When the box started to move, the gripper's centre was {_lr(lt[1])} of the middle of "
|
| 409 |
+
f"the box (measured along the box's long side).")
|
| 410 |
+
out["detail"] = " ".join(parts)
|
| 411 |
+
return out
|
| 412 |
+
|
| 413 |
+
# ------------------------------------------------------------ scripted primitives (agent-command counted)
|
| 414 |
+
def _cmd(self, target, yaw=None, speed=None, tol=0.004, max_steps=250):
|
| 415 |
+
"""one agent command (move_eef; a gripper change rides on a move)"""
|
| 416 |
+
self.ncmd = getattr(self, "ncmd", 0) + 1
|
| 417 |
+
budget = getattr(self, "budget", None)
|
| 418 |
+
if budget is not None and self.ncmd > budget:
|
| 419 |
+
raise _Budget()
|
| 420 |
+
self.sk.move_to(target, yaw=yaw, speed=speed, tol=tol, max_steps=max_steps)
|
| 421 |
+
if budget is not None and self._sim_used() >= 3.0 * budget: # the server's motion budget (3 s per command)
|
| 422 |
+
raise _Budget()
|
| 423 |
+
|
| 424 |
+
def _sim_used(self):
|
| 425 |
+
return (self.sk.n_steps - getattr(self, "sim0", 0)) * 0.05
|
| 426 |
+
|
| 427 |
+
def _push_at(self, face, v, dist, speed=PUSH_SPEED, runup=RUNUP):
|
| 428 |
+
"""One push on the box as it lies now, with the closed gripper rotated to the face: face "back" (push
|
| 429 |
+
forward along the box's short side), "front" (push backwards) at long-side coordinate v (box frame), or
|
| 430 |
+
"left_end" / "right_end" (push along the long side at the middle of that end face). `dist` = how far the
|
| 431 |
+
fingers' front travels past the face. Commands: up (if low, 1), above the run-up point (1), down (1), push (1)."""
|
| 432 |
+
sk = self.sk
|
| 433 |
+
p, yaw = sk._box_pose()
|
| 434 |
+
R = _rot(yaw)
|
| 435 |
+
if face in ("back", "front"):
|
| 436 |
+
s = -1.0 if face == "back" else 1.0
|
| 437 |
+
n, q, gyaw = R @ np.array([s, 0.0]), p[:2] + R @ np.array([s * HALF[0], v]), yaw
|
| 438 |
+
else:
|
| 439 |
+
s = 1.0 if face == "left_end" else -1.0
|
| 440 |
+
n, q, gyaw = R @ np.array([0.0, s]), p[:2] + R @ np.array([0.0, s * HALF[1]]), yaw + np.pi / 2
|
| 441 |
+
start = q + n * (runup + FINGER_AHEAD)
|
| 442 |
+
end = q - n * (dist - FINGER_AHEAD)
|
| 443 |
+
e = sk.eef_pos()
|
| 444 |
+
if e[2] < Z_PUSH + 0.05:
|
| 445 |
+
self._cmd([e[0], e[1], Z_SAFE], speed=0.2)
|
| 446 |
+
self._cmd([start[0], start[1], Z_SAFE], yaw=gyaw)
|
| 447 |
+
self._cmd([start[0], start[1], Z_PUSH], tol=0.003)
|
| 448 |
+
self._cmd([end[0], end[1], Z_PUSH], speed=speed, tol=0.004, max_steps=400)
|
| 449 |
+
|
| 450 |
+
# ------------------------------------------------------------ scripted execution (cross protocol)
|
| 451 |
+
def execute(self, inst, params):
|
| 452 |
+
"""Closed gripper behind the box at lateral offset `c` (from the box's middle, along its long axis), then one
|
| 453 |
+
slow straight move_to forward ending `end_dx` beyond the nominal end point (target centre minus half the box
|
| 454 |
+
depth minus the finger offset), then lift. 4 commands (the gripper closes with the first one)."""
|
| 455 |
+
sk = self.sk
|
| 456 |
+
p = envs.obj_pos(self.env, BOX) # perfect perception of the current scene
|
| 457 |
+
t = self.target_xy(inst)
|
| 458 |
+
c = float(params["c"])
|
| 459 |
+
y = p[1] + c
|
| 460 |
+
face = p[0] - HALF[0]
|
| 461 |
+
x_end = t[0] - HALF[0] - FINGER_AHEAD + float(params.get("end_dx", 0.0))
|
| 462 |
+
sk.set_gripper(True, steps=8)
|
| 463 |
+
self._cmd([face - RUNUP, y, Z_PUSH + 0.08], yaw=0.0)
|
| 464 |
+
self._cmd([face - RUNUP, y, Z_PUSH], tol=0.003)
|
| 465 |
+
self._cmd([x_end, y, Z_PUSH], speed=PUSH_SPEED, tol=0.004, max_steps=400)
|
| 466 |
+
self._cmd([x_end - 0.03, y, Z_PUSH + 0.10], speed=0.2)
|
| 467 |
+
|
| 468 |
+
def default_params(self, inst):
|
| 469 |
+
return dict(c=0.0, end_dx=0.0) # Sonnet 5.5 (cla2 / cla4 / full5): yaw 0, middle of the back face, one push
|
| 470 |
+
|
| 471 |
+
def oracle_params(self, inst):
|
| 472 |
+
return dict(c=float(inst["com_offset"]), end_dx=0.0)
|
| 473 |
+
|
| 474 |
+
STEP = 0.06 # first correction toward the lagging end (the expected |e| range is unknown to the learner)
|
| 475 |
+
YAW_OK = 3.0 # deg: the corrector turns the box back until it is within this
|
| 476 |
+
GAIN0 = 2.8 # deg of turn per cm of a push at the leading end from the front, 3 cm from the end (measured)
|
| 477 |
+
SAFE_V = HALF[1] - 0.02 # contact points stay 2 cm inside the ends
|
| 478 |
+
|
| 479 |
+
def bracket(self, pushes):
|
| 480 |
+
"""Contact point estimate from logged pushes on the back / front face: a push whose box turned
|
| 481 |
+
counterclockwise passed to the right of the centre of mass when pushing forward (back face) and to its left
|
| 482 |
+
when pushing backwards (front face); a long push that did not turn passed within ~2 cm of it."""
|
| 483 |
+
lo, hi = -self.SAFE_V, self.SAFE_V
|
| 484 |
+
lo_set = hi_set = False
|
| 485 |
+
for m in pushes:
|
| 486 |
+
if m.get("face") not in ("back", "front") or m.get("gripper_open"):
|
| 487 |
+
continue
|
| 488 |
+
v, turn = m["touch_v"], m["turned_deg"] * (1.0 if m["face"] == "back" else -1.0)
|
| 489 |
+
if turn > 3.0:
|
| 490 |
+
lo, lo_set = max(lo, v + 0.01), True
|
| 491 |
+
elif turn < -3.0:
|
| 492 |
+
hi, hi_set = min(hi, v - 0.01), True
|
| 493 |
+
elif abs(turn) < 1.5 and m["moved_cm"] >= 3.0:
|
| 494 |
+
lo, hi, lo_set, hi_set = max(lo, v - 0.02), min(hi, v + 0.02), True, True
|
| 495 |
+
if lo > hi: # inconsistent (contacts slide): trust the newest
|
| 496 |
+
lo, hi = hi, lo
|
| 497 |
+
if lo_set and hi_set:
|
| 498 |
+
c = 0.5 * (lo + hi)
|
| 499 |
+
elif lo_set:
|
| 500 |
+
c = lo + self.STEP
|
| 501 |
+
elif hi_set:
|
| 502 |
+
c = hi - self.STEP
|
| 503 |
+
else:
|
| 504 |
+
c = 0.0
|
| 505 |
+
return float(np.clip(c, -self.SAFE_V, self.SAFE_V))
|
| 506 |
+
|
| 507 |
+
def adapt_params(self, inst, history):
|
| 508 |
+
"""Cross-attempt start point: push where the pushes of the earlier attempts put the centre of mass."""
|
| 509 |
+
return dict(c=round(self.bracket([m for h in history for m in h["outcome"]["box_moves"]]), 4), end_dx=0.0)
|
| 510 |
+
|
| 511 |
+
@staticmethod
|
| 512 |
+
def _front_runup(p, yaw, v):
|
| 513 |
+
"""run-up for a push on the front face at v that keeps the gripper's put-down point within X_DOWN; None when
|
| 514 |
+
even a 1.5 cm run-up does not fit (the box is too far forward to get in front of it)"""
|
| 515 |
+
R = _rot(yaw)
|
| 516 |
+
f, n_out = p[:2] + R @ np.array([HALF[0], v]), R @ np.array([1.0, 0.0])
|
| 517 |
+
runup = min(RUNUP, (X_DOWN - f[0]) / max(n_out[0], 0.2) - FINGER_AHEAD)
|
| 518 |
+
return float(runup) if runup >= 0.015 else None
|
| 519 |
+
|
| 520 |
+
def adaptive_attempt(self, inst, c0, prior_pushes=()):
|
| 521 |
+
"""In-attempt corrector: the first push as `execute` (at c0: the middle in attempt 1, like the naive policy);
|
| 522 |
+
then, after every push, look at the box (perfect perception) and push again until it is inside or the agent
|
| 523 |
+
budget would run out. Turned more than YAW_OK -> push its leading end back from the front (it turns back with
|
| 524 |
+
little translation), or if it is too far forward for that, the lagging end forward from behind; not turned
|
| 525 |
+
but short / past the far edge / out at a side -> push it straight from behind / from the front at the
|
| 526 |
+
estimated centre of mass, or along its long side at an end face. Returns the number of corrective pushes."""
|
| 527 |
+
self.execute(inst, dict(c=c0, end_dx=0.0))
|
| 528 |
+
sk = self.sk
|
| 529 |
+
t = self.target_xy(inst)
|
| 530 |
+
gain = self.GAIN0
|
| 531 |
+
sim_budget = 3.0 * self.budget if self.budget is not None else np.inf
|
| 532 |
+
n = 0
|
| 533 |
+
while True:
|
| 534 |
+
p, yaw = sk._box_pose()
|
| 535 |
+
fit = sk.fit(p, yaw)
|
| 536 |
+
if fit["inside"] or sk.lost:
|
| 537 |
+
return n
|
| 538 |
+
if (self.budget is not None and self.ncmd + 4 > self.budget) or self._sim_used() + 10.0 > sim_budget:
|
| 539 |
+
return n
|
| 540 |
+
n += 1
|
| 541 |
+
yd = np.degrees(yaw)
|
| 542 |
+
c_est = self.bracket(list(prior_pushes) + sk.box_moves)
|
| 543 |
+
if abs(yd) > self.YAW_OK:
|
| 544 |
+
for vm in (HALF[1] - 0.03, 0.06, 0.04, 0.02): # the leading (light) end, or nearer the middle if
|
| 545 |
+
v_lead = -np.sign(yd) * vm # the end is out of reach; +v = the box's left end
|
| 546 |
+
runup = self._front_runup(p, yaw, v_lead)
|
| 547 |
+
if runup is not None:
|
| 548 |
+
break
|
| 549 |
+
if runup is not None:
|
| 550 |
+
d = float(np.clip(abs(yd) / gain, 1.0, 10.0)) / 100
|
| 551 |
+
self._push_at("front", v_lead, d, runup=runup)
|
| 552 |
+
dy = abs(yd) - abs(np.degrees(sk._box_pose()[1]))
|
| 553 |
+
if dy > 1.0:
|
| 554 |
+
gain = float(np.clip(dy / (100 * d), 1.0, 5.0))
|
| 555 |
+
else:
|
| 556 |
+
self._push_at("back", np.sign(yd) * (HALF[1] - 0.01), 0.03)
|
| 557 |
+
else:
|
| 558 |
+
dx = t[0] - p[0]
|
| 559 |
+
if fit["overshot"]:
|
| 560 |
+
runup = self._front_runup(p, yaw, c_est)
|
| 561 |
+
if runup is None:
|
| 562 |
+
return n
|
| 563 |
+
self._push_at("front", c_est, max(0.005, -dx), runup=runup)
|
| 564 |
+
elif fit["sideways"]:
|
| 565 |
+
dyy = t[1] - p[1]
|
| 566 |
+
self._push_at("right_end" if dyy > 0 else "left_end", 0.0, max(0.005, abs(dyy) - 0.005))
|
| 567 |
+
else:
|
| 568 |
+
self._push_at("back", c_est, max(0.005, dx))
|
| 569 |
+
|
| 570 |
+
def run_scripted(self, kind, inst, k=None, seed=0, on_attempt=None):
|
| 571 |
+
"""Cross protocol with the agent's command budget per attempt (agent_max_steps, default 40 commands and
|
| 572 |
+
3 s of motion per command; one move_eef = one command). naive / oracle / blind: one push, then finish.
|
| 573 |
+
adaptive: in-attempt corrector (`adaptive_attempt`); attempt 1 starts with the naive push, later attempts
|
| 574 |
+
at the contact point estimated from all earlier pushes."""
|
| 575 |
+
k = k or self.max_attempts
|
| 576 |
+
rng = np.random.default_rng(seed)
|
| 577 |
+
history = []
|
| 578 |
+
for a in range(k):
|
| 579 |
+
self.reset_instance(inst)
|
| 580 |
+
self.ncmd, self.budget = 0, int(getattr(self, "agent_max_steps", 40))
|
| 581 |
+
if kind == "oracle":
|
| 582 |
+
params = self.oracle_params(inst)
|
| 583 |
+
elif kind == "naive":
|
| 584 |
+
params = self.default_params(inst)
|
| 585 |
+
elif kind == "blind":
|
| 586 |
+
params = self.default_params(inst) if a == 0 else self.blind_params(inst, a, rng)
|
| 587 |
+
elif kind == "adaptive":
|
| 588 |
+
params = self.default_params(inst) if a == 0 else self.adapt_params(inst, history)
|
| 589 |
+
else:
|
| 590 |
+
raise ValueError(kind)
|
| 591 |
+
try:
|
| 592 |
+
if kind == "adaptive":
|
| 593 |
+
prior = [m for h in history for m in h["outcome"]["box_moves"]]
|
| 594 |
+
params["corrections"] = self.adaptive_attempt(inst, params["c"], prior)
|
| 595 |
+
else:
|
| 596 |
+
self.execute(inst, params)
|
| 597 |
+
except _Budget:
|
| 598 |
+
params["budget_used_up"] = True
|
| 599 |
+
self.budget = None
|
| 600 |
+
out = self.outcome(inst)
|
| 601 |
+
out["commands"] = self.ncmd
|
| 602 |
+
history.append(dict(attempt=a + 1, params=params, outcome=out))
|
| 603 |
+
if on_attempt:
|
| 604 |
+
on_attempt(a, params, out)
|
| 605 |
+
if out["success"] or kind in ("oracle", "naive"):
|
| 606 |
+
break
|
| 607 |
+
return history
|
| 608 |
+
|
| 609 |
+
blind_sigma = 0.008
|
| 610 |
+
|
| 611 |
+
def blind_params(self, inst, attempt, rng):
|
| 612 |
+
"""Same plan (push at the middle) with a small random variation of the contact point; no history."""
|
| 613 |
+
return dict(c=float(rng.normal(0.0, self.blind_sigma)), end_dx=0.0)
|
leaf/release/source_packages/models-20261115-g56sol_canary_20261114/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/models-20261115-g56sol_canary_20261114/lff/source_closure/scripts/full_report.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Summarise a full run (all tasks x harnesses) from the robot-server logs only, so every harness is measured
|
| 2 |
+
the same way.
|
| 3 |
+
|
| 4 |
+
python scripts/full_report.py --batch full1 [--out ../docs/full1_table.md]
|
| 5 |
+
|
| 6 |
+
Per run: outcome of every attempt, attempts used, robot commands, close_gripper calls that ended holding an
|
| 7 |
+
object, "empty done" attempts (the agent ended an attempt without a single move / gripper command in it), and
|
| 8 |
+
wall time from the first to the last server request.
|
| 9 |
+
"""
|
| 10 |
+
import argparse
|
| 11 |
+
import collections
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 16 |
+
LEVEL = {"l1": "L1", "l2": "L2", "l3": "L3", "l4": "L4", "l5": "L5", "l6": "L6", "l7": "L7"}
|
| 17 |
+
HARNESS_NAME = {"gpt_player": "ours", "rpent": "RPent", "gptpolicy": "GPT-Policy", "claude": "ours (Claude CLI)"}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def run_info(r):
|
| 21 |
+
ev = [json.loads(l) for l in open(os.path.join(r["log"], "events.jsonl"))]
|
| 22 |
+
calls = [e for e in ev if e["ev"] == "call"]
|
| 23 |
+
dones = [e for e in ev if e["ev"] == "done"]
|
| 24 |
+
http = [e for e in ev if e["ev"] == "http"]
|
| 25 |
+
# v1: move_to / open_gripper / close_gripper; v2 and la: move_eef [gripper=open|close] (holding is only in `raw`,
|
| 26 |
+
# the agent never sees it)
|
| 27 |
+
acts_per_attempt = collections.Counter(e["attempt"] for e in calls if e["cmd"] in ("move_to", "open_gripper", "close_gripper")
|
| 28 |
+
or (e["cmd"] == "move_eef" and (e.get("report") or {}).get("ok")))
|
| 29 |
+
empty = sum(1 for d in dones if acts_per_attempt.get(d["attempt"], 0) == 0)
|
| 30 |
+
closes = [e for e in calls if e["cmd"] == "close_gripper"
|
| 31 |
+
or (e["cmd"] == "move_eef" and (e.get("args") or {}).get("gripper") == "close" and (e.get("report") or {}).get("ok"))]
|
| 32 |
+
held = sum(1 for e in closes if (e.get("report") or {}).get("holding_object") or (e.get("raw") or {}).get("holding_object"))
|
| 33 |
+
first = next((d["attempt"] for d in dones if d["success"]), None)
|
| 34 |
+
wall = (http[-1]["t_send"] - http[0]["t_recv"]) / 60 if http else None
|
| 35 |
+
return dict(outcomes="".join("S" if d["success"] else "F" for d in dones), attempts=len(dones), first=first,
|
| 36 |
+
cmds=len(calls), closes=len(closes), held=held, empty=empty, wall=wall)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main():
|
| 40 |
+
ap = argparse.ArgumentParser()
|
| 41 |
+
ap.add_argument("--batch", default="full1")
|
| 42 |
+
ap.add_argument("--out", default=None)
|
| 43 |
+
ap.add_argument("--runs", default="gpt", help="runs/<runs>/<batch>/manifest.json (gpt or claude)")
|
| 44 |
+
a = ap.parse_args()
|
| 45 |
+
m = json.load(open(os.path.join(ROOT, "runs", a.runs, a.batch, "manifest.json")))
|
| 46 |
+
rows = {}
|
| 47 |
+
for r in m["runs"]:
|
| 48 |
+
try:
|
| 49 |
+
h = r.get("harness") or ("claude" if r.get("cond") in ("harness", "noharness") else "gpt_player")
|
| 50 |
+
rows[(r["task"], h)] = dict(run_info(r), k=r["k"])
|
| 51 |
+
except FileNotFoundError:
|
| 52 |
+
pass
|
| 53 |
+
tasks = sorted({t for t, _ in rows}, key=lambda t: (t[:2], t))
|
| 54 |
+
hs = [h for h in ("gpt_player", "rpent", "gptpolicy", "claude") if any(k[1] == h for k in rows)]
|
| 55 |
+
L = [f"# {a.batch}: one run per task x harness (see manifest for model / perception / style)", "",
|
| 56 |
+
"Cell = outcome of each attempt (S success, F failure); `·` = run missing. Measured from robot-server logs.", "",
|
| 57 |
+
"| task | level | " + " | ".join(HARNESS_NAME[h] for h in hs) + " |", "|---|---|" + "---|" * len(hs)]
|
| 58 |
+
for t in tasks:
|
| 59 |
+
cells = []
|
| 60 |
+
for h in hs:
|
| 61 |
+
x = rows.get((t, h))
|
| 62 |
+
cells.append("·" if x is None else (x["outcomes"] or "—"))
|
| 63 |
+
L.append(f"| {t} | {LEVEL.get(t[:2], '?')} | " + " | ".join(cells) + " |")
|
| 64 |
+
L += ["", "| harness | runs | success @1 | success @3 | grasps held / close_gripper | empty-done attempts | "
|
| 65 |
+
"commands / attempt | wall min / run |", "|---|---|---|---|---|---|---|---|"]
|
| 66 |
+
for h in hs:
|
| 67 |
+
xs = [x for (t, hh), x in rows.items() if hh == h and x["attempts"] > 0]
|
| 68 |
+
n = len(xs)
|
| 69 |
+
att = sum(x["attempts"] for x in xs)
|
| 70 |
+
L.append(f"| {HARNESS_NAME[h]} | {n} | {sum(1 for x in xs if x['first'] == 1)} | "
|
| 71 |
+
f"{sum(1 for x in xs if x['first'])} | {sum(x['held'] for x in xs)} / {sum(x['closes'] for x in xs)} | "
|
| 72 |
+
f"{sum(x['empty'] for x in xs)} / {att} | {sum(x['cmds'] for x in xs) / max(att, 1):.1f} | "
|
| 73 |
+
f"{sum(x['wall'] or 0 for x in xs) / max(n, 1):.0f} |")
|
| 74 |
+
by_level = collections.defaultdict(lambda: [0, 0])
|
| 75 |
+
for (t, h), x in rows.items():
|
| 76 |
+
if x["attempts"]:
|
| 77 |
+
by_level[LEVEL.get(t[:2], "?")][0] += bool(x["first"])
|
| 78 |
+
by_level[LEVEL.get(t[:2], "?")][1] += 1
|
| 79 |
+
L += ["", "Success @3 by level (all harnesses pooled): " +
|
| 80 |
+
", ".join(f"{lv} {s}/{n}" for lv, (s, n) in sorted(by_level.items()))]
|
| 81 |
+
txt = "\n".join(L)
|
| 82 |
+
print(txt)
|
| 83 |
+
if a.out:
|
| 84 |
+
with open(a.out, "w") as f:
|
| 85 |
+
f.write(txt + "\n")
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
if __name__ == "__main__":
|
| 89 |
+
main()
|