#!/usr/bin/env python3 # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 """Read one frame of contact patches, whichever layout the dataset uses. The sidecar (``contacts/hand_obj/episode_*.npz``) stores, per frame that had contact: _tri (n, 3, 3) float32 the face's three vertices _depth (n,) float32 penetration, negative _shape_pair (n, 2) int32 which two shapes touched and, since 2026-09-12, the SOLVER'S contacts on the same collision pass (``tools/solver_contacts.py``; m is a few dozen, not thousands; only on frames that have a patch): _mj_pair (m, 2) int32 (hand shape, object shape) _mj_pos (m, 3) float32 contact point, world _mj_normal (m, 3) float32 unit, from the hand into the object _mj_dist (m,) float32 signed distance, negative = penetration _mj_force (m, 3) float32 force ON THE OBJECT, world, newtons Centroid, normal, area and force are NOT stored, because each is a function of those and storing both would be storing the same thing twice while still losing the patch's actual shape. :func:`read` computes them. The same layout, in ``contacts/obj_obj/episode_*.npz``, holds the OBJECT-OBJECT surface (peg<->socket, nut<->bolt, gear<->gear: every pair of hydroelastic task-object shapes, target and props, never a hand or the table), recorded live or built from the recorded poses by ``tools/compile_contacts.py --pairs object-object``. It is a separate file, not extra keys in ``hand_obj/``, because several readers take the frame index from ANY key's prefix and then index ``_depth`` -- a frame with object contact and no hand contact would break them. Two whole-episode arrays travel with it: ``contact_count`` and ``contact_available_count``, one entry per recorded frame (the parquet carries those for the hand-object patch; this sidecar carries its own). Every function here reads either file. Neither file is per-pair. A scene with THREE objects records (A,B), (A,C) and (B,C) into the one ``obj_obj`` sidecar, and both hands share the one ``hand_obj`` sidecar; ``_shape_pair`` says which two shapes each face belongs to, resolvable through ``meta/assets/shapes.json``. Nothing here caps the object count, and :func:`split_by_pair` slices one pair back out. Older datasets stored ``c``/``normal``/``area``/``force`` and no vertices. Those are read too, and report ``tri = None`` -- the triangles cannot be recovered from a centroid, so a consumer that genuinely needs patch GEOMETRY has to check for it rather than assume. Everything else is identical either way, so the common case needs no branch. Force ----- Two forces, and they are not the same thing. ``force`` (derived, per face) is ``area * kh * |depth|``: the hydroelastic pressure law, with ``kh`` a property of the RUN that lives in the dataset's ``meta`` and is passed in here rather than assumed. It is the pressure DISTRIBUTION over the patch -- which faces carry the load -- and its absolute scale is not to be trusted: in a measured flat-pad pinch it summed to ~3.5x the force actually applied, because the overlap is what the constraint solver leaves rather than something ``kh`` sets. ``mj_force`` (stored, per solver contact) is what MuJoCo-Warp applied: the normal and friction force it solved for on each reduced contact, on the object, in newtons. Sum it over a frame for the net force the hand exerts on the object. It is coarser (a few dozen points) and it is the truth. """ from __future__ import annotations import os import numpy as np FIELDS = ("tri", "c", "normal", "area", "depth", "force", "shape_pair") MJ_FIELDS = ("mj_pair", "mj_pos", "mj_normal", "mj_dist", "mj_force") #: Which shape pairs a capture keeps. ``hand-object``: one shape a hand's, #: the other a task object's (target or prop), either order -- what the live #: recorder writes to ``contacts/``. ``object-object``: both shapes task #: objects', on different shapes -- the nut on its bolt as much as the peg in #: the socket, since the two are bodies of one asset there; never a hand, the #: table or the world. PAIRS = ("hand-object", "object-object") #: Where each class's sidecar lives under the dataset, relative to its root. #: Both live under ``contacts/`` so one directory holds every patch a #: recording made, whatever it touched. SIDECAR_DIR = {"hand-object": os.path.join("contacts", "hand_obj"), "object-object": os.path.join("contacts", "obj_obj")} def sidecar_path(root: str, episode: int, pairs: str = "hand-object") -> str: """The sidecar file for one episode of one pair class. The single place that spells the layout out. Callers that build the path themselves are how the two classes drifted apart in the first place. """ if pairs not in PAIRS: raise ValueError(f"pairs must be one of {PAIRS}, not {pairs!r}") return os.path.join(root, SIDECAR_DIR[pairs], f"episode_{episode:06d}.npz") def split_by_pair(frame: dict) -> dict: """One frame's faces grouped by the shape pair they belong to. Keyed by ``(lo, hi)`` shape index, so a scene with any number of objects can be read one interaction at a time without the sidecar having to be split on disk. Returns ``{}`` when the frame carries no ``shape_pair``. """ sp = frame.get("shape_pair") if sp is None: return {} sp = np.asarray(sp) keys = np.sort(sp, axis=1) n = len(sp) out: dict = {} for lo, hi in np.unique(keys, axis=0): m = (keys[:, 0] == lo) & (keys[:, 1] == hi) sub = {k: (v[m] if isinstance(v, np.ndarray) and len(v) == n else v) for k, v in frame.items() if k != "n"} sub["n"] = int(m.sum()) out[(int(lo), int(hi))] = sub return out def capture(verts, depth, pair, cap=0, hand_shapes=None, object_shapes=None, pairs: str = "hand-object"): """Filter a solver surface and report valid faces lost to the recording cap. A zero cap keeps all valid faces. This does not change solver contacts. ``pairs`` picks the class of shape pair kept (:data:`PAIRS`); it needs both shape sets, and without them nothing is filtered. """ if pairs not in PAIRS: raise ValueError(f"pairs must be one of {PAIRS}, not {pairs!r}") if cap < 0: raise ValueError("contact face cap must be >= 0") tri = np.asarray(verts).reshape(-1, 3, 3) depth = np.asarray(depth) pair = np.asarray(pair).reshape(-1, 2) if len(tri) != len(depth) or len(pair) != len(depth): raise ValueError("contact surface arrays have inconsistent lengths") if hand_shapes is not None and object_shapes is not None: # Filter BEFORE the cap so resting gears cannot crowd a grasp out of # the recording. Two hands share the same membership set. o0 = np.isin(pair[:, 0], list(object_shapes)) o1 = np.isin(pair[:, 1], list(object_shapes)) if pairs == "object-object": keep = o0 & o1 & (pair[:, 0] != pair[:, 1]) else: h0 = np.isin(pair[:, 0], list(hand_shapes)) h1 = np.isin(pair[:, 1], list(hand_shapes)) keep = (h0 & o1) | (h1 & o0) tri, depth, pair = tri[keep], depth[keep], pair[keep] valid = (np.isfinite(depth) & (depth < 0) & np.isfinite(tri).all(axis=(1, 2))) tri, depth, pair = tri[valid], depth[valid], pair[valid] area2 = np.linalg.norm(np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0]), axis=1) valid = area2 > 1e-12 tri, depth, pair = tri[valid], depth[valid], pair[valid] available = len(depth) n = min(available, cap) if cap else available stats = {"contact_available_count": available, "contact_dropped_count": available - n} data = ({"tri": tri[:n].astype(np.float32), "depth": depth[:n].astype(np.float32), "shape_pair": pair[:n].astype(np.int32)} if n else None) return data, stats def frames_with_contact(z) -> list[int]: """Frame indices that have a patch, ascending.""" out = set() for k in z.files: head, _, tail = k.partition("_") if tail in ("depth",) and head.isdigit(): out.add(int(head)) return sorted(out) def frames_with_solver_contact(z) -> list[int]: """Frame indices that have solver contacts (``mj_*``), ascending.""" out = set() for k in z.files: head, _, tail = k.partition("_") if tail == "mj_pair" and head.isdigit(): out.add(int(head)) return sorted(out) def read_solver(z, frame: int) -> dict | None: """One frame's solver contacts: the ``mj_*`` arrays plus ``n``, or None when the frame has none (or the dataset predates them).""" p = f"{frame:06d}_" if p + "mj_pair" not in z: return None out = {k: np.asarray(z[p + k]) for k in MJ_FIELDS if p + k in z} out["n"] = int(len(out["mj_pair"])) return out def read(z, frame: int, kh: float | None = None, limit: int | None = None) -> dict | None: """One frame's contact patches, with the derived fields filled in. Args: z: an open ``np.load`` of a contacts sidecar. frame: frame index, as it appears in the key prefix. kh: contact stiffness from the dataset meta. Without it ``force`` is None rather than wrong -- there is no sensible default, and a silently assumed stiffness is exactly the freezing this layout exists to avoid. limit: keep at most this many faces (for viewers with fixed budgets). Returns None when that frame had no contact. The solver's contacts, when the frame has them, come back under the ``mj_*`` keys (None otherwise); :func:`read_solver` reads those alone. The writer stores solver rows only on frames that have a patch, so a frame with a patch is the only kind. """ p = f"{frame:06d}_" if p + "depth" not in z: return None mj = read_solver(z, frame) depth = np.asarray(z[p + "depth"]) n = len(depth) if limit is None else min(len(depth), limit) depth = depth[:n] out: dict = {"depth": depth, "n": n} out["shape_pair"] = (np.asarray(z[p + "shape_pair"])[:n] if p + "shape_pair" in z else None) if p + "tri" in z: # current layout tri = np.asarray(z[p + "tri"])[:n] v0, v1, v2 = tri[:, 0], tri[:, 1], tri[:, 2] nrm = np.cross(v1 - v0, v2 - v0) ln = np.linalg.norm(nrm, axis=1) # The writer drops degenerate faces, so this cannot divide by zero on a # well-formed file. Guarded anyway: a diagnostic must not be the thing # that raises on a truncated or hand-edited dataset. safe = np.maximum(ln, 1e-20) out["tri"] = tri out["c"] = (v0 + v1 + v2) / 3.0 out["normal"] = nrm / safe[:, None] out["area"] = ln / 2.0 else: # pre-triangle datasets out["tri"] = None for f in ("c", "normal", "area"): out[f] = np.asarray(z[p + f])[:n] if p + f in z else None if p + "force" in z: # stored by the old writer out["force"] = np.asarray(z[p + "force"])[:n] elif kh is not None and out["area"] is not None: out["force"] = out["area"] * float(kh) * np.abs(depth) else: out["force"] = None out.update({k: (None if mj is None else mj.get(k)) for k in MJ_FIELDS}) return out def kh_from_meta(meta: dict) -> float | None: """``kh`` out of a dataset's meta, wherever that build put it.""" for path in (("contact", "kh"), ("kh",), ("physics", "kh"), ("collection", "kh")): cur = meta for key in path: if not isinstance(cur, dict) or key not in cur: cur = None break cur = cur[key] if isinstance(cur, (int, float)): return float(cur) return None