Datasets:
Download tools/task_spec.py from vrmanipulation/vr_dataset: direct link, hf CLI and curl.
- Browser
- Download file 124 kB
-
https://huggingface.co/datasets/vrmanipulation/vr_dataset/resolve/main/tools/task_spec.py
- Command line
-
hf download hf://datasets/vrmanipulation/vr_dataset/tools/task_spec.py
-
curl -L -o task_spec.py https://huggingface.co/datasets/vrmanipulation/vr_dataset/resolve/main/tools/task_spec.py
124 kB
"""Task definitions as data: one JSON file per task, under tasks/.
Why
---
A task used to be spread across three places in ``collect_env.py`` that had to
agree and nothing checked: the function that spawns the assets, the branch that
picks the success criterion, and the dict that describes the scene for
``meta/scene.json``. Change the cube's size in one and the dataset says the
other. A task file is the single place: the scene, the physics, and what
counts as success, in one document that is also copied into every dataset the
task produces.
A file looks like this (see ``tasks/cube_pickup.json``)::
{
"name": "cube_pickup",
"description": "pick the cube up off the table",
"table": {"size": [0.9, 0.9, 0.05], "top_z": 0.90, "pos": [0.55, -0.2]},
"objects": [
{"name": "cube", "role": "target", "shape": "cuboid",
"size": [0.06, 0.06, 0.06], "mass": 0.1,
"on_table": true, "xy": [0.0, 0.0], "yaw_deg": 0.0,
"friction": 1.0}
],
"success": {"type": "lift", "height_m": 0.10, "hold_s": 5.0},
"physics": {"friction": 1.0}
}
Conventions that keep a file honest:
* ``on_table`` places an object by its own geometry -- it is dropped so its
underside rests on the table top, with a 1 mm gap. Writing an absolute z is
allowed (``"z"``) but then a change to the table height silently floats or
buries it.
* ``xy`` is relative to the table centre, so moving the table moves the task.
* Exactly one object carries ``"role": "target"``. It is the one the success
criterion reads and the one the hand<->object contact filter looks for, and
it must land at the prim path ``/Object`` for either to work.
* ``hands`` is ``"both"``. Collection has been bimanual only since
2026-09-28: a task that needs one hand is still recorded with two, the
other free, and the collector refuses a task file that names one side.
``"right"`` / ``"left"`` still LOAD, because this reader also opens the
``meta/task.json`` of datasets recorded before that.
* Anything absent falls back to the CLI default, and startup prints what was
used. A task file never has to restate the whole world.
"""
from __future__ import annotations
import json
import math
import os
TASKS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"tasks")
#: shape name -> (isaaclab spawner attribute, the kwarg carrying its size)
SHAPES = {
"cuboid": ("MeshCuboidCfg", "size"),
"sphere": ("MeshSphereCfg", "radius"),
"cylinder": ("MeshCylinderCfg", None), # radius + height
"capsule": ("MeshCapsuleCfg", None),
"cone": ("MeshConeCfg", None),
}
SUCCESS_TYPES = ("lift", "handover", "axis_upright", "reorient_face", "joint_angle",
"joint_open", "joint_sequence", "insert", "separate", "pose_target", "count",
"all", "turn")
#: What an `all` may hold: criteria graded on poses (no joint criteria yet).
ALL_SUB_TYPES = ("lift", "axis_upright", "insert", "separate", "pose_target", "count")
#: The operator's hands, in the order they are spawned and recorded. Same
#: order as ``embodiment.openxr.tracking.SIDES``, and it is load-bearing:
#: ``observation.wrist_pose`` concatenates one 7-float pose per hand in this
#: order, so a reader splits it by index and has to agree.
SIDES = ("left", "right")
#: What a task file's ``hands`` key may say, and which sides each spawns.
HAND_CHOICES = {"left": ("left",), "right": ("right",),
"both": ("left", "right")}
#: shapes that are a USD file rather than a primitive. ``usd`` is one rigid
#: body; ``articulation`` is a USD with joints in it, spawned as an
#: ArticulationCfg so its joint coordinate can be read and written -- which is
#: what an "open it" task is entirely about.
USD_SHAPES = ("usd", "articulation")
#: Fallback diffuse colour for a primitive whose task file names none. Warm
#: orange: it separates from the table's grey, from the blue MANO hand
#: (``--hand-rgb``) and from the green/pink tracking overlay, and it stays
#: distinguishable under the desaturating effect of a headset's optics. Objects
#: override it with a ``"color": [r, g, b]`` key.
DEFAULT_COLOR = (0.85, 0.35, 0.10)
#: The table's own colour, for the same reason. Neutral and dark enough that a
#: light object on top of it reads as an object rather than as a patch.
TABLE_COLOR = (0.30, 0.31, 0.34)
def find(name: str) -> str | None:
"""Path of the task file for `name`, or None. A path to a task file (a dataset's own meta/task.json,
whose name may no longer match anything under tasks/) is taken as it is."""
if name.endswith(".json") and os.path.exists(name):
return name
p = os.path.join(TASKS_DIR, f"{name}.json")
return p if os.path.exists(p) else None
#: Not a task: the universal hand settings, shared by every task file.
NOT_A_TASK = ("hand",)
def available() -> list[str]:
if not os.path.isdir(TASKS_DIR):
return []
return sorted(f[:-5] for f in os.listdir(TASKS_DIR)
if f.endswith(".json") and f[:-5] not in NOT_A_TASK)
def load(path: str) -> dict:
"""Read and validate a task file. Raises with the offending field named.
A task file used to be able to carry ``variants`` -- alternative builds
merged over the base by ``--variant``. The two builds that used it (the
tuned asset and the source asset it departs from) are two TASK FILES as
of 2026-09-10, paired by the source file's ``_baseline_of``, so that each
build has its own probe result, its own dataset and its own row in
TASKS.md rather than hiding behind a flag on the other one.
"""
with open(path) as fh:
spec = json.load(fh)
spec["_path"] = os.path.abspath(path)
name = spec.get("name") or os.path.basename(path)[:-5]
spec["name"] = name
objs = spec.get("objects") or []
if not objs:
raise ValueError(f"{path}: no objects")
targets = [o for o in objs if o.get("role") == "target"]
if len(targets) != 1:
raise ValueError(f"{path}: expected exactly one object with "
f'"role": "target", found {len(targets)}')
seen = set()
for o in objs:
n = o.get("name")
if not n or n in seen:
raise ValueError(f"{path}: objects need unique names, got {n!r}")
seen.add(n)
sh = o.get("shape", "cuboid")
if sh not in SHAPES and sh not in USD_SHAPES:
raise ValueError(f"{path}: object {n!r} has unknown shape {sh!r}; "
f"expected one of {sorted(SHAPES)} or "
f"{list(USD_SHAPES)}")
if sh in USD_SHAPES and not o.get("usd"):
raise ValueError(f"{path}: object {n!r} is shape {sh!r} but has "
f"no \"usd\" path")
if "z" not in o and not o.get("on_table", True):
raise ValueError(f"{path}: object {n!r} has neither \"z\" nor "
f'"on_table"')
for o in objs:
# A per-object contact voxel. Optional, and checked here because a
# typo ("voxel": 0.0005) would silently leave a 0.5 mm socket at the
# scene's 2 mm and the insertion would bind on a grid, not a wall.
if "voxel_size" in o:
v = o["voxel_size"]
if not isinstance(v, (int, float)) or not 1e-5 <= float(v) <= 0.05:
raise ValueError(f"{path}: object {o['name']!r} voxel_size "
f"must be metres in [1e-5, 0.05], got {v!r}")
if "gravity_compensation" in o:
v = o["gravity_compensation"]
if not isinstance(v, (int, float)) or not 0.0 <= float(v) <= 1.0:
raise ValueError(f"{path}: object {o['name']!r} "
f"gravity_compensation must be in [0, 1] "
f"(1 = weightless), got {v!r}")
# A voxel per COLLIDER, keyed by a substring of the collider prim's
# path. The part that mates (a prong, a shaft) wants a fine grid; the
# part the hand holds does not, and Newton extracts every contact pair
# on the finer shape's grid, so a fine grid on the held part makes
# every grasp 5x slower (measured: 167 vs 800 steps/s).
if "voxel_size_parts" in o:
vp = o["voxel_size_parts"]
if not isinstance(vp, dict) or not vp:
raise ValueError(f"{path}: object {o['name']!r} voxel_size_parts "
f"must be a non-empty object of "
f'{{"<collider substring>": metres}}')
for k, v in vp.items():
if not isinstance(k, str) or not k or k.startswith("_"):
raise ValueError(f"{path}: object {o['name']!r} "
f"voxel_size_parts key {k!r} must be a "
f"substring of a collider prim path")
if not isinstance(v, (int, float)) or not 1e-5 <= float(v) <= 0.05:
raise ValueError(f"{path}: object {o['name']!r} "
f"voxel_size_parts[{k!r}] must be metres "
f"in [1e-5, 0.05], got {v!r}")
# Colliders of a hydroelastic object that stay RIGID, by substring
# of the collider prim path: a plate a gear rests on does not need a
# pressure field (50k faces of one, measured), its shafts do.
if "rigid_parts" in o:
rp = o["rigid_parts"]
if not isinstance(rp, list) or not rp or not all(
isinstance(k, str) and k and not k.startswith("_") for k in rp):
raise ValueError(f"{path}: object {o['name']!r} rigid_parts must be "
f"a non-empty list of collider prim-path substrings")
if not o.get("hydroelastic") and o.get("role") != "target":
raise ValueError(f"{path}: object {o['name']!r} rigid_parts only "
f"means something on a hydroelastic object")
# Contact STIFFNESS per object: the hydroelastic modulus of this
# object's shapes (the scene's `kh` for the rest, the hand included)
# and the MuJoCo constraint impedance of its contacts. A thread or a
# press fit that has to hold against a hand PUSHING (tens of N) on a
# few mm2 of flank needs a stiffer pair than a fingertip on a cube;
# see "Contact stiffness: the nut that was pushed through its thread"
# in tasks/README.md for what each one does.
if "kh" in o:
v = o["kh"]
if not isinstance(v, (int, float)) or not 1e6 <= float(v) <= 1e15:
raise ValueError(f"{path}: object {o['name']!r} kh must be a "
f"hydroelastic modulus in [1e6, 1e15] Pa/m, "
f"got {v!r}")
if "contact_impedance" in o:
v = o["contact_impedance"]
if not isinstance(v, (int, float)) or not 0.5 <= float(v) < 1.0:
raise ValueError(f"{path}: object {o['name']!r} contact_impedance "
f"must be in [0.5, 1) (MuJoCo solimp d0/dmax; "
f"the default is 0.9/0.95), got {v!r}")
if spec.get("hands") == "single":
# a task file copied into a dataset by the release/1.0 collector, which wrote
# "single" for a right-hand task; read back as that so the dataset's own
# meta/task.json still loads
spec["hands"] = "right"
if "hands" in spec and spec["hands"] not in HAND_CHOICES:
raise ValueError(f"{path}: \"hands\" must be one of "
f"{sorted(HAND_CHOICES)}, got {spec['hands']!r}")
s = spec.get("success") or {}
tc = spec.get("physics", {}).get("thread_contact")
if tc is not None:
if not isinstance(tc, dict) or not (s.get('type') == 'separate' or
(s.get('type') == 'insert' and 'thread' in s)):
raise ValueError(f"{path}: physics.thread_contact requires a threaded insert or separate criterion")
if tc.get('condim') not in (1, 3, 4, 6):
raise ValueError(f"{path}: thread_contact.condim must be 1, 3, 4 or 6")
mu = tc.get('torsional_friction')
sr = tc.get('solref')
if 'torsional_friction' in tc and (not isinstance(mu, (int, float)) or not 0 <= mu < float('inf')):
raise ValueError(f"{path}: thread_contact.torsional_friction must be finite and nonnegative")
if 'solref' in tc and (not isinstance(sr, list) or len(sr) != 2 or not all(
isinstance(x, (int, float)) and 0 < x < float('inf') for x in sr)):
raise ValueError(f"{path}: thread_contact.solref needs positive [timeconst, dampratio]")
if s.get("type") not in SUCCESS_TYPES:
raise ValueError(f"{path}: success.type must be one of "
f"{list(SUCCESS_TYPES)}, got {s.get('type')!r}")
names = {o["name"] for o in objs}
if s["type"] in ("pose_target", "axis_upright") and s.get("of") is not None \
and s["of"] not in names:
raise ValueError(f"{path}: success.of {s['of']!r} is not an object")
if s["type"] == "pose_target" and s.get("goal_of") is not None:
if s["goal_of"] not in names:
raise ValueError(f"{path}: success.goal_of {s['goal_of']!r} is not an object")
if "goal_xy" in s or "goal_yaw_deg" in s:
raise ValueError(f"{path}: success.goal_of replaces goal_xy / goal_yaw_deg "
f"(the goal is that object's pose, read every frame)")
if s["type"] == "all":
subs = s.get("of")
if not isinstance(subs, list) or len(subs) < 1:
raise ValueError(f"{path}: success.of for `all` must list one or more criteria "
f"(one: a criterion graded on a `part` other than the target)")
for k, sub in enumerate(subs):
if sub.get("type") not in ALL_SUB_TYPES:
raise ValueError(f"{path}: all.of[{k}].type must be one of {ALL_SUB_TYPES}")
for key in ("part", "into"):
if sub.get(key) is not None and sub[key] not in names:
raise ValueError(f"{path}: all.of[{k}].{key} {sub[key]!r} is not an object")
if sub["type"] in ("insert", "separate") and not sub.get("into"):
raise ValueError(f"{path}: all.of[{k}] ({sub['type']}) needs into")
if s["type"] == "pose_target":
if not any(k in s for k in ("goal_xy", "goal_of", "region", "goal_yaw_deg",
"displace_m")):
raise ValueError(f"{path}: pose_target needs goal_xy, goal_of, region, "
f"goal_yaw_deg or displace_m")
for ax, rng in (s.get("region") or {}).items():
if ax not in ("x", "y", "z") or len(rng) != 2 or rng[0] > rng[1]:
raise ValueError(f"{path}: pose_target.region[{ax!r}] must be [lo, hi]")
if s["type"] == "count":
if s.get("mode", "insert") not in ("insert", "region"):
raise ValueError(f"{path}: count.mode must be insert or region")
bad = [n for n in list(s.get("objects") or []) + [s.get("into")] if n not in names]
if bad or not s.get("objects"):
raise ValueError(f"{path}: count needs objects and into, all named objects (bad: {bad})")
if not 1 <= int(s.get("need", 0)) <= len(s["objects"]):
raise ValueError(f"{path}: count.need must be 1..{len(s['objects'])}")
if s["type"] == "handover":
if s.get("direction", "any") not in ("any", "right_to_left", "left_to_right"):
raise ValueError(f"{path}: success.direction for a handover must be any, "
f"right_to_left or left_to_right")
if spec.get("hands") != "both":
raise ValueError(f"{path}: a handover needs \"hands\": \"both\"")
if s["type"] == "lift" and not isinstance(s.get("height_m"), (int, float)):
raise ValueError(f"{path}: success.height_m must be a number")
if s["type"] == "lift" and s.get("max_hands_touching") is not None:
# How many hands may touch the lifted objects during the hold. Counted
# from hand<->object contact, so it needs both hands and every named
# object in contact recording (hydroelastic).
mh = s["max_hands_touching"]
if not isinstance(mh, int) or isinstance(mh, bool) or mh < 0:
raise ValueError(f"{path}: success.max_hands_touching must be an int >= 0")
if not s.get("objects"):
raise ValueError(f"{path}: success.max_hands_touching needs success.objects")
if spec.get("hands") != "both":
raise ValueError(f"{path}: success.max_hands_touching needs \"hands\": \"both\"")
dry = [o["name"] for o in spec["objects"] if o["name"] in s["objects"]
and o.get("role") != "target" and not o.get("hydroelastic")]
if dry:
raise ValueError(f"{path}: success.max_hands_touching counts hand contact on "
f"{dry}, which need \"hydroelastic\": true to record any")
if s["type"] in ("joint_angle", "joint_open"):
# WHICH object's joint. The target's, unless `of` names another one:
# a hammer task grades the NAIL's slide while the hand is on the
# HAMMER, and only one of those can be /Object.
of = s.get("of")
if of is not None and of not in seen:
raise ValueError(f"{path}: success.of must name an object in this "
f"file, got {of!r}; have {sorted(seen)}")
g = graded(spec)
if g.get("shape") != "articulation":
raise ValueError(f"{path}: success.type {s['type']!r} reads a "
f"joint, so {g['name']!r} must be "
f'"shape": "articulation"'
+ ("" if of else " (or name an articulated prop "
"in success.of)"))
if s["type"] == "joint_angle":
if not isinstance(s.get("min_deg"), (int, float)):
raise ValueError(f"{path}: success.min_deg must be a number")
js = s.get("joints")
if js is not None:
# SEVERAL joints, every one of which must have moved: a hand's
# three finger knuckles closed on a cube. joint_angle only --
# joint_open grades a fraction of ONE joint's travel and two
# joints rarely share one.
if (not isinstance(js, list) or not js
or not all(isinstance(j, str) and j for j in js)):
raise ValueError(f"{path}: success.joints must be a non-empty "
f"list of joint names, got {js!r}")
have = joint_names(graded(spec), path)
miss = [j for j in js if j not in have]
if miss:
raise ValueError(f"{path}: success.joints {miss} are not in "
f"{graded(spec)['name']!r}, which has {have}")
elif joint_kind(graded(spec), path) == "prismatic":
raise ValueError(f"{path}: success.type 'joint_angle' is degrees, "
f"and the graded joint is a SLIDE. Use "
f"'joint_open' with a fraction of its travel.")
if s["type"] == "joint_open" and s.get("joints") is not None:
raise ValueError(f"{path}: success.joints is only for 'joint_angle'")
if s.get("require_tool_contact") is not None:
if not isinstance(s["require_tool_contact"], bool) or s["type"] != "joint_open" \
or s.get("min_tool_speed_mps") is None:
raise ValueError(f"{path}: success.require_tool_contact is a true/false that "
f"qualifies a joint_open with min_tool_speed_mps")
w = s.get("tool_contact_window_s")
if w is not None and (not isinstance(w, (int, float)) or w < 0
or not s.get("require_tool_contact")):
raise ValueError(f"{path}: success.tool_contact_window_s is seconds >= 0 and needs "
f"require_tool_contact")
if s["type"] == "joint_open":
f = s.get("fraction")
if not isinstance(f, (int, float)) or not 0.0 < float(f) <= 1.0:
raise ValueError(f"{path}: success.fraction must be a number in "
f"(0, 1] — the share of the joint's authored "
f"travel that counts as open, got {f!r}")
# The travel comes from the ASSET, so a task file that names a
# fraction of a joint the asset does not have is caught here rather
# than as an empty range that can never be satisfied.
joint_travel(graded(spec), path)
if s["type"] == "joint_sequence":
# Several joints in ORDER, each on a named articulated object: pull
# one nail, then drive another. Every step names its object, its
# direction, and either an absolute coordinate to reach ("to") or a
# share of that joint's authored travel ("fraction").
steps = s.get("steps")
if not isinstance(steps, list) or len(steps) < 2:
raise ValueError(f"{path}: success.steps must be a list of at least "
f"two steps for a joint_sequence")
for i, st in enumerate(steps):
if not isinstance(st, dict) or st.get("of") not in seen:
raise ValueError(f"{path}: success.steps[{i}].of must name an object "
f"in this file; have {sorted(seen)}")
o = next(x for x in objs if x["name"] == st["of"])
if o.get("shape") != "articulation":
raise ValueError(f"{path}: success.steps[{i}] reads a joint, so "
f"{st['of']!r} must be \"shape\": \"articulation\"")
if st.get("direction") not in ("increase", "decrease"):
raise ValueError(f"{path}: success.steps[{i}].direction must be "
f"increase or decrease")
if ("to" in st) == ("fraction" in st):
raise ValueError(f"{path}: success.steps[{i}] needs exactly one of "
f"'to' (a coordinate) or 'fraction' (of the travel)")
if "fraction" in st and not (isinstance(st["fraction"], (int, float))
and 0.0 < float(st["fraction"]) <= 1.0):
raise ValueError(f"{path}: success.steps[{i}].fraction must be in (0, 1]")
if "to" in st and not isinstance(st["to"], (int, float)):
raise ValueError(f"{path}: success.steps[{i}].to must be a number")
# WHICH joint of that object: its `joint.name` unless the step
# names one (`joint`) -- two nails on one block are two steps
# on the same object.
jn = st.get("joint")
if jn is not None and jn not in joint_names(o, path):
raise ValueError(f"{path}: success.steps[{i}].joint {jn!r} is not a "
f"joint of {st['of']!r}, which has {joint_names(o, path)}")
joint_travel(step_object(o, st), path) # the asset has the joint
if s["type"] == "reorient_face":
fc = target(spec).get("face_colors")
if not fc:
raise ValueError(f"{path}: success.type 'reorient_face' names the "
f"colour that ended up, so the target needs a "
f'"face_colors" map (see tools/make_color_cube.py)')
# `up_color` names the ONE colour that has to end up (the goal), as
# against the older "any neighbouring face" rule. Checked here so a
# colour the cube does not have fails at load rather than grading a
# face nobody meant.
want = s.get("up_color")
if want is not None:
if not isinstance(want, str):
raise ValueError(f"{path}: success.up_color must be a colour name")
hits = [k for k, v in fc.items() if v == want]
if len(hits) != 1:
raise ValueError(f"{path}: success.up_color {want!r} names "
f"{len(hits)} of the target's faces "
f"({fc}); it has to name exactly one")
if s.get("up_face") is not None and s["up_face"] not in fc:
raise ValueError(f"{path}: success.up_face {s['up_face']!r} is not "
f"one of the target's faces ({sorted(fc)})")
if s["type"] == "turn":
if s.get("into") not in names:
raise ValueError(f"{path}: success.into {s.get('into')!r} is not an object (turn is "
f"measured about that body's axis)")
if not isinstance(s.get("min_deg"), (int, float)) or not 0 < s["min_deg"] < float("inf"):
raise ValueError(f"{path}: success.min_deg must be positive")
if s.get("direction", "cw") not in ("cw", "ccw", "any"):
raise ValueError(f"{path}: success.direction must be cw, ccw or any")
if s["type"] in ("insert", "separate"):
if "thread" in s:
if s["type"] != "insert" or not isinstance(s["thread"], dict):
raise ValueError(f"{path}: success.thread requires insert and a parameter object")
t = s["thread"]
for k in ("pitch_m", "min_turns", "max_tilt_deg", "pitch_tolerance_m"):
if not isinstance(t.get(k), (int, float)) or not 0 < t[k] < float('inf'):
raise ValueError(f"{path}: success.thread.{k} must be positive and finite")
if not isinstance(t.get("engagement_depth_m"), (int, float)) or not -float('inf') < t['engagement_depth_m'] < float('inf'):
raise ValueError(f"{path}: success.thread.engagement_depth_m must be finite")
if t['max_tilt_deg'] >= 90 or t['engagement_depth_m'] >= s.get('depth_m', -float('inf')):
raise ValueError(f"{path}: thread needs tilt < 90 degrees and engagement before final depth")
# The two criteria that read a second body, so the only ones whose
# task file can name an object that is not there. Caught here
# rather than at env.scene[...], which raises a KeyError naming an
# InteractiveScene key and not the task file that asked for it.
into = s.get("into")
if into not in seen:
raise ValueError(f"{path}: success.into must name an object in "
f"this file, got {into!r}; have {sorted(seen)}")
if into == target(spec)["name"]:
raise ValueError(f"{path}: success.into is the target itself "
f"({into!r}) — {s['type']} is a relation between "
f"two bodies")
if "through" in s:
# A through-bore (pipeline.ThroughSuccess): no one-sided depth -- the engagement
# along [lo, hi] is graded, so depth_m / max_depth_m / tail_max_depth_m do not apply.
th = s["through"]
if s["type"] != "insert" or not isinstance(th, dict) or "thread" in s:
raise ValueError(f"{path}: success.through requires insert, a parameter "
f"object, and no thread")
b = th.get("bore_m")
if not (isinstance(b, list) and len(b) == 2
and all(isinstance(c, (int, float)) for c in b) and b[1] > b[0]):
raise ValueError(f"{path}: success.through.bore_m must be [lo, hi], hi > lo")
me = th.get("min_engagement_m")
if not isinstance(me, (int, float)) or not 0 < me <= b[1] - b[0] + 1e-9:
raise ValueError(f"{path}: success.through.min_engagement_m must be in "
f"(0, {b[1] - b[0]}]")
for k in ("depth_m", "max_depth_m", "tail_max_depth_m"):
if k in s:
raise ValueError(f"{path}: success.{k} does not apply to a through-bore")
if s.get("tail_local") is None or not isinstance(s.get("clearance_m"), (int, float)):
raise ValueError(f"{path}: success.through needs tail_local and clearance_m")
ec = th.get("end_clearance_m")
if ec is not None and (not isinstance(ec, (int, float)) or ec <= 0):
raise ValueError(f"{path}: success.through.end_clearance_m must be positive")
for k in ((("clearance_m",) if "through" in s
else ("depth_m",) if s.get("lateral_box_m") else ("clearance_m", "depth_m"))
if s["type"] == "insert" else ("min_m",)):
if not isinstance(s.get(k), (int, float)):
raise ValueError(f"{path}: success.{k} must be a number")
# A through-hole shorter than the peg bounds the head from ABOVE too
# (past it the peg is out the far side), and can ask the TAIL to be
# on the axis as well, so the peg threads the bore rather than poking
# its tip near the axis at an angle. See pipeline.InsertSuccess.
md = s.get("max_depth_m")
if md is not None and (not isinstance(md, (int, float)) or md <= s.get("depth_m", float("inf"))):
raise ValueError(f"{path}: success.max_depth_m must be a number above "
f"depth_m ({s['depth_m']}), got {md!r}")
td = s.get("tail_max_depth_m")
if td is not None and (not isinstance(td, (int, float)) or s.get("tail_local") is None):
raise ValueError(f"{path}: success.tail_max_depth_m needs a number and tail_local")
def _is_xyz(v):
return len(v) == 3 and all(isinstance(c, (int, float)) for c in v)
for k in ("axis", "tail_local"):
v = s.get(k)
if v is not None and not _is_xyz(v):
raise ValueError(f"{path}: success.{k} must be three numbers, "
f"got {v!r}")
# head_local: one point, or a LIST of points for a part that goes in
# either end first (Factory's round peg). into_local likewise: one
# hole, or a LIST for a part with several a head may go into (the
# four corner holes of FurnitureBench's tabletop). Any of them counts.
for k in ("head_local", "into_local"):
v = s.get(k)
if v is not None and not (_is_xyz(v) or (
len(v) > 0 and all(isinstance(h, (list, tuple)) and _is_xyz(h)
for h in v))):
raise ValueError(f"{path}: success.{k} must be three numbers "
f"or a list of xyz points, got {v!r}")
# The headless self-test, if the file carries one. Checked for shape
# here so `collect_env --probe` fails at load rather than after a minute
# of Isaac Sim startup. What it MEANS is documented on collect_env's
# --probe flag; this only checks it is well-formed.
pr = spec.get("probe")
if pr is not None:
if not isinstance(pr, dict):
raise ValueError(f"{path}: probe must be an object")
_kinds = [k for k in ("joint", "joints", "pos", "poses") if k in pr]
if len(_kinds) != 1:
raise ValueError(f"{path}: probe needs exactly one of \"joint\" "
f"(a coordinate for the graded joints), \"joints\" "
f"({{name: coordinate}} for any joints), \"pos\" "
f"(a target position) or \"poses\" ({{object: "
f"{{pos, rot_xyzw, in|table}}}} for several), got "
f"{sorted(k for k in pr if not k.startswith('_'))}")
if "poses" in pr:
_pp = pr["poses"]
if not isinstance(_pp, dict) or not _pp:
raise ValueError(f"{path}: probe.poses must be a non-empty {{object: pose}}")
for _on, _v in _pp.items():
if _on not in names:
raise ValueError(f"{path}: probe.poses names {_on!r}, not an object")
if (not isinstance(_v, dict) or not isinstance(_v.get("pos"), list)
or len(_v["pos"]) != 3):
raise ValueError(f"{path}: probe.poses[{_on!r}] needs \"pos\": [x, y, z]")
if _v.get("in") is not None and _v["in"] not in names:
raise ValueError(f"{path}: probe.poses[{_on!r}].in {_v['in']!r} is not an object")
if "joint" in pr and not isinstance(pr["joint"], (int, float)):
raise ValueError(f"{path}: probe.joint must be a number")
if "joints" in pr:
jv = pr["joints"]
if (not isinstance(jv, dict) or not jv or not all(
isinstance(k, str) and isinstance(v, (int, float))
for k, v in jv.items())):
raise ValueError(f"{path}: probe.joints must be {{name: number}}")
# A bare key is a joint of the graded asset; "object:joint"
# names any articulated object's joint (a sequence task writes
# two props' nails at once).
have = joint_names(graded(spec), path)
miss = []
for k in jv:
if ":" in k:
on, jn = k.split(":", 1)
if on not in seen:
raise ValueError(f"{path}: probe.joints key {k!r} names an "
f"object not in this file")
o = next(x for x in objs if x["name"] == on)
if jn not in joint_names(o, path):
miss.append(k)
elif k not in have:
miss.append(k)
if miss:
raise ValueError(f"{path}: probe.joints {miss} are not joints of "
f"their objects ({graded(spec)['name']!r} has {have})")
if "pos" in pr:
for k in ("pos", "rot_xyzw"):
v = pr.get(k)
if k == "pos" or v is not None:
if v is None or len(v) != (3 if k == "pos" else 4):
raise ValueError(f"{path}: probe.{k} must be "
f"{3 if k == 'pos' else 4} numbers")
if pr.get("in") is not None and pr["in"] not in seen:
raise ValueError(f"{path}: probe.in must name an object in "
f"this file, got {pr['in']!r}")
cd = (spec.get("physics") or {}).get("condim")
if cd is not None and (isinstance(cd, bool) or cd not in (1, 3, 4, 6)):
raise ValueError(f"{path}: physics.condim must be 1, 3, 4 or 6, got {cd!r}")
return spec
def hand_sides(spec: dict | None, default: str = "both") -> tuple[str, ...]:
"""Which hands this task is driven with, in spawn order.
A task file's ``"hands"`` key, falling back to ``default`` (which is where
a typed ``--hand`` arrives). Always returns a tuple ordered as
:data:`SIDES`, because that order is the layout of
``observation.wrist_pose`` in the recorded dataset.
"""
want = ((spec or {}).get("hands") or default)
if want not in HAND_CHOICES:
raise ValueError(f"unknown hand selection {want!r}; "
f"expected one of {sorted(HAND_CHOICES)}")
return HAND_CHOICES[want]
def target(spec: dict) -> dict:
return next(o for o in spec["objects"] if o.get("role") == "target")
def step_object(obj: dict, step: dict) -> dict:
"""`obj` with its `joint.name` replaced by the step's `joint`, when the
step names one -- what the limit helpers read the joint from."""
jn = step.get("joint")
if jn is None:
return obj
return dict(obj, joint=dict(obj.get("joint") or {}, name=jn))
def step_label(step: dict) -> str:
"""The key a sequence step's joint is read under: "object" or
"object:joint"."""
return f"{step['of']}:{step['joint']}" if step.get("joint") else str(step["of"])
def graded(spec: dict) -> dict:
"""The object whose JOINT a joint criterion reads.
The target, unless ``success.of`` names another object. Nothing else in
the pipeline changes with it: the target is still the body the hand's
contact is counted against and the one spawned at /Object. For a
``joint_sequence`` it is the first step's object, so that object's
joints are the ones ``observation.object_joint_pos`` records.
"""
s = spec.get("success") or {}
if s.get("type") == "joint_sequence" and s.get("steps"):
return next(o for o in spec["objects"] if o["name"] == s["steps"][0]["of"])
of = s.get("of")
# `all` lists its sub-criteria under `of`, and `count` grades a set of
# objects: neither has ONE joint owner, so the target's joints are recorded.
if of is None or not isinstance(of, str) or s.get("type") in ("all", "count"):
return target(spec)
return next(o for o in spec["objects"] if o["name"] == of)
def per_object_voxel(spec: dict, default: float) -> dict[str, float]:
"""object name -> hydroelastic voxel size, for every object.
One number per object rather than one per scene: an 8 mm socket wants
0.25 mm and the hand does not, and the hand's SDFs are 31 of the shapes.
Newton already keeps the voxel size per shape; this is only where the
task file gets to say so.
"""
return {o["name"]: float(o.get("voxel_size", default))
for o in spec["objects"]}
def rigid_parts(spec: dict) -> dict[str, list[str]]:
"""object name -> collider substrings that stay rigid (no pressure field)."""
return {o["name"]: [str(k) for k in o["rigid_parts"]]
for o in spec["objects"] if o.get("rigid_parts")}
def per_object_kh(spec: dict) -> dict[str, float]:
"""object name -> hydroelastic modulus, for objects that set `kh`."""
return {o["name"]: float(o["kh"]) for o in spec["objects"] if "kh" in o}
def per_object_impedance(spec: dict) -> dict[str, float]:
"""object name -> MuJoCo contact impedance (solimp d0 = dmax), for
objects that set `contact_impedance`."""
return {o["name"]: float(o["contact_impedance"])
for o in spec["objects"] if "contact_impedance" in o}
def voxel_parts(spec: dict) -> dict[str, dict[str, float]]:
"""object name -> {collider substring: voxel size}, for objects that
name any. See the validation of ``voxel_size_parts`` in :func:`load`."""
return {o["name"]: {str(k): float(v) for k, v in o["voxel_size_parts"].items()}
for o in spec["objects"] if o.get("voxel_size_parts")}
def finest_voxel(spec: dict, default: float) -> dict[str, float]:
"""object name -> the SMALLEST voxel any of its colliders is sampled at.
What a penetration or clearance check should compare against: two
parts that mate do so on their finest grids, whatever the rest of the
body is sampled at.
"""
out = per_object_voxel(spec, default)
for name, parts in voxel_parts(spec).items():
out[name] = min(out[name], *parts.values())
return out
def _joint_limits(obj: dict, path: str = "") -> tuple[float, float, str]:
"""(lower, upper, kind) of the graded joint, in the coordinate's own SI
unit -- radians for a hinge, metres for a slide -- from the asset itself.
`joint_open` grades a FRACTION of a joint's travel, so it needs to know the
travel -- and the only honest source is the asset, not the task file. A
number copied into the task file is a second place for the joint's range to
live, and the ARCTIC assets are rebuilt from source with a ``--upper-deg``
that is expected to be retuned; a copy would go stale silently and the
criterion would quietly ask for a different share of the throw.
Read straight off the authored joint rather than from a composed stage: a
limit is an attribute, not a measurement, so there is nothing here that
needs the BBoxCache treatment ``half_height`` warns about. USD stores a
revolute limit in DEGREES and a prismatic one in metres; the coordinate
the criterion sees is radians or metres.
⚠️ Read from the asset AS VENDORED, before `scale` is baked. A prismatic
limit scales with the geometry (bake_scale does that at spawn), so the
metres returned here are multiplied by the object's `scale` to match what
the simulator will report. A revolute limit is scale-free.
"""
import math # noqa: PLC0415
from pxr import Usd, UsdPhysics # noqa: PLC0415
usd = resolve_usd(obj)
where = f"{path}: " if path else ""
if not os.path.exists(usd):
raise ValueError(f"{where}the target's asset is not there ({usd}). "
f"An ARCTIC asset is gitignored — rebuild it with the "
f"command in the task's \"_rebuild\" key.")
stage = Usd.Stage.Open(usd)
if stage is None:
raise ValueError(f"{where}could not open {usd}")
want = (obj.get("joint") or {}).get("name")
found = {}
for prim in stage.Traverse():
if prim.IsA(UsdPhysics.RevoluteJoint):
j = UsdPhysics.RevoluteJoint(prim)
found[prim.GetPath().name] = (
math.radians(float(j.GetLowerLimitAttr().Get() or 0.0)),
math.radians(float(j.GetUpperLimitAttr().Get() or 0.0)),
"revolute")
elif prim.IsA(UsdPhysics.PrismaticJoint):
j = UsdPhysics.PrismaticJoint(prim)
s = float(obj.get("scale", 1.0))
found[prim.GetPath().name] = (
float(j.GetLowerLimitAttr().Get() or 0.0) * s,
float(j.GetUpperLimitAttr().Get() or 0.0) * s,
"prismatic")
if not found:
raise ValueError(f"{where}{usd} has no revolute or prismatic joint, so "
f"there is no travel for success.type 'joint_open' "
f"to be a fraction of")
if want is not None and want not in found:
raise ValueError(f"{where}joint {want!r} is not in the asset, which "
f"has {sorted(found)}")
lo, hi, kind = found[want] if want is not None else next(iter(found.values()))
if abs(hi - lo) < 1e-6:
raise ValueError(f"{where}the graded joint's limits are both "
f"{lo:.4f}, so it has no travel to open through")
return lo, hi, kind
def joint_names(obj: dict, path: str = "") -> list[str]:
"""Every revolute or prismatic joint in the asset, by prim name."""
from pxr import Usd, UsdPhysics # noqa: PLC0415
usd = resolve_usd(obj)
where = f"{path}: " if path else ""
if not os.path.exists(usd):
raise ValueError(f"{where}the asset is not there ({usd})")
stage = Usd.Stage.Open(usd)
if stage is None:
raise ValueError(f"{where}could not open {usd}")
return sorted(p.GetPath().name for p in stage.Traverse()
if p.IsA(UsdPhysics.RevoluteJoint)
or p.IsA(UsdPhysics.PrismaticJoint))
def joint_travel(obj: dict, path: str = "") -> tuple[float, float]:
"""(lower, upper) of the graded joint: radians for a hinge, metres for a
slide. See :func:`_joint_limits`."""
lo, hi, _ = _joint_limits(obj, path)
return lo, hi
def joint_kind(obj: dict, path: str = "") -> str:
"""'revolute' or 'prismatic', for the graded joint."""
return _joint_limits(obj, path)[2]
def rotation_xyzw(obj: dict) -> tuple[float, float, float, float]:
"""Spawn rotation, XYZW.
⚠️ XYZW, and identity is ``(0, 0, 0, 1)`` -- Isaac Lab documents
``InitialStateCfg.rot`` as WXYZ but passes the tuple verbatim into an XYZW
slot for anything Newton drives, so the documented identity ``(1,0,0,0)``
arrives as a 180 degree turn about X. ``yaw_deg`` covers the common case;
``rot_xyzw`` is there for assets authored lying down, which is most
cylindrical ones.
The two COMPOSE: ``yaw_deg`` is applied about world +z on top of any
``rot_xyzw``, rather than being ignored when one is present. That matters
for the imported assets, whose ``rot_xyzw`` is printed by an importer and
is the thing to trust over the task file (see ``_rebuild`` in the ARCTIC
tasks) -- a scene-level correction has to be expressible WITHOUT editing
that quaternion into something nobody can check against the importer
again. No task set both before this, so nothing moved.
"""
import math
h = math.radians(float(obj.get("yaw_deg", 0.0))) / 2.0
yaw = (0.0, 0.0, math.sin(h), math.cos(h))
if "rot_xyzw" not in obj:
return yaw
q = [float(v) for v in obj["rot_xyzw"]]
n_ = math.sqrt(sum(v * v for v in q)) or 1.0
q = [v / n_ for v in q]
# yaw * q, XYZW: the yaw is a WORLD-frame turn, so it pre-multiplies.
ax, ay, az, aw = yaw
bx, by, bz, bw = q
return (aw * bx + ax * bw + ay * bz - az * by,
aw * by - ax * bz + ay * bw + az * bx,
aw * bz + ax * by - ay * bx + az * bw,
aw * bw - ax * bx - ay * by - az * bz)
def half_height(obj: dict) -> float:
"""Distance from an object's centre down to its lowest point.
This is what ``on_table`` needs, and getting it from the geometry is the
point: a task file that says "resting on the table" stays true when the
size changes.
"""
sh = obj.get("shape", "cuboid")
if sh == "cuboid":
return float(obj["size"][2]) / 2.0
if sh == "sphere":
return float(obj["radius"])
if sh in ("cylinder", "cone"):
return float(obj["height"]) / 2.0
if sh == "capsule":
return float(obj["height"]) / 2.0 + float(obj["radius"])
# A USD's extent is not known until it is composed, so the CALLER measures
# it (collect_env.seat_z, which also applies the spawn rotation). This is
# only the fallback for a file that states one.
return float(obj.get("half_height", 0.0))
def object_pos(spec: dict, obj: dict, table_x: float, table_y: float,
table_top: float) -> tuple[float, float, float]:
"""World spawn position, resolving `on_table` and table-relative xy."""
dx, dy = (obj.get("xy") or (0.0, 0.0))[:2]
z = (float(obj["z"]) if "z" in obj
else table_top + half_height(obj) + float(obj.get("clearance", 0.001)))
return (table_x + float(dx), table_y + float(dy), z)
# --------------------------------------------------------------- spawning ---
def resolve_usd(obj: dict) -> str:
"""Absolute path of an object's USD.
A RELATIVE path resolves against tasks/, which is where vendored assets
live -- that is what lets a task run on a machine with no DexVerse
checkout. An absolute path still works and is what you use while trying
an asset out, before importing it.
"""
p = os.path.expanduser(str(obj["usd"]))
return p if os.path.isabs(p) else os.path.normpath(os.path.join(TASKS_DIR, p))
def spawn_cfg(obj: dict, sim_utils, rigid_props, mass_props, collision_props,
usd_path: str | None = None):
"""The isaaclab spawn cfg for one object.
``usd_path`` overrides the file's own path, and the caller is expected to
pass the PREPARED asset: a USD spawned as-authored gets no SDF and no
``approximation = none``, so it loads, runs, looks right and records no
contact at all. See prepare_asset.prepare and DESIGN.md.
"""
sh = obj.get("shape", "cuboid")
# GRAVITY COMPENSATION, per object, through the MuJoCo solver's own
# body-level gravcomp. Wanted for a part that has to STAY where a blow
# leaves it: MuJoCo's joint friction is a soft constraint that leaks
# about a tenth of a steady load as creep (measured on the nail: 2 N of
# weight against 8 N of friction crept 10 mm/s), and no friction value
# fixes a leak that is a fraction of the load. Removing the load does.
gc = obj.get("gravity_compensation")
def _rp(**kw):
if gc is None:
return rigid_props(**kw)
return sim_utils.MujocoRigidBodyPropertiesCfg(gravcomp=float(gc), **kw)
# A FIXED object is scenery with a collider: it takes part in contact and
# nothing moves it. Same mechanism the table uses (SceneCfg.table), and for
# the same reason -- a 0.2 kg socket that a peg is being pushed into slides
# away, and the demo becomes a shove rather than an insertion. It stays a
# RigidObject, so the success criterion can still read its pose.
rp = _rp(kinematic_enabled=True) if obj.get("fixed") else _rp()
common = dict(rigid_props=rp,
mass_props=mass_props(mass=float(obj.get("mass", 0.1))),
collision_props=collision_props())
# A PRIMITIVE WITH NO MATERIAL IS THE SAME GREY AS THE TABLE, and a cube the
# operator cannot pick out of the surface it is sitting on is not a task
# they can perform. Isaac Lab authors no visual material by default, so an
# unstated colour is not "the asset's own look", it is the fallback. USD
# objects keep whatever they were authored with.
if sh not in ("usd", "articulation"):
common["visual_material"] = sim_utils.PreviewSurfaceCfg(
diffuse_color=tuple(float(c) for c in obj.get("color", DEFAULT_COLOR)),
roughness=float(obj.get("roughness", 0.6)),
metallic=0.0)
if sh == "articulation":
# No mass_props: the asset authors a mass per LINK, and one figure
# stamped over an articulation would give every part the whole
# object's mass. rigid_props still apply (they are per body).
return sim_utils.UsdFileCfg(
usd_path=usd_path or resolve_usd(obj),
rigid_props=_rp(), collision_props=collision_props(),
articulation_props=sim_utils.ArticulationRootPropertiesCfg(
fix_root_link=bool(obj.get("fixed_base", False)),
enabled_self_collisions=bool(obj.get("self_collisions", False))))
if sh == "usd":
return sim_utils.UsdFileCfg(usd_path=usd_path or resolve_usd(obj),
**common)
cls = getattr(sim_utils, SHAPES[sh][0])
if sh == "cuboid":
return cls(size=tuple(float(v) for v in obj["size"]), **common)
if sh == "sphere":
return cls(radius=float(obj["radius"]), **common)
return cls(radius=float(obj["radius"]), height=float(obj["height"]), **common)
def prim_path(obj: dict) -> str:
"""Where an object is spawned.
🔴 The target MUST be ``/Object``: the hand<->object broadphase filter and
the contact-pair statistics both select bodies whose label contains
``/Object``, so a target spawned anywhere else records contact that nothing
counts.
"""
return ("{ENV_REGEX_NS}/Object" if obj.get("role") == "target"
else "{ENV_REGEX_NS}/Prop_" + obj["name"])
def scene_dict(spec: dict, table_x: float, table_y: float, table_top: float,
placement: dict | None = None) -> dict:
"""The task's OBJECTS, for meta/scene.json. The table is described by the
caller, which owns the table geometry.
`placement` is name -> (pos, rot_xyzw) AS SPAWNED, and it wins over the
file: a USD object's height is measured from the composed asset, so
recomputing it here would write a different number into the dataset than
the physics used.
"""
out: dict = {}
for o in spec["objects"]:
pos, rot = (placement or {}).get(
o["name"], (object_pos(spec, o, table_x, table_y, table_top),
rotation_xyzw(o)))
rec = {"pos": tuple(pos), "rot_xyzw": tuple(rot),
"yaw_deg": float(o.get("yaw_deg", 0.0)),
"mass": float(o.get("mass", 0.1)), "role": o.get("role", "prop"),
# Whether anything can move it. A dataset that does not say so
# cannot be replayed: a kinematic socket and a 0.2 kg one that
# happened not to move look identical in the recorded poses.
"fixed": bool(o.get("fixed", False))}
# Only when the file pins one: the scene-wide value is recorded by
# the caller, and a key that is absent here means "that one".
if "voxel_size" in o:
rec["voxel_size"] = float(o["voxel_size"])
if o.get("voxel_size_parts"):
rec["voxel_size_parts"] = {str(k): float(v)
for k, v in o["voxel_size_parts"].items()}
# The NOMINAL pose is what `pos`/`rot_xyzw` above record. When the
# task randomizes this object, each episode's actual start pose is in
# meta/episodes.jsonl under `randomization`; this says it happened.
if o.get("randomize"):
rec["randomize"] = dict(o["randomize"])
if o.get("shape", "cuboid") in USD_SHAPES:
rec["usd"] = resolve_usd(o)
rec["usd_declared"] = o["usd"]
rec["scale"] = o.get("scale", 1.0)
else:
rec["primitive"] = o.get("shape", "cuboid")
for k in ("size", "radius", "height"):
if k in o:
rec[k] = o[k]
out[o["name"]] = rec
return out
def make_success(spec: dict, hold_steps: int, pipeline, joint_limits=None):
"""(criterion, task text) for the success block.
`joint_limits` = (lo, hi, "revolute"|"prismatic") stands in for reading the graded joint's
limits from its asset USD -- what tools/bddl_eval.py passes from a dataset's own
meta/assets/bodies.json, so a recording can be graded where the asset (and pxr) is not.
For a joint_sequence it is {step_label: (lo, hi, kind)}, one per step."""
s = spec["success"]
if s.get("no_carry"):
# No carrying (StaySupported): grade the criterion as written, but only
# while the object has stayed on the table / ledge.
nc = s["no_carry"]
crit, text, blurb = make_success({**spec, "success": {k: v for k, v in s.items()
if k != "no_carry"}},
hold_steps, pipeline, joint_limits)
if getattr(crit, "VALUE", "z") not in ("poses", "named_poses", "pose", "z"):
raise ValueError(f"success.no_carry cannot wrap a {crit.VALUE!r} criterion")
name = nc.get("object") or target(spec)["name"]
hx, hy, hz = (float(x) for x in nc["half_extents_m"])
corners = [(sx * hx, sy * hy, sz * hz) for sx in (-1, 1) for sy in (-1, 1)
for sz in (-1, 1)]
tb = spec.get("table") or {}
max_air = int(round(float(nc.get("max_air_s", 0.2)) * hold_steps
/ max(float(s.get("hold_s", 2.0)), 1e-9)))
wrapped = pipeline.StaySupported(
crit, name, corners, float(tb.get("top_z", TABLE_TOP_Z)),
float(nc["max_height_m"]), max_air, part=target(spec)["name"],
into=s.get("into"))
return (wrapped, text,
f"{blurb}; and {name} never carried: its lowest corner never more than "
f"{float(nc['max_height_m']) * 1e3:.0f} mm above the table for over "
f"{float(nc.get('max_air_s', 0.2)):g} s")
if s["type"] == "lift":
h = float(s["height_m"])
names = list(s.get("objects") or [])
if names:
# EVERY named object up at once -- the two-cube, one-per-hand check.
known = {o["name"] for o in spec["objects"]}
bad = [n for n in names if n not in known]
if bad:
raise ValueError(f"success.objects names {bad}, which are not in objects")
if s.get("max_hands_touching") is not None:
mh = int(s["max_hands_touching"])
return (pipeline.MultiLiftHandsSuccess(names, h, hold_steps, mh),
spec.get("task_text") or f"lift {' and '.join(names)} {h * 100:.0f} cm",
f"every one of {names} lifted {h * 100:.1f} cm above where it started, "
f"together, with at most {mh} hand(s) touching them throughout the hold")
return (pipeline.MultiLiftSuccess(names, h, hold_steps),
spec.get("task_text") or f"lift {' and '.join(names)} {h * 100:.0f} cm",
f"every one of {names} lifted {h * 100:.1f} cm above where it started, together")
return (pipeline.LiftSuccess(h, hold_steps),
spec.get("task_text") or f"lift the cube {h * 100:.0f} cm",
f"object lifted {h * 100:.1f} cm above where it started")
if s["type"] == "handover":
crit = pipeline.HandoverSuccess(
height_m=float(s.get("height_m", 0.08)), near_m=float(s.get("near_m", 0.06)),
far_m=float(s.get("far_m", 0.12)), hold_steps=hold_steps,
direction=str(s.get("direction", "any")))
return (crit,
spec.get("task_text") or "pick it up with one hand and hand it to the other",
f"the target, lifted {float(s.get('height_m', 0.08)) * 100:.0f} cm, taken by one "
f"hand and then held by the other ({s.get('direction', 'any')})")
if s["type"] == "reorient_face":
tgt = target(spec)
crit = pipeline.FaceNeighborSuccess(
face_colors=tgt.get("face_colors"),
tolerance_deg=float(s.get("tolerance_deg", 25.0)),
hold_steps=hold_steps,
require_resting=bool(s.get("require_resting", True)),
resting_tol_m=float(s.get("resting_tol_m", 0.01)),
up_color=s.get("up_color"), up_face=s.get("up_face"))
goal = s.get("up_color") or s.get("up_face")
return (crit,
spec.get("task_text")
or (f"roll the cube so the {goal} face is up" if goal
else "roll the cube onto a neighbouring colour"),
(f"the {goal} face is up within "
f"{s.get('tolerance_deg', 25.0):.0f} deg"
if goal else
"a face PERPENDICULAR to the one that started up is up within "
f"{s.get('tolerance_deg', 25.0):.0f} deg")
+ (" and the cube is resting again"
if s.get("require_resting", True) else "")
+ (" (any other colour does NOT count)" if goal
else " (the opposite face does NOT count)"))
if s["type"] == "joint_angle":
g = graded(spec)
js = s.get("joints")
label = (", ".join(js) if js
else str(g.get("joint", {}).get("name", "joint")))
crit = pipeline.JointAngleSuccess(
min_deg=float(s["min_deg"]), hold_steps=hold_steps,
direction=str(s.get("direction", "any")), label=label)
return (crit,
spec.get("task_text") or f"open it past {float(s['min_deg']):.0f} degrees",
(f"EVERY one of {g['name']}'s joints {js} moved"
if js else f"{g['name']}'s joint moved")
+ f" >= {float(s['min_deg']):.0f} deg from where it started "
f"({s.get('direction', 'any')})")
if s["type"] == "joint_open":
g = graded(spec)
lo, hi, kind = joint_limits if joint_limits is not None else _joint_limits(g)
frac = float(s["fraction"])
tool_speed = s.get("min_tool_speed_mps")
crit = pipeline.JointOpenSuccess(
lo=lo, hi=hi, fraction=frac, hold_steps=hold_steps,
direction=str(s.get("direction", "any")),
label=str(g.get("joint", {}).get("name", "joint")),
unit="m" if kind == "prismatic" else "rad",
min_tool_speed=None if tool_speed is None else float(tool_speed),
require_tool_contact=bool(s.get("require_tool_contact", False)),
# seconds -> steps at the rate the hold is counted in (hold_steps = hold_s * hz)
tool_contact_window_steps=int(round(float(s.get("tool_contact_window_s", 0.0))
* hold_steps / float(s.get("hold_s", 2.0)))))
need, u = crit._human(crit.need)
span, _ = crit._human(crit.span)
return (crit,
spec.get("task_text") or f"open it {frac:.0%} of the way",
f"{g['name']}'s joint moved >= {frac:.0%} of its "
f"{span:.1f} {u} authored travel ({need:.1f} {u}) from where "
f"it started ({s.get('direction', 'any')})"
+ ("" if tool_speed is None else
f", counting only travel delivered while the tool was "
f"moving >= {float(tool_speed):.2f} m/s"))
if s["type"] == "joint_sequence":
steps = []
blurb = []
for st in s["steps"]:
o = next(x for x in spec["objects"] if x["name"] == st["of"])
lo, hi, kind = (joint_limits[step_label(st)] if isinstance(joint_limits, dict)
else _joint_limits(step_object(o, st)))
unit = "m" if kind == "prismatic" else "rad"
d = {"name": step_label(st), "direction": st["direction"], "unit": unit}
hu = (lambda v: f"{v * 1e3:.0f} mm") if unit == "m" else (lambda v: f"{math.degrees(v):.0f} deg")
if "to" in st:
d["to"] = float(st["to"])
blurb.append(f"{step_label(st)} {st['direction']}d to {hu(float(st['to']))}")
else:
d["need"] = abs(hi - lo) * float(st["fraction"])
blurb.append(f"{step_label(st)} {st['direction']}d >= "
f"{float(st['fraction']):.0%} of its {hu(abs(hi - lo))} travel")
steps.append(d)
crit = pipeline.JointSequenceSuccess(steps, hold_steps)
return (crit,
spec.get("task_text") or " then ".join(
f"{st['direction']} {st['of']}" for st in s["steps"]),
" THEN ".join(blurb) + " (each step latches; the last is held)")
if s["type"] == "insert" and "through" in s:
# A through-bore: the peg's centreline inside it, either end first, either mouth.
th = s["through"]
crit = pipeline.ThroughSuccess(
bore_m=tuple(th["bore_m"]), min_engagement_m=float(th["min_engagement_m"]),
head_local=tuple(s["head_local"]), tail_local=tuple(s["tail_local"]),
axis_local=tuple(s.get("axis", (1.0, 0.0, 0.0))),
clearance_m=float(s["clearance_m"]), hold_steps=hold_steps, into=str(s["into"]),
into_local=tuple(s.get("into_local", (0.0, 0.0, 0.0))),
end_clearance_m=th.get("end_clearance_m"))
lo, hi = (float(x) for x in th["bore_m"])
full = abs(float(th["min_engagement_m"]) - (hi - lo)) < 1e-9
return (crit,
spec.get("task_text") or f"insert it into the {s['into']}",
(f"the peg all the way through the {s['into']}" if full else
f"the peg >= {float(th['min_engagement_m']) * 1e3:.0f} mm into the "
f"{s['into']}'s {abs(hi - lo) * 1e3:.0f} mm bore")
+ f", either end first, from either side, within "
f"{float(s['clearance_m']) * 1e3:.0f} mm of its axis")
if s["type"] == "insert":
cls = pipeline.ThreadSuccess if "thread" in s else pipeline.InsertSuccess
crit = cls(
**s.get("thread", {}),
head_local=tuple(s.get("head_local", (0.1, 0.0, 0.0))),
axis_local=tuple(s.get("axis", (1.0, 0.0, 0.0))),
clearance_m=float(s.get("clearance_m", 0.0)),
depth_m=float(s["depth_m"]),
hold_steps=hold_steps, into=str(s["into"]),
into_local=tuple(s.get("into_local", (0.0, 0.0, 0.0))),
max_depth_m=s.get("max_depth_m"),
tail_local=(None if s.get("tail_local") is None else tuple(s["tail_local"])),
tail_max_depth_m=s.get("tail_max_depth_m"),
**({"lateral_box_m": s["lateral_box_m"]} if s.get("lateral_box_m") else {}))
where = (f"inside the box {s['lateral_box_m']} (m) of the {s['into']}'s frame"
if s.get("lateral_box_m") else
f"within {float(s['clearance_m']) * 1e3:.0f} mm of the {s['into']}'s axis")
return (crit,
spec.get("task_text") or f"insert it into the {s['into']}",
f"the target's head is {where} and "
f"{float(s['depth_m']) * 1e3:.0f} mm past its "
+ ("origin" if "into_local" not in s else
f"point {tuple(s['into_local'])}")
+ (f" (and no more than {float(s['max_depth_m']) * 1e3:.0f} mm)"
if s.get("max_depth_m") is not None else "")
+ (" with its tail on the axis too" if s.get("tail_local") is not None else "")
+ (f" and its tail no farther than {float(s['tail_max_depth_m']) * 1e3:.0f} mm along the axis"
if s.get("tail_max_depth_m") is not None else "")
+ (f" after {s['thread']['min_turns']:g} net turns following the thread pitch"
if "thread" in s else ""))
if s["type"] == "turn":
crit = pipeline.TurnSuccess(
axis_local=tuple(s.get("axis_local", (0.0, 0.0, 1.0))), min_deg=float(s["min_deg"]),
hold_steps=hold_steps, direction=str(s.get("direction", "cw")),
max_offset_m=float(s.get("max_offset_m", 0.003)), into=str(s["into"]),
label=target(spec)["name"])
return (crit,
spec.get("task_text") or f"turn it on the {s['into']}",
f"{target(spec)['name']} turned >= {float(s['min_deg']):.0f} deg "
f"{s.get('direction', 'cw')} about the {s['into']}'s axis "
f"{tuple(s.get('axis_local', (0.0, 0.0, 1.0)))}, still seated on it")
if s["type"] == "separate":
crit = pipeline.SeparateSuccess(
head_local=tuple(s.get("head_local", (0.0, 0.0, 0.0))),
min_m=float(s["min_m"]), hold_steps=hold_steps, into=str(s["into"]),
into_local=tuple(s.get("into_local", (0.0, 0.0, 0.0))))
return (crit,
spec.get("task_text") or f"take it off the {s['into']}",
f"the target's head at least {float(s['min_m']) * 1e3:.1f} mm from "
f"its seat on the {s['into']}"
+ ("" if "into_local" not in s else f" (point {tuple(s['into_local'])})")
+ ", in any direction")
if s["type"] == "axis_upright":
crit = pipeline.AxisUprightSuccess(
tuple(s.get("axis", (0, 0, 1))), float(s.get("tolerance_deg", 20.0)), hold_steps)
if s.get("of"):
crit = pipeline.NamedPoseCriterion(crit, s["of"])
return (crit,
spec.get("task_text") or "stand it upright",
f"{s.get('of') or 'the target'}'s local axis {s.get('axis')} within "
f"{s.get('tolerance_deg', 20.0):.0f} deg of vertical")
if s["type"] == "pose_target":
tb = spec.get("table") or {}
txy = tb.get("pos", TABLE_POS)
name = s.get("of") or target(spec)["name"]
crit = pipeline.PoseTargetSuccess(
name, (float(txy[0]), float(txy[1]), float(tb.get("top_z", TABLE_TOP_Z))), hold_steps,
goal_xy=s.get("goal_xy"), tol_m=float(s.get("tol_m", 0.02)), region=s.get("region"),
goal_yaw_deg=s.get("goal_yaw_deg"), tol_deg=float(s.get("tol_deg", 15.0)),
symmetry=int(s.get("symmetry", 1)), displace_m=s.get("displace_m"),
goal_of=s.get("goal_of"))
parts = []
if s.get("goal_of") is not None:
parts.append(f"on {s['goal_of']} (its origin within "
f"{float(s.get('tol_m', 0.02)) * 1e3:.0f} mm, its facing within "
f"{s.get('tol_deg', 15.0)} deg, symmetry {s.get('symmetry', 1)})")
if s.get("goal_xy") is not None:
parts.append(f"within {float(s.get('tol_m', 0.02)) * 1e3:.0f} mm of table point "
f"{tuple(s['goal_xy'])}")
if s.get("region"):
parts.append(f"inside table-frame region {s['region']}")
if s.get("goal_yaw_deg") is not None:
parts.append(f"facing {s['goal_yaw_deg']} deg within {s.get('tol_deg', 15.0)} "
f"(symmetry {s.get('symmetry', 1)})")
if s.get("displace_m") is not None:
parts.append(f"moved >= {float(s['displace_m']) * 1e3:.0f} mm from its start")
return (crit, spec.get("task_text") or f"move the {name} to its goal",
f"{name} " + " and ".join(parts))
if s["type"] == "all":
subs, blurbs = [], []
tname = target(spec)["name"]
for sub in s["of"]:
part = sub.get("part") or tname
sub_spec = dict(spec, success=dict(sub, hold_s=0.0))
if sub["type"] in ("pose_target", "axis_upright") and "of" not in sub:
sub_spec["success"]["of"] = part
c, _, b = make_success(sub_spec, 1, pipeline, joint_limits)
subs.append((c, part, sub.get("into")))
blurbs.append(f"[{part}] {b}")
return (pipeline.AllSuccess(subs, hold_steps),
spec.get("task_text") or "assemble every part",
" AND ".join(blurbs) + ", all at once")
if s["type"] == "count":
crit = pipeline.CountSuccess(
s["objects"], s["into"], int(s["need"]), hold_steps, mode=s.get("mode", "insert"),
holes=s.get("holes"), axis=tuple(s.get("axis", (0.0, 0.0, 1.0))),
head_local=tuple(s.get("head_local", (0.0, 0.0, 0.0))),
clearance_m=float(s.get("clearance_m", 0.003)), depth_m=float(s.get("depth_m", 0.01)),
center_local=tuple(s.get("center_local", (0.0, 0.0, 0.0))),
radius_m=float(s.get("radius_m", 0.05)), z_m=tuple(s.get("z_m", (-0.05, 0.05))),
max_tilt_deg=s.get("max_tilt_deg"), up_local=tuple(s.get("up_local", (0.0, 0.0, 1.0))),
max_depth_m=s.get("max_depth_m"))
return (crit, spec.get("task_text") or f"put {s['need']} of them in the {s['into']}",
f"{s['need']} of {len(s['objects'])} objects "
+ (f"inserted in the {s['into']}'s holes" if s.get("mode", "insert") == "insert"
else f"inside the {s['into']}") + ", together")
raise ValueError(f"success.type {s['type']!r} is declared in the schema "
f"but not wired into make_success yet")
HAND_KEYS = ("finger_kp", "finger_kd", "effort_limit", "hand_friction", "hand_mass",
"torsional_friction", "finger_error_cap", "armature",
"wrist_kp", "wrist_kd", "wrist_rot_authority", "wrist_rot_zeta",
"wrist_max_torque", "wrist_max_force")
def hand_path() -> str:
return os.path.join(TASKS_DIR, "hand.json")
def load_hand() -> dict:
"""The universal hand settings, or {} if tasks/hand.json is absent."""
p = hand_path()
if not os.path.exists(p):
return {}
with open(p) as fh:
d = json.load(fh)
return {k: float(d[k]) for k in HAND_KEYS if k in d}
def save_hand(values: dict) -> str:
"""Write hand values back, keeping the file's notes."""
p = hand_path()
d = json.load(open(p)) if os.path.exists(p) else {}
for k, v in values.items():
if k in HAND_KEYS:
d[k] = float(v)
with open(p, "w") as fh:
json.dump(d, fh, indent=1)
return p
def save_task_object(spec_path: str, obj_name: str, mass=None, friction=None) -> str:
"""Write a tuned object mass / friction into a task file, in place."""
d = json.load(open(spec_path))
for o in d["objects"]:
if o["name"] == obj_name:
if mass is not None:
o["mass"] = float(mass)
if friction is not None:
o["friction"] = float(friction)
with open(spec_path, "w") as fh:
json.dump(d, fh, indent=1)
return spec_path
def physics_overrides(spec: dict) -> dict:
"""CLI arg name -> value, for the flags a task file may pin."""
out = {}
ph = spec.get("physics") or {}
for key, arg in (("friction", "friction"),
("hand_friction", "hand_friction"), ("kh", "kh"),
("voxel_size", "voxel_size"), ("physics_hz", "physics_hz"),
("effort_limit", "effort_limit"),
("torsional_friction", "torsional_friction"),
("finger_kp", "finger_kp"), ("finger_kd", "finger_kd"),
("finger_error_cap", "finger_error_cap"),
("solref_timeconst", "solref_timeconst")):
if key in ph:
out[arg] = float(ph[key])
# MuJoCo solver substeps: an integer, and the one physics knob that sets
# how HARD a contact can be (the refsafe floor is 2 x the solver dt). A
# contact-thread task pins 2; see tools/mj_substeps.py.
if "mj_substeps" in ph:
out["mj_substeps"] = int(ph["mj_substeps"])
# Contact dimensionality on every shape (1, 3, 4 or 6); 4 unless pinned.
if "condim" in ph:
out["condim"] = int(ph["condim"])
if "hold_s" in (spec.get("success") or {}):
out["success_hold_s"] = float(spec["success"]["hold_s"])
return out
def per_object_friction(spec: dict) -> dict[str, float]:
"""object name -> friction, for the objects that pin their own."""
return {o["name"]: float(o["friction"])
for o in spec["objects"] if "friction" in o}
def per_object_rolling_friction(spec: dict) -> dict[str, float]:
"""object name -> rolling friction [m] (MuJoCo's third friction
coefficient: resisting torque = value x normal force), for the objects
that ask for it. Those objects' shapes get condim 6; the solver takes the
max of a pair's condim and coefficients, so every contact they make
resists rolling and no other contact changes."""
return {o["name"]: float(o["rolling_friction"])
for o in spec["objects"] if "rolling_friction" in o}
def per_object_base_mass(spec: dict) -> dict[str, float]:
"""object name -> mass [kg] of an ARTICULATION's root link (its housing:
the machine body, the cabinet carcass), for the objects that ask for it.
An articulation authors a mass per link, so "mass" cannot apply; this sets
the one link that makes the object heavy and leaves the moving parts (a
door, a lever) at their authored mass. Yuemin, 2026-10-01: "objects like
book shelf and coffee machine are really heavy, so either increase their
weight or attach them to the table"."""
out = {}
for o in spec["objects"]:
if "base_mass" not in o:
continue
if o.get("shape") != "articulation":
raise ValueError(f"{spec.get('name')}: {o['name']!r} has base_mass but is not "
f"an articulation -- use mass")
out[o["name"]] = float(o["base_mass"])
return out
# ------------------------------------------------------- randomization ---
def randomization(spec: dict) -> dict[str, dict]:
"""object name -> {"xy": (rx, ry), "yaw": (lo, hi)} for every object
whose task file carries a ``randomize`` block.
The block is written per OBJECT, because which parts of a scene may move
is a property of the task: the peg is free to start anywhere within reach,
the socket it goes into is bolted down, and the two gears already seated
on their shafts must stay exactly where the base's shafts are::
"randomize": {"xy_m": 0.12, "yaw_deg": 180}
"randomize": {"xy_m": [0.05, 0.02], "yaw_deg": [-30, 30]}
"randomize": {"like": "gear_base"}
``xy_m`` is a half-range (uniform in ``[-r, +r]`` on each axis, metres,
relative to the object's nominal ``xy``); a pair gives x and y their own.
``yaw_deg`` is a half-range about the nominal yaw, or an explicit
``[lo, hi]``. Height is never randomized: ``on_table`` already puts the
object on the table, and a yaw about +z or a slide across it keeps it
there. Anything absent is zero.
``min_separation_m`` is RETIRED (Richard, 2026-10-02: "As long as two
object does not overlap, it is a fine initial state"): a centre-to-centre
distance kept every pair a conservative circle apart. Objects are now
drawn independently and the scene is drawn again only when two of them
actually OVERLAP -- see :func:`footprints` and :func:`sample_offsets`.
The key is ignored if an old meta/task.json carries it.
``min_gap_m`` is NOT that key come back: it is a clearance on top of the
no-overlap rule, for an object whose contact reaches past its mesh -- a
2 mm SDF and a solver margin make a draw that is 0.2 mm clear of its
neighbour a draw that starts in contact (hammer_nail, 2026-10-25: the
hammer spawned resting on the nail block). The pair is drawn again unless
their outlines are at least the larger of the two objects' gaps apart.
``{"like": <other object>}`` takes that object's DRAW rather than a range
of its own, so the two move as one rigid group. Some scenes are only
randomizable that way: gear_mesh spawns the large and small gears already
seated on the base's shafts, and nut_thread_contact spawns the nut
registered on the bolt's thread five pitches up. An independent draw on
the base would leave its gears hanging in the air; a shared one carries
them. A ``like`` chain must end at an object with real ranges, and a
cycle raises.
A follower may also vary ABOUT its place in the group: ``rel_xy_m``
(a half-range, ``[rx, ry]``, or ``[[x_lo, x_hi], [y_lo, y_hi]]``) and
``rel_yaw_deg`` (a half-range or ``[lo, hi]``, about its own centre) are
drawn in the NOMINAL layout's frame, before the group's draw moves and
turns the whole group -- so the box of pivot_box_against_wall_fixed starts
in front of the wall's ledge at a varied distance, offset and heading
(Richard, 2026-10-03: "no variance of relative pose between box and
wall"). Such a follower is no longer rigid with its source, so the
overlap check tests it against its source like any other pair.
"""
out: dict[str, dict] = {}
names = {o.get("name") for o in spec.get("objects", [])}
for o in spec.get("objects", []):
r = o.get("randomize")
if not r:
continue
if "like" in r:
src = r["like"]
if src not in names:
raise ValueError(f"{o['name']}: randomize.like names {src!r}, "
f"which this task does not have ({sorted(names)})")
if src == o["name"]:
raise ValueError(f"{o['name']}: randomize.like names itself")
out[o["name"]] = {"like": src}
if "rel_xy_m" in r or "rel_yaw_deg" in r:
rel = r.get("rel_xy_m", 0.0)
if isinstance(rel, (int, float)):
rel = [float(rel), float(rel)]
axes = []
for v in list(rel)[:2]:
lo, hi = ((float(v[0]), float(v[1])) if isinstance(v, (list, tuple))
else (-float(v), float(v)))
axes.append((lo, hi))
ry = r.get("rel_yaw_deg", 0.0)
ylo, yhi = ((float(ry[0]), float(ry[1])) if isinstance(ry, (list, tuple))
else (-float(ry), float(ry)))
if len(axes) != 2 or any(hi < lo for lo, hi in axes) or yhi < ylo:
raise ValueError(f"{o['name']}: randomize.rel_xy_m / rel_yaw_deg must be "
f"half-ranges or ordered [lo, hi] pairs (got {r})")
out[o["name"]].update(rel_xy=tuple(axes), rel_yaw=(ylo, yhi))
continue
if "region" in r:
# ANYWHERE the robot can reach: the centre uniform over the table
# (less edge_margin_m, so the part does not hang off) and inside
# the task's workspace. Not a range about the nominal pose -- the
# nominal only matters for a run with randomization off.
if r["region"] != "workspace":
raise ValueError(f"{o['name']}: randomize.region must be \"workspace\", "
f"got {r['region']!r}")
if "xy_m" in r:
raise ValueError(f"{o['name']}: randomize.region replaces xy_m; give one")
if not spec.get("workspace"):
raise ValueError(f"{o['name']}: randomize.region \"workspace\" needs the "
f"task to name a \"workspace\"")
yaw = r.get("yaw_deg", 180.0)
lo, hi = ((float(yaw[0]), float(yaw[1])) if isinstance(yaw, (list, tuple))
else (-float(yaw), float(yaw)))
edge = float(r.get("edge_margin_m", 0.05))
if hi < lo or edge < 0:
raise ValueError(f"{o['name']}: randomize ranges must be non-negative (got {r})")
out[o["name"]] = {"region": "workspace", "xy": (0.0, 0.0), "yaw": (lo, hi),
"edge": edge}
out[o["name"]].update(_min_gap(o, r))
# Per-object reach rule over the workspace file's own "require":
# "both" = where BOTH arms reach (a fixture in a two-handed task,
# tools/make_fixed_variants.py), "any" = either arm, an arm's name
# (e.g. "right") = that arm alone (a one-handed fixture, worked by
# the operator's dominant hand).
if "reach" in r:
if not isinstance(r["reach"], str) or not r["reach"]:
raise ValueError(f"{o['name']}: randomize.reach must be \"both\", "
f"\"any\" or an arm's name, got {r['reach']!r}")
out[o["name"]]["reach"] = r["reach"]
continue
xy = r.get("xy_m", 0.0)
if isinstance(xy, (list, tuple)):
rx, ry = (float(xy[0]), float(xy[1])) if len(xy) >= 2 else (float(xy[0]),) * 2
else:
rx = ry = float(xy)
yaw = r.get("yaw_deg", 0.0)
if isinstance(yaw, (list, tuple)):
lo, hi = float(yaw[0]), float(yaw[1])
else:
lo, hi = -float(yaw), float(yaw)
if rx < 0 or ry < 0 or hi < lo:
raise ValueError(f"{o['name']}: randomize ranges must be non-negative "
f"half-ranges or an ordered [lo, hi] (got {r})")
if rx or ry or hi != lo:
out[o["name"]] = {"xy": (rx, ry), "yaw": (lo, hi), **_min_gap(o, r)}
return out
def _min_gap(o: dict, r: dict) -> dict:
"""``{"gap": metres}`` from a randomize block's ``min_gap_m``, or nothing."""
if "min_gap_m" not in r:
return {}
g = r["min_gap_m"]
if not isinstance(g, (int, float)) or isinstance(g, bool) or g < 0:
raise ValueError(f"{o['name']}: randomize.min_gap_m must be a number >= 0, got {g!r}")
return {"gap": float(g)}
def nominal_xy(spec: dict) -> dict[str, tuple[float, float]]:
"""Every object's nominal table-relative ``xy`` -- what the separation
check in :func:`sample_offsets` measures the draws from. Objects with no
``randomize`` block are in it too: a drawn part must keep clear of a
fixed one just as much as of another drawn one."""
return {o["name"]: tuple(float(v) for v in (o.get("xy") or (0.0, 0.0))[:2])
for o in spec.get("objects", [])}
def describe_randomization(rand: dict[str, dict]) -> str:
"""The one-line summary of a :func:`randomization` spec, in its order.
A FOLLOWER (``randomize.like``) carries no ranges of its own -- it takes
its source's draw -- so it has nothing to print but the source it follows.
Reading ranges out of every entry is what used to crash the run banner on
the two group-randomized tasks (gear_mesh, nut_thread_contact).
"""
def one(n: str, r: dict) -> str:
if "like" in r:
if r.get("rel_xy"):
(xl, xh), (yl, yh) = r["rel_xy"]
return (f"{n} follows {r['like']}, then x [{xl * 1e3:+.0f}, {xh * 1e3:+.0f}] "
f"y [{yl * 1e3:+.0f}, {yh * 1e3:+.0f}] mm, yaw [{r['rel_yaw'][0]:+.0f}, "
f"{r['rel_yaw'][1]:+.0f}] deg about its place")
return f"{n} follows {r['like']}"
if r.get("region"):
return (f"{n} anywhere reachable"
+ (" by BOTH arms" if r.get("reach") == "both"
else f" by the {r['reach']} arm" if r.get("reach") not in (None, "any")
else "")
+ f" on the table ({r['edge'] * 1e3:.0f} mm from its "
f"edge), yaw [{r['yaw'][0]:+.0f}, {r['yaw'][1]:+.0f}] deg")
return (f"{n} xy ±{r['xy'][0] * 1e3:.0f}/±{r['xy'][1] * 1e3:.0f} mm, "
f"yaw [{r['yaw'][0]:+.0f}, {r['yaw'][1]:+.0f}] deg")
return "; ".join(one(n, r) for n, r in rand.items())
def sample_offsets(rng, rand: dict[str, dict], scale: float = 1.0,
nominal_xy: dict[str, tuple] | None = None,
tries: int = 1000, workspace: dict | None = None,
table_half_m=None, reject=None,
footprints: dict | None = None) -> dict[str, dict]:
"""One draw per randomized object: ``{name: {"dx", "dy", "dyaw_deg"}}``.
``rng`` is a ``numpy.random.Generator``; ``scale`` multiplies every range
(0 disables the draw without touching the task file, which is what
``--randomize-scale 0`` is for). Objects are drawn in the order the task
file lists them, so a seed reproduces a session exactly.
``footprints`` (:func:`footprints`, with ``nominal_xy``) turns on the
OVERLAP check: every object is drawn independently, and a scene in which
any two objects interpenetrate -- in plan (their convex outlines) AND in
height -- is discarded and the WHOLE scene drawn again (Richard,
2026-10-02: no minimum distance, only no overlap). The joint draw stays
uniform over the layouts that fit, and a seed still reproduces the
session because the rejected draws are part of its sequence. An object
and its followers (``randomize.like``) are one rigid group and are not
checked against each other; objects that are not randomized are checked
where they stand. After ``tries`` rejections the scene cannot be laid out
on this table, and that is an error in the task file, not a layout to
fall back on.
``workspace`` (:func:`load_workspace`, the task's ``"workspace"`` file)
adds a second rejection on the same terms: a scene with any object's
centre -- followers included, at the spot their orbit puts them -- out of
the robot's reach is drawn again. It needs ``nominal_xy``.
With ``footprints`` and ``table_half_m``, a scene with any object's
outline past the table's edge is drawn again too (:func:`off_table`).
``reject`` -- ``reject(draw) -> bool`` -- is a last, caller-supplied test
on the same terms (the whole scene drawn again). collect_env passes one
that refuses a scene putting any object's bounding box on a hand: a
FIXED object drawn onto a hand traps it -- the wrist cannot push out of an
immovable body, and the gesture gate reads the trapped pinch as a grasp,
so neither reset nor skip fires (Richard, 2026-10-01).
"""
if any(r.get("region") for r in rand.values()):
if workspace is None or nominal_xy is None or table_half_m is None:
raise ValueError("randomize.region needs the workspace, nominal_xy and "
"table_half_m")
# Every rule about WHERE an object may start is about its outline's CENTRE, not its
# origin (Richard, 2026-10-21: "is the center within the workspace or is some corner
# as the anchor within the workspace?"): an asset's origin can sit at a hinge or an
# edge -- the ARCTIC box's is 15 cm from its middle -- so placing the origin put the
# body up to that far outside the band. Without footprints the origin stands in.
offsets = outline_centres(footprints) if footprints else {}
ctx = {"workspace": workspace, "nominal_xy": nominal_xy, "table_half_m": table_half_m,
"centre_offset": offsets}
for _ in range(max(1, int(tries))):
out = _draw_once(rng, rand, scale, ctx)
if nominal_xy is None:
return out
if footprints and overlapping(out, rand, nominal_xy, footprints):
continue
if footprints and table_half_m is not None and off_table(out, nominal_xy, footprints,
table_half_m):
continue
if reject is not None and reject(out):
continue
if workspace is None:
return out
centres = placed_centres(out, nominal_xy, offsets)
radii = {n: r["edge"] for n, r in rand.items() if r.get("region")}
if not any(reach_excess(xy, _reach_ws(workspace, rand.get(n, {})),
radii.get(n, 0.0)) > 0.0 for n, xy in centres.items()):
return out
raise ValueError(f"randomize: {tries} draws and none kept every object "
+ (f"within {workspace.get('name', 'the workspace')}'s reach, "
if workspace is not None else "")
+ "off the others and off the hands -- the objects do not fit "
"where they may be drawn")
#: Interpenetration (metres, in plan and in height at once) below which two
#: objects count as touching, not overlapping: a nominal layout may set one
#: part against another, and a hull's facets are not exact to a millimetre.
OVERLAP_TOL_M = 0.002
def _hull2(pts):
"""Convex hull of 2-D points, counter-clockwise, as an (N, 2) array."""
import numpy as np
pts = np.unique(np.round(np.asarray(pts, dtype=float).reshape(-1, 2), 6), axis=0)
if len(pts) < 3:
return pts
try:
from scipy.spatial import ConvexHull # noqa: PLC0415
return pts[ConvexHull(pts).vertices]
except Exception: # noqa: BLE001 (collinear, or no scipy)
pts = pts[np.lexsort((pts[:, 1], pts[:, 0]))]
def half(seq):
h = []
for p in seq:
while len(h) >= 2 and ((h[-1][0] - h[-2][0]) * (p[1] - h[-2][1])
- (h[-1][1] - h[-2][1]) * (p[0] - h[-2][0])) <= 0:
h.pop()
h.append(p)
return h
lo, up = half(pts), half(pts[::-1])
return np.array(lo[:-1] + up[:-1])
def _rotate_points(pts, q_xyzw):
import numpy as np
x, y, z, w = (float(v) for v in q_xyzw)
r = np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - z * w), 2 * (x * z + y * w)],
[2 * (x * y + z * w), 1 - 2 * (x * x + z * z), 2 * (y * z - x * w)],
[2 * (x * z - y * w), 2 * (y * z + x * w), 1 - 2 * (x * x + y * y)]])
return np.asarray(pts, dtype=float) @ r.T
def _primitive_points(obj: dict):
"""Points spanning a primitive's surface, in its own frame."""
import numpy as np
sh = obj.get("shape", "cuboid")
if sh == "cuboid":
hx, hy, hz = (float(v) / 2.0 for v in obj["size"])
return np.array([[x, y, z] for x in (-hx, hx) for y in (-hy, hy) for z in (-hz, hz)])
a = np.linspace(0.0, 2 * np.pi, 32, endpoint=False)
ring = np.stack([np.cos(a), np.sin(a), np.zeros_like(a)], axis=1)
r = float(obj.get("radius", 0.0))
if sh == "sphere":
return np.concatenate([ring * r, [[0, 0, r], [0, 0, -r]]])
h = float(obj.get("height", 0.0)) / 2.0 + (r if sh == "capsule" else 0.0)
return np.concatenate([ring * r + [0, 0, h], ring * r - [0, 0, h]])
def _usd_points_cached(usd: str, mtime: float):
"""Every mesh point of an asset (and the box of any other gprim), in the
asset's root frame -- what collect_env.link_lows measures the seat from."""
import numpy as np
from pxr import Usd, UsdGeom # noqa: PLC0415
key = (usd, mtime)
if key in _USD_POINTS:
return _USD_POINTS[key]
stage = Usd.Stage.Open(usd)
if stage is None:
raise ValueError(f"could not open {usd}")
chunks = []
# Instance proxies too: a YCB asset keeps its mesh in an instanced
# prototype (collect_env de-instances it before spawning, see _staged).
for prim in stage.Traverse(Usd.TraverseInstanceProxies()):
if not prim.IsA(UsdGeom.Gprim):
continue
xf = np.array(UsdGeom.Xformable(prim).ComputeLocalToWorldTransform(0)).T
if prim.IsA(UsdGeom.Mesh):
pts = UsdGeom.Mesh(prim).GetPointsAttr().Get()
if not pts:
continue
p = np.asarray(pts, dtype=float)
else:
ext = UsdGeom.Boundable.ComputeExtentFromPlugins(UsdGeom.Boundable(prim),
Usd.TimeCode.Default())
if not ext:
continue
lo, hi = np.asarray(ext[0], float), np.asarray(ext[1], float)
p = np.array([[x, y, z] for x in (lo[0], hi[0]) for y in (lo[1], hi[1])
for z in (lo[2], hi[2])])
chunks.append((xf[:3, :3] @ p.T).T + xf[:3, 3])
if not chunks:
raise ValueError(f"{usd}: no geometry to measure a footprint from")
pts = np.concatenate(chunks)
# Only the outline and the height range matter: keep the 3-D points that
# can be on either (the 2-D hull's points and the extremes in z).
keep = set(range(len(pts)))
try:
from scipy.spatial import ConvexHull # noqa: PLC0415
keep = set(ConvexHull(pts).vertices.tolist())
except Exception: # noqa: BLE001
pass
pts = pts[sorted(keep)]
_USD_POINTS[key] = pts
return pts
_USD_POINTS: dict = {}
def footprint(obj: dict, table_top: float | None = None) -> dict:
"""An object's OUTLINE ON THE TABLE at its nominal spawn: ``{"hull": (N, 2)
convex outline about its own nominal xy, "z": (lo, hi) world heights}``.
From the geometry the scene is built from -- a primitive's size, a USD's
mesh points scaled and turned by the spawn rotation (the nominal
``yaw_deg`` included) -- and seated the way collect_env seats it, so its
lowest point is on the table. A draw only turns it about +z and slides
it, which moves the outline rigidly and leaves the heights alone.
Convex: a rack, a shelf or a box is its outline, filled -- a part drawn
INTO one is not a starting layout anyway (that is what ``like`` is for).
An articulation is measured as authored, every link where the asset
puts it."""
import numpy as np
table_top = TABLE_TOP_Z if table_top is None else float(table_top)
sh = obj.get("shape", "cuboid")
if sh in USD_SHAPES:
usd = resolve_usd(obj)
pts = _usd_points_cached(usd, os.path.getmtime(usd)) * float(obj.get("scale", 1.0))
else:
pts = _primitive_points(obj)
pts = _rotate_points(pts, rotation_xyzw(obj))
zlo, zhi = float(pts[:, 2].min()), float(pts[:, 2].max())
if "z" in obj:
z0 = float(obj["z"])
else:
z0 = table_top - zlo + float(obj.get("clearance", 0.002 if sh in USD_SHAPES else 0.001))
return {"hull": _hull2(pts[:, :2]), "z": (z0 + zlo, z0 + zhi)}
def footprints(spec: dict, table_top: float | None = None) -> dict[str, dict]:
""":func:`footprint` of every object in a task, for :func:`sample_offsets`.
Needs pxr for a USD object (Isaac's python, or usd-core)."""
return {o["name"]: footprint(o, table_top) for o in spec.get("objects", [])}
def _groups(rand: dict[str, dict]) -> dict[str, str]:
"""object -> the root of its rigid group (itself, or what it follows)."""
def root(n, seen=()):
r = rand.get(n) or {}
src = r.get("like")
if r.get("rel_xy"): # varies about its source: not rigid with it
return n
return n if not src or src in seen else root(src, seen + (n,))
return {n: root(n) for n in rand}
def placed_outlines(draw: dict[str, dict], nominal_xy: dict[str, tuple],
footprints_: dict[str, dict]) -> dict:
"""Every object's outline (table frame, (N, 2)) after one draw -- turned
about its own nominal centre, or about its source's for a follower,
exactly as :func:`offset_pose` turns the body."""
import numpy as np
out = {}
for n, fp in footprints_.items():
if n not in nominal_xy:
continue
pts = np.asarray(fp["hull"], dtype=float) + np.asarray(nominal_xy[n], dtype=float)
d = draw.get(n)
if d is not None:
piv = np.asarray(nominal_xy[d["pivot"]] if d.get("pivot") else nominal_xy[n], float)
a = math.radians(float(d["dyaw_deg"]))
c, sn = math.cos(a), math.sin(a)
pts = (pts - piv) @ np.array([[c, sn], [-sn, c]]) + piv + [d["dx"], d["dy"]]
out[n] = pts
return out
def _penetration(a, b, full: bool = False) -> float:
"""How deep two convex outlines interpenetrate (separating-axis test):
<= 0 means apart. ``full`` keeps going past the first separating axis,
so a negative result is the widest separation over every edge normal --
never more than the true distance between the outlines."""
import numpy as np
best = float("inf")
for poly in (a, b):
if len(poly) < 2:
continue
e = np.roll(poly, -1, axis=0) - poly
nrm = np.stack([-e[:, 1], e[:, 0]], axis=1)
ln = np.linalg.norm(nrm, axis=1)
nrm = nrm[ln > 1e-12] / ln[ln > 1e-12, None]
pa, pb = a @ nrm.T, b @ nrm.T
ov = np.minimum(pa.max(0), pb.max(0)) - np.maximum(pa.min(0), pb.min(0))
best = min(best, float(ov.min()))
if best <= 0 and not full:
return best
return best
def overlapping(draw: dict[str, dict], rand: dict[str, dict],
nominal_xy: dict[str, tuple], footprints_: dict[str, dict],
tol: float = OVERLAP_TOL_M) -> list[tuple[str, str]]:
"""The pairs of objects that overlap after this draw -- in plan by more
than ``tol`` AND in height by more than ``tol``. Pairs inside one rigid
group (a source and its followers) are skipped. A pair where either
object has a ``gap`` (randomize.min_gap_m) must instead be at least the
larger gap apart in plan."""
outl = placed_outlines(draw, nominal_xy, footprints_)
grp = _groups(rand)
names = list(outl)
hits = []
for i, a in enumerate(names):
for b in names[i + 1:]:
if grp.get(a, a) == grp.get(b, b):
continue
za, zb = footprints_[a]["z"], footprints_[b]["z"]
if min(za[1], zb[1]) - max(za[0], zb[0]) <= tol:
continue
gap = max((rand.get(a) or {}).get("gap", 0.0), (rand.get(b) or {}).get("gap", 0.0))
if gap > 0.0:
if _penetration(outl[a], outl[b], full=True) > -gap:
hits.append((a, b))
elif _penetration(outl[a], outl[b]) > tol:
hits.append((a, b))
return hits
def off_table(draw: dict[str, dict], nominal_xy: dict[str, tuple], footprints_: dict[str, dict],
table_half_m, tol: float = OVERLAP_TOL_M) -> list[str]:
"""The objects whose drawn OUTLINE reaches past the table's edge by more
than ``tol``. ``edge_margin_m`` keeps a region draw's centre a circle in
from the edge, but a follower rides its source and has no margin of its
own: pivot_box_against_wall_fixed's box, 24 cm in front of a wall drawn
near an edge, hung off the table and fell at spawn (Richard, 2026-10-03)."""
import numpy as np
th = table_half_m
hx, hy = (float(th), float(th)) if isinstance(th, (int, float)) else (float(th[0]), float(th[1]))
outl = placed_outlines(draw, nominal_xy, footprints_)
return [n for n, pts in outl.items()
if (np.abs(pts[:, 0]).max() > hx + tol) or (np.abs(pts[:, 1]).max() > hy + tol)]
def _reach_ws(workspace: dict | None, r: dict) -> dict | None:
"""The workspace an object is checked against: its own ``reach`` rule
(randomize.reach) over the file's ``require``."""
if workspace is None or not r.get("reach"):
return workspace
if r["reach"] in ("both", "any"):
return dict(workspace, require=r["reach"])
arms = [a for a in workspace["arms"] if a.get("name") == r["reach"]]
if not arms:
raise ValueError(f"randomize.reach {r['reach']!r}: {workspace.get('name', 'the workspace')} "
f"has no such arm ({[a.get('name') for a in workspace['arms']]})")
return dict(workspace, arms=arms, require="any")
def reach_cover(xy, workspace: dict, band_m: float) -> float:
"""How well a spot is inside reach, 0..1: per arm, how deep it is inside
that arm's annulus (from reach_m inward and from min_reach_m outward) over
``band_m``, smoothed; combined over the arms as the workspace's
``require`` says -- "any": covered if ANY arm covers it well (1 - the
product of the shortfalls), so the inner edge of one arm's reach costs
nothing where the other arm is deep; "both": the product."""
import math
per = []
for a in workspace["arms"]:
d = math.hypot(float(xy[0]) - float(a["base_xy"][0]),
float(xy[1]) - float(a["base_xy"][1]))
depth = min(float(a["reach_m"]) - d, d - float(a.get("min_reach_m", 0.0)))
t = min(1.0, max(0.0, depth / float(band_m)))
per.append(t * t * (3.0 - 2.0 * t)) # smoothstep
if not per:
return 0.0
out = 1.0
if workspace.get("require", "any") == "both":
for v in per:
out *= v
return out
for v in per:
out *= (1.0 - v)
return 1.0 - out
def _region_xy(rng, r: dict, ctx: dict) -> tuple[float, float]:
"""A centre on the table (less the edge margin) and inside the workspace.
With the workspace's ``focus`` (Richard, 2026-10-02: weight the centre,
since the far regions mostly vary the pick-up, not the task): a 2-D
Gaussian about the focus point, cut to the table and the reach by
rejection -- every reachable spot can still be drawn, the far ones less
often. Without one: uniform, by rejection over the table square."""
th = ctx["table_half_m"]
hx, hy = (float(th), float(th)) if isinstance(th, (int, float)) else (float(th[0]), float(th[1]))
hx, hy = hx - float(r["edge"]), hy - float(r["edge"])
if hx <= 0 or hy <= 0:
raise ValueError(f"edge_margin_m {r['edge']} leaves no table")
ws = ctx["workspace"]
focus = (ws or {}).get("_focus")
wsr = _reach_ws(ws, r)
for _ in range(10000):
if focus:
x = float(rng.normal(focus["xy"][0], focus["sigma_m"]))
y = float(rng.normal(focus["xy"][1], focus["sigma_m"]))
if abs(x) > hx or abs(y) > hy:
continue
else:
x, y = float(rng.uniform(-hx, hx)), float(rng.uniform(-hy, hy))
if reach_excess((x, y), wsr, float(r["edge"])) > 0.0:
continue
if focus and focus.get("edge_band_m"):
# ...and thinned near the edge of reach (Richard, 2026-10-02):
# kept with probability reach_cover(), so a spot only one arm
# just reaches comes up rarely and one the other arm covers well
# does not lose anything.
if float(rng.uniform()) >= reach_cover((x, y), wsr, focus["edge_band_m"]):
continue
return x, y
raise ValueError("randomize.region: no reachable spot on the table after 10000 draws")
def _draw_once(rng, rand: dict[str, dict], scale: float, ctx: dict | None = None) -> dict[str, dict]:
"""One unchecked draw -- see :func:`sample_offsets`."""
out: dict[str, dict] = {}
for name in rand: # dict order == task file order
if "like" in rand[name]:
continue # resolved below, after its source
(rx, ry), (lo, hi) = rand[name]["xy"], rand[name]["yaw"]
s = float(scale)
if rand[name].get("region"):
# scale 0 (--randomize-scale 0, --probe) is the nominal pose; any
# other scale is the whole region -- a region has no half-range
# to shrink.
if s == 0.0:
out[name] = {"dx": 0.0, "dy": 0.0, "dyaw_deg": 0.0}
continue
# the point drawn is the outline's CENTRE (uniform over the region); the
# heading after it, as before, so a seed's sequence is unchanged; then the
# origin that puts the centre there at that heading
x, y = _region_xy(rng, rand[name], ctx or {})
dyaw = float(rng.uniform(lo, hi)) if hi != lo else 0.0
ox, oy = (ctx.get("centre_offset") or {}).get(name, (0.0, 0.0))
c, sn = math.cos(math.radians(dyaw)), math.sin(math.radians(dyaw))
nx, ny = ctx["nominal_xy"][name]
out[name] = {"dx": x - (c * ox - sn * oy) - nx, "dy": y - (sn * ox + c * oy) - ny,
"dyaw_deg": dyaw}
continue
dx = float(rng.uniform(-rx, rx)) * s if rx else 0.0
dy = float(rng.uniform(-ry, ry)) * s if ry else 0.0
dyaw = float(rng.uniform(lo, hi)) * s if hi != lo else 0.0
out[name] = {"dx": dx, "dy": dy, "dyaw_deg": dyaw}
# Followers take their source's draw. Resolved after every range has been
# drawn so the RNG sequence -- and therefore a seed -- does not depend on
# the order followers happen to appear in.
# 🔴 A follower takes its source's draw AND its source's PIVOT. A shared
# yaw applied in place turns each object about its own centre, which for
# a gear seated on a shaft 55 mm from the base's centre leaves it 5 mm off
# the shaft (measured -- the probe's "randomization takes" check found it).
# A rigid group turns about ONE point, so the follower carries the name of
# the object it orbits and offset_pose does the orbit.
# A follower that varies about its place (rel_xy_m / rel_yaw_deg) draws
# its own jitter here, in task-file order after every range, and is then
# written as an ordinary draw about its OWN nominal centre (no pivot):
# moved by the jitter in the nominal layout, then carried round the
# source's pivot by the source's draw.
jit = {}
for n in rand:
r = rand[n]
if "like" in r and r.get("rel_xy"):
s = float(scale)
(xl, xh), (yl, yh) = r["rel_xy"]
yl_, yh_ = r["rel_yaw"]
jit[n] = (float(rng.uniform(xl, xh)) * s if xh != xl else 0.0,
float(rng.uniform(yl, yh)) * s if yh != yl else 0.0,
float(rng.uniform(yl_, yh_)) * s if yh_ != yl_ else 0.0)
pending = [n for n in rand if "like" in rand[n]]
while pending:
progressed = False
for n in list(pending):
src = rand[n]["like"]
if src in out:
if n in jit:
nom = (ctx or {}).get("nominal_xy")
if nom is None:
raise ValueError(f"{n}: randomize.rel_xy_m needs nominal_xy")
d = out[src]
px, py = (nom[d["pivot"]] if d.get("pivot") else nom[src])
fx, fy = nom[n][0] + jit[n][0], nom[n][1] + jit[n][1]
c, sn = math.cos(math.radians(d["dyaw_deg"])), math.sin(math.radians(d["dyaw_deg"]))
ox, oy = fx - px, fy - py
cx, cy = px + c * ox - sn * oy + d["dx"], py + sn * ox + c * oy + d["dy"]
out[n] = {"dx": cx - nom[n][0], "dy": cy - nom[n][1],
"dyaw_deg": d["dyaw_deg"] + jit[n][2]}
else:
out[n] = dict(out[src], pivot=src)
pending.remove(n)
progressed = True
if not progressed:
raise ValueError(f"randomize.like cannot be resolved for "
f"{sorted(pending)}: a cycle, or it follows an "
f"object with no ranges of its own")
return out
#: The table: 1.0 m DEEP (x, away from the operator) by 1.2 m WIDE (y, along
#: the edge the operator -- and the robot -- stand at), top at 0.90 m, centred
#: so its near edge stays 0.10 m in front of where the operator stands (world
#: x = 0.10). It was a 0.9 m square centred at x = 0.55 until 2026-09-28.
TABLE_SIZE = (1.0, 1.2)
TABLE_POS = (0.60, -0.20)
TABLE_TOP_Z = 0.90
TABLE_THICKNESS = 0.05
#: What every task SHARES (Richard, 2026-09-29: "all hands/table must share
#: parameters"). A task file under tasks/ may not carry a "table" block or
#: pin any of these physics keys -- they are the table's (friction is the
#: table's and the scene default) and the hand's (kh, voxel_size, condim,
#: rate). The shared values are collect_env's flag defaults and hand.json. A
#: dataset's own meta/task.json still may: it records what that session ran.
SHARED_PHYSICS = ("friction", "kh", "voxel_size", "physics_hz", "condim",
"mj_substeps", "hand_friction", "torsional_friction",
"finger_kp", "finger_kd", "finger_error_cap", "effort_limit",
"solref_timeconst")
def shared_violations(spec: dict) -> list[str]:
"""How a task file breaks the collection rules of 2026-09-29 (Richard):
(1) nothing fixed to the table, (2) bimanual, (3) every object drawn
anywhere in the workspace at any heading, as furniture_one_leg, and (4)
one table and one hand for every task. Empty when it keeps them.
An object may stay fixed only if it says why in ``_why_fixed_exception``
(push_t's goal outline: no collider, a mark on the table, not a part).
A follower (``randomize.like``) is drawn with its source and exempt.
A FIXED VARIANT (``"variant": {"kind": "fixed", "of": <free task>}``,
written by tools/make_fixed_variants.py; Richard 2026-10-01: keep a free
and a fixed version of each task with a fixture) may fix its fixtures
and draw them at a small heading range; translation is still drawn over
the workspace, and every object that is NOT fixed keeps rule (3).
"""
out = []
fixed_variant = (spec.get("variant") or {}).get("kind") == "fixed"
if "table" in spec:
out.append('carries a "table" block (the table is shared: '
"task_spec.TABLE_* and collect_env's --table-* defaults)")
pinned = sorted(k for k in (spec.get("physics") or {}) if k in SHARED_PHYSICS)
if pinned:
out.append(f"pins shared physics {pinned} (hand.json / collect_env defaults)")
if spec.get("hands", "both") != "both":
out.append(f'"hands" is {spec.get("hands")!r}, not "both"')
if not spec.get("workspace"):
out.append('names no "workspace" (randomize.region needs one)')
for o in spec.get("objects") or []:
n = o.get("name")
if o.get("_why_fixed_exception"):
continue
is_fixed = bool(o.get("fixed") or o.get("fixed_base"))
if (is_fixed and not fixed_variant) or o.get("gravity_compensation"):
out.append(f"{n!r} is fixed/welded/weightless (nothing is fixed to the table)")
r = o.get("randomize") or {}
if "like" in r:
continue
if is_fixed and fixed_variant:
if r.get("region") != "workspace":
out.append(f"{n!r} (a fixture of a fixed variant) is not drawn over the "
f'workspace (randomize {{"region": "workspace", ...}})')
continue
if r.get("region") != "workspace" or float(r.get("yaw_deg", 0)) != 180.0:
out.append(f"{n!r} is not drawn over the whole workspace at any yaw "
f'(randomize {{"region": "workspace", "yaw_deg": 180, ...}})')
return out
def table_dims(size=None) -> tuple[float, float]:
"""``(x, y)`` extent of the table top, from whichever form ``size`` takes:
None (the default), one number (a square -- every dataset before
2026-09-28), a list ``[x, y]`` or ``[x, y, thickness]``, or the
collector's ``--table-size`` string ``"x,y"`` / ``"s"``."""
if size is None:
return TABLE_SIZE
if isinstance(size, str):
size = [float(v) for v in size.split(",") if v.strip()]
if isinstance(size, (int, float)):
return float(size), float(size)
size = [float(v) for v in size]
if len(size) == 1:
return size[0], size[0]
return size[0], size[1]
def table_half(spec: dict | None) -> tuple[float, float]:
"""Half the table's x and y extent for a task (its "table" block, else the default)."""
sx, sy = table_dims(((spec or {}).get("table") or {}).get("size"))
return sx / 2.0, sy / 2.0
def load_workspace(spec: dict, path: str | None = None) -> dict | None:
"""The robot workspace a task names under ``"workspace"``, or None.
``"workspace"`` is a file name under ``tasks/workspaces/`` (or a path
relative to the task file). The workspace is the robot that will LEARN
from the demos, not anything in the scene: its arms' bases and planar
reach, in the table frame every object's ``xy`` is written in. See
``tasks/workspaces/flexiv_rizon4_bimanual.json``.
"""
import json
ref = spec.get("workspace")
if not ref:
return None
here = os.path.dirname(os.path.abspath(path or spec.get("_path") or
os.path.join(TASKS_DIR, "x.json")))
cands = [os.path.join(TASKS_DIR, "workspaces", ref),
os.path.join(here, ref), os.path.join(here, "workspaces", ref)]
f = next((c for c in cands if os.path.exists(c)), None)
if f is None:
raise ValueError(f"workspace {ref!r} not found (looked in {cands})")
with open(f) as fh:
ws = json.load(fh)
if ws.get("frame", "table") != "table":
raise ValueError(f"{f}: only the table frame is supported, got {ws.get('frame')!r}")
if ws.get("require", "any") not in ("any", "both"):
raise ValueError(f"{f}: require must be \"any\" or \"both\"")
arms = ws.get("arms") or []
if not arms:
raise ValueError(f"{f}: no arms")
for a in arms:
lo, hi = float(a.get("min_reach_m", 0.0)), float(a["reach_m"])
if float(a.get("keepout_m", 0.0)) < 0.0:
raise ValueError(f"{f}: arm {a.get('name')!r} keepout_m must be >= 0")
if not 0.0 <= lo < hi or len(a.get("base_xy", ())) != 2:
raise ValueError(f"{f}: arm {a.get('name')!r} needs base_xy [x, y] "
f"and 0 <= min_reach_m < reach_m")
ws["_file"] = f
fo = ws.get("focus")
if fo:
sig = float(fo.get("sigma_m", 0.0))
if sig <= 0.0:
raise ValueError(f"{f}: focus.sigma_m must be > 0")
c = fo.get("center", "reach_centroid")
if c == "reach_centroid":
c = reach_centroid(ws, table_half(spec))
elif not (isinstance(c, (list, tuple)) and len(c) == 2):
raise ValueError(f"{f}: focus.center must be [x, y] or \"reach_centroid\"")
band = float(fo.get("edge_band_m", 0.0))
if band < 0.0:
raise ValueError(f"{f}: focus.edge_band_m must be >= 0")
ws["_focus"] = {"xy": (float(c[0]), float(c[1])), "sigma_m": sig, "edge_band_m": band}
return ws
def reach_centroid(workspace: dict, table_half_m, step: float = 0.01) -> tuple[float, float]:
"""The centre of the part of the table the workspace reaches (a 1 cm
grid, 5 cm in from the edges) -- the focus of the draws by default, so it
follows the robot's mounting when that is measured."""
hx, hy = (float(v) - 0.05 for v in table_half_m)
sx = sy = n = 0.0
nx, ny = int(round(2 * hx / step)) + 1, int(round(2 * hy / step)) + 1
for i in range(nx):
x = -hx + i * step
for j in range(ny):
y = -hy + j * step
if reach_excess((x, y), workspace) <= 0.0:
sx, sy, n = sx + x, sy + y, n + 1
if not n:
raise ValueError(f"{workspace.get('name', 'workspace')}: reaches no part of the table")
return round(sx / n, 3), round(sy / n, 3)
def reach_excess(xy, workspace: dict, radius: float = 0.0) -> float:
"""How far ``xy`` (table frame) is outside the workspace, metres; <= 0
means reachable. Per arm, the distance outside its annulus (beyond
``reach_m``, or inside ``min_reach_m``); combined over arms by
``require``: "any" takes the best arm, "both" the worst."""
import math
per, keep = [], -float("inf")
for a in workspace["arms"]:
d = math.hypot(float(xy[0]) - float(a["base_xy"][0]),
float(xy[1]) - float(a["base_xy"][1]))
per.append(max(d - float(a["reach_m"]),
float(a.get("min_reach_m", 0.0)) - d))
# every arm's KEEP-OUT counts, whichever arm does the reaching: with
# require "any", a spot inside the left arm's min_reach is still
# "reachable" by the right arm -- and that spot is the left arm's
# own base, which no object can occupy
# ...and the keep-out is from the object's EDGE, not its centre: a
# tabletop centred just outside it would still sit on the base
keep = max(keep, float(a.get("keepout_m", 0.0)) + float(radius) - d)
reach = min(per) if workspace.get("require", "any") == "any" else max(per)
return max(reach, keep)
def out_of_reach(centres: dict, workspace: dict, radii: dict | None = None) -> list[str]:
"""The objects whose centre is out of reach (or whose footprint, of radius
``radii[name]``, reaches into a base's keep-out), in ``centres`` order."""
radii = radii or {}
return [n for n, xy in centres.items()
if reach_excess(xy, workspace, radii.get(n, 0.0)) > 0.0]
def band_outline(workspace: dict, table_half_m, n: int = 1441, tol: float = 1e-6) -> list[tuple[str, str, float, list]]:
"""The OUTLINE of where object centres may be drawn, as arc segments in the table frame:
``[(arm name, "reach" | "min", radius, [(theta0, theta1), ...]), ...]`` -- each arm's
outer (reach_m) and inner (min_reach_m) circle, kept only where that circle IS the
region's edge: inside every other arm's band for require "both" (their intersection),
outside every other arm's band for "any" (their union), and on the table. Richard,
2026-10-21: draw the boundary of the intersection, not each arm's full arc."""
import math
hx, hy = (float(table_half_m), float(table_half_m)) if isinstance(table_half_m, (int, float)) \
else (float(table_half_m[0]), float(table_half_m[1]))
arms = workspace.get("arms") or []
both = workspace.get("require", "any") == "both"
def inside(a, x, y):
d = math.hypot(x - float(a["base_xy"][0]), y - float(a["base_xy"][1]))
return float(a.get("min_reach_m", 0.0)) - tol <= d <= float(a["reach_m"]) + tol
out = []
for a in arms:
bx, by = float(a["base_xy"][0]), float(a["base_xy"][1])
others = [b for b in arms if b is not a]
for kind, r in (("reach", float(a["reach_m"])), ("min", float(a.get("min_reach_m", 0.0)))):
if r <= 0.0:
continue
th = [-math.pi + 2 * math.pi * k / (n - 1) for k in range(n)]
def keep(t):
x, y = bx + r * math.cos(t), by + r * math.sin(t)
if abs(x) > hx or abs(y) > hy:
return False
if both:
return all(inside(b, x, y) for b in others)
return not any(inside(b, x, y) for b in others)
k = [keep(t) for t in th]
segs = [(th[i], th[i + 1]) for i in range(n - 1) if k[i] and k[i + 1]]
if segs:
out.append((a.get("name", "?"), kind, r, segs))
return out
def outline_centres(footprints_: dict[str, dict]) -> dict[str, tuple[float, float]]:
"""Each object's outline centre (area centroid of its footprint hull) relative to its
origin, table frame, at its nominal heading: what a draw keeps inside the workspace."""
import numpy as np
out = {}
for n, f in (footprints_ or {}).items():
h = np.asarray(f["hull"], dtype=float)
if len(h) < 3:
out[n] = (float(h[:, 0].mean()), float(h[:, 1].mean())) if len(h) else (0.0, 0.0)
continue
x, y = h[:, 0], h[:, 1]
xs, ys = np.roll(x, -1), np.roll(y, -1)
cr = x * ys - xs * y
a = cr.sum() / 2.0
if abs(a) < 1e-12:
out[n] = (float(x.mean()), float(y.mean()))
continue
out[n] = (float(((x + xs) * cr).sum() / (6 * a)), float(((y + ys) * cr).sum() / (6 * a)))
return out
def placed_centres(draw: dict[str, dict], nominal_xy: dict[str, tuple],
offsets: dict[str, tuple] | None = None) -> dict:
"""Every object's outline CENTRE after one draw (table frame): its origin where
:func:`drawn_centres` puts it, plus its outline-centre offset turned by the draw's
heading. With no offsets this is drawn_centres."""
import math
out = drawn_centres(draw, nominal_xy)
for n, (x, y) in list(out.items()):
ox, oy = (offsets or {}).get(n, (0.0, 0.0))
a = math.radians((draw.get(n) or {}).get("dyaw_deg", 0.0))
out[n] = (x + math.cos(a) * ox - math.sin(a) * oy, y + math.sin(a) * ox + math.cos(a) * oy)
return out
def drawn_centres(draw: dict[str, dict], nominal_xy: dict[str, tuple]) -> dict:
"""Every object's table-frame ORIGIN after one draw (see :func:`placed_centres` for
the outline centre the workspace rules use) -- a follower where its
orbit about its source's centre puts it (as :func:`offset_pose` places it),
an undrawn object at its nominal."""
import math
out = {}
for n, (x, y) in nominal_xy.items():
d = draw.get(n)
if d is None:
out[n] = (x, y)
continue
if d.get("pivot"):
px, py = nominal_xy[d["pivot"]]
c, sn = math.cos(math.radians(d["dyaw_deg"])), math.sin(math.radians(d["dyaw_deg"]))
ox, oy = x - px, y - py
x, y = px + c * ox - sn * oy, py + sn * ox + c * oy
out[n] = (x + d["dx"], y + d["dy"])
return out
def offset_pose(pos, rot_xyzw, dx: float, dy: float, dyaw_deg: float,
pivot_xy=None):
"""The nominal spawn pose moved by one draw: ``(pos, rot_xyzw)``.
The yaw is a WORLD-frame turn about +z, so it pre-multiplies the spawn
quaternion exactly the way ``yaw_deg`` does in :func:`rotation_xyzw`, and
the offset is added in world x/y. Height is untouched (see
:func:`randomization`).
``pivot_xy`` turns the object about that world point instead of about its
own centre -- what a shared draw (``randomize.like``) needs, since a rigid
group turns about one point and a gear seated 55 mm off the base's centre
has to travel round it.
"""
import math
h = math.radians(float(dyaw_deg)) / 2.0
ax, ay, az, aw = 0.0, 0.0, math.sin(h), math.cos(h)
bx, by, bz, bw = (float(v) for v in rot_xyzw)
rot = (aw * bx + ax * bw + ay * bz - az * by,
aw * by - ax * bz + ay * bw + az * bx,
aw * bz + ax * by - ay * bx + az * bw,
aw * bw - ax * bx - ay * by - az * bz)
px, py = float(pos[0]), float(pos[1])
if pivot_xy is not None:
c, sn = math.cos(math.radians(float(dyaw_deg))), math.sin(math.radians(float(dyaw_deg)))
ox, oy = px - float(pivot_xy[0]), py - float(pivot_xy[1])
px = float(pivot_xy[0]) + c * ox - sn * oy
py = float(pivot_xy[1]) + sn * ox + c * oy
p = (px + float(dx), py + float(dy), float(pos[2]))
return p, rot
"""Task definitions as data: one JSON file per task, under tasks/.
Why
---
A task used to be spread across three places in ``collect_env.py`` that had to
agree and nothing checked: the function that spawns the assets, the branch that
picks the success criterion, and the dict that describes the scene for
``meta/scene.json``. Change the cube's size in one and the dataset says the
other. A task file is the single place: the scene, the physics, and what
counts as success, in one document that is also copied into every dataset the
task produces.
A file looks like this (see ``tasks/cube_pickup.json``)::
{
"name": "cube_pickup",
"description": "pick the cube up off the table",
"table": {"size": [0.9, 0.9, 0.05], "top_z": 0.90, "pos": [0.55, -0.2]},
"objects": [
{"name": "cube", "role": "target", "shape": "cuboid",
"size": [0.06, 0.06, 0.06], "mass": 0.1,
"on_table": true, "xy": [0.0, 0.0], "yaw_deg": 0.0,
"friction": 1.0}
],
"success": {"type": "lift", "height_m": 0.10, "hold_s": 5.0},
"physics": {"friction": 1.0}
}
Conventions that keep a file honest:
* ``on_table`` places an object by its own geometry -- it is dropped so its
underside rests on the table top, with a 1 mm gap. Writing an absolute z is
allowed (``"z"``) but then a change to the table height silently floats or
buries it.
* ``xy`` is relative to the table centre, so moving the table moves the task.
* Exactly one object carries ``"role": "target"``. It is the one the success
criterion reads and the one the hand<->object contact filter looks for, and
it must land at the prim path ``/Object`` for either to work.
* ``hands`` is ``"both"``. Collection has been bimanual only since
2026-09-28: a task that needs one hand is still recorded with two, the
other free, and the collector refuses a task file that names one side.
``"right"`` / ``"left"`` still LOAD, because this reader also opens the
``meta/task.json`` of datasets recorded before that.
* Anything absent falls back to the CLI default, and startup prints what was
used. A task file never has to restate the whole world.
"""
from __future__ import annotations
import json
import math
import os
TASKS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
"tasks")
#: shape name -> (isaaclab spawner attribute, the kwarg carrying its size)
SHAPES = {
"cuboid": ("MeshCuboidCfg", "size"),
"sphere": ("MeshSphereCfg", "radius"),
"cylinder": ("MeshCylinderCfg", None), # radius + height
"capsule": ("MeshCapsuleCfg", None),
"cone": ("MeshConeCfg", None),
}
SUCCESS_TYPES = ("lift", "handover", "axis_upright", "reorient_face", "joint_angle",
"joint_open", "joint_sequence", "insert", "separate", "pose_target", "count",
"all", "turn")
#: What an `all` may hold: criteria graded on poses (no joint criteria yet).
ALL_SUB_TYPES = ("lift", "axis_upright", "insert", "separate", "pose_target", "count")
#: The operator's hands, in the order they are spawned and recorded. Same
#: order as ``embodiment.openxr.tracking.SIDES``, and it is load-bearing:
#: ``observation.wrist_pose`` concatenates one 7-float pose per hand in this
#: order, so a reader splits it by index and has to agree.
SIDES = ("left", "right")
#: What a task file's ``hands`` key may say, and which sides each spawns.
HAND_CHOICES = {"left": ("left",), "right": ("right",),
"both": ("left", "right")}
#: shapes that are a USD file rather than a primitive. ``usd`` is one rigid
#: body; ``articulation`` is a USD with joints in it, spawned as an
#: ArticulationCfg so its joint coordinate can be read and written -- which is
#: what an "open it" task is entirely about.
USD_SHAPES = ("usd", "articulation")
#: Fallback diffuse colour for a primitive whose task file names none. Warm
#: orange: it separates from the table's grey, from the blue MANO hand
#: (``--hand-rgb``) and from the green/pink tracking overlay, and it stays
#: distinguishable under the desaturating effect of a headset's optics. Objects
#: override it with a ``"color": [r, g, b]`` key.
DEFAULT_COLOR = (0.85, 0.35, 0.10)
#: The table's own colour, for the same reason. Neutral and dark enough that a
#: light object on top of it reads as an object rather than as a patch.
TABLE_COLOR = (0.30, 0.31, 0.34)
def find(name: str) -> str | None:
"""Path of the task file for `name`, or None. A path to a task file (a dataset's own meta/task.json,