#!/usr/bin/env python3 # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """Move a WELDED articulation, so a fixed-base object can still be randomized. ``fixed_base: true`` puts an articulation on a fixed joint to the world, and writing such a body's root pose does nothing -- which is why the ARCTIC, OakInk2 and Synthesis tasks had no ``randomize`` block and every demo of them recorded before 2026-09-10 starts from the identical pose. SEVEN tasks are welded now -- ``unscrew_cap``, ``oakink2_laptop_open``, ``synthesis_laptop_open`` and ``hammer_nail``'s nail board (five until 2026-09-12, when ``oakink2_bottle_uncap`` was deleted), and since 2026-09-16 the three one-handed ARCTIC twins ``microwave_open_fixed``, ``espressomachine_lever_fixed`` and ``capsulemachine_lever_fixed``. The ten ARCTIC objects were welded too until 2026-09-10, when they were un-welded deliberately (tasks/README.md, *Welded or free?*); the free files take the ordinary root-pose write now, and this module is not their path any more. It is still the path for the seven, and one line in a task file puts any of the ten back on it -- the three ``_fixed`` files are exactly that line. Un-welding is not the way out of the randomization problem, and never was: a welded object randomizes fine through the anchor. Newton maps a fixed-root body to a MuJoCo **mocap** body, and a mocap body is exactly the thing you are allowed to move at any time:: # newton/_src/solvers/mujoco/solver_mujoco.py, _update_joint_properties() # "Update mocap body transforms first (fixed-root bodies have no MuJoCo # joints)." -> reads model.joint_X_p, writes mjw_data.mocap_pos/quat So the world-anchor of the weld -- ``model.joint_X_p`` for the world->root FIXED joint -- is writable, and ``solver.notify_model_changed(JOINT_PROPERTIES)`` is the supported way to push it through. The object stays welded: no table contact, no drift under a lever, and no solver cost. Un-welding trades that for table contact; what it actually costs was never resolved (tasks/README.md, *Welded or free?*, and logs/bench/ -- the n=3 A/B there is noise-dominated). 🔴 Newton stores a transform as ``(px, py, pz, qx, qy, qz, qw)`` -- position first, quaternion XYZW last, the same layout the task files use. Isaac Lab's ``root_pose`` is ``(px, py, pz, qw, qx, qy, qz)``. Getting that wrong moves the object somewhere plausible-looking, which is the failure this note exists to prevent. """ from __future__ import annotations import numpy as np def find_weld_joints(model, labels_of_interest: dict[str, str]) -> dict[str, int]: """``{object name: joint index}`` for each welded root among the labels. ``labels_of_interest`` maps an object's name to the body-label prefix its root carries (``/Object`` for the target, ``/Prop_`` otherwise). A weld is a joint whose parent is the world (-1), whose type is FIXED, and whose child body's label starts with that prefix. An object that has no such joint is simply absent from the result -- it is not welded. """ import newton # noqa: PLC0415 jtype = np.asarray(model.joint_type.numpy()).reshape(-1) jparent = np.asarray(model.joint_parent.numpy()).reshape(-1) jchild = np.asarray(model.joint_child.numpy()).reshape(-1) labels = [str(x) for x in (getattr(model, "body_label", []) or [])] fixed = int(newton.JointType.FIXED) out: dict[str, int] = {} for j in range(len(jtype)): if int(jtype[j]) != fixed or int(jparent[j]) != -1: continue b = int(jchild[j]) name = labels[b] if 0 <= b < len(labels) else "" for obj, prefix in labels_of_interest.items(): # The ROOT of the articulation, so the shortest matching label # wins: /Object/base is the root, /Object/base/lid is not. The # prefix must end a path SEGMENT: /Prop_nail must not take # /Prop_nail_block_1's weld. if (name.endswith(prefix) or prefix + "/" in name) and obj not in out: out[obj] = j return out def anchor_pose(model, joint_index: int) -> tuple[tuple, tuple]: """``(pos, rot_xyzw)`` of one weld's world anchor, as the model has it.""" xp = np.asarray(model.joint_X_p.numpy()) t = np.asarray(xp[joint_index]).reshape(-1) return (float(t[0]), float(t[1]), float(t[2])), \ (float(t[3]), float(t[4]), float(t[5]), float(t[6])) def move_welds(model, solver, moves: dict[int, tuple], state=None) -> None: """Write ``{joint index: (pos, rot_xyzw)}`` into the welds and publish it. One ``notify_model_changed`` for the whole batch: it re-packs MuJoCo's mocap arrays, so calling it per object would do that work per object. ``state``: re-run FK on it, so its ``body_q`` -- what the NEXT collide() reads -- has the welded bodies at their new anchor. Without it they stay wherever the last FK put them until the solver step re-derives them, and one collide() with the old pose is enough: Isaac Lab only re-solves the articulations it flagged dirty, a scene reset flags the block back at its nominal anchor and that flag is consumed before this runs, so the first step after a reset saw the nail block at its NOMINAL pose -- a hammer drawn there started inside it and was thrown 9 m up, a solver blow-up every reset of that layout (hammer_nail_fixed, 2026-10-25, 103 in one session). """ if not moves: return import newton # noqa: PLC0415 xp = np.asarray(model.joint_X_p.numpy()).copy() for j, (pos, rot) in moves.items(): xp[j] = np.asarray([pos[0], pos[1], pos[2], rot[0], rot[1], rot[2], rot[3]], dtype=xp.dtype) model.joint_X_p.assign(xp) solver.notify_model_changed(newton.ModelFlags.JOINT_PROPERTIES) if state is not None: newton.eval_fk(model, state.joint_q, state.joint_qd, state) def check_solver_anchors(model, solver, joints) -> None: """Reject a split between Newton's fixed-root pose and MuJoCo's pivot. Reading the articulation's root pose alone cannot detect this: FK uses joint_X_p even when the solver's mocap transform was never updated. Called at randomization checks, not in the per-step hot path. """ import warp as wp wanted = set(int(j) for j in joints) if not wanted: return mapping = solver.mjc_mocap_to_newton_jnt.numpy() positions = solver.mjw_data.mocap_pos.numpy() rotations = solver.mjw_data.mocap_quat.numpy() # MuJoCo WXYZ xp, xc = model.joint_X_p.numpy(), model.joint_X_c.numpy() checked = set() for world, slot in np.ndindex(mapping.shape): j = int(mapping[world, slot]) if j not in wanted: continue parent = wp.transform(wp.vec3(*xp[j, :3]), wp.quat(*xp[j, 3:])) child = wp.transform(wp.vec3(*xc[j, :3]), wp.quat(*xc[j, 3:])) expected = np.asarray(wp.transform_multiply(parent, wp.transform_inverse(child))) actual_q = rotations[world, slot][[1, 2, 3, 0]] pos_error = np.linalg.norm(positions[world, slot] - expected[:3]) quat_error = min(np.linalg.norm(actual_q - expected[3:]), np.linalg.norm(actual_q + expected[3:])) if pos_error > 1e-5 or quat_error > 1e-5: raise RuntimeError( f"Weld joint {j}: Newton collision anchor and MuJoCo solver pivot " f"disagree ({pos_error * 1000:.3f} mm, quaternion error {quat_error:.6g}); " "publish the weld with move_welds(), not a root-pose write") checked.add(j) if checked != wanted: raise RuntimeError(f"Weld joints missing from MuJoCo mocap mapping: {sorted(wanted - checked)}") # Where a recorded episode says its welded objects sat, in order of trust. # ``weld_anchors`` is read back from model.joint_X_p the moment a demo starts # (already Newton's (pos, rot_xyzw) layout); ``randomization.objects`` is the # draw that was written into the anchor (same layout); ``start_poses`` is Isaac # Lab's root_state_w (pos, rot WXYZ) and needs the swap this module's docstring # warns about. Episodes recorded before any of these existed fall back to the # nominal anchor, which is where they were. ANCHOR_SOURCES = ("weld_anchors", "randomization", "start_poses", "nominal") def episode_anchors(episode: dict, weld_joints: dict[str, int], nominal: dict[int, tuple]) -> tuple[dict[int, tuple], dict[str, str]]: """``({joint index: (pos, rot_xyzw)}, {object name: source})`` for one recorded episode -- the anchor every welded object must be put back on before its states are replayed, and where each number came from. A welded root's pose is NOT in ``observation.state`` (a fixed joint has no coordinates), so an offline replay that only wrote joint_q back would leave the object wherever the scene was built -- or wherever the previous episode's anchor was. Every joint in ``weld_joints`` therefore gets an entry: an episode with no record of its own goes to ``nominal``. """ moves: dict[int, tuple] = {} sources: dict[str, str] = {} wa = episode.get("weld_anchors") or {} ro = (episode.get("randomization") or {}).get("objects") or {} sp = episode.get("start_poses") or {} for name, j in weld_joints.items(): if name in wa and "pos" in wa[name] and "rot_xyzw" in wa[name]: moves[j] = (tuple(float(v) for v in wa[name]["pos"]), tuple(float(v) for v in wa[name]["rot_xyzw"])) sources[name] = "weld_anchors" elif name in ro and "pos" in ro[name] and "rot_xyzw" in ro[name]: moves[j] = (tuple(float(v) for v in ro[name]["pos"]), tuple(float(v) for v in ro[name]["rot_xyzw"])) sources[name] = "randomization" elif name in sp and len(sp[name]) >= 7: p = [float(v) for v in sp[name]] # root_state_w is (x y z, qw qx qy qz): W first. moves[j] = ((p[0], p[1], p[2]), (p[4], p[5], p[6], p[3])) sources[name] = "start_poses" else: moves[j] = nominal[j] sources[name] = "nominal" return moves, sources