Skip to content

Nist assembly

Mesh and SDF contacts

A Franka assembles ten NIST task-board parts with a pretrained policy.

0.00 s
The steel preset, recordedon an NVIDIA RTX PRO 6000 Blackwell, sped up 2× (the readout shows sim time).

Run it

Terminal window
cd examples
# the default preset (steel_rolling), then the others
uv run shelf play nist_assembly
uv run shelf play nist_assembly --solver steel
# change solver settings live
uv run shelf tune nist_assembly

Source: examples/shelf/03_mesh_sdf_contacts/nist_assembly/ · ported from examples/demos/nist.py @ https://github.com/isaac-sim/IsaacLab/pull/9177 (head 2a28cad06), ported to Newton

Presets

PresetSolverStatusChecked
steel_rollingdefaultsteel variantworks2026-12-02, newton 06dd39d0a, NVIDIA RTX PRO 6000 Blackwell Server Edition

Solvers with no row are untested on this example. The full settings are inpresets.toml.

Code

examples/shelf/03_mesh_sdf_contacts/nist_assembly/example.py
# SPDX-FileCopyrightText: Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
# SPDX-License-Identifier: BSD-3-Clause
# Modified for Steel Shelf: a standalone Newton port that runs without Isaac Lab.
###########################################################################
# NIST ten-part assembly
#
# A Franka arm assembles ten parts into a NIST task board with a pretrained
# policy. This is a standalone Newton port of the NIST demo
# (examples/demos/nist.py) in https://github.com/isaac-sim/IsaacLab/pull/9177,
# ported from its head commit 2a28cad06. The demo and the alphaNIST policy are
# by ooctipus; the policy was trained in MuJoCo Warp. The port runs the same
# TorchScript policy on the same assets, which are downloaded at run time from
# Isaac Lab's public content and cached; neither is bundled here.
#
# Physics runs at 100 Hz with 8 solver substeps and the policy at 25 Hz. Each
# reset yaws and places the board and drops the ten parts over a square. The
# seed picks ten of the nineteen part types (fixed for the run) and seeds the
# reset sampling, the way the Isaac Lab demo does.
#
# Command: python -m shelf play nist_assembly
# python -m shelf play nist_assembly --solver steel --world-count 4
# python -m shelf play nist_assembly --viewer null --world-count 4 --record outputs/nist_rec
#
###########################################################################
from __future__ import annotations
import atexit
import gzip
import json
import math
import os
import random
import tempfile
import urllib.request
from pathlib import Path
from typing import NamedTuple
import numpy as np
import torch # the policy is TorchScript; install the `policy` extra
import warp as wp
import newton
import newton.examples
from common import presets
ASSET_ROOT = "https://omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/IsaacLab"
POLICY_PATH = "PretrainedCheckpoints/rsl_rl/demo-alphaNIST.pt"
ROBOT_PATH = "Robots/FrankaEmika/franka_panda.usda"
BOARD_PATH = "Factory/NIST/Taskboard/nistboard.usd"
PART_DIR = "Factory/NIST"
class Assembly(NamedTuple):
"""Static asset metadata: positions [m], masses [kg], xyzw poses. Local frame rotations are identity."""
identity: int
name: str
plug: str
socket: str
board_pose: tuple[float, ...]
held_align: tuple[float, float, float]
fixed_tip: tuple[float, float, float]
seated: tuple[float, float, float]
plug_mass: float
socket_mass: float = 0.05
# The policy reads each selected part's one-hot identity in this 19-entry order.
# fmt: off
ASSEMBLIES = (
Assembly(0, "nut_thread_m8", "nut_m8", "bolt_m8",
(0.0473, -0.0407, 0.0172, 1.0, 0.0, 0.0, 0.0),
(0.0, 0.0, 0.0093), (0.0, 0.0, 0.026), (0.0, 0.0, 0.018), 0.03),
Assembly(1, "nut_thread_m12", "nut_m12", "bolt_m12",
(0.3473, -0.2665, 0.0212, 1.0, 0.0, 0.0, 0.0),
(0.0, 0.0, 0.013), (0.0, 0.0, 0.035), (0.0, 0.0, 0.0218), 0.03),
Assembly(2, "nut_thread_m16", "nut_m16", "bolt_m16",
(0.04715, -0.3416, 0.0194, 1.0, 0.0, 0.0, 0.0),
(0.0, 0.0, 0.01), (0.0, 0.0, 0.035), (0.0, 0.0, 0.022), 0.03),
Assembly(3, "gear_mesh_small", "gear_small", "gear_base",
(0.0474, -0.1713, -0.0002, 0.7071, -0.7071, 0.0, 0.0),
(0.05075, 0.0, 0.005), (0.0508, 0.0, 0.025), (0.05075, 0.0, 0.005), 0.019),
Assembly(4, "gear_mesh_medium", "gear_medium", "gear_base",
(0.0474, -0.1713, -0.0002, 0.7071, -0.7071, 0.0, 0.0),
(0.02025, 0.0, 0.005), (0.02025, 0.0, 0.025), (0.02025, 0.0, 0.005), 0.012),
Assembly(5, "gear_mesh_large", "gear_large", "gear_base",
(0.0474, -0.1713, -0.0002, 0.7071, -0.7071, 0.0, 0.0),
(-0.0303, 0.0, 0.005), (-0.0303, 0.0, 0.025), (-0.0303, 0.0, 0.005), 0.019),
Assembly(6, "rod_insert_4mm", "round_peg_4mm", "round_hole_4mm",
(0.3473, -0.1918, -0.0001, 0.7071, -0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(7, "rod_insert_8mm", "round_peg_8mm", "round_hole_8mm",
(0.3473, -0.1164, -0.0001, 0.7071, -0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(8, "rod_insert_12mm", "round_peg_12mm", "round_hole_12mm",
(0.1226, -0.0422, -0.0001, 0.7071, -0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(9, "rod_insert_16mm", "round_peg_16mm", "round_hole_16mm",
(0.1221, -0.2665, -0.0001, 0.7071, -0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(10, "peg_insert_4mm", "rectangular_peg_4mm", "rectangular_hole_4mm",
(0.1971, -0.1915, -0.0003, 0.7071, -0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(11, "peg_insert_8mm", "rectangular_peg_8mm", "rectangular_hole_8mm",
(0.2717, -0.2659, -0.0003, 0.7071, -0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(12, "peg_insert_12mm", "rectangular_peg_12mm", "rectangular_hole_12mm",
(0.1971, -0.0413, -0.0003, 0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(13, "peg_insert_16mm", "rectangular_peg_16mm", "rectangular_hole_16mm",
(0.3472, -0.0413, -0.0003, 0.7071, 0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.009), (0.0, 0.0, 0.0), 0.019),
Assembly(14, "usba", "usb_a_plug", "usb_a_socket",
(0.2721, -0.0415, -0.0001, 0.7071, 0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0335), (0.0, 0.0, 0.0416), (0.0, 0.0, 0.0335), 0.05, 0.012),
Assembly(15, "waterproof", "waterproof_plug", "waterproof_socket",
(0.1981, -0.1166, -0.0002, 0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 0.021), (0.0, 0.0, 0.034), (0.0, 0.0, 0.021), 0.05),
Assembly(16, "bnc", "bnc_plug", "bnc_socket",
(0.2797, -0.1915, 0.0, 0.7071, 0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0107), (0.0, 0.0, 0.0107), (0.0, 0.0, 0.0107), 0.05),
Assembly(17, "dsub", "dsub_plug", "dsub_socket",
(0.2129, -0.2659, -0.019, 0.7071, -0.7071, 0.0, 0.0),
(0.0, 0.0, 0.0), (0.0, 0.0, 0.0061), (0.0, 0.0, 0.0), 0.005),
Assembly(18, "rj45", "rj45_plug", "rj45_socket",
(0.3473, -0.3415, 0.0, 0.0, 1.0, 0.0, 0.0),
(0.0, 0.0, 0.015), (0.0, 0.0, 0.028), (0.0, 0.0, 0.015), 0.05),
)
# fmt: on
NUM_PARTS = 10
SELECTION_SEED = 1701
GRASP = (0.0, 0.0, 0.107, 0.0, -1.0, 0.0, 0.0)
WORKSPACE_LOWER = (0.0, -0.675, -0.05)
WORKSPACE_UPPER = (1.0, 0.675, 1.0)
BOARD_CENTER_LOCAL = (0.19232847446867662, -0.191768517928605, 0.0)
BOARD_CENTER_RANGE = ((0.40, 0.50), (-0.03, 0.03), (0.0206, 0.0206))
DROP_POSITION_RANGE = ((0.15, 0.85), (-0.35, 0.35), (0.12, 0.14))
BOARD_INIT = ((0.452824, 0.19145, 0.0206), (0.0, 1.0, 0.0, 0.0))
ENV_SPACING = 2.0
PHYSICS_DT = 0.01
DECIMATION = 4
EPISODE_STEPS = 3500 # 140 s at 25 Hz
# Contact materials: (mu, ke [N/m], kd [N s/m]).
PART_MATERIAL = (0.75, 1.6e5, 800.0)
GROUND_MATERIAL = (1.0, 2500.0, 100.0)
ROBOT_MATERIAL = (0.75, 1.0e6, 2000.0)
PART_CONTACT_GAP = 0.005
DEFAULT_CONTACT_GAP = 0.01
PART_SDF = {"max_resolution": 256, "narrow_band_range": (-0.005, 0.005)}
DEFAULT_SDF = {"max_resolution": 64, "narrow_band_range": (-0.005, 0.005)}
PART_INERTIA_ADD = 1.0e-5 # [kg m^2] on each loose part's principal diagonal
# Franka drives: joint name -> (stiffness, damping, effort limit, velocity limit, armature).
ARM_JOINTS = [f"panda_joint{i}" for i in range(1, 8)]
FINGER_JOINTS = ["panda_finger_joint1", "panda_finger_joint2"]
DRIVES = {
"panda_joint1": (600.0, 50.0, 87.0, 20.0, 0.6057),
"panda_joint2": (600.0, 50.0, 87.0, 20.0, 0.6057),
"panda_joint3": (600.0, 50.0, 87.0, 20.0, 0.4625),
"panda_joint4": (600.0, 50.0, 87.0, 20.0, 0.4625),
"panda_joint5": (250.0, 30.0, 12.0, 25.0, 0.2055),
"panda_joint6": (150.0, 25.0, 12.0, 25.0, 0.2055),
"panda_joint7": (50.0, 15.0, 12.0, 25.0, 0.2055),
"panda_finger_joint1": (350.0, 175.0, 70.0, 2.0, 0.1),
"panda_finger_joint2": (0.0, 0.0, 1.0, 2.0, 0.1),
}
HOME = {
"panda_joint1": 0.00871,
"panda_joint2": -0.10368,
"panda_joint3": -0.00794,
"panda_joint4": -1.49139,
"panda_joint5": -0.00083,
"panda_joint6": 1.38774,
"panda_joint7": 0.0,
"panda_finger_joint1": 0.0,
"panda_finger_joint2": 0.04,
}
ARM_ACTION_SCALE = (0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.2)
GRIPPER_OPEN, GRIPPER_CLOSED = 0.04, 0.0
def cache_dir() -> Path:
"""Download cache for the Isaac Lab assets and policy."""
root = os.environ.get("STEEL_SHELF_CACHE") or os.path.join(
os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "steel-shelf"
)
return Path(root) / "isaaclab-nist"
def fetch(relative: str) -> Path:
"""Download an Isaac Lab content file and, for a USD layer, every layer it composes; cached."""
from pxr import Sdf # noqa: PLC0415 (USD is only needed once assets are fetched)
root = cache_dir()
pending, seen = [relative], set()
while pending:
rel = pending.pop()
if rel in seen:
continue
seen.add(rel)
target = root / rel
if not target.is_file():
target.parent.mkdir(parents=True, exist_ok=True)
# A unique partial file and an atomic rename let concurrent first runs share the cache.
fd, partial = tempfile.mkstemp(dir=target.parent, prefix=target.name + ".", suffix=".part")
os.close(fd)
print(f"Downloading {ASSET_ROOT}/{rel}", flush=True)
try:
urllib.request.urlretrieve(f"{ASSET_ROOT}/{rel}", partial)
os.replace(partial, target)
finally:
if os.path.exists(partial):
os.remove(partial)
if target.suffix in (".usd", ".usda", ".usdc"):
layer = Sdf.Layer.FindOrOpen(str(target))
for dep in layer.GetCompositionAssetDependencies():
if dep and "://" not in dep and not dep.startswith("/"):
pending.append(os.path.normpath(os.path.join(os.path.dirname(rel), dep)))
return root / relative
def select_assemblies(seed: int) -> tuple[Assembly, ...]:
"""The ten part types of a run, chosen by ``seed`` from the 19-type catalog."""
return tuple(random.Random(seed).sample(ASSEMBLIES, NUM_PARTS))
class Example:
def __init__(self, viewer, args):
self.preset = presets.load(__file__)
self.viewer = viewer
self.test_mode = args.test
self.world_count = args.world_count
self.seed = args.seed
self.deterministic = args.deterministic
self.record_hz = args.record_hz if args.record else None
self.fps = self.preset.fps
self.frame_dt = 1.0 / self.fps
self.sim_substeps = self.preset.substeps
self.physics_dt = self.frame_dt / DECIMATION
self.sim_dt = self.physics_dt / self.sim_substeps
self.sim_time = 0.0
self.device = wp.get_device()
self.torch_device = torch.device(f"cuda:{self.device.ordinal}" if self.device.is_cuda else "cpu")
if self.device.is_cuda:
# Torch shares warp's stream, so captured physics and the policy stay in order without syncs.
torch.cuda.set_stream(wp.stream_to_torch(self.device.stream))
self.selection_seed = args.selection_seed
self.assemblies = select_assemblies(self.selection_seed)
print("Parts:", ", ".join(part.name for part in self.assemblies), flush=True)
# Isaac Lab seeds every generator from the env seed before building the scene.
random.seed(self.seed)
np.random.seed(self.seed)
torch.manual_seed(self.seed)
wp.rand_init(self.seed)
self.policy = torch.jit.load(str(fetch(POLICY_PATH)), map_location=self.torch_device).eval()
self._build_model()
self.build_solver()
self.state_0 = self.model.state()
self.state_1 = self.model.state()
self.control = self.model.control()
self._init_buffers()
self._startup_randomization()
self.viewer.set_model(self.model)
# Look at all boards from the front right, as the demo's camera does.
center = self.env_origins.mean(axis=0) + np.array((0.35, 0.0, 0.2))
span = float(np.ptp(self.env_origins[:, :2], axis=0).max()) if self.world_count > 1 else 0.0
eye = center + (1.0 + 0.9 * span) * np.array((1.0, -0.8, 0.75))
d = (center - eye) / np.linalg.norm(center - eye)
pitch, yaw = np.degrees(np.arcsin(d[2])), np.degrees(np.arctan2(d[1], d[0]))
self.viewer.set_camera(pos=wp.vec3(*eye.tolist()), pitch=float(pitch), yaw=float(yaw))
self.recorder = Recorder(args.record, self, args.record_hz) if args.record else None
self.reset_worlds(torch.arange(self.world_count, device=self.torch_device))
self.obs_policy, self.obs_slots = self._observe(update_history=True)
self.capture()
# ----- scene -----
def _build_model(self):
world = newton.ModelBuilder()
newton.solvers.SolverSteel.register_custom_attributes(world)
world.default_shape_cfg.gap = DEFAULT_CONTACT_GAP
world.default_shape_cfg.margin = 0.0
self.layout = {}
def add(label, path, xform, edit=None):
from pxr import Usd # noqa: PLC0415
stage = Usd.Stage.Open(str(fetch(path)))
if edit is not None:
edit(stage)
body_start, shape_start, joint_start = world.body_count, world.shape_count, world.joint_count
world.add_usd(
stage,
xform=xform,
schema_resolvers=[newton.usd.SchemaResolverNewton(), newton.usd.SchemaResolverPhysx()],
hide_collision_shapes=True,
load_visual_shapes=True,
)
# Label every entity under the asset's scene name, as Isaac Lab's prim paths do.
for labels, start in ((world.body_label, body_start), (world.shape_label, shape_start),
(world.joint_label, joint_start)):
for i in range(start, len(labels)):
labels[i] = f"{label}/{labels[i].lstrip('/')}"
self.layout[label] = (range(body_start, world.body_count), range(shape_start, world.shape_count),
range(joint_start, world.joint_count))
def rigid(kinematic, mass):
def edit(stage):
from pxr import UsdPhysics # noqa: PLC0415
for prim in stage.Traverse():
if prim.HasAPI(UsdPhysics.RigidBodyAPI):
UsdPhysics.RigidBodyAPI(prim).CreateKinematicEnabledAttr(kinematic)
if mass is not None:
UsdPhysics.MassAPI.Apply(prim).CreateMassAttr(mass)
return edit
board_pos, board_quat = BOARD_INIT
add("NistBoard", BOARD_PATH, wp.transform(board_pos, board_quat), rigid(True, None))
add("Robot", ROBOT_PATH, wp.transform_identity())
sockets = {part.socket: part for part in self.assemblies}
bp, bq = torch.tensor(board_pos), torch.tensor(board_quat)
for socket, part in sockets.items():
offset = torch.tensor(part.board_pose)
pos, quat = combine_frame_transforms(bp, bq, offset[:3], offset[3:])
add(f"fixed_{socket}", f"{PART_DIR}/{socket}.usd", wp.transform(pos.tolist(), quat.tolist()),
rigid(True, part.socket_mass))
for slot, part in enumerate(self.assemblies):
add(f"held_{slot:02d}", f"{PART_DIR}/{part.plug}.usd",
wp.transform((0.0, 0.0, 2.0 + 0.1 * slot), (0.0, 0.0, 0.0, 1.0)), rigid(False, part.plug_mass))
self._set_shape_properties(world)
self._set_drives(world)
builder = newton.ModelBuilder()
newton.solvers.SolverSteel.register_custom_attributes(builder)
builder.default_shape_cfg.gap = DEFAULT_CONTACT_GAP
builder.default_shape_cfg.margin = 0.0
ground = newton.ModelBuilder.ShapeConfig(mu=GROUND_MATERIAL[0], ke=GROUND_MATERIAL[1], kd=GROUND_MATERIAL[2],
gap=DEFAULT_CONTACT_GAP, margin=0.0)
builder.add_ground_plane(cfg=ground)
self.env_origins = grid_origins(self.world_count, ENV_SPACING)
for origin in self.env_origins:
builder.add_world(world, xform=wp.transform(origin.tolist(), wp.quat_identity()))
self.model = builder.finalize()
self._index_model(world)
def _set_shape_properties(self, world):
rolling = self.preset.model.get("part_mu_rolling")
for label, (bodies, shapes, _) in self.layout.items():
for s in shapes:
if not world.shape_flags[s] & newton.ShapeFlags.COLLIDE_SHAPES:
continue
if label == "Robot":
mu, ke, kd = ROBOT_MATERIAL
world.shape_gap[s] = 0.0
world.shape_material_restitution[s] = 0.0
else:
mu, ke, kd = PART_MATERIAL
world.shape_gap[s] = PART_CONTACT_GAP if label != "NistBoard" else DEFAULT_CONTACT_GAP
world.shape_material_mu[s], world.shape_material_ke[s], world.shape_material_kd[s] = mu, ke, kd
world.shape_margin[s] = 0.0
part = label.startswith(("fixed_", "held_"))
_mesh_sdf(world, s, authored=part, **(PART_SDF if part else DEFAULT_SDF))
# The demo's materials replace the asset's own, which carry no torsional or rolling friction.
world.shape_material_friction_mode[s] = int(newton.ShapeFrictionMode.SLIDING)
if rolling is not None and label.startswith("held_"):
world.shape_material_friction_mode[s] = int(newton.ShapeFrictionMode.SLIDING_ROLLING)
world.shape_material_mu_rolling[s] = rolling
if label.startswith("held_"):
for b in bodies:
inertia = np.array(world.body_inertia[b], dtype=np.float64).reshape(3, 3)
inertia[np.diag_indices(3)] += PART_INERTIA_ADD
world.body_inertia[b] = wp.mat33(*inertia.ravel().tolist())
def _set_drives(self, world):
for j in self.layout["Robot"][2]:
name = world.joint_label[j].rsplit("/", 1)[-1]
if name not in DRIVES:
continue
ke, kd, effort, velocity, armature = DRIVES[name]
d = world.joint_qd_start[j]
world.joint_target_ke[d], world.joint_target_kd[d] = ke, kd
world.joint_effort_limit[d], world.joint_velocity_limit[d] = effort, velocity
world.joint_armature[d] = armature
# Isaac Lab's implicit actuators drive position and velocity (the velocity target stays zero); the
# passive second finger has no gains and is effort-driven, so the mimic constraint moves it.
passive = ke == 0.0 and kd == 0.0
mode = newton.JointTargetMode.EFFORT if passive else newton.JointTargetMode.POSITION_VELOCITY
world.joint_target_mode[d] = int(mode)
world.joint_q[world.joint_q_start[j]] = HOME[name]
world.joint_target_q[d] = HOME[name]
def _index_model(self, world):
"""Per-world body, coordinate and DOF indices of everything the policy and resets touch."""
dev = self.torch_device
n = self.world_count
offsets = {"body": world.body_count, "coord": world.joint_coord_count, "dof": world.joint_dof_count}
w = torch.arange(n, device=dev)[:, None]
def tile(local, kind):
return torch.tensor(local, device=dev)[None] + w * offsets[kind]
body_name = [lab.rsplit("/", 1)[-1] for lab in world.body_label]
robot = list(self.layout["Robot"][0])
joint_of_body = {c: j for j, c in enumerate(world.joint_child)}
sockets = list(dict.fromkeys(part.socket for part in self.assemblies))
self.socket_names = sockets
self.robot_bodies = tile(robot, "body")
self.root_body = tile([robot[0]], "body")[:, 0]
self.hand_body = tile([b for b in robot if body_name[b] == "panda_hand"], "body")[:, 0]
self.board_body = tile([self.layout["NistBoard"][0][0]], "body")[:, 0]
socket_local = [self.layout[f"fixed_{s}"][0][0] for s in sockets]
held_local = [self.layout[f"held_{k:02d}"][0][0] for k in range(NUM_PARTS)]
self.socket_bodies = tile(socket_local, "body")
self.fixed_bodies = tile([self.layout[f"fixed_{p.socket}"][0][0] for p in self.assemblies], "body")
self.held_bodies = tile(held_local, "body")
def free_coords(local, width, kind):
start = world.joint_q_start if kind == "coord" else world.joint_qd_start
first = tile([start[joint_of_body[b]] for b in local], kind)
return first[..., None] + torch.arange(width, device=dev)
self.board_q = free_coords([self.layout["NistBoard"][0][0]], 7, "coord")[:, 0]
self.socket_q = free_coords(socket_local, 7, "coord")
self.held_q = free_coords(held_local, 7, "coord")
self.held_qd = free_coords(held_local, 6, "dof")
robot_joint = {world.joint_label[j].rsplit("/", 1)[-1]: j for j in self.layout["Robot"][2]}
order = ARM_JOINTS + FINGER_JOINTS
self.robot_q = tile([world.joint_q_start[robot_joint[k]] for k in order], "coord")
self.robot_qd = tile([world.joint_qd_start[robot_joint[k]] for k in order], "dof")
self.home = torch.tensor([HOME[k] for k in order], device=dev)
self.env_origin_t = torch.tensor(self.env_origins, dtype=torch.float32, device=dev)
self.robot_collision_shape_count = sum(
1 for s in self.layout["Robot"][1] if world.shape_flags[s] & newton.ShapeFlags.COLLIDE_SHAPES
)
self.articulation_world = wp.to_torch(self.model.articulation_world).long()
def build_solver(self):
"""Build the solver and everything bound to its instance; the tuner calls this again to swap it."""
collision = self.preset.collision
self.collision_pipeline = newton.CollisionPipeline(
self.model,
broad_phase=collision.need("broad_phase"),
reduce_contacts=collision.need("reduce_contacts"),
rigid_contact_max=collision.need("rigid_contact_max_per_world") * self.world_count,
max_triangle_pairs=max(1_000_000, collision.need("max_triangle_pairs_per_world") * self.world_count),
include_static_kinematic_pairs=collision.need("include_static_kinematic_pairs"),
deterministic=self.deterministic,
)
self.contacts = self.collision_pipeline.contacts()
mode = wp.DeterministicMode.RUN_TO_RUN if self.deterministic else wp.DeterministicMode.NOT_GUARANTEED
self.solver = self.preset.make_solver(self.model, deterministic=mode)
self.observables = None
if self.record_hz == 100:
kinds = {self.solver.ObservableKind.CONTACT_F}
self.observables = self.solver.observables(kinds=kinds, contacts=self.contacts)
# Each contact's force summed over a physics step's substeps; reading forces leaves the solve unchanged.
self.contact_f_sum = wp.zeros(self.observables.contact_f.shape[0], dtype=wp.vec3, device=self.device)
# ----- buffers -----
def _init_buffers(self):
n = self.world_count
dev = self.torch_device
self.body_q = wp.to_torch(self.state_0.body_q)
self.assemblies_t = {
"held_align": torch.tensor([(*p.held_align, 0, 0, 0, 1) for p in self.assemblies], device=dev, dtype=torch.float32),
"fixed_tip": torch.tensor([(*p.fixed_tip, 0, 0, 0, 1) for p in self.assemblies], device=dev, dtype=torch.float32),
"seated": torch.tensor([(*p.seated, 0, 0, 0, 1) for p in self.assemblies], device=dev, dtype=torch.float32),
}
self.identity = torch.eye(len(ASSEMBLIES), device=dev)[[p.identity for p in self.assemblies]]
self.grasp = torch.tensor(GRASP, device=dev)
self.action_scale = torch.tensor(ARM_ACTION_SCALE, device=dev)
self.last_action = torch.zeros((n, 8), device=dev)
self.history = {}
self.history_fill = torch.ones(n, dtype=torch.bool, device=dev)
self.episode_steps = torch.zeros(n, dtype=torch.long, device=dev)
# Per-env physics inputs written before each captured physics step.
self.arm_delta = wp.zeros((n, 7), dtype=wp.float32)
self.grip_target = wp.zeros(n, dtype=wp.float32)
self.robot_q_wp = wp.from_torch(self.robot_q.to(torch.int32).contiguous())
self.arm_delta_t = wp.to_torch(self.arm_delta)
self.grip_target_t = wp.to_torch(self.grip_target)
# Steel does not read MuJoCo's gravcomp attribute, so the arm's weight is cancelled with a body force.
mass = self.model.body_mass.numpy()
gravity = self.model.gravity.numpy()[0]
f = np.zeros((self.model.body_count, 6), dtype=np.float32)
for b in self.robot_bodies.flatten().tolist():
f[b, :3] = -mass[b] * gravity
self.gravcomp = wp.array(f, dtype=wp.spatial_vector)
# Episode bookkeeping: the first episode of every world.
self.first_done = torch.zeros(n, dtype=torch.bool, device=dev)
self.first_success = torch.zeros(n, dtype=torch.bool, device=dev)
self.first_timeout = torch.zeros(n, dtype=torch.bool, device=dev)
self.first_count = torch.zeros(n, dtype=torch.long, device=dev)
self.first_steps = torch.zeros(n, dtype=torch.long, device=dev)
self.first_assembled = torch.full((n, NUM_PARTS), -1, dtype=torch.long, device=dev)
self.first_left = torch.full((n, NUM_PARTS), -1, dtype=torch.long, device=dev)
self.episodes = 0
self.successes = 0
def _startup_randomization(self):
"""Consume the generator as Isaac Lab's startup events do, so resets draw the same samples."""
n = self.world_count
# Robot friction and restitution are sampled per env and collider; both ranges are a single value.
torch.rand((n, self.robot_collision_shape_count), device=self.torch_device)
torch.rand((n, self.robot_collision_shape_count), device=self.torch_device)
# Each loose part's inertia increment is sampled per env; the range is a single value.
for _ in range(NUM_PARTS):
torch.rand((n, 1), device=self.torch_device)
# ----- reset -----
def reset_worlds(self, env_ids):
"""Home the robot, place and yaw the board, and drop the ten parts in the worlds ``env_ids``."""
count = len(env_ids)
if count == 0:
return
dev = self.torch_device
joint_q = wp.to_torch(self.state_0.joint_q)
joint_qd = wp.to_torch(self.state_0.joint_qd)
joint_q[self.robot_q[env_ids]] = self.home
joint_qd[self.robot_qd[env_ids]] = 0.0
board_pos, board_quat = (torch.tensor(v, device=dev).expand(count, -1) for v in BOARD_INIT)
yaw = torch.rand(count, device=dev) * 6.28 - 3.14
zero = torch.zeros_like(yaw)
board_quat = quat_mul(board_quat.contiguous(), quat_from_euler_xyz(zero, zero, yaw))
bounds = torch.tensor(BOARD_CENTER_RANGE, device=dev)
center = bounds[:, 0] + torch.rand((count, 3), device=dev) * (bounds[:, 1] - bounds[:, 0])
board_pos = center - quat_apply(board_quat, torch.tensor(BOARD_CENTER_LOCAL, device=dev).expand(count, -1))
board_pos = board_pos + self.env_origin_t[env_ids]
joint_q[self.board_q[env_ids]] = torch.cat((board_pos, board_quat), dim=-1)
sockets = {part.socket: part for part in self.assemblies}
for k, (socket, part) in enumerate(sockets.items()):
offset = torch.tensor(part.board_pose, device=dev)
pos, quat = combine_frame_transforms(board_pos, board_quat, offset[:3].expand(count, -1), offset[3:].expand(count, -1))
joint_q[self.socket_q[env_ids, k]] = torch.cat((pos, quat), dim=-1)
positions = torch.empty((count, NUM_PARTS, 3), device=dev)
bounds = torch.tensor(DROP_POSITION_RANGE, device=dev)
for slot in range(NUM_PARTS):
pending = torch.arange(count, device=dev)
for _ in range(512):
if len(pending) == 0:
break
candidate = bounds[:, 0] + torch.rand((len(pending), 3), device=dev) * (bounds[:, 1] - bounds[:, 0])
clear = ((candidate[:, None, :2] - positions[pending, :slot, :2]).square().sum(dim=-1) >= 0.1**2).all(dim=1)
positions[pending[clear], slot] = candidate[clear]
pending = pending[~clear]
if len(pending):
raise RuntimeError("Could not sample separated loose parts inside the drop region.")
angles = (torch.rand((count, 3), device=dev) * 2.0 - 1.0) * torch.tensor((1.57, 1.57, 3.14), device=dev)
quat = quat_from_euler_xyz(*angles.unbind(-1))
joint_q[self.held_q[env_ids, slot]] = torch.cat((positions[:, slot] + self.env_origin_t[env_ids], quat), dim=-1)
joint_qd[self.held_qd[env_ids, slot]] = 0.0
mask = torch.zeros(self.world_count + 1, dtype=torch.bool, device=dev)
mask[env_ids] = True
self.solver.reset(self.state_0, world_mask=wp.from_torch(mask), flags=0)
fk_mask = mask[self.articulation_world.clamp(min=0)] & (self.articulation_world >= 0)
newton.eval_fk(self.model, self.state_0.joint_q, self.state_0.joint_qd, self.state_0, wp.from_torch(fk_mask))
self.last_action[env_ids] = 0.0
self.history_fill[env_ids] = True
self.episode_steps[env_ids] = 0
# ----- observations -----
def _observe(self, update_history: bool):
body_q = wp.to_torch(self.state_0.body_q)
body_qd = wp.to_torch(self.state_0.body_qd)
joint_q = wp.to_torch(self.state_0.joint_q)
joint_qd = wp.to_torch(self.state_0.joint_qd)
com = wp.to_torch(self.model.body_com)
n = self.world_count
hand = body_q[self.hand_body]
root = body_q[self.root_body]
grasp = self.grasp.expand(n, -1)
ee_pos, ee_quat = combine_frame_transforms(hand[:, :3], hand[:, 3:], grasp[:, :3], grasp[:, 3:])
ee_pose_b = torch.cat(subtract_frame_transforms(root[:, :3], root[:, 3:], ee_pos, ee_quat), dim=-1)
# Link-frame velocity of the hand from its centre-of-mass twist, then the grasp point's.
hand_vel = body_qd[self.hand_body]
ang = hand_vel[:, 3:]
link_lin = hand_vel[:, :3] + torch.cross(ang, quat_apply(hand[:, 3:], -com[self.hand_body]), dim=-1)
lever = quat_apply(hand[:, 3:], grasp[:, :3])
lin = link_lin + torch.cross(ang, lever, dim=-1)
ee_vel_b = torch.cat((quat_apply_inverse(root[:, 3:], lin), quat_apply_inverse(root[:, 3:], ang)), dim=-1)
robot_terms = {
"ee_pose": ee_pose_b,
"ee_vel": ee_vel_b,
"joint_pos": joint_q[self.robot_q],
"joint_vel": joint_qd[self.robot_qd],
"last_action": self.last_action.clone(),
}
slots = self._slot_geometry(body_q, hand)
terms = {**robot_terms, "slots": slots}
if update_history:
for key, value in terms.items():
buf = self.history.get(key)
if buf is None:
buf = self.history[key] = value[:, None].repeat(1, 5, *([1] * (value.ndim - 1))).clone()
buf.copy_(torch.cat((buf[:, 1:], value[:, None]), dim=1))
fill = self.history_fill.view(-1, *([1] * (buf.ndim - 1)))
torch.where(fill, value[:, None].expand_as(buf), buf, out=buf)
self.history_fill[:] = False
obs_policy = torch.cat([self.history[k].reshape(n, -1) for k in robot_terms], dim=-1)
obs_slots = self.history["slots"].clone()
return obs_policy, obs_slots
def _slot_geometry(self, body_q, hand):
"""The policy's per-part relative poses and identities; also sets ``assembled`` and ``invalid``."""
n = self.world_count
held = body_q[self.held_bodies]
fixed = body_q[self.fixed_bodies]
grasp = self.grasp.expand(n, -1)
ee_pos, ee_quat = combine_frame_transforms(hand[:, :3], hand[:, 3:], grasp[:, :3], grasp[:, 3:])
ee_pos, ee_quat = ee_pos[:, None].expand(-1, NUM_PARTS, -1), ee_quat[:, None].expand(-1, NUM_PARTS, -1)
align = self.assemblies_t["held_align"].expand_as(held)
tip = self.assemblies_t["fixed_tip"].expand_as(fixed)
held_pos, held_quat = combine_frame_transforms(held[..., :3], held[..., 3:], align[..., :3], align[..., 3:])
fixed_pos, fixed_quat = combine_frame_transforms(fixed[..., :3], fixed[..., 3:], tip[..., :3], tip[..., 3:])
poses = (
*subtract_frame_transforms(fixed_pos, fixed_quat, held_pos, held_quat),
*subtract_frame_transforms(ee_pos, ee_quat, held_pos, held_quat),
*subtract_frame_transforms(ee_pos, ee_quat, fixed_pos, fixed_quat),
)
seated = self.assemblies_t["seated"].expand_as(fixed)
goal_pos, goal_quat = combine_frame_transforms(fixed[..., :3], fixed[..., 3:], seated[..., :3], seated[..., 3:])
error_pos, error_quat = subtract_frame_transforms(goal_pos, goal_quat, held_pos, held_quat)
x, y, z, w = error_quat.unbind(-1)
roll = torch.atan2(2.0 * (w * x + y * z), 1.0 - 2.0 * (x.square() + y.square()))
pitch = torch.asin((2.0 * (w * y - z * x)).clamp(-1.0, 1.0))
aligned = roll.abs() + pitch.abs() < 0.025
self.assembled = aligned & (error_pos[..., :2].norm(dim=-1) < 0.0025) & (error_pos[..., 2] < 0.001)
position = held[..., :3] - self.env_origin_t[:, None]
lower, upper = position.new_tensor(WORKSPACE_LOWER), position.new_tensor(WORKSPACE_UPPER)
self.outside = (position < lower).any(-1) | (position > upper).any(-1)
self.invalid = (~torch.isfinite(held)).any(dim=(1, 2)) | ~torch.isfinite(hand).all(dim=1) | self.outside.any(dim=1)
return torch.cat((*poses, self.identity.expand(n, -1, -1)), dim=-1)
# ----- stepping -----
def capture(self):
self.graph = None
if self.device.is_cuda:
with wp.ScopedCapture() as capture:
self.simulate()
self.graph = capture.graph
def simulate(self):
"""One physics step: drive targets, collide, then the solver substeps."""
wp.launch(
_set_targets,
dim=self.world_count,
inputs=[self.state_0.joint_q, self.robot_q_wp, self.arm_delta, self.grip_target],
outputs=[self.control.joint_target_q],
)
self.collision_pipeline.collide(self.state_0, self.contacts, dt=self.physics_dt)
if self.observables is not None:
self.contact_f_sum.zero_()
for i in range(self.sim_substeps):
wp.copy(self.state_0.body_f, self.gravcomp)
self.solver.step(self.state_0, self.state_1, self.control, self.contacts, self.sim_dt,
observables=self.observables)
if self.observables is not None:
wp.launch(_add_contact_force, dim=self.contact_f_sum.shape[0], inputs=[self.observables.contact_f],
outputs=[self.contact_f_sum])
if self.sim_substeps % 2 == 1 and i == self.sim_substeps - 1:
self.state_0.assign(self.state_1)
else:
self.state_0, self.state_1 = self.state_1, self.state_0
self.state_0.clear_forces()
def step(self):
with torch.inference_mode():
actions = self.policy(self.obs_policy, self.obs_slots)
if not torch.isfinite(actions).all():
raise RuntimeError("The policy returned nonfinite actions.")
self.last_action.copy_(actions)
self.arm_delta_t.copy_(actions[:, :7] * self.action_scale)
self.grip_target_t.copy_(torch.where(actions[:, 7] < 0, GRIPPER_CLOSED, GRIPPER_OPEN))
for _ in range(DECIMATION):
if self.graph is not None:
wp.capture_launch(self.graph)
else:
self.simulate()
if self.recorder is not None:
self.recorder.on_physics_step()
self.sim_time += self.frame_dt
self.episode_steps += 1
self._terminate_and_reset()
self.obs_policy, self.obs_slots = self._observe(update_history=True)
def _terminate_and_reset(self):
body_q = wp.to_torch(self.state_0.body_q)
self._slot_geometry(body_q, body_q[self.hand_body])
joint_q = wp.to_torch(self.state_0.joint_q)[self.robot_q]
joint_qd = wp.to_torch(self.state_0.joint_qd)[self.robot_qd]
assembled = self.assembled.sum(dim=1)
failed = self.invalid | ~torch.isfinite(joint_q).all(dim=1) | ~torch.isfinite(joint_qd).all(dim=1)
success = (assembled == NUM_PARTS) & ~failed
timeout = self.episode_steps >= EPISODE_STEPS
done = success | failed | timeout
if (self.test_mode or self.recorder is not None) and bool(done.any()):
# Before any outcome is kept or recorded, and before a masked reset clears the world's overflow flags.
self.check_capacity()
first = ~self.first_done
newly = self.assembled & (self.first_assembled < 0) & first[:, None]
self.first_assembled[newly] = self.episode_steps[:, None].expand_as(newly)[newly]
left = self.outside & (self.first_left < 0) & first[:, None]
self.first_left[left] = self.episode_steps[:, None].expand_as(left)[left]
ended = done & first
self.first_success |= ended & success
self.first_timeout |= ended & timeout & ~success & ~failed
self.first_count[ended] = assembled[ended]
self.first_steps[ended] = self.episode_steps[ended]
self.first_done |= ended
if self.recorder is not None:
self.recorder.on_env_step(done, success, timeout & ~success & ~failed, assembled)
env_ids = torch.nonzero(done).flatten()
if len(env_ids):
for e in env_ids.tolist():
self.episodes += 1
self.successes += int(success[e])
if not self.test_mode:
print(f"Episode {self.episodes} (world {e}): {int(assembled[e])}/10 assembled, "
f"{int(self.episode_steps[e]) * self.frame_dt:.1f}s; "
f"complete-board successes {self.successes}/{self.episodes}", flush=True)
self.reset_worlds(env_ids)
def render(self):
self.viewer.begin_frame(self.sim_time)
self.viewer.log_state(self.state_0)
self.viewer.end_frame()
def summary(self) -> dict:
"""First-episode outcome of every world."""
done = self.first_done
invalid = done & ~self.first_success & ~self.first_timeout
return {
"worlds": self.world_count,
"done": int(done.sum()),
"success": int(self.first_success.sum()),
"timeout": int(self.first_timeout.sum()),
"invalid": int(invalid.sum()),
"success_rate": float(self.first_success.float().mean()),
"parts": [p.name for p in self.assemblies],
"assembled_step": self.first_assembled.tolist(),
"left_workspace_step": self.first_left.tolist(),
"episode_steps": self.first_steps.tolist(),
"assembled": self.first_count.tolist(),
}
def test_final(self):
result = self.summary()
print("NIST", json.dumps({k: v for k, v in result.items() if k in ("worlds", "done", "success", "timeout", "invalid", "success_rate")}), flush=True)
self.check_capacity()
if self.recorder is not None:
self.recorder.close()
assert result["done"] == self.world_count, f"Only {result['done']}/{self.world_count} first episodes finished."
assert result["success"] >= self.check_min_success, (
f"{result['success']}/{self.world_count} boards assembled; the check needs {self.check_min_success}."
)
def check_capacity(self):
"""Raise if Steel dropped contacts or rows in any world since that world's last reset.
A recording then marks every world without a checked outcome as rejected.
"""
if not isinstance(self.solver, newton.solvers.SolverSteel):
return
try:
self.solver.check_constraint_capacity()
except RuntimeError as error:
if self.recorder is not None:
self.recorder.rejected = str(error).split(". ")[0]
raise
@property
def check_min_success(self) -> int:
return int(self.preset.model.get("check_min_success", 1))
@staticmethod
def create_parser():
parser = newton.examples.create_parser()
newton.examples.add_world_count_arg(parser)
parser.set_defaults(world_count=4)
parser.add_argument("--seed", type=int, default=1701, help="Seed of the reset sampling.")
parser.add_argument("--selection-seed", type=int, default=SELECTION_SEED,
help="Seed that picks the ten part types (1701 matches the Isaac Lab demo).")
parser.add_argument("--deterministic", action="store_true",
help="Sort contacts and solve in a fixed order, so a run can repeat on the same build and GPU.")
parser.add_argument("--record", type=str, default=None,
help="Write a replay of each world's first episode to this directory.")
parser.add_argument("--record-hz", type=int, choices=(25, 100), default=25,
help="Replay pose rate: 25 (every policy step) or 100 (every physics step, plus contacts).")
return parser
@wp.kernel
def _set_targets(
joint_q: wp.array(dtype=wp.float32),
robot_q: wp.array2d(dtype=wp.int32),
arm_delta: wp.array2d(dtype=wp.float32),
grip: wp.array(dtype=wp.float32),
target: wp.array(dtype=wp.float32),
):
"""Relative arm targets from the current joint positions, and the binary gripper command on both fingers.
Position targets share the joint-coordinate layout of ``joint_q``."""
w = wp.tid()
for i in range(7):
target[robot_q[w, i]] = joint_q[robot_q[w, i]] + arm_delta[w, i]
target[robot_q[w, 7]] = grip[w]
target[robot_q[w, 8]] = grip[w]
@wp.kernel
def _add_contact_force(contact_f: wp.array(dtype=wp.spatial_vector), total: wp.array(dtype=wp.vec3)):
c = wp.tid()
total[c] = total[c] + wp.spatial_top(contact_f[c])
def _mesh_sdf(builder, shape, authored, max_resolution, narrow_band_range):
"""Give a collider a texture SDF; ``authored`` replaces any SDF settings, curved primitives become meshes first."""
geo = builder.shape_type[shape]
if geo == newton.GeoType.CAPSULE:
radius, half_height = float(builder.shape_scale[shape][0]), float(builder.shape_scale[shape][1])
builder.shape_source[shape] = newton.Mesh.create_capsule(
radius, half_height, up_axis=newton.Axis.Z, segments=32, compute_uvs=False, compute_inertia=False
)
builder.shape_type[shape] = newton.GeoType.MESH
builder.shape_scale[shape] = wp.vec3(1.0)
elif geo not in (newton.GeoType.MESH, newton.GeoType.CONVEX_MESH, newton.GeoType.BOX):
raise ValueError(f"No SDF conversion for {builder.shape_label[shape]} ({newton.GeoType(geo).name}).")
has_sdf = builder.shape_sdf_max_resolution[shape] is not None or getattr(builder.shape_source[shape], "sdf", None) is not None
if authored or not has_sdf:
builder.shape_sdf_max_resolution[shape] = max_resolution
builder.shape_sdf_narrow_band_range[shape] = narrow_band_range
def grid_origins(count: int, spacing: float) -> np.ndarray:
"""World origins on Isaac Lab's square clone grid."""
rows = int(math.ceil(math.sqrt(count)))
cols = int(math.ceil(count / rows))
ii, jj = np.meshgrid(np.arange(rows), np.arange(cols), indexing="ij")
origins = np.zeros((count, 3), dtype=np.float32)
origins[:, 0] = -(ii.flatten()[:count] - (rows - 1) / 2) * spacing
origins[:, 1] = (jj.flatten()[:count] - (cols - 1) / 2) * spacing
return origins
# ----- quaternion helpers (xyzw), scripted like Isaac Lab's math utilities so results match to the bit -----
@torch.jit.script
def quat_mul(q1, q2):
x1, y1, z1, w1 = q1.unbind(-1)
x2, y2, z2, w2 = q2.unbind(-1)
ww = (z1 + x1) * (x2 + y2)
yy = (w1 - y1) * (w2 + z2)
zz = (w1 + y1) * (w2 - z2)
xx = ww + yy + zz
qq = 0.5 * (xx + (z1 - x1) * (x2 - y2))
w = qq - ww + (z1 - y1) * (y2 - z2)
x = qq - xx + (x1 + w1) * (x2 + w2)
y = qq - yy + (w1 - x1) * (y2 + z2)
z = qq - zz + (z1 + y1) * (w2 - x2)
return torch.stack([x, y, z, w], dim=-1)
@torch.jit.script
def quat_apply(quat, vec):
xyz, vec = torch.broadcast_tensors(quat[..., :3], vec)
t = xyz.cross(vec, dim=-1) * 2
return vec + quat[..., 3:4] * t + xyz.cross(t, dim=-1)
@torch.jit.script
def quat_apply_inverse(quat, vec):
xyz, vec = torch.broadcast_tensors(quat[..., :3], vec)
t = xyz.cross(vec, dim=-1) * 2
return vec - quat[..., 3:4] * t + xyz.cross(t, dim=-1)
@torch.jit.script
def quat_inv(q):
return torch.cat((-q[..., :3], q[..., 3:4]), dim=-1) / q.pow(2).sum(dim=-1, keepdim=True).clamp(min=1e-9)
@torch.jit.script
def quat_from_euler_xyz(roll, pitch, yaw):
cy, sy = torch.cos(yaw * 0.5), torch.sin(yaw * 0.5)
cr, sr = torch.cos(roll * 0.5), torch.sin(roll * 0.5)
cp, sp = torch.cos(pitch * 0.5), torch.sin(pitch * 0.5)
qw = cy * cr * cp + sy * sr * sp
qx = cy * sr * cp - sy * cr * sp
qy = cy * cr * sp + sy * sr * cp
qz = sy * cr * cp - cy * sr * sp
return torch.stack([qx, qy, qz, qw], dim=-1)
@torch.jit.script
def combine_frame_transforms(t01, q01, t12, q12):
return t01 + quat_apply(q01, t12), quat_mul(q01, q12)
@torch.jit.script
def subtract_frame_transforms(t01, q01, t02, q02):
q10 = quat_inv(q01)
return quat_apply(q10, t02 - t01), quat_mul(q10, q02)
class Recorder:
"""Writes each world's first episode for the NIST replay viewer: manifest.json, pose streams, scene.glb.
Bodies are ordered board, the 11 Franka links, the fixtures (in part order) and the ten loose parts. Pose files
are gzip of int16 per-frame deltas, channels (body, x y z qx qy qz qw) by frame, positions in units of
``pos_q`` m and quaternions times 32767. At 100 Hz each frame is a physics step and a contact file holds, per
frame and per touching body pair, a u16 count, then i16 load centres [N, 3] (``pos_q`` m), i16 net contact
forces [N, 3] (``force_q`` N) and u8 viewer body pairs [N, 2], the force acting on the first body of the pair.
"""
POS_Q, FORCE_Q = 5e-5, 4e-3
def __init__(self, out_dir, example, hz):
self.out = Path(out_dir)
self.out.mkdir(parents=True, exist_ok=True)
self.ex = example
self.hz = hz
self.source = "pub" if hz == 25 else "hr"
self.frames, self.contacts = [], []
self.done = torch.zeros(example.world_count, dtype=torch.bool, device=example.torch_device)
self.ended_at = [None] * example.world_count
self.closed = False
self.rejected = None # the capacity error that invalidates every world without a checked outcome
ex = example
self.body_ids = torch.cat((ex.board_body[:, None], ex.robot_bodies, ex.socket_bodies, ex.held_bodies), dim=1)
# Viewer body index of every model body (255: not drawn).
lookup = np.full(ex.model.body_count + 1, 255, dtype=np.int64)
for row in self.body_ids.cpu().numpy():
lookup[row] = np.arange(len(row))
self.viewer_body = lookup
# Writes whatever was recorded if the run stops before every world finished its first episode.
atexit.register(self.close)
def _pose(self):
q = wp.to_torch(self.ex.state_0.body_q)[self.body_ids].clone()
q[..., :3] -= self.ex.env_origin_t[:, None]
return q.cpu().numpy()
def on_physics_step(self):
if self.hz == 100 and not self.closed:
self.frames.append(self._pose())
self.contacts.append(self._contact_frame())
def on_env_step(self, done, success, timeout, assembled):
if self.closed:
return
if self.hz == 25:
self.frames.append(self._pose())
step = len(self.frames) - 1
for e in torch.nonzero(done & ~self.done).flatten().tolist():
self.ended_at[e] = step
self.done |= done
if bool(self.done.all()):
self.close()
def _contact_frame(self):
"""Each touching body pair's net force over the physics step and its load centre, keyed by world and pair.
The net force sums the normal and friction forces of the pair's contacts, averaged over the substeps; the load
centre is the force-weighted mean of the contact midpoints."""
ex = self.ex
c = ex.contacts
n = int(c.rigid_contact_count.numpy()[0])
s0, s1 = c.rigid_contact_shape0.numpy()[:n], c.rigid_contact_shape1.numpy()[:n]
shape_body = ex.model.shape_body.numpy()
b0, b1 = shape_body[s0], shape_body[s1]
body_q = ex.state_0.body_q.numpy()
point = 0.5 * (_to_world(body_q, b0, c.rigid_contact_point0.numpy()[:n])
+ _to_world(body_q, b1, c.rigid_contact_point1.numpy()[:n]))
force = ex.contact_f_sum.numpy()[:n] / ex.sim_substeps # on b0
world = ex.model.shape_world.numpy()
w = np.where(world[s0] >= 0, world[s0], world[s1])
a, b = self.viewer_body[b0], self.viewer_body[b1]
# The force goes on the later body in viewer order (parts last); undrawn bodies such as the ground come first.
rank_a, rank_b = np.where(a == 255, -1, a), np.where(b == 255, -1, b)
flip = rank_a < rank_b
on, by = np.where(flip, b, a), np.where(flip, a, b)
force = np.where(flip[:, None], -force, force)
keep = (w >= 0) & (on != 255) & ~((on == 0) & (by == 255))
key = (w[keep].astype(np.int64) * 256 + on[keep]) * 256 + by[keep]
keys, pair = np.unique(key, return_inverse=True)
mag = np.linalg.norm(force[keep], axis=1)
net = np.zeros((len(keys), 3))
np.add.at(net, pair, force[keep])
load = np.bincount(pair, mag, len(keys))
centre = np.stack([np.bincount(pair, mag * point[keep][:, k], len(keys)) for k in range(3)], -1)
live = load >= self.FORCE_Q
keys = keys[live]
return keys, centre[live] / load[live, None] - ex.env_origins[keys >> 16], net[live]
def close(self):
if self.closed or not self.frames:
return
self.closed = True
ex = self.ex
frames = np.stack(self.frames) # [frames, worlds, bodies, 7]
result = ex.summary()
per = 1 if self.hz == 25 else DECIMATION
arm = ex.preset.name
runs, episodes = {}, []
for e in range(ex.world_count):
last = self.ended_at[e] if self.ended_at[e] is not None else len(frames) - 1
name = f"{self.source}/{arm}_{e:03d}.bin"
(self.out / self.source).mkdir(exist_ok=True)
_write_pose(self.out / name, frames[: last + 1, e, :, :3].astype(np.float64), frames[: last + 1, e, :, 3:], self.POS_Q)
events = [{"f": int(s) * per - 1, "part": k, "kind": "assembled"}
for k, s in enumerate(result["assembled_step"][e]) if s >= 0]
events += [{"f": int(s) * per - 1, "part": k, "kind": "left"}
for k, s in enumerate(result["left_workspace_step"][e]) if s >= 0]
duration = result["episode_steps"][e] * ex.frame_dt
assembled = result["assembled"][e]
if not ex.first_done[e]:
# The run stopped, or a capacity check rejected the step, while the world was in its first episode.
duration = int(ex.episode_steps[e]) * ex.frame_dt
assembled = int(ex.assembled[e].sum())
if self.rejected is not None and not ex.first_done[e]:
outcome, label = "invalid", f"Rejected: {self.rejected}"
elif not ex.first_done[e]:
outcome, label = "partial", f"Unfinished: {assembled}/{NUM_PARTS} assembled"
elif ex.first_success[e]:
outcome, label = "success", "Success"
elif ex.first_timeout[e]:
outcome, label = "timeout", "Timeout"
else:
left = [ev["part"] for ev in sorted(events, key=lambda x: x["f"]) if ev["kind"] == "left"]
outcome, label = "invalid", "Left workspace: " + (_part_label(ex.assemblies[left[0]]) if left else "?")
run = {"file": name, "frames": last + 1, "fps": self.hz, "outcome": outcome, "outcome_label": label,
"duration": round(duration, 2), "assembled": assembled,
"events": sorted(events, key=lambda x: x["f"])}
if self.hz == 100:
run["contacts"], run["contacts_n"] = self._write_contacts(e, last), None
run["forces"] = ex.observables is not None
run["contacts_per"] = "pair"
runs[str(e)] = {self.source: {arm: run}}
episodes.append({"env": e, "group": f"{_ARM_LABEL.get(arm, arm)} - {outcome}",
"title": f"world {e} - {label}", "a": arm, "b": None, "caption": ""})
names = ["NistBoard", *[ex.model.body_label[b].rsplit("/", 1)[-1] for b in ex.robot_bodies[0].tolist()],
*[f"fixed_{s}" for s in ex.socket_names], *[f"held_{i:02d}" for i in range(NUM_PARTS)]]
manifest = {
"bodies": [{"path": n, "name": n} for n in names],
"parts": [{"key": p.name, "label": _part_label(p), "socket": _socket_label(p)} for p in ex.assemblies],
"arms": {arm: _ARM_LABEL.get(arm, arm)},
"sources": {self.source: {"label": "Every policy step, 25 Hz" if self.hz == 25 else "Every physics step, 100 Hz",
"fps": self.hz}},
"pos_q": self.POS_Q, "force_q": self.FORCE_Q,
"workspace": [list(WORKSPACE_LOWER), list(WORKSPACE_UPPER)],
"episodes": episodes, "runs": runs,
"seed": ex.seed, "selection_seed": ex.selection_seed,
}
with open(self.out / "manifest.json", "w") as f:
json.dump(manifest, f, separators=(",", ":"))
self._write_glb(self.out / "scene.glb")
print(f"Recorded {ex.world_count} worlds to {self.out}", flush=True)
def _write_contacts(self, world, last):
counts, pts, forces, pairs = [], [], [], []
for keys, centre, net in self.contacts[: last + 1]:
mine = keys >> 16 == world
counts.append(int(mine.sum()))
pts.append(centre[mine])
forces.append(net[mine])
pairs.append(np.stack(((keys[mine] >> 8) & 255, keys[mine] & 255), -1))
blob = (np.array(counts, "<u2").tobytes()
+ np.clip(np.round(np.concatenate(pts) / self.POS_Q), -32767, 32767).astype("<i2").tobytes()
+ np.clip(np.round(np.concatenate(forces) / self.FORCE_Q), -32767, 32767).astype("<i2").tobytes()
+ np.clip(np.concatenate(pairs), 0, 255).astype("u1").tobytes())
name = f"{self.source}/{self.ex.preset.name}_{world:03d}_c.bin"
with gzip.open(self.out / name, "wb", compresslevel=9) as f:
f.write(blob)
return name
def _write_glb(self, path):
"""World 0's drawn geometry, one node ``b<index>_*`` per viewer body in that body's frame."""
import trimesh # noqa: PLC0415 (only the recorder writes a GLB)
model = self.ex.model
flags = model.shape_flags.numpy()
shape_body, shape_type = model.shape_body.numpy(), model.shape_type.numpy()
scale, xform, color = model.shape_scale.numpy(), model.shape_transform.numpy(), model.shape_color.numpy()
scene = trimesh.Scene()
bodies = self.body_ids[0].tolist()
for index, body in enumerate(bodies):
shapes = [s for s in np.nonzero(shape_body == body)[0] if flags[s] & int(newton.ShapeFlags.VISIBLE)]
if not shapes: # an asset without a separate visual mesh is drawn with its collider
shapes = [s for s in np.nonzero(shape_body == body)[0] if flags[s] & int(newton.ShapeFlags.COLLIDE_SHAPES)]
for s in shapes:
if shape_type[s] == int(newton.GeoType.BOX):
mesh = trimesh.creation.box(extents=2.0 * scale[s])
elif shape_type[s] in (int(newton.GeoType.MESH), int(newton.GeoType.CONVEX_MESH)):
src = model.shape_source[s]
mesh = trimesh.Trimesh(np.asarray(src.vertices) * scale[s], np.asarray(src.indices).reshape(-1, 3), process=False)
else:
continue
m = np.eye(4)
m[:3, :3] = trimesh.transformations.quaternion_matrix(np.roll(xform[s, 3:], 1))[:3, :3]
m[:3, 3] = xform[s, :3]
mesh.apply_transform(m)
rgb = [float(x) for x in color[s][:3]] if color is not None else [0.7, 0.7, 0.7]
mesh.visual = trimesh.visual.TextureVisuals(material=trimesh.visual.material.PBRMaterial(
baseColorFactor=[*rgb, 1.0], metallicFactor=0.05, roughnessFactor=0.55))
scene.add_geometry(mesh, node_name=f"b{index}_{len(scene.graph.nodes)}", geom_name=f"g{index}_{len(scene.geometry)}")
scene.export(str(path))
_ARM_LABEL = {"steel": "Steel", "steel_rolling": "Steel + rolling friction 1 mm"}
def _part_label(part: Assembly) -> str:
return part.plug.replace("_", " ")
def _socket_label(part: Assembly) -> str:
return part.socket.replace("_", " ")
def _rotate(q, v):
"""Rotate vectors ``v`` by xyzw quaternions ``q`` (numpy)."""
xyz, w = q[:, :3], q[:, 3:4]
t = 2.0 * np.cross(xyz, v)
return v + w * t + np.cross(xyz, t)
def _to_world(body_q, body, point):
"""Body-frame contact points in world frame; static shapes (body -1) are already there."""
out = point.copy()
moving = body >= 0
out[moving] = body_q[body[moving], :3] + _rotate(body_q[body[moving], 3:], point[moving])
return out
def _write_pose(path, pos, quat, pos_q):
"""Gzip of planar int16 time-deltas, channels (body, [x y z qx qy qz qw]) by frame."""
q = quat.astype(np.float64)
q /= np.linalg.norm(q, axis=-1, keepdims=True)
for t in range(1, len(q)):
s = np.sign((q[t] * q[t - 1]).sum(-1))
s[s == 0] = 1
q[t] *= s[:, None]
a = np.concatenate([np.round(pos / pos_q), np.round(q * 32767)], -1).astype(np.int64)
d = np.diff(a, axis=0, prepend=0)
d = ((d + 32768) % 65536 - 32768).astype("<i2")
with gzip.open(path, "wb", compresslevel=9) as f:
f.write(np.ascontiguousarray(d.transpose(1, 2, 0)).tobytes())
if __name__ == "__main__":
parser = Example.create_parser()
viewer, args = newton.examples.init(parser)
newton.examples.run(Example(viewer, args), args)

README

A Franka arm picks ten parts off a table and inserts them into a NIST task board, driven by a pretrained policy: nuts onto bolts, pegs into holes, a gear onto its shaft and USB-A, RJ45, D-sub and waterproof connectors into their sockets. Every contact between a part and a fixture is a mesh against a signed distance field.

This is a standalone Newton port of the NIST demo (examples/demos/nist.py) in isaac-sim/IsaacLab#9177, ported from the pull request’s head commit 2a28cad06. It runs without Isaac Lab: Newton’s ModelBuilder imports the same USD assets, Newton’s CollisionPipeline collides them and SolverSteel steps them. The demo and the alphaNIST policy are by ooctipus; the policy was trained in MuJoCo Warp.

uv sync --extra policy                                      # the policy needs torch
uv run python -m shelf play nist_assembly                   # Steel + rolling friction, 4 boards
uv run python -m shelf play nist_assembly --solver steel    # Steel without rolling friction
uv run python -m shelf play nist_assembly --viewer null --world-count 4 --seed 1703 --deterministic \
    --num-frames 3500 --record outputs/nist_1703                # a replay of every board's first episode
uv run python -m shelf check nist_assembly

The first run downloads the policy and about 120 MB of USD (for the default part set) from Isaac Lab’s public content (omniverse-content-production.s3-us-west-2.amazonaws.com/Assets/Isaac/6.2/Isaac/IsaacLab) into ~/.cache/steel-shelf/isaaclab-nist (STEEL_SHELF_CACHE moves it). The policy and the USD assets are not bundled here; the ported code keeps Isaac Lab’s BSD-3-Clause notice (see Provenance).

What the port reproduces

The example rebuilds the demo’s scene, physics settings, policy inputs and resets, so that the same seed gives the same board. Run against Isaac Lab’s demo on the same Newton build and seeds, the finalized models agree on every body mass, centre of mass and inertia, every collider’s material, gap, margin, SDF and friction mode, and every drive gain, limit, armature and target mode. The reset poses agree to 1e-16 rad, the policy’s robot observations are bitwise identical and its per-part observations agree to 1.2e-7, and the first actions agree to 6e-6. With --deterministic on both sides, the arm follows the same path to within 3e-7 m until the first parts land. From there those small differences grow through contact and the runs separate. For scale, two default (nondeterministic) runs of the same stack are already millimetres apart when the parts land. Over the same 32 seeds of four boards, Isaac Lab and this example finish with:

Preset Isaac Lab demo This example Boards lost (part left the workspace)
steel_rolling 82.0% (105/128) 83.6% (107/128) 1 / 2
steel 55.5% (71/128) 60.9% (78/128) 24 / 23, 19 / 18 of them the 16 mm round peg

Complete boards over every board’s first 140 s episode; the remaining boards timed out with parts still loose.

Scene Franka (franka_panda.usda, gripper colliders only), the NIST board, the fixtures and ten loose parts per world; --selection-seed picks ten of the 19 part types (the default, 1701, picks the demo’s set) and --seed seeds each reset
Timing 100 Hz physics with 8 Steel substeps, policy at 25 Hz, 140 s episodes
Contacts Texture SDF on every finite collider: resolution 256 and a +-5 mm band on parts and fixtures, resolution 64 elsewhere; 5 mm contact gap on parts and fixtures; contacts between the kinematic board and fixtures are skipped
Materials mu 0.75 on parts, board, fixtures and fingers; ground mu 1.0
Arm the demo’s implicit drives (stiffness 600 to 50, damping 50 to 15, armature 0.61 to 0.21), joint limits on; gravity is cancelled with a per-link body force, as the demo does for Steel
Policy TorchScript; robot history [N, 195] and per-part history [N, 5, 10, 40]; relative joint targets re-applied every physics step and a binary gripper
Success all ten parts seated (2.5 mm laterally, 1 mm deep, 0.025 rad tilt); a part leaving the workspace ends the episode

Presets

steel_rolling (the default) adds 1 mm of rolling friction to the loose parts (ShapeFrictionMode.SLIDING_ROLLING, mu_rolling = 0.001). Without it the 16 mm round peg, when it lands on its side, rolls off the edge of the workspace before the arm reaches it. steel is plain Steel at 12 iterations, kept to show that failure; steel_rolling runs four. With only rolling friction changed, on the same 32 seeds of four boards, the boards lost go from 23 to 1 at 12 iterations (18 to 0 of them the round peg) and from 43 to 2 at four iterations (36 to 0).

Both presets differ from the demo’s own Steel settings (iterations=8, baumgarte=0.05, joint limits off, free_body_constraint_max=4096), which assembled about half the boards: joint limits on, Baumgarte 0.2, contact_gap_gate=0 (no rows for contacts that are still apart), free_body_constraint_max=1280 and no contact generation between the board and its fixtures, which never move relative to each other. The parity runs above used these settings on both sides.

check runs four boards of seed 1701 for one full episode and fails on any board left unfinished, on fewer complete boards than the preset’s check_min_success, or on dropped contact rows.

Replays

--record DIR writes every world’s first episode for the NIST replay viewer: manifest.json, a pose stream per world (pub/, every policy step, or with --record-hz 100 every physics step in hr/ plus each touching body pair’s net contact force and load centre) and scene.glb. --deterministic sorts contacts and fixes the solve order. On the build and GPU the port was checked on, two runs of a seed matched bitwise over the first 50 policy steps.

Provenance

  • Code: ported from examples/demos/nist.py in isaac-sim/IsaacLab#9177 (head 2a28cad06), Copyright (c) 2022-2026 The Isaac Lab Project Developers, BSD-3-Clause (licenses/IsaacLab-BSD-3-Clause.txt). The part table, constants and reset sampling are copied; the scene, stepping, observations and actions are rewritten on Newton.
  • Policy: demo-alphaNIST.pt by ooctipus, trained in MuJoCo Warp, downloaded at run time.
  • Assets: the Franka, the NIST board, fixtures and parts are downloaded at run time from Isaac Lab’s public content and remain under their own terms (see licenses/runtime-assets/isaaclab-nist.txt).