From 759b969b928ba03a40a7ce1ea588551d2bd58fb3 Mon Sep 17 00:00:00 2001 From: yunjul Date: Thu, 26 Nov 2026 19:29:52 +0800 Subject: [PATCH] egocap: add Manus glove calibration tools Two terminal tools under examples/egocap/tools/calibration/ place a Manus glove on the rig from its raw fingertip sensors: - calibrate_aim_to_coil.py: the glove's main coil in the controller aim frame, from one clamped fingertip sensor while the controller is turned around it. - calibrate_coil_to_wrist.py: the recorded wrist frame in the main-coil frame, from the five fingertip sensors and the hand skeleton. Each tool records its take from a running CaptureServer through the capture client, the backend's conversion functions and the recording service, with no page or camera, then solves it. Only the calibrated side is recorded, so the other glove and controller can stay off. The tool lists what to switch on and the steps, waits for the devices and names any that is missing. An existing episode can be solved instead. Data selection and acceptance are fixed rules, so a take needs no judgement: every check prints its value and, when it fails, what to change. A passed transform is saved in the station calibration file wrist_calibration_offsets.json, which a recording copies into every session; a failed take saves nothing. Signed-off-by: yunjul Co-Authored-By: Claude Fable 5.2 --- examples/egocap/.gitignore | 3 + examples/egocap/AGENTS.md | 10 + examples/egocap/README.md | 3 + .../egocap/tests/tools/test_calibration.py | 232 ++++++++++++++++ examples/egocap/tools/calibration/README.md | 138 ++++++++++ .../egocap/tools/calibration/calib_common.py | 217 +++++++++++++++ .../calibration/calibrate_aim_to_coil.py | 257 ++++++++++++++++++ .../calibration/calibrate_coil_to_wrist.py | 192 +++++++++++++ examples/egocap/tools/calibration/record.py | 236 ++++++++++++++++ 9 files changed, 1288 insertions(+) create mode 100644 examples/egocap/tests/tools/test_calibration.py create mode 100644 examples/egocap/tools/calibration/README.md create mode 100644 examples/egocap/tools/calibration/calib_common.py create mode 100644 examples/egocap/tools/calibration/calibrate_aim_to_coil.py create mode 100644 examples/egocap/tools/calibration/calibrate_coil_to_wrist.py create mode 100644 examples/egocap/tools/calibration/record.py diff --git a/examples/egocap/.gitignore b/examples/egocap/.gitignore index 4d585ae87a..572ebd4737 100644 --- a/examples/egocap/.gitignore +++ b/examples/egocap/.gitignore @@ -5,3 +5,6 @@ tmp/ # Real per-lab station identity (serials, operators, IPs); only the *.example.* templates ship. recording/egocap/egocap_stations.json recording/egocap/stations/ego_stations.yaml + +# Takes recorded by tools/calibration/ when it is run from this directory. +calibration_takes/ diff --git a/examples/egocap/AGENTS.md b/examples/egocap/AGENTS.md index 252ccdeeae..76403de40f 100644 --- a/examples/egocap/AGENTS.md +++ b/examples/egocap/AGENTS.md @@ -94,3 +94,13 @@ before any file is written. An existing derived episode is refused, never replac CaptureServer README's offset table and descriptor example. Check each against the code's output, not by eye. - The acquisition adapter runs one code path for the real, mock and replay SDKs. Give a new SDK capability to all three; never probe the SDK for it, which turns a missing export into silently absent data. + +## Command-line tools carry their own procedure + +- The steps an operator follows to use a tool (which devices are worn, switched on or in view, and what to do) + are written once, in the tool's `--help`. Its README summarizes and points there, and no page UI is added for + a tool unless that is asked for. +- A script brought in from experiments is product code once it is here: drop diagnostics, plots and report + fields that no acceptance check or consumer uses, and keep each check's threshold and advice in one table. +- A calibration result belongs to the station: a tool saves it in the station's calibration directory and + keeps what else that file holds; it is never a file in the checkout. diff --git a/examples/egocap/README.md b/examples/egocap/README.md index bfa05fac20..03905e4d88 100644 --- a/examples/egocap/README.md +++ b/examples/egocap/README.md @@ -145,6 +145,9 @@ for tracking, and the `oak` extra plus a camera's device ID for OAK-D cameras. S The backend and frontends are unchanged between mock and real mode — CaptureServer is the only process that differs. +A rig with Manus gloves mounted on the controllers is calibrated with the terminal tools in +[`tools/calibration/`](tools/calibration/README.md). + ## Both UIs - The **capture/recording page** (`frontend/`) is always served once built; see diff --git a/examples/egocap/tests/tools/test_calibration.py b/examples/egocap/tests/tools/test_calibration.py new file mode 100644 index 0000000000..527ea55803 --- /dev/null +++ b/examples/egocap/tests/tools/test_calibration.py @@ -0,0 +1,232 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +from __future__ import annotations + +import asyncio +import json +import sys +import time +from pathlib import Path + +import numpy as np +import pytest +import zarr +from scipy.spatial.transform import Rotation + +# tools/calibration/ is a plain scripts directory, not a package; the root makes ``tests`` importable when +# this directory is run on its own. +_ROOT = Path(__file__).resolve().parents[2] +sys.path[:0] = [str(_ROOT / "tools" / "calibration"), str(_ROOT)] +import calib_common as common # noqa: E402 +import calibrate_aim_to_coil as aim_to_coil # noqa: E402 +import calibrate_coil_to_wrist as coil_to_wrist # noqa: E402 +import record # noqa: E402 +from tests.backend.test_recording_adapter import default_tracking_values # noqa: E402 + +from capture_server import protocol # noqa: E402 +from capture_server.client import CaptureFrame # noqa: E402 + +RATE_HZ = 60.0 +TRUTH = common.transform(Rotation.from_rotvec([0.4, -1.1, 0.7]).as_matrix(), [0.03, -0.07, 0.05]) + + +def _write_source(episode: Path, source: str, fields: dict[str, np.ndarray]) -> None: + group = zarr.open_group(str(episode / source), mode="w") + for name, values in fields.items(): + group.create_array(name, data=values) + + +def _poses(rotations: Rotation, positions: np.ndarray) -> np.ndarray: + poses = np.zeros((*positions.shape[:-1], 4, 4)) + poses[..., :3, :3] = rotations.as_matrix().reshape(*positions.shape[:-1], 3, 3) + poses[..., :3, 3] = positions + poses[..., 3, 3] = 1.0 + return poses + + +def _wave(times: np.ndarray, amplitude: float, seed: int, shape: tuple[int, ...] = ()) -> np.ndarray: + """Smooth, reproducible motion: (len(times), *shape, 3) sums of two slow sinusoids.""" + rng = np.random.default_rng(seed) + freq = rng.uniform(0.15, 0.5, (2, *shape, 3)) + phase = rng.uniform(0, 2 * np.pi, (2, *shape, 3)) + return ( + amplitude * np.sin(2 * np.pi * freq * times.reshape(-1, *[1] * (len(shape) + 2)) + phase).sum(axis=1) / 2 + ) + + +def _coil_to_wrist_episode(tmp_path: Path) -> Path: + times = np.arange(0, 40.0, 1 / RATE_HZ) + rng = np.random.default_rng(0) + offsets = rng.uniform(-0.01, 0.01, (5, 3)) + # Wrist-frame joints: static everywhere except the five moving fingertips. + joints = np.tile(rng.uniform(-0.05, 0.05, (25, 3)), (len(times), 1, 1)) + joints[:, coil_to_wrist.TIP] += _wave(times, 0.06, 1, (5,)) + sensor_rotations = Rotation.from_rotvec(_wave(times, 1.6, 2, (5,)).reshape(-1, 3)) + tips_in_coil = joints[:, coil_to_wrist.TIP] @ TRUTH[:3, :3].T + TRUTH[:3, 3] + sensor_positions = tips_in_coil - np.einsum( + "nkij,kj->nki", sensor_rotations.as_matrix().reshape(-1, 5, 3, 3), offsets + ) + episode = tmp_path / "session" / "episode_0" + _write_source( + episode, + "manus_glove", + { + "capture_time": 1000.0 + times, + "left_hand_pose": _poses(Rotation.identity(len(times) * 25), joints), + "left_sensor_pose": _poses(sensor_rotations, sensor_positions), + }, + ) + return episode + + +def _aim_to_coil_episode(tmp_path: Path, delay_s: float = 0.05, turn_rad: float = 2.2) -> Path: + times = np.arange(0, 40.0, 1 / RATE_HZ) + clamp = np.array([0.2, 1.1, -0.4]) + + def aim(at: np.ndarray) -> tuple[Rotation, np.ndarray]: + return Rotation.from_rotvec(_wave(at, turn_rad, 3)), clamp + _wave(at, 0.15, 4) + + # The sensor row stamped t holds what the coil measured when the controller was where it was at t - delay. + rotation, position = aim(times - delay_s) + in_aim = np.einsum("nji,nj->ni", rotation.as_matrix(), clamp - position) + in_coil = (in_aim - TRUTH[:3, 3]) @ TRUTH[:3, :3] + sensor_positions = np.zeros((len(times), 5, 3)) + sensor_positions[:, 2] = in_coil + episode = tmp_path / "session" / "episode_0" + _write_source(episode, "pico_controller", {"capture_time": 1000.0 + times, "right_pose": _poses(*aim(times))}) + _write_source( + episode, + "manus_glove", + { + "capture_time": 1000.0 + times, + "right_sensor_pose": _poses(Rotation.identity(len(times) * 5), sensor_positions), + }, + ) + return episode + + +def _run(tool, episode: Path, *args: str) -> tuple[int, dict]: + """The exit status and the results file's content after solving ``episode``.""" + results = episode.parents[1] / "results.json" + status = tool.main([str(episode), *args, "--results", str(results)]) + return status, json.loads(results.read_text()) if results.is_file() else {} + + +def test_coil_to_wrist_recovers_the_transform_and_saves_it_in_the_station_file(tmp_path, monkeypatch): + # The station's file may hold more than these tools write; that is kept. + monkeypatch.setenv("EGOCAP_CALIBRATION_DIR", str(tmp_path / "calibration")) + station = tmp_path / "calibration" / "wrist_calibration_offsets.json" + station.parent.mkdir() + station.write_text('{"other": 1}') + assert coil_to_wrist.main([str(_coil_to_wrist_episode(tmp_path)), "--side", "left"]) == 0 + results = json.loads(station.read_text()) + assert results == {"other": 1, "left": {"T_coil_wrist": results["left"]["T_coil_wrist"]}} + assert np.allclose(np.array(results["left"]["T_coil_wrist"]), TRUTH, atol=1e-4) + + +def test_a_failed_take_says_what_to_change_and_keeps_the_earlier_result(tmp_path, capsys): + episode = _coil_to_wrist_episode(tmp_path) + _, earlier = _run(coil_to_wrist, episode, "--side", "left") + group = zarr.open_group(str(episode / "manus_glove"), mode="r+") + hand, sensor = group["left_hand_pose"][:], group["left_sensor_pose"][:] + hand[:, coil_to_wrist.TIP[0]] = hand[0, coil_to_wrist.TIP[0]] + sensor[:, 0] = sensor[0, 0] + group["left_hand_pose"][:], group["left_sensor_pose"][:] = hand, sensor + status, results = _run(coil_to_wrist, episode, "--side", "left") + assert status == 1 and results == earlier + printed = capsys.readouterr().out + assert "[FAIL] least-turned sensor: thumb" in printed and "-> Bend the thumb more." in printed + assert "[FAIL] least-moved fingertip: thumb" in printed and "FAIL. Nothing was saved; record again." in printed + + +def test_aim_to_coil_recovers_the_transform(tmp_path): + status, results = _run(aim_to_coil, _aim_to_coil_episode(tmp_path), "--side", "right", "--finger", "middle") + solved = np.array(results["right"]["T_controller_manus"]) + assert status == 0 and list(results["right"]) == ["T_controller_manus"] + assert common.rotation_between_deg(TRUTH, solved) < 0.2 and np.allclose(solved[:3, 3], TRUTH[:3, 3], atol=5e-4) + + +def test_aim_to_coil_fails_a_take_whose_controller_barely_turned(tmp_path, capsys): + status, results = _run( + aim_to_coil, _aim_to_coil_episode(tmp_path, turn_rad=0.3), "--side", "right", "--finger", "middle" + ) + assert status == 1 and results == {} + assert "[FAIL] how far the controller turned" in capsys.readouterr().out + + +class _FakeCaptureClient: + """Stands in for CaptureClient: delivers the given tracking values at 60 Hz until stopped.""" + + values: dict = {} + + def __init__(self, url: str) -> None: + self._task: asyncio.Task | None = None + + async def start(self, *, sources, plugins, on_capture_frame, on_stopped) -> None: + description = protocol.tracking_stream_descriptor(tuple(sources), RATE_HZ) + + async def run() -> None: + sequence = 0 + while True: + stamp = time.monotonic_ns() + payload = protocol.encode_tracking_frame(self.values) + on_capture_frame(CaptureFrame("s", description, 0, sequence, stamp, stamp, payload)) + sequence += 1 + await asyncio.sleep(1 / RATE_HZ) + + self._task = asyncio.ensure_future(run()) + + async def stop(self) -> None: + if self._task is not None: + self._task.cancel() + + +def _record(tmp_path, monkeypatch, values, record_s=0.5, controllers=True): + monkeypatch.setattr(record, "CaptureClient", _FakeCaptureClient) + monkeypatch.setattr(_FakeCaptureClient, "values", values) + # Enter is "pressed" at once to start and after ``record_s`` to stop. + delays = iter((0.0, record_s)) + + async def enter(prompt): + await asyncio.sleep(next(delays)) + + monkeypatch.setattr(record, "_enter", enter) + return asyncio.run(record.record_take("ws://x", tmp_path / "takes", "task", "left", controllers, "PROCEDURE")) + + +def test_a_recorded_take_is_an_episode_the_solvers_read(tmp_path, monkeypatch, capsys): + episode = _record(tmp_path, monkeypatch, default_tracking_values()) + assert episode.parent.parent == tmp_path / "takes" and "PROCEDURE" in capsys.readouterr().out + glove = common.read_source(episode, "manus_glove", ("left_hand_pose", "left_sensor_pose"), "") + controller = common.read_source(episode, "pico_controller", ("left_pose",), "") + assert 15 < len(glove["capture_time"]) == len(controller["capture_time"]) + assert not (episode / "manus_glove" / "right_hand_pose").exists() + assert (glove["left_sensor_pose"][:, :, 3, 3] == 1).all() + + +def test_recording_waits_for_the_devices_and_says_which_are_missing(tmp_path, monkeypatch, capsys): + values = default_tracking_values() | {"manus_left.sensor_present": 0, "controller_left.aim_is_valid": 0} + monkeypatch.setattr(record, "LIVE_S", 0.05) + waited = record._wait_until_live + + async def give_up(feed, needed, side): + await asyncio.wait_for(waited(feed, needed, side), timeout=0.5) + + monkeypatch.setattr(record, "_wait_until_live", give_up) + with pytest.raises(TimeoutError): + _record(tmp_path, monkeypatch, values) + printed = capsys.readouterr().out + assert "Waiting for the left controller. Turn it on" in printed + assert "Waiting for the left glove's fingertip sensors." in printed + assert "Waiting for the left glove. Turn it on" not in printed + assert not list((tmp_path / "takes").glob("*/episode_*")) + + +def test_a_take_needs_only_the_calibrated_side(tmp_path, monkeypatch): + values = default_tracking_values() | {"controller_right.aim_is_valid": 0, "head.is_valid": 0} + values["hand_right.joint_valid"] = np.zeros(26, dtype=np.uint8) + episode = _record(tmp_path, monkeypatch, values) + assert len(common.read_source(episode, "pico_controller", ("left_pose",), "")["capture_time"]) > 15 + assert len(common.read_source(episode, "manus_glove", ("left_sensor_pose",), "")["capture_time"]) > 15 diff --git a/examples/egocap/tools/calibration/README.md b/examples/egocap/tools/calibration/README.md new file mode 100644 index 0000000000..133f2340d5 --- /dev/null +++ b/examples/egocap/tools/calibration/README.md @@ -0,0 +1,138 @@ + + +# Manus glove calibration tools + +A Manus glove reports the hand relative to the glove itself, not to the room. On this rig the glove is +located through the controller mounted on it, which the headset tracks. Two fixed transforms connect the +two, and these tools measure them: + +```text +room --(controller pose, tracked)--> controller --(1)--> glove main coil --(2)--> wrist and fingers +``` + +| | Tool | Measures | Redo it when | +| --- | --- | --- | --- | +| 1 | `calibrate_aim_to_coil.py` | where the glove's main coil sits on the controller | the mount on the controller changes | +| 2 | `calibrate_coil_to_wrist.py` | where the wrist sits relative to the main coil | the glove is recalibrated in Manus, or worn differently | + +Do each one for the left and the right hand. Each tool records a short take in the terminal, solves it, +prints PASS or FAIL with what to change, and saves a passed result. + +## Before you start + +The tools record from a CaptureServer and need nothing else of the stack: no page, cameras or LiveKit. + +1. Build IsaacCapture with the Manus plugin and start the CloudXR service, as + [`capture_server/README.md`](../../capture_server/README.md) describes under "Setup (real)". +2. Start CaptureServer from the `egocap` directory: + + ```bash + ISAAC_ROOT=/path/to/IsaacCapture uv run capture-server + ``` + + Nothing else may be using it: stop the full stack first, since its backend holds the same server. + +## Running a calibration + +From the `egocap` directory: + +```bash +uv run python tools/calibration/calibrate_aim_to_coil.py --side left --finger middle +uv run python tools/calibration/calibrate_coil_to_wrist.py --side left +``` + +The tool then: + +1. Lists what to switch on and the steps of the take. `--help` shows the same. +2. Waits for the devices it needs and names any that is missing. +3. Starts recording when you press Enter, and stops when you press Enter again. +4. Solves the take and prints each check with PASS or FAIL. A failed check says what to change. + +Only the hand being calibrated is needed; the other glove and controller can stay off. + +### 1. Aim to coil + +The glove is not worn. One fingertip sensor is held still while the controller, with the glove's main coil +on it, is turned around it; the only mount position that keeps the sensor in one place is the answer. + +1. Mount the controller on the glove. Turn on the glove, the controller and the headset, and keep the + controller where the headset can see it. +2. Clamp one fingertip sensor so it cannot move, and not against metal. Pass its finger as `--finger`. +3. Start the tool and press Enter. Slowly turn the controller in many directions for about two minutes, + without pulling on the clamped sensor. Press Enter to stop. + +### 2. Coil to wrist + +The glove is worn; the controller and the headset are not needed. The fingers are moved through a set of +motions, and the tool finds the one placement in which the fingertip sensors agree with the hand skeleton +that Manus reports. + +1. Put the glove on, push each fingertip sensor onto its fingertip, and keep the hand empty and off metal. +2. Start the tool and press Enter. Follow the motions it lists: single fingers, fists, spreading, thumb + circles and counting, at 3-4 seconds per motion, about 100 seconds in all. Press Enter to stop. + +### Options + +| Option | Meaning | +| --- | --- | +| `--side left\|right` | the hand to calibrate | +| `--finger NAME` | aim to coil only: the finger whose sensor is clamped (`thumb`, `index`, `middle`, `ring`, `little`) | +| `--capture-server URL` | CaptureServer to record from; default `ws://127.0.0.1:8082` | +| `--takes-dir DIR` | where the recorded take is kept; default `calibration_takes/` in the working directory | +| `--results FILE` | where a passed result is saved; default `wrist_calibration_offsets.json` in the station's calibration directory | +| `EPISODE` (first argument) | solve a recording again instead of recording a new take | + +`EPISODE` is an episode directory, or a session directory to use its last episode. A recording made with the +full stack also works; it has glove data only while both gloves are on, and controller data only while the +headset sees both controllers. + +## Results + +A passed calibration replaces its entry in `wrist_calibration_offsets.json` in the station's calibration +directory (`EGOCAP_CALIBRATION_DIR`, by default `~/egocap_data/calibration`). Anything else in that file is +kept. A recording copies the file into every session, so each session carries the calibration it was +recorded with. + +```json +{"left": {"T_controller_manus": [...], "T_coil_wrist": [...]}, "right": {...}} +``` + +Both are 4x4, in meters. `T_controller_manus` maps the main-coil frame into the controller aim frame; +`T_coil_wrist` maps the recorded `hand_pose` wrist frame into the main-coil frame. Chained with a recorded +controller pose they place the glove's hand in the room: +`T_room_wrist = controller pose x T_controller_manus x T_coil_wrist`. + +A failed take saves nothing, so the earlier result stays. To try a calibration without touching the +station's file, pass `--results` with another path. + +## If it does not work + +| You see | Do this | +| --- | --- | +| `Cannot reach CaptureServer ...` | Check that CaptureServer is running and that the full stack is stopped. Pass `--capture-server` if it listens on another port. On a machine with proxy variables set, unset them for this command. | +| `Waiting for the ... glove` | Turn the glove on and check that it is connected. Manus takes a few seconds to find a glove after the server starts. | +| `Waiting for the ... controller` | Turn the controller on and keep it where the headset can see it; the headset must be tracking. | +| `Only N s of ...` | The take is too short, or the device dropped out for most of it. Record again. | +| `FAIL` | Follow the line under each failed check and record again. | + +## How a take is judged + +Both tools (`calib_common.py`) first drop what cannot be used: lost controller tracking, or frames without +fingertip data. They then split the take into 5-second pieces and throw out a piece that fits badly when it is +left out of the fit, trim the remaining outliers, and solve from several random starts to make sure there is +only one answer. + +The checks, fixed in each script's `ACCEPT`: + +| Check | Aim to coil | Coil to wrist | +| --- | --- | --- | +| fit error | < 5 mm | < 2.5 mm | +| first half vs second half | < 5 deg | < 1.5 deg | +| part of the take thrown out | < 30 % | < 50 % | +| enough motion | controller turned > 90 deg | every sensor turned > 60 deg, every fingertip moved > 20 mm | +| other | glove lag between 0 and 200 ms, controller tracking lost < 30 % | sensor within 30 mm of its fingertip | +| other answers that fit as well | none within 1 deg | none within 1 deg | diff --git a/examples/egocap/tools/calibration/calib_common.py b/examples/egocap/tools/calibration/calib_common.py new file mode 100644 index 0000000000..8984723abe --- /dev/null +++ b/examples/egocap/tools/calibration/calib_common.py @@ -0,0 +1,217 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Rules shared by the Manus calibration solvers, so that no take needs a per-run judgement. + +Windows are rejected by a leave-one-segment-out score (a window is scored by a fit that did not see it, so a +bad window cannot pull the model toward itself), points are trimmed inside the kept windows, and a calibration +passes only if every row of its acceptance table does. +""" + +from __future__ import annotations + +import json +from collections.abc import Callable +from pathlib import Path + +import numpy as np +import zarr +from scipy.spatial.transform import Rotation + +#: The recorded fingertip-sensor order of ``manus_glove/{side}_sensor_pose``. +FINGERS = ("thumb", "index", "middle", "ring", "little") +#: A take with less usable data than this has too few windows for the selection rules. +MIN_TAKE_S = 20.0 +SEG_WINDOW_S = 5.0 +#: A window is dropped when its held-out rms exceeds this many times the median of the kept windows. +SEG_FACTOR = 1.5 +SEG_MAX_PASSES = 6 +#: Evaluation cap of a held-out fit, which is warm-started from the current solution. +SEG_HELD_OUT_NFEV = 30 +TRIM_K = 2.5 +TRIM_PASSES = 3 + +#: The station calibration file passed results go into; a recording copies it into every session. +RESULTS_NAME = "wrist_calibration_offsets.json" + +#: Why a full recording can lack a source, as told to the operator. +GLOVE_ROWS_HINT = "A full recording has glove data only while both gloves are on and connected." +CONTROLLER_ROWS_HINT = "A full recording has controller data only while the headset sees both controllers." +SENSOR_HINT = "Check that the glove is on and connected." + + +def rms(values: np.ndarray) -> float: + """Root mean square of ``values``.""" + return float(np.sqrt(np.mean(np.square(values)))) + + +def transform(rotation: np.ndarray, translation: np.ndarray) -> np.ndarray: + """The 4x4 homogeneous transform of a rotation matrix and a translation.""" + out = np.eye(4) + out[:3, :3] = rotation + out[:3, 3] = translation + return out + + +def rotation_between_deg(a: np.ndarray, b: np.ndarray) -> float: + """Angle in degrees between the rotations of two 4x4 transforms.""" + return float(np.degrees(Rotation.from_matrix(a[:3, :3].T @ b[:3, :3]).magnitude())) + + +def orientation_span_deg(rotations: Rotation) -> float: + """Twice the 95th-percentile angle of ``rotations`` from their mean: how far a body turned.""" + return 2 * float(np.percentile(np.degrees((rotations.mean().inv() * rotations).magnitude()), 95)) + + +def random_rotations(count: int, seed: int) -> np.ndarray: + """``count`` reproducible random rotation matrices, the solvers' only starting points.""" + return Rotation.random(count, random_state=seed).as_matrix() + + +def segment_reject( + times: np.ndarray, + usable: np.ndarray, + fit: Callable[..., np.ndarray], + resid: Callable[[np.ndarray], np.ndarray], + p0: np.ndarray, + *, + floor_mm: float, + held_out_stride: int, +) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Leave-one-segment-out rejection of ``SEG_WINDOW_S`` windows. + + ``fit(frame_mask, p0[, max_nfev])`` returns parameters and ``resid(p)`` a per-frame residual in mm. A + window is dropped when its held-out rms exceeds ``max(SEG_FACTOR * median, floor_mm)`` over the kept + windows. Returns the per-window keep mask, each frame's window index and the parameters. + """ + window = (times // SEG_WINDOW_S).astype(int) + count = window.max() + 1 + # A window with too few usable frames cannot be scored, so it is never kept. + keep = np.array([(usable & (window == w)).sum() >= 20 for w in range(count)]) + # Held-out fits are thinned for speed; the scores use every frame. + thinned = np.arange(len(times)) % held_out_stride == 0 + p = fit(usable & keep[window], p0) + for _ in range(SEG_MAX_PASSES): + scores = np.full(count, np.nan) + for w in np.flatnonzero(keep): + held_out = fit(usable & keep[window] & (window != w) & thinned, p, SEG_HELD_OUT_NFEV) + scores[w] = rms(resid(held_out)[usable & (window == w)]) + # The floor stops the relative threshold from ratcheting down once the data is clean. + kept = keep & ~(scores > max(SEG_FACTOR * np.nanmedian(scores), floor_mm)) + if np.array_equal(kept, keep): + break + keep = kept + p = fit(usable & keep[window], p) + return keep, window, p + + +def point_trim( + mask: np.ndarray, + fit: Callable[..., np.ndarray], + resid: Callable[[np.ndarray], np.ndarray], + p: np.ndarray, + floor_mm: float = 0.0, +) -> tuple[np.ndarray, np.ndarray]: + """Trim residuals above ``max(TRIM_K * rms, floor_mm)`` inside ``mask``; returns the mask and parameters.""" + base = mask + for _ in range(TRIM_PASSES): + p = fit(mask, p) + residual = resid(p) + # Trimming restarts from the full selection, so a point can come back once the fit improves. + trimmed = base & (residual < max(TRIM_K * rms(residual[mask]), floor_mm)) + if np.array_equal(trimmed, mask): + break + mask = trimmed + return mask, p + + +def multistart_ambiguity_deg(results: list[tuple[float, np.ndarray]], tolerance_deg: float) -> float: + """Largest rotation between the best (rms, transform) and another that fits within 5% of it. + + Differences up to ``tolerance_deg`` are the same solution and count as 0. + """ + best_rms, best = min(results, key=lambda result: result[0]) + angles = [rotation_between_deg(best, other) for other_rms, other in results if other_rms <= 1.05 * best_rms] + return max((angle for angle in angles if angle > tolerance_deg), default=0.0) + + +def resolve_episode(path: Path) -> Path: + """``path`` itself when it is an episode directory, or the last episode of the session directory it names.""" + indices = [int(child.name[8:]) for child in path.glob("episode_*") if child.name[8:].isdigit()] + if not indices: + return path + episode = path / f"episode_{max(indices)}" + print(f"Using the session's last episode: {episode}") + return episode + + +def read_source(episode: Path, source: str, fields: tuple[str, ...], hint: str) -> dict[str, np.ndarray]: + """``capture_time`` and the named fields of one numeric source of a recorded (not time-aligned) episode. + + ``hint`` tells the operator what makes the recorder write this source; it ends the refusal of an episode + that has no rows of it. + """ + if not (episode / source).is_dir(): + raise SystemExit(f"{episode} has no {source} data. {hint}") + group = zarr.open_group(str(episode / source), mode="r") + stored = {name for name, _ in group.arrays()} + # A missing field is never substituted: the episode was recorded by a version that did not store it. + missing = [name for name in fields if name not in stored] + if missing: + raise SystemExit(f"{episode}: {source} has no {', '.join(missing)}. Record a new take.") + data = {name: group[name][:] for name in ("capture_time", *fields)} + if len(data["capture_time"]) == 0: + raise SystemExit(f"{episode} has no {source} data. {hint}") + return data + + +def require_take(usable_times: np.ndarray, what: str, hint: str) -> None: + """Refuse a take whose usable samples span less than ``MIN_TAKE_S``.""" + seconds = float(np.ptp(usable_times)) if len(usable_times) else 0.0 + if seconds < MIN_TAKE_S: + raise SystemExit(f"Only {seconds:.0f} s of {what}; a take needs at least {MIN_TAKE_S:.0f} s. {hint}") + + +def finger_name(index: int) -> str: + """A finger as an operator would say it.""" + return FINGERS[index] if index == 0 else f"{FINGERS[index]} finger" + + +def finish( + results: Path, + side: str, + name: str, + result: np.ndarray, + accept: dict[str, tuple], + values: dict[str, float], + **names: str, +) -> int: + """Judge ``values`` against an acceptance table, print it, save a passed result and return the exit status. + + ``accept`` maps a check to (label, ``<`` or ``>``, threshold, unit, advice); a failed row prints its advice, + which says what to change in the next take. ``names`` fill the ``{...}`` fields of labels and advice. A + passed 4x4 ``result`` replaces ``results[side][name]`` and leaves the rest of the file as it was; a failed + one never replaces an earlier result. + """ + passed = True + for key, (label, op, threshold, unit, advice) in accept.items(): + value = float(values[key]) + ok = value < threshold if op == "<" else value > threshold + passed = passed and ok + label = label.format(**names) + print(f" [{'ok' if ok else 'FAIL':4s}] {label:40s} {value:8.2f} {unit:3s} (need {op} {threshold:g})") + if not ok: + print(f" -> {advice.format(**names)}") + if not passed: + print(" => FAIL. Nothing was saved; record again.") + return 1 + saved = json.loads(results.read_text()) if results.is_file() else {} + entry = saved.setdefault(side, {}) if isinstance(saved, dict) else None + if not isinstance(entry, dict): + raise SystemExit(f"{results} is not laid out by side. Pass --results with another file.") + entry[name] = result.tolist() + results.parent.mkdir(parents=True, exist_ok=True) + results.write_text(json.dumps(saved, indent=2, sort_keys=True) + "\n") + print(f" => PASS. Saved as {side} {name} in {results}") + return 0 diff --git a/examples/egocap/tools/calibration/calibrate_aim_to_coil.py b/examples/egocap/tools/calibration/calibrate_aim_to_coil.py new file mode 100644 index 0000000000..6c7af208a9 --- /dev/null +++ b/examples/egocap/tools/calibration/calibrate_aim_to_coil.py @@ -0,0 +1,257 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Find where a glove's main coil sits on its controller. + +One fingertip sensor is clamped at a fixed point while the controller and coil are turned around it. Model +(position only; the clamped housing may rotate): ``R_A(t-d) (R_X b(t) + t_X) + t_A(t-d) = y``. ``A`` is the +controller aim pose (``pico_controller/{side}_pose``), ``b`` the clamped sensor's position in the main-coil +frame (``manus_glove/{side}_sensor_pose``), ``X`` the unknown aim-from-coil transform, ``y`` the fixed point and +``d`` the delay of the glove data behind the controller, which is scanned. +""" + +from __future__ import annotations + +import argparse +import sys +from collections.abc import Callable +from pathlib import Path + +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation, Slerp + +# tools/calibration/ is a plain scripts directory, not a package. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import calib_common as common # noqa: E402 +import record # noqa: E402 + +#: What the operator does to record the take; shown by --help and before recording. +PROCEDURE = """What you need: + glove not worn, turned on, with the controller mounted on it + controller turned on, where the headset can see it + headset turned on and tracking + The other glove and controller are not needed. + +Steps: + 1. Clamp one fingertip sensor so it cannot move, and not against metal. Name its finger with --finger. + 2. When recording starts, slowly turn the controller in many directions for about two minutes. + Keep it moving and do not pull on the clamped sensor. +""" + +#: A controller sample is a glitch after a stream gap or a tracking jump; ``pad`` neighbours go with it. +GLITCH = dict(gap_s=0.04, jump_deg=6.0, jump_m=0.012, pad=2) +DELAY_COARSE_MS = np.arange(-100, 301, 10.0) +DELAY_FINE_HALF_MS = 9 +SEG_FLOOR_MM = 6.0 +HELD_OUT_STRIDE = 4 +TRIM_FLOOR_MM = 4.0 +HUBER_MM = 3.0 +RANDOM_STARTS = 8 +_DELAY_ADVICE = "The glove and controller data do not line up. Keep the controller moving the whole time." +#: Each check as (label, comparison, threshold, unit, what to change when it fails). The half-split gate catches +#: clamp slip; noise alone reaches 3-4 degrees on a 30-40 s take. +ACCEPT = { + "rms": ("fit error", "<", 5.0, "mm", "The clamped sensor moved. Clamp it firmly."), + "half_split": ("first half vs second half", "<", 5.0, "deg", "The clamp slipped. Clamp it firmly."), + "dropped": ("part of the take thrown out", "<", 0.30, "", "Check the clamp and turn the controller slower."), + "glitch": ("controller tracking lost", "<", 0.30, "", "Keep the controller where the headset can see it."), + "rotation": ( + "how far the controller turned", + ">", + 90.0, + "deg", + "Turn the controller further, in more directions.", + ), + "delay_low": ("glove lag, at least", ">", 0.0, "ms", _DELAY_ADVICE), + "delay_high": ("glove lag, at most", "<", 200.0, "ms", _DELAY_ADVICE), + "ambiguity": ("other answers that fit as well", "<", 1.0, "deg", "Turn the controller in more directions."), +} + + +class Track: + """The controller aim pose over time, interpolated, with its glitch samples marked.""" + + def __init__(self, times: np.ndarray, poses: np.ndarray) -> None: + """Index (N,4,4) aim poses by time and mark stream gaps and tracking jumps.""" + self.times = times + self.position = poses[:, :3, 3] + rotation = Rotation.from_matrix(poses[:, :3, :3]) + self.slerp = Slerp(times, rotation) + # A step is bad when it spans a gap or moves further than a tracked controller can in one sample. + turned = np.degrees((rotation[:-1].inv() * rotation[1:]).magnitude()) + moved = np.linalg.norm(np.diff(self.position, axis=0), axis=1) + bad = (np.diff(times) > GLITCH["gap_s"]) | (turned > GLITCH["jump_deg"]) | (moved > GLITCH["jump_m"]) + self.bad = bad.copy() + for k in range(1, GLITCH["pad"] + 1): + self.bad[k:] |= bad[:-k] + self.bad[:-k] |= bad[k:] + + def at(self, query: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Rotation matrices, positions and a usable mask at the ``query`` times.""" + inside = (query > self.times[0]) & (query < self.times[-1]) + clipped = np.clip(query, self.times[0], self.times[-1]) + step = np.clip(np.searchsorted(self.times, clipped), 1, len(self.times) - 1) - 1 + position = np.stack([np.interp(clipped, self.times, self.position[:, k]) for k in range(3)], axis=1) + return self.slerp(clipped).as_matrix(), position, inside & ~self.bad[step] + + +def load(episode: Path, side: str, finger: str) -> tuple[Track, np.ndarray, np.ndarray]: + """The controller aim track, and the clamped sensor's sample times and (N,3) main-coil positions.""" + aim = f"{side}_pose" + controller = common.read_source(episode, "pico_controller", (aim,), common.CONTROLLER_ROWS_HINT) + sensor = f"{side}_sensor_pose" + glove = common.read_source(episode, "manus_glove", (sensor,), common.GLOVE_ROWS_HINT) + # The recorder zeroes an unreported sensor set, so a real transform ends in 1. + reported = (glove[sensor][:, :, 3, 3] == 1).all(axis=1) + times = glove["capture_time"][reported] + common.require_take(times, f"{side} fingertip-sensor data", common.SENSOR_HINT) + track = Track(controller["capture_time"], controller[aim]) + return track, times, glove[sensor][reported, common.FINGERS.index(finger), :3, 3] + + +def unpack(p: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Rotation and translation of X, and the fixed point y, of a parameter vector.""" + return Rotation.from_rotvec(p[:3]).as_matrix(), p[3:6], p[6:9] + + +def aim_from_coil(p: np.ndarray) -> np.ndarray: + """The 4x4 transform X of a parameter vector.""" + rotation, translation, _ = unpack(p) + return common.transform(rotation, translation) + + +class Problem: + """The fit at one delay: controller poses already interpolated onto the sensor times.""" + + def __init__(self, aim_rotation: np.ndarray, aim_position: np.ndarray, b: np.ndarray) -> None: + """Store the per-sample aim pose and sensor position.""" + self.aim_rotation, self.aim_position, self.b = aim_rotation, aim_position, b + + def error(self, p: np.ndarray, rows: np.ndarray | slice = slice(None)) -> np.ndarray: + """Offset in mm, (rows, 3), of the sensor carried into the room frame by ``p`` from the fixed point.""" + rotation, translation, point = unpack(p) + in_aim = self.b[rows] @ rotation.T + translation + return (np.einsum("nij,nj->ni", self.aim_rotation[rows], in_aim) + self.aim_position[rows] - point) * 1000 + + def resid(self, p: np.ndarray) -> np.ndarray: + """Per-sample distance from the fixed point, in mm.""" + return np.linalg.norm(self.error(p), axis=1) + + def fit(self, mask: np.ndarray, p0: np.ndarray, max_nfev: int = 400) -> np.ndarray: + """Robust least squares on the masked samples.""" + rows = np.flatnonzero(mask) + return least_squares( + lambda p: self.error(p, rows).ravel(), + p0, + loss="huber", + f_scale=HUBER_MM, + x_scale="jac", + max_nfev=max_nfev, + ).x + + def start(self, rotation: np.ndarray) -> np.ndarray: + """Starting parameters at ``rotation``, zero translation and the median point that implies.""" + p = np.concatenate([Rotation.from_matrix(rotation).as_rotvec(), np.zeros(6)]) + p[6:9] = np.median(self.error(p), axis=0) / 1000 + return p + + +def quick_rms(problem: Problem, ok: np.ndarray, p0: np.ndarray) -> tuple[float, np.ndarray]: + """One robust fit and one trim: cheap enough to rank starts and delays, not a final solution.""" + p = problem.fit(ok, p0) + residual = problem.resid(p) + mask = ok & (residual < max(common.TRIM_K * np.median(residual[ok]), TRIM_FLOOR_MM)) + p = problem.fit(mask, p) + return common.rms(problem.resid(p)[mask]), p + + +def scan_delay( + at_delay: Callable[[float], tuple[Problem, np.ndarray]], p0: np.ndarray +) -> tuple[float, np.ndarray]: + """The delay in ms that minimises the quick rms, and the solution there. + + A coarse grid, a 1 ms grid around its best, then a parabola through the fine minimum. + ``at_delay(ms)`` returns the (problem, usable mask) at that delay. + """ + scan = {} + for delay in DELAY_COARSE_MS: + scan[float(delay)], p0 = quick_rms(*at_delay(delay), p0) + coarse = min(scan, key=scan.get) + for delay in np.arange(coarse - DELAY_FINE_HALF_MS, coarse + DELAY_FINE_HALF_MS + 0.1, 1.0): + scan[float(delay)] = quick_rms(*at_delay(delay), p0)[0] + best = min(scan, key=scan.get) + near = [delay for delay in scan if abs(delay - best) <= 3] + curve = np.polyfit(near, [scan[delay] for delay in near], 2) + # A parabola without a minimum keeps the grid's best. + if curve[0] > 0: + best = float(np.clip(-curve[1] / (2 * curve[0]), best - 3, best + 3)) + return best, p0 + + +def main(argv: list[str] | None = None) -> int: + """Record (or read) one take, solve it and save a passed result; returns 0 only when every check passed.""" + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], epilog=PROCEDURE, formatter_class=argparse.RawDescriptionHelpFormatter + ) + record.add_arguments(parser) + parser.add_argument( + "--finger", choices=common.FINGERS, required=True, help="the finger whose sensor is clamped" + ) + args = parser.parse_args(argv) + episode = record.episode_for(args, "glove calibration: aim to coil", True, PROCEDURE) + track, sensor_times, b = load(episode, args.side, args.finger) + times = sensor_times - sensor_times[0] + + def at_delay(delay_ms: float) -> tuple[Problem, np.ndarray]: + """The problem and usable mask with the controller read ``delay_ms`` before each sensor sample.""" + aim_rotation, aim_position, ok = track.at(sensor_times - delay_ms / 1000) + return Problem(aim_rotation, aim_position, b), ok + + problem, ok = at_delay(0.0) + common.require_take(sensor_times[ok], f"{args.side} controller tracking", common.CONTROLLER_ROWS_HINT) + print(f"Solving the {args.side} hand: {times[-1]:.0f} s recorded, {ok.mean():.0%} usable...") + + # 1. Initial solution at zero delay from random starts; there is no external initial guess. + starts = [problem.start(r) for r in common.random_rotations(RANDOM_STARTS, seed=0)] + p0 = min((quick_rms(problem, ok, start) for start in starts), key=lambda candidate: candidate[0])[1] + + # 2. The glove data lags the controller by an unknown delay. + delay_ms, p0 = scan_delay(at_delay, p0) + problem, ok = at_delay(delay_ms) + + # 3. Leave-one-segment-out rejection, then point trimming inside the kept segments. + keep, window, p = common.segment_reject( + times, ok, problem.fit, problem.resid, p0, floor_mm=SEG_FLOOR_MM, held_out_stride=HELD_OUT_STRIDE + ) + mask, p = common.point_trim(ok & keep[window], problem.fit, problem.resid, p, TRIM_FLOOR_MM) + + # 4. Multi-start on the final selection: a second solution that fits as well means the take is ambiguous. + fits = [p, *(problem.fit(mask, problem.start(r)) for r in common.random_rotations(RANDOM_STARTS, seed=1))] + results = [(common.rms(problem.resid(q)[mask]), aim_from_coil(q)) for q in fits] + best = min(range(len(fits)), key=lambda i: results[i][0]) + (fit_rms, x), p = results[best], fits[best] + + # 5. Stability (the two time halves must agree) and how far the controller turned around the clamp. + half = times < np.median(times[mask]) + split_deg = common.rotation_between_deg( + aim_from_coil(problem.fit(mask & half, p)), aim_from_coil(problem.fit(mask & ~half, p)) + ) + span_deg = common.orientation_span_deg(Rotation.from_matrix(problem.aim_rotation[mask])) + + values = dict( + rms=fit_rms, + half_split=split_deg, + dropped=1 - keep.mean(), + glitch=1 - ok.mean(), + rotation=span_deg, + delay_low=delay_ms, + delay_high=delay_ms, + ambiguity=common.multistart_ambiguity_deg(results, ACCEPT["ambiguity"][2]), + ) + return common.finish(args.results, args.side, "T_controller_manus", x, ACCEPT, values) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/egocap/tools/calibration/calibrate_coil_to_wrist.py b/examples/egocap/tools/calibration/calibrate_coil_to_wrist.py new file mode 100644 index 0000000000..2ec52c30a7 --- /dev/null +++ b/examples/egocap/tools/calibration/calibrate_coil_to_wrist.py @@ -0,0 +1,192 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Find where a glove's main coil sits relative to the wrist. + +Model (position only, five fingertips): ``a_t + R_At x_k = R_Y b_t + t_Y``. ``a_t``, ``R_At`` are a +fingertip sensor's pose in the main-coil frame (``manus_glove/{side}_sensor_pose``), ``b_t`` the same +fingertip in the wrist frame (``manus_glove/{side}_hand_pose``), ``x_k`` each finger's unknown tip offset in +its sensor frame and ``Y`` the coil-from-wrist transform. +""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation + +# tools/calibration/ is a plain scripts directory, not a package. +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import calib_common as common # noqa: E402 +import record # noqa: E402 + +#: What the operator does to record the take; shown by --help and before recording. +PROCEDURE = """What you need: + glove worn, each fingertip sensor pushed onto its fingertip, nothing in the hand + The other glove, the controllers and the headset are not needed. + +Steps, about 100 seconds. Move slowly, 3-4 seconds per motion, and keep the hand off metal. + 1. Hold the open hand still for two seconds. + 2. Bend each finger on its own, index to little, three times each. + Then move the thumb across the palm to the base of the little finger, three times. + 3. Three times each: make a fist; bend only the knuckles; bend only the fingers. + 4. Spread the fingers and close them, three times. Wag the index, then the little finger, three times each. + 5. Thumb: touch each fingertip for a second, twice round. Draw three big circles each way. + Lift and lower it three times. + 6. Count from one to five on your fingers and back, twice. Then tap the fingers as on a piano, twice. + 7. Hold the open hand still for two seconds, then stop. +""" + +#: The fingertip rows of the 25-joint ``hand_pose`` stack, thumb to little finger. +TIP = [4, 9, 14, 19, 24] +SEG_FLOOR_MM = 3.0 +#: Neighbouring frames are strongly correlated, so fits use a subset; residuals and scores use every frame. +FIT_STRIDE = 4 +HELD_OUT_STRIDE = 16 +HUBER_MM = 5.0 +RANDOM_STARTS = 6 +#: Each check as (label, comparison, threshold, unit, what to change when it fails). ``x_k`` is identified by the +#: sensor rotation and ``Y`` by the fingertip travel, both measured on kept frames. +ACCEPT = { + "rms": ("fit error", "<", 2.5, "mm", "A fingertip sensor is loose. Push each one onto its fingertip."), + "half_split": ("first half vs second half", "<", 1.5, "deg", "The glove moved on the hand. Put it on firmly."), + "dropped": ("part of the take thrown out", "<", 0.50, "", "Move slower, and keep fists short."), + "sensor_span": ("least-turned sensor: {still}", ">", 60.0, "deg", "Bend the {still} more."), + "tip_spread": ("least-moved fingertip: {narrow}", ">", 20.0, "mm", "Move the {narrow} more."), + "tip_offset": ("sensor distance from fingertip", "<", 30.0, "mm", "Push each sensor onto its fingertip."), + "ambiguity": ("other answers that fit as well", "<", 1.0, "deg", "Do every step, and move every finger."), +} + + +def load(episode: Path, side: str) -> tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + """One hand's times, usable mask, (N,5,4,4) sensor poses and (N,5,3) wrist-frame fingertip positions.""" + hand, sensor = f"{side}_hand_pose", f"{side}_sensor_pose" + data = common.read_source(episode, "manus_glove", (hand, sensor), common.GLOVE_ROWS_HINT) + # The recorder zeroes an unreported sensor set and an invalid joint, so a real transform ends in 1. + reported = (data[sensor][:, :, 3, 3] == 1).all(axis=1) + tips_valid = (data[hand][:, TIP, 3, 3] == 1).all(axis=1) + times = data["capture_time"] - data["capture_time"][0] + common.require_take(times[reported], f"{side} fingertip-sensor data", common.SENSOR_HINT) + return times, reported & tips_valid, data[sensor], data[hand][:, TIP][:, :, :3, 3] + + +class Problem: + """The fit in point-level storage (five rows per frame), so a fit runs only on its selected rows.""" + + def __init__(self, sensors: np.ndarray, tips: np.ndarray) -> None: + """Flatten the (N,5,4,4) sensor poses and (N,5,3) wrist-frame tip positions.""" + self.frames = len(sensors) + self.a = sensors[:, :, :3, 3].reshape(-1, 3) + self.rotation = sensors[:, :, :3, :3].reshape(-1, 3, 3) + self.b = tips.reshape(-1, 3) + self.finger = np.tile(np.arange(5), self.frames) + + def residual_rows(self, p: np.ndarray, rows: np.ndarray | slice) -> np.ndarray: + """Model error in mm, (rows, 3), for ``p`` = rotation vector of Y, translation of Y, five offsets.""" + offsets = p[6:].reshape(5, 3)[self.finger[rows]] + tip_in_coil = self.a[rows] + np.einsum("nij,nj->ni", self.rotation[rows], offsets) + return (tip_in_coil - self.b[rows] @ Rotation.from_rotvec(p[:3]).as_matrix().T - p[3:6]) * 1000 + + def residual_points(self, p: np.ndarray) -> np.ndarray: + """Per-fingertip error magnitude in mm, (N, 5).""" + return np.linalg.norm(self.residual_rows(p, slice(None)), axis=1).reshape(self.frames, 5) + + def residual_frames(self, p: np.ndarray) -> np.ndarray: + """Per-frame mean of the five fingertip errors, in mm.""" + return self.residual_points(p).mean(axis=1) + + def fit(self, mask: np.ndarray, p0: np.ndarray, max_nfev: int = 200) -> np.ndarray: + """Robust least squares on a frame mask (N,) or a point mask (N, 5).""" + points = np.repeat(mask[:, None], 5, axis=1) if mask.ndim == 1 else mask + # Thinned in time only: every selected finger of a used frame stays. + rows = np.flatnonzero((points & (np.arange(self.frames) % FIT_STRIDE == 0)[:, None]).ravel()) + return least_squares( + lambda p: self.residual_rows(p, rows).ravel(), + p0, + loss="huber", + f_scale=HUBER_MM, + x_scale="jac", + max_nfev=max_nfev, + ).x + + @staticmethod + def start(rotation: np.ndarray) -> np.ndarray: + """Starting parameters at ``rotation`` with zero translation and offsets.""" + return np.concatenate([Rotation.from_matrix(rotation).as_rotvec(), np.zeros(18)]) + + @staticmethod + def coil_from_wrist(p: np.ndarray) -> np.ndarray: + """The 4x4 transform Y of a parameter vector.""" + return common.transform(Rotation.from_rotvec(p[:3]).as_matrix(), p[3:6]) + + +def main(argv: list[str] | None = None) -> int: + """Record (or read) one take, solve it and save a passed result; returns 0 only when every check passed.""" + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], epilog=PROCEDURE, formatter_class=argparse.RawDescriptionHelpFormatter + ) + record.add_arguments(parser) + args = parser.parse_args(argv) + episode = record.episode_for(args, "glove calibration: coil to wrist", False, PROCEDURE) + times, usable, sensors, tips = load(episode, args.side) + problem = Problem(sensors, tips) + print(f"Solving the {args.side} hand: {times[-1]:.0f} s recorded, {usable.mean():.0%} usable...") + + # 1. Initial solution from random starts on a thinned frame set; there is no external initial guess. + thin = usable & (np.arange(len(times)) % HELD_OUT_STRIDE == 0) + candidates = [problem.fit(thin, Problem.start(r)) for r in common.random_rotations(RANDOM_STARTS, seed=0)] + p0 = min(candidates, key=lambda p: common.rms(problem.residual_frames(p)[thin])) + + # 2. Leave-one-segment-out rejection, then point trimming inside the kept segments. + keep, window, p = common.segment_reject( + times, + usable, + problem.fit, + problem.residual_frames, + p0, + floor_mm=SEG_FLOOR_MM, + held_out_stride=HELD_OUT_STRIDE, + ) + kept_frames = usable & keep[window] + mask, p = common.point_trim( + np.repeat(kept_frames[:, None], 5, axis=1), problem.fit, problem.residual_points, p + ) + + # 3. Multi-start on the final selection: a second solution that fits as well means the take is ambiguous. + fits = [p, *(problem.fit(mask, Problem.start(r)) for r in common.random_rotations(RANDOM_STARTS, seed=1))] + results = [(common.rms(problem.residual_points(q)[mask]), Problem.coil_from_wrist(q)) for q in fits] + best = min(range(len(fits)), key=lambda i: results[i][0]) + (fit_rms, coil_from_wrist), p = results[best], fits[best] + offsets = p[6:].reshape(5, 3) + + # 4. Stability (the two time halves must agree) and diversity of the motion that identifies the unknowns. + half = (times < np.median(times[kept_frames]))[:, None] + split_deg = common.rotation_between_deg( + Problem.coil_from_wrist(problem.fit(mask & half, p)), Problem.coil_from_wrist(problem.fit(mask & ~half, p)) + ) + rotations = sensors[kept_frames][:, :, :3, :3] + span = [common.orientation_span_deg(Rotation.from_matrix(rotations[:, k])) for k in range(5)] + spread = [np.sqrt(np.linalg.eigvalsh(np.cov(tips[kept_frames, k].T)).max()) * 1000 for k in range(5)] + still, narrow = common.finger_name(np.argmin(span)), common.finger_name(np.argmin(spread)) + + values = dict( + rms=fit_rms, + half_split=split_deg, + dropped=1 - keep.mean(), + sensor_span=min(span), + tip_spread=min(spread), + tip_offset=np.linalg.norm(offsets, axis=1).max() * 1000, + ambiguity=common.multistart_ambiguity_deg(results, ACCEPT["ambiguity"][2]), + ) + return common.finish( + args.results, args.side, "T_coil_wrist", coil_from_wrist, ACCEPT, values, still=still, narrow=narrow + ) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/egocap/tools/calibration/record.py b/examples/egocap/tools/calibration/record.py new file mode 100644 index 0000000000..fc9c9148e8 --- /dev/null +++ b/examples/egocap/tools/calibration/record.py @@ -0,0 +1,236 @@ +# SPDX-FileCopyrightText: 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 + +"""Record one calibration take from a running CaptureServer, from the terminal. + +Tracking frames go through the same conversion and recording service as any Ego Capture recording, so the take +is an ordinary episode holding ``pico_controller`` and ``manus_glove``. No page, camera or LiveKit is involved. +""" + +from __future__ import annotations + +import argparse +import asyncio +import sys +import time +from pathlib import Path + +import calib_common as common +from websockets.exceptions import WebSocketException + +from capture_server import protocol +from capture_server.client import ( + CaptureClient, + CaptureFrame, + CaptureStopped, + ManusPluginConfig, + RequestRejectedError, +) +from egocap.core.data_root import calibration_dir +from egocap_web.recording_adapter import ( + MANUS_GLOVE_SPEC, + PICO_CONTROLLER_SPEC, + RecordingAdapterError, + convert_controller_aim_pose, + convert_hand_pose, + convert_sensor_pose, + validate_tracking_descriptor, +) +from recording_service import ( + Disposition, + FieldSpec, + NumericSample, + NumericSourceSpec, + QcConfig, + RecordingService, + ServiceConfig, + SubmissionStatus, +) + +#: A device counts as live while its last row is younger than this. +LIVE_S = 1.0 +_GLOVE, _CONTROLLER, _SENSORS = MANUS_GLOVE_SPEC.name, PICO_CONTROLLER_SPEC.name, "sensors" +#: What to tell the operator while something the take needs is not live. +_WAITING = { + _GLOVE: "Waiting for the {side} glove. Turn it on and check it is connected.", + _SENSORS: "Waiting for the {side} glove's fingertip sensors. " + common.SENSOR_HINT, + _CONTROLLER: "Waiting for the {side} controller. Turn it on and keep it where the headset can see it.", +} + + +def _specs(side: str, controllers: bool) -> tuple[NumericSourceSpec, ...]: + """The take's sources: the fields of the calibrated side only, named and typed as a full recording's. + + A full recording writes a row only while both hands, or the headset and both controllers, are valid. A take + holds one side, so the other glove and controller can stay off. + """ + glove = NumericSourceSpec( + _GLOVE, + ( + FieldSpec(f"{side}_hand_pose", "float64", (25, 4, 4)), + FieldSpec(f"{side}_sensor_pose", "float64", (5, 4, 4)), + ), + MANUS_GLOVE_SPEC.frame_type, + ) + controller = NumericSourceSpec( + _CONTROLLER, (FieldSpec(f"{side}_pose", "float64", (4, 4)),), PICO_CONTROLLER_SPEC.frame_type + ) + return (glove, controller) if controllers else (glove,) + + +def add_arguments(parser: argparse.ArgumentParser) -> None: + """The arguments every calibration tool takes: which hand, where the take comes from, where results go.""" + parser.add_argument("--side", choices=("left", "right"), required=True, help="the hand to calibrate") + parser.add_argument( + "episode", type=Path, nargs="?", help="a recording to solve again; leave out to record a new take" + ) + parser.add_argument("--capture-server", default="ws://127.0.0.1:8082", help="CaptureServer to record from") + parser.add_argument( + "--results", + type=Path, + default=calibration_dir() / common.RESULTS_NAME, + help="file a passed result is saved in", + ) + parser.add_argument("--takes-dir", type=Path, default=Path("calibration_takes"), help="where a take is kept") + + +class _Feed: + """Turns tracking frames into the take's rows and remembers which devices are live.""" + + def __init__(self, service: RecordingService, side: str, controllers: bool) -> None: + """Feed ``service`` with the ``side`` glove and, with ``controllers``, that side's controller.""" + self._service = service + self._side = side + self._controllers = controllers + self._seen: dict[str, float] = {} + self._layout_checked = False + self.episode_id: str | None = None + self.problem: str | None = None + #: Set once the take is over, so that our own stop is not reported as a failure. + self.finished = False + + def on_frame(self, frame: CaptureFrame) -> None: + """Convert one frame; submit its rows while an episode is open.""" + # The layout is checked once: a mismatch would decode every later frame wrongly. + if not self._layout_checked: + self._layout_checked = True + try: + validate_tracking_descriptor(frame.description) + except RecordingAdapterError as exc: + self.problem = f"CaptureServer's tracking layout is not the one this checkout records: {exc}" + if self.problem is not None: + return + tracking = protocol.decode_tracking_frame(frame.payload) + side, now, rows = self._side, time.monotonic(), {} + # A row is written only for a valid hand or controller, never a placeholder. + hand = convert_hand_pose(tracking, side) + if hand is not None: + rows[_GLOVE] = {f"{side}_hand_pose": hand, f"{side}_sensor_pose": convert_sensor_pose(tracking, side)} + if tracking[f"manus_{side}.sensor_present"]: + self._seen[_SENSORS] = now + aim = convert_controller_aim_pose(tracking, side) if self._controllers else None + if aim is not None: + rows[_CONTROLLER] = {f"{side}_pose": aim} + stamp, received = frame.capture_time_ns / 1e9, frame.receive_time_ns / 1e9 + for source, fields in rows.items(): + self._seen[source] = now + if self.episode_id is not None: + sample = NumericSample(source, stamp, received, fields, ("host_clock", frame.session_id)) + # A full queue would leave a hole in the take, which the solver cannot see. + if self._service.submit_sample(self.episode_id, sample).status is not SubmissionStatus.ACCEPTED: + self.problem = "The recorder could not keep up and lost data. Record again." + + def on_stopped(self, stopped: CaptureStopped) -> None: + """Remember why CaptureServer ended the session, unless the take had already finished.""" + if not self.finished: + self.problem = f"CaptureServer stopped: {stopped.error_message or stopped.reason}" + + def missing(self, needed: tuple[str, ...]) -> list[str]: + """What the take needs that is not live.""" + now = time.monotonic() + return [name for name in needed if now - self._seen.get(name, -LIVE_S) >= LIVE_S] + + +async def _wait_until_live(feed: _Feed, needed: tuple[str, ...], side: str) -> None: + """Return once every needed stream is live, telling the operator what is still missing as it changes.""" + told: list[str] = [] + while feed.problem is None: + # Checked after a pause, so that the first frames have had time to arrive. + await asyncio.sleep(LIVE_S / 2) + missing = feed.missing(needed) + if not missing: + return + if missing != told: + print("\n".join(_WAITING[name].format(side=side) for name in missing), flush=True) + told = missing + + +async def _enter(prompt: str) -> None: + """Wait for the operator to press Enter. + + Read through the event loop, not a thread blocked in ``input``: that thread would keep Ctrl-C from ending + the tool until Enter is pressed. + """ + loop = asyncio.get_running_loop() + pressed = loop.create_future() + print(prompt, end="", flush=True) + loop.add_reader(sys.stdin, lambda: pressed.done() or pressed.set_result(sys.stdin.readline())) + try: + await pressed + finally: + loop.remove_reader(sys.stdin) + + +async def record_take(url: str, takes_dir: Path, task: str, side: str, controllers: bool, procedure: str) -> Path: + """Guide the operator through one take and return its kept episode directory. + + ``controllers`` says whether the take needs controller rows; ``procedure`` is shown before recording. + """ + specs = _specs(side, controllers) + sources = tuple(spec.name for spec in specs) + service = RecordingService(ServiceConfig(takes_dir, specs, qc=QcConfig(required_sources=sources))) + feed = _Feed(service, side, controllers) + client = CaptureClient(url) + await service.open_session() + try: + try: + await client.start( + # Every source, also for a glove-only take: a hands-only session delivers no glove data. + sources=tuple(protocol.SourceType), + plugins=(ManusPluginConfig(),), + on_capture_frame=feed.on_frame, + on_stopped=feed.on_stopped, + ) + except (RequestRejectedError, OSError, WebSocketException, protocol.ProtocolError) as exc: + # No server, a server that is serving another client, or a proxy in the way of a local address. + raise SystemExit( + f"Cannot reach CaptureServer at {url} ({exc or type(exc).__name__}). Check that it is running " + "and that nothing else is using it. For a local address, unset the proxy variables." + ) from exc + print(procedure, flush=True) + await _wait_until_live(feed, (*sources, _SENSORS), side) + if feed.problem is None: + await _enter("Ready. Press Enter to start recording. ") + episode = await service.start_episode(task) + feed.episode_id = episode.episode_id + await _enter("Recording. Press Enter when you are done. ") + feed.episode_id = None + result = await service.stop_episode(episode.episode_id) + finally: + feed.finished = True + await client.stop() + await service.close() + if feed.problem is not None: + raise SystemExit(feed.problem) + if result.disposition is not Disposition.KEPT: + raise SystemExit(f"The take could not be saved: {'; '.join(result.issues)}") + print(f"Recorded {result.duration_seconds:.0f} s to {result.final_path}") + return result.final_path + + +def episode_for(args: argparse.Namespace, task: str, controllers: bool, procedure: str) -> Path: + """The episode to solve: the one named on the command line, or a take recorded now.""" + if args.episode is not None: + return common.resolve_episode(args.episode) + return asyncio.run(record_take(args.capture_server, args.takes_dir, task, args.side, controllers, procedure))