diff --git a/src/linkerhand_calibration/linkerhand_calibration/README.md b/src/linkerhand_calibration/linkerhand_calibration/README.md new file mode 100644 index 0000000..f2eb015 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/README.md @@ -0,0 +1,10 @@ +# Python 程序目录 + +- `models/`:各手型的专属代码、配置、源 URDF 和型号文档。 +- `core/`:共享的数据结构、几何、拟合和 URDF 处理。 +- `runtime/`:共享的采集状态机、ROS/SDK 接线、离线收尾与发布。 +- `profiles/`:型号 YAML 的加载与检查。 +- `compat/`:历史数据格式与旧入口。 +- `tools/`:独立诊断和辅助命令。 + +本目录根层仍有两类文件:`product.py`、`acquisition.py`、`extrinsics.py` 等共享入口;`full_hand.py`、`trajectory.py`、`pnp.py` 等历史导入兼容文件。新增型号专属实现应放在 `models/<型号>/`,新增共享实现应放在对应的 `core/` 或 `runtime/` 子目录,不继续堆在根层。 diff --git a/src/linkerhand_calibration/linkerhand_calibration/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/__init__.py new file mode 100644 index 0000000..23257e1 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/__init__.py @@ -0,0 +1,5 @@ +"""Profile-driven LinkerHand calibration and validated URDF correction.""" + +from .core import CalibrationProfile, ProfileKey + +__all__ = ["CalibrationProfile", "ProfileKey"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/acquisition.py b/src/linkerhand_calibration/linkerhand_calibration/acquisition.py new file mode 100644 index 0000000..79e09fb --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/acquisition.py @@ -0,0 +1,748 @@ +"""Hardware-independent point acquisition state.""" + +from __future__ import annotations + +from bisect import bisect_left +from collections import deque +from dataclasses import dataclass, field +from typing import Any, Mapping, Sequence + +import numpy as np + +from .core import robust_rotation_summary +from .pnp import SquareTagPose + + +TAG_PAIR_ROLES: dict[str, tuple[str, str]] = { + "t0_t3": ("t0", "t3"), + "t3_t4": ("t3", "t4"), + "t4_t5": ("t4", "t5"), +} +PAIR_NAMES: tuple[str, ...] = tuple(TAG_PAIR_ROLES) + + +@dataclass(frozen=True) +class TagQuality: + hamming: int + decision_margin: float + edge_pixels: float + reprojection_error_px: float | None = None + + +def tag_quality_is_valid( + quality: TagQuality, + *, + maximum_hamming: int, + minimum_decision_margin: float, + minimum_edge_pixels: float, + maximum_reprojection_error_px: float | None = None, +) -> bool: + detection_valid = ( + quality.hamming <= maximum_hamming + and quality.decision_margin >= minimum_decision_margin + and quality.edge_pixels >= minimum_edge_pixels + ) + if not detection_valid: + return False + if maximum_reprojection_error_px is None: + return True + return ( + quality.reprojection_error_px is not None + and quality.reprojection_error_px <= maximum_reprojection_error_px + ) + + +def update_pnp_reset_watchdog( + *, + detection_good: bool, + pnp_valid: bool, + now: float, + invalid_since: float | None, + reset_after_seconds: float, +) -> tuple[float | None, bool]: + """Track continuous PnP-only failures and request a throttled reset.""" + reset_after = float(reset_after_seconds) + if reset_after <= 0.0: + raise ValueError("reset_after_seconds must be positive") + if not detection_good or pnp_valid: + return None, False + since = float(now) if invalid_since is None else float(invalid_since) + if float(now) - since >= reset_after: + # Start a new interval so a permanently bad view is not reset on every + # frame. The next valid frame clears the interval. + return float(now), True + return since, False + + +def required_resume_views(active_view: str | None) -> tuple[str, ...]: + """Require only the active view on resume; start still checks all views.""" + all_views = ("front", "side", "top") + if active_view is None: + return all_views + view = str(active_view) + if view not in all_views: + raise ValueError(f"unknown calibration view: {view}") + return (view,) + + +@dataclass(frozen=True) +class Observation: + stamp_ns: int + received_at: float + relative_quaternion_xyzw: Mapping[str, tuple[float, float, float, float]] + tag_quality: Mapping[str, TagQuality] + state_u8: tuple[float, ...] = () + state_stamp_ns: int | None = None + state_sync_error_ns: int | None = None + tag_quaternion_xyzw: Mapping[ + str, tuple[float, float, float, float] + ] = field(default_factory=dict) + tag_translation_xyz_m: Mapping[ + str, tuple[float, float, float] + ] = field(default_factory=dict) + tag_pose_candidates: Mapping[ + str, tuple[SquareTagPose, ...] + ] = field(default_factory=dict) + + +@dataclass(frozen=True) +class StateSample: + stamp_ns: int + position_u8: tuple[float, ...] + channel_stamps_ns: tuple[int, ...] = () + + +def interpolate_state_u8( + samples: Sequence[StateSample], + stamp_ns: int, + *, + maximum_skew_ns: int, +) -> tuple[tuple[float, ...], int] | None: + """Interpolate a profile-sized hand state at an image timestamp. + + The SDK publishes state independently from the camera. Continuous + calibration must therefore use the image timestamp instead of whichever + state happened to arrive most recently in the ROS callback thread. + """ + if maximum_skew_ns < 0: + raise ValueError("maximum_skew_ns must be non-negative") + if not samples: + return None + if any(sample.channel_stamps_ns for sample in samples): + # A multi-frame SDK does not observe all motors at the same instant. + # De-duplicate each channel by its CAN receipt, then interpolate it + # independently. Repeated publication never creates extra support. + samples = tuple(sample for sample in samples if sample.stamp_ns >= stamp_ns-maximum_skew_ns + and sample.channel_stamps_ns and min(sample.channel_stamps_ns) <= stamp_ns+maximum_skew_ns) + if not samples: + return None + count = len(samples[0].position_u8) + channels = [dict() for _ in range(count)] + for sample in samples: + if len(sample.position_u8) != count or len(sample.channel_stamps_ns) != count: + return None + for index, (stamp, value) in enumerate(zip(sample.channel_stamps_ns, sample.position_u8)): + if stamp in channels[index] and channels[index][stamp] != value: + return None + channels[index][stamp] = value + matches = [interpolate_state_u8(tuple(StateSample(stamp, (value,)) + for stamp, value in sorted(channel.items())), stamp_ns, maximum_skew_ns=maximum_skew_ns) + for channel in channels] + if any(match is None for match in matches): + return None + return tuple(match[0][0] for match in matches), max(match[1] for match in matches) + stamps = [int(sample.stamp_ns) for sample in samples] + index = bisect_left(stamps, int(stamp_ns)) + + if index < len(samples) and stamps[index] == int(stamp_ns): + state = samples[index].position_u8 + return (tuple(float(value) for value in state), 0) + + before = samples[index - 1] if index > 0 else None + after = samples[index] if index < len(samples) else None + if before is not None and after is not None: + before_gap = int(stamp_ns) - int(before.stamp_ns) + after_gap = int(after.stamp_ns) - int(stamp_ns) + nearest_gap = min(before_gap, after_gap) + if nearest_gap > maximum_skew_ns: + return None + denominator = int(after.stamp_ns) - int(before.stamp_ns) + if denominator <= 0: + return ( + tuple(float(value) for value in before.position_u8), + nearest_gap, + ) + fraction = before_gap / denominator + before_values = np.asarray(before.position_u8, dtype=float) + after_values = np.asarray(after.position_u8, dtype=float) + if ( + before_values.ndim != 1 + or before_values.size == 0 + or after_values.shape != before_values.shape + ): + return None + interpolated = before_values + fraction * (after_values - before_values) + return ( + tuple(float(value) for value in interpolated), + nearest_gap, + ) + + nearest = before if before is not None else after + if nearest is None: + return None + gap = abs(int(stamp_ns) - int(nearest.stamp_ns)) + if gap > maximum_skew_ns or not nearest.position_u8: + return None + return (tuple(float(value) for value in nearest.position_u8), gap) + + +# Physical-angle profiles use the same timestamp interpolation. Keep the old +# public name for compatibility and offer a unit-neutral spelling to new code. +interpolate_state = interpolate_state_u8 + + +class ContinuousSweepCollector: + """Collect timestamp-synchronised observations during one end-to-end move.""" + + def __init__( + self, + *, + endpoint_tolerance_u8: float = 2.0, + endpoint_hold_seconds: float = 1.0, + timeout_seconds: float = 90.0, + invalid_timeout_seconds: float = 2.0, + minimum_valid_frames: int = 40, + minimum_state_span_u8: float = 240.0, + ) -> None: + if endpoint_tolerance_u8 < 0.0: + raise ValueError("endpoint_tolerance_u8 must be non-negative") + if endpoint_hold_seconds <= 0.0: + raise ValueError("endpoint_hold_seconds must be positive") + if timeout_seconds <= 0.0 or invalid_timeout_seconds <= 0.0: + raise ValueError("sweep timeouts must be positive") + if minimum_valid_frames < 3: + raise ValueError("minimum_valid_frames must be at least 3") + if minimum_state_span_u8 <= 0.0: + raise ValueError("minimum_state_span_u8 must be positive") + self.endpoint_tolerance_u8 = float(endpoint_tolerance_u8) + self.endpoint_hold_seconds = float(endpoint_hold_seconds) + self.timeout_seconds = float(timeout_seconds) + self.invalid_timeout_seconds = float(invalid_timeout_seconds) + self.minimum_valid_frames = int(minimum_valid_frames) + self.minimum_state_span_u8 = float(minimum_state_span_u8) + self.observations: list[Observation] = [] + self.motor_index = 0 + self.start_u8 = 255.0 + self.target_u8 = 0.0 + self.started_at: float | None = None + self.last_valid_at: float | None = None + self.endpoint_since: float | None = None + self.state = "idle" + self.reason = "" + + def start( + self, + now: float, + *, + motor_index: int, + start_u8: int, + target_u8: int, + ) -> None: + if motor_index not in (0, 15): + raise ValueError("continuous thumb sweep only permits motor 0 or 15") + if {int(start_u8), int(target_u8)} != {0, 255}: + raise ValueError("continuous sweep endpoints must be 0 and 255") + self.observations.clear() + self.motor_index = int(motor_index) + self.start_u8 = float(start_u8) + self.target_u8 = float(target_u8) + self.started_at = float(now) + self.last_valid_at = float(now) + self.endpoint_since = None + self.state = "collecting" + self.reason = "" + + @property + def active(self) -> bool: + return self.state == "collecting" + + @property + def valid_frames_seen(self) -> int: + return len(self.observations) + + @property + def state_span_u8(self) -> float: + if not self.observations: + return 0.0 + values = [ + float(observation.state_u8[self.motor_index]) + for observation in self.observations + ] + return float(max(values) - min(values)) + + def add( + self, observation: Observation, now: float + ) -> list[Observation] | None: + if not self.active: + return None + if ( + len(observation.state_u8) != 20 + or observation.state_sync_error_ns is None + ): + return None + value = float(observation.state_u8[self.motor_index]) + if not np.isfinite(value) or not -3.0 <= value <= 258.0: + return None + now = float(now) + self.observations.append(observation) + self.last_valid_at = now + + if abs(value - self.target_u8) <= self.endpoint_tolerance_u8: + if self.endpoint_since is None: + self.endpoint_since = now + else: + self.endpoint_since = None + + enough_endpoint_hold = ( + self.endpoint_since is not None + and now - self.endpoint_since >= self.endpoint_hold_seconds + ) + if ( + enough_endpoint_hold + and len(self.observations) >= self.minimum_valid_frames + and self.state_span_u8 >= self.minimum_state_span_u8 + ): + self.state = "complete" + return list(self.observations) + return None + + def poll(self, now: float) -> None: + if not self.active: + return + now = float(now) + if now - float(self.started_at) > self.timeout_seconds: + self.state = "failed" + self.reason = "sweep_timeout" + elif now - float(self.last_valid_at) > self.invalid_timeout_seconds: + self.state = "failed" + self.reason = "synchronised_tag_state_timeout" + + +def aggregate_sweep_observations( + observations: Sequence[Observation], + *, + motor_index: int, + start_u8: int, + target_u8: int, + endpoint_tolerance_u8: float, +) -> dict[int, dict[str, Any]]: + """Robustly aggregate continuous observations into integer motor bins.""" + if not observations: + raise ValueError("cannot aggregate an empty continuous sweep") + bins: dict[int, list[Observation]] = {} + for observation in observations: + if len(observation.state_u8) != 20: + continue + value = float(observation.state_u8[motor_index]) + if abs(value - float(start_u8)) <= endpoint_tolerance_u8: + command = int(start_u8) + elif abs(value - float(target_u8)) <= endpoint_tolerance_u8: + command = int(target_u8) + else: + command = int(np.clip(np.rint(value), 0, 255)) + bins.setdefault(command, []).append(observation) + return { + command: aggregate_observations(values) + for command, values in sorted(bins.items()) + } + + +class PointCollector: + """Wait for a stable pose, then aggregate a fixed number of frames.""" + + def __init__( + self, + *, + stable_frames: int = 15, + capture_frames: int = 30, + minimum_settle_seconds: float = 0.4, + maximum_stable_spread_rad: float = np.deg2rad(0.3), + stability_mode: str = "rotation", + maximum_stable_translation_spread_m: float = 0.003, + settle_timeout_seconds: float = 5.0, + capture_timeout_seconds: float = 5.0, + ) -> None: + if stable_frames < 3 or capture_frames < 3: + raise ValueError("stable_frames and capture_frames must be at least 3") + self.stable_frames = int(stable_frames) + self.capture_frames = int(capture_frames) + self.minimum_settle_seconds = float(minimum_settle_seconds) + self.maximum_stable_spread_rad = float(maximum_stable_spread_rad) + self.stability_mode = str(stability_mode) + self.maximum_stable_translation_spread_m = float( + maximum_stable_translation_spread_m + ) + if self.stability_mode not in {"rotation", "translation"}: + raise ValueError( + "stability_mode must be rotation or translation" + ) + if self.maximum_stable_translation_spread_m <= 0.0: + raise ValueError( + "maximum_stable_translation_spread_m must be positive" + ) + self.settle_timeout_seconds = float(settle_timeout_seconds) + self.capture_timeout_seconds = float(capture_timeout_seconds) + self._stable: deque[Observation] = deque(maxlen=self.stable_frames) + self._captured: list[Observation] = [] + self._consecutive_invalid_frames = 0 + self.started_at: float | None = None + self.capture_started_at: float | None = None + self.state = "idle" + self.reason = "" + self.stable_spread_rad: dict[str, float] = {} + self.stable_spread_m: dict[str, float] = {} + self.required_state_index: int | None = None + self.required_state_u8: float | None = None + self.maximum_state_error_u8: float | None = None + + def start( + self, + now: float, + *, + required_state_index: int | None = None, + required_state_u8: float | None = None, + maximum_state_error_u8: float | None = None, + ) -> None: + state_constraints = ( + required_state_index, + required_state_u8, + maximum_state_error_u8, + ) + if any(value is not None for value in state_constraints) and not all( + value is not None for value in state_constraints + ): + raise ValueError( + "point state constraint parameters must be provided together" + ) + if required_state_index is not None: + if not 0 <= int(required_state_index) < 20: + raise ValueError("required_state_index must be in [0, 19]") + if not np.isfinite(float(required_state_u8)): + raise ValueError("required_state_u8 must be finite") + if float(maximum_state_error_u8) < 0.0: + raise ValueError( + "maximum_state_error_u8 must be non-negative" + ) + self._stable.clear() + self._captured.clear() + self._consecutive_invalid_frames = 0 + self.started_at = float(now) + self.capture_started_at = None + self.state = "settling" + self.reason = "" + self.stable_spread_rad = {} + self.stable_spread_m = {} + self.required_state_index = ( + None + if required_state_index is None + else int(required_state_index) + ) + self.required_state_u8 = ( + None if required_state_u8 is None else float(required_state_u8) + ) + self.maximum_state_error_u8 = ( + None + if maximum_state_error_u8 is None + else float(maximum_state_error_u8) + ) + + @property + def active(self) -> bool: + return self.state in {"settling", "capturing"} + + @property + def stable_frames_seen(self) -> int: + return len(self._stable) + + @property + def capture_frames_seen(self) -> int: + return len(self._captured) + + def _window_is_stable(self) -> bool: + if len(self._stable) < self.stable_frames: + return False + if self.stability_mode == "translation": + spreads: dict[str, float] = {} + for pair, (parent, child) in TAG_PAIR_ROLES.items(): + if any( + parent not in observation.tag_translation_xyz_m + or child not in observation.tag_translation_xyz_m + for observation in self._stable + ): + self.reason = f"{pair}_translation_missing" + return False + vectors = np.asarray( + [ + np.asarray( + observation.tag_translation_xyz_m[child], + dtype=float, + ) + - np.asarray( + observation.tag_translation_xyz_m[parent], + dtype=float, + ) + for observation in self._stable + ], + dtype=float, + ) + reference = np.median(vectors, axis=0) + spreads[pair] = float( + np.max(np.linalg.norm(vectors - reference, axis=1)) + ) + self.stable_spread_m = spreads + for pair, spread in spreads.items(): + if spread > self.maximum_stable_translation_spread_m: + self.reason = f"{pair}_not_stable" + return False + return True + spreads: dict[str, float] = {} + for pair in PAIR_NAMES: + quaternions = [ + observation.relative_quaternion_xyzw[pair] + for observation in self._stable + ] + _, spread = robust_rotation_summary(quaternions) + spreads[pair] = float(spread) + self.stable_spread_rad = spreads + for pair, spread in spreads.items(): + if spread > self.maximum_stable_spread_rad: + self.reason = f"{pair}_not_stable" + return False + return True + + def _state_is_acceptable(self, observation: Observation) -> bool: + if self.required_state_index is None: + return True + if ( + len(observation.state_u8) != 20 + or observation.state_sync_error_ns is None + ): + return False + value = float(observation.state_u8[self.required_state_index]) + return bool( + np.isfinite(value) + and abs(value - float(self.required_state_u8)) + <= float(self.maximum_state_error_u8) + ) + + def _return_to_settling(self, reason: str) -> None: + self._stable.clear() + self._captured.clear() + self._consecutive_invalid_frames = 0 + self.capture_started_at = None + self.state = "settling" + self.reason = str(reason) + self.stable_spread_rad = {} + self.stable_spread_m = {} + + def add( + self, observation: Observation, now: float + ) -> dict[str, Any] | None: + if not self.active: + return None + self._consecutive_invalid_frames = 0 + now = float(now) + if not self._state_is_acceptable(observation): + self._return_to_settling("motor_position_out_of_tolerance") + return None + if self.state == "settling": + self._stable.append(observation) + elapsed = now - float(self.started_at) + if elapsed >= self.minimum_settle_seconds and self._window_is_stable(): + self.state = "capturing" + self.capture_started_at = now + self._captured.clear() + self.reason = "" + return None + + self._captured.append(observation) + if len(self._captured) < self.capture_frames: + return None + # Validate continuity across the boundary as well as inside the + # capture block. A planar branch can switch immediately after the + # stable window and then look perfectly stable for every capture + # frame; checking only the captured frames would accept that jump. + stability_aggregate = aggregate_observations( + [*self._stable, *self._captured] + ) + if self.stability_mode == "translation": + unstable_pairs = [ + pair + for pair, spread in stability_aggregate[ + "maximum_translation_spread_m" + ].items() + if float(spread) + > self.maximum_stable_translation_spread_m + ] + else: + unstable_pairs = [ + pair + for pair, spread in stability_aggregate[ + "maximum_spread_rad" + ].items() + if float(spread) > self.maximum_stable_spread_rad + ] + if unstable_pairs: + self._return_to_settling( + f"{unstable_pairs[0]}_capture_not_stable" + ) + return None + self.state = "complete" + return aggregate_observations(self._captured) + + def poll(self, now: float) -> None: + if not self.active: + return + now = float(now) + if self.state == "settling": + if now - float(self.started_at) > self.settle_timeout_seconds: + self.state = "failed" + self.reason = self.reason or "settle_timeout" + elif self.state == "capturing": + if now - float(self.capture_started_at) > self.capture_timeout_seconds: + self.state = "failed" + self.reason = "capture_timeout" + + def mark_invalid_frame(self) -> None: + """Skip one invalid frame while retaining the recent valid window.""" + if self.state == "capturing": + self._return_to_settling("invalid_tag_frame") + return + if self.state == "settling": + self._consecutive_invalid_frames += 1 + if self._consecutive_invalid_frames >= 3: + self._stable.clear() + self.reason = "invalid_tag_frame" + + +def aggregate_observations( + observations: Sequence[Observation], +) -> dict[str, Any]: + if not observations: + raise ValueError("cannot aggregate an empty observation sequence") + relative: dict[str, list[float]] = {} + spread: dict[str, float] = {} + for pair in PAIR_NAMES: + quaternion, maximum = robust_rotation_summary( + [ + observation.relative_quaternion_xyzw[pair] + for observation in observations + ] + ) + relative[pair] = [float(value) for value in quaternion] + spread[pair] = float(maximum) + + quality: dict[str, dict[str, float]] = {} + tag_names = sorted(observations[0].tag_quality) + for tag_name in tag_names: + values = [ + observation.tag_quality[tag_name] for observation in observations + ] + quality[tag_name] = { + "minimum_decision_margin": float( + min(value.decision_margin for value in values) + ), + "minimum_edge_pixels": float(min(value.edge_pixels for value in values)), + "maximum_hamming": int(max(value.hamming for value in values)), + } + reprojection_errors = [ + float(value.reprojection_error_px) + for value in values + if value.reprojection_error_px is not None + ] + if reprojection_errors: + quality[tag_name]["maximum_reprojection_error_px"] = float( + max(reprojection_errors) + ) + + states = [ + observation.state_u8 + for observation in observations + if len(observation.state_u8) == 20 + ] + state_median: list[float] = [] + if states: + state_median = [ + float(value) + for value in np.median(np.asarray(states, dtype=float), axis=0) + ] + sync_errors = [ + int(observation.state_sync_error_ns) + for observation in observations + if observation.state_sync_error_ns is not None + ] + tag_translations: dict[str, list[float]] = {} + translation_spread: dict[str, float] = {} + translation_roles = sorted( + set.intersection( + *( + set(observation.tag_translation_xyz_m) + for observation in observations + ) + ) + if observations + else set() + ) + for role in translation_roles: + values = np.asarray( + [ + observation.tag_translation_xyz_m[role] + for observation in observations + ], + dtype=float, + ) + if values.shape == (len(observations), 3) and np.all( + np.isfinite(values) + ): + tag_translations[role] = [ + float(value) + for value in np.median(values, axis=0) + ] + for pair, (parent, child) in TAG_PAIR_ROLES.items(): + if parent not in translation_roles or child not in translation_roles: + continue + vectors = np.asarray( + [ + np.asarray( + observation.tag_translation_xyz_m[child], + dtype=float, + ) + - np.asarray( + observation.tag_translation_xyz_m[parent], + dtype=float, + ) + for observation in observations + ], + dtype=float, + ) + reference = np.median(vectors, axis=0) + translation_spread[pair] = float( + np.max(np.linalg.norm(vectors - reference, axis=1)) + ) + + return { + "stamp_start_ns": int(observations[0].stamp_ns), + "stamp_end_ns": int(observations[-1].stamp_ns), + "valid_frames": len(observations), + "relative_quaternion_xyzw": relative, + "maximum_spread_rad": spread, + "tag_quality": quality, + "state_u8_median": state_median, + "tag_translation_xyz_m": tag_translations, + "maximum_translation_spread_m": translation_spread, + "maximum_state_sync_error_ms": ( + None + if not sync_errors + else float(max(sync_errors)) / 1_000_000.0 + ), + } diff --git a/src/linkerhand_calibration/linkerhand_calibration/alignment_view.py b/src/linkerhand_calibration/linkerhand_calibration/alignment_view.py new file mode 100644 index 0000000..85490e0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/alignment_view.py @@ -0,0 +1,4 @@ +"""Compatibility import for G20 alignment_view.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.alignment_view") diff --git a/src/linkerhand_calibration/linkerhand_calibration/calibrated_joint_state_bridge.py b/src/linkerhand_calibration/linkerhand_calibration/calibrated_joint_state_bridge.py new file mode 100644 index 0000000..fdb26dd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/calibrated_joint_state_bridge.py @@ -0,0 +1,377 @@ +"""Map explicit SDK commands or feedback to corrected URDF joint coordinates. + +Unified artifacts load their certified manifest and standard URDF. The old +readers below are used only when a historical payload is explicitly supplied. + +The static encoder-zero corrections in ``zero_angles`` are already baked into +the corrected URDF joint origins. This bridge therefore publishes only the +dynamic ``angle_rad`` values and never adds the static offsets a second time. + +Schema-v5 trajectories are fitted against timestamp-synchronised hardware +feedback, not controller set-points. They must therefore be queried with the +SDK ``hand_state`` topic. The retained schema-v4 path is command-indexed for +backwards compatibility only. +""" + +from __future__ import annotations + +import json +import math +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np +import rclpy +from rclpy.node import Node +from sensor_msgs.msg import JointState + +G20_COMMAND_NAMES: tuple[str, ...] = ( + "thumb_cmc_pitch", + "index_mcp_pitch", + "middle_mcp_pitch", + "ring_mcp_pitch", + "pinky_mcp_pitch", + "thumb_cmc_roll", + "index_mcp_roll", + "middle_mcp_roll", + "ring_mcp_roll", + "pinky_mcp_roll", + "thumb_cmc_yaw", + "reserved_11", + "reserved_12", + "reserved_13", + "reserved_14", + "thumb_mcp", + "index_pip", + "middle_pip", + "ring_pip", + "pinky_pip", +) + +# Match the stable ordering used by the existing MuJoCo bridge. JointState +# consumers must use names, but retaining the ordering also keeps logs and +# direct comparisons deterministic. +G20_URDF_JOINT_NAMES: tuple[str, ...] = ( + "index_dip", + "index_mcp_pitch", + "index_mcp_roll", + "index_pip", + "middle_dip", + "middle_mcp_pitch", + "middle_mcp_roll", + "middle_pip", + "pinky_dip", + "pinky_mcp_pitch", + "pinky_mcp_roll", + "pinky_pip", + "ring_dip", + "ring_mcp_pitch", + "ring_mcp_roll", + "ring_pip", + "thumb_cmc_pitch", + "thumb_cmc_roll", + "thumb_cmc_yaw", + "thumb_ip", + "thumb_mcp", +) + + +class CalibratedCommandMapper: + """Validated, profile-specific lookup from SDK u8 values to URDF radians.""" + + def __init__( + self, payload: Mapping[str, Any], *, expected_side: str | None = None + ) -> None: + from .full_hand import get_hand_calibration_profile, infer_compact_payload_layout, validate_compact_payload + from .compat.legacy_diagnostic_tools.models import get_default_registry, validate_schema_v6_runtime_payload + from .compat.legacy_diagnostic_tools.models.o12.artifacts import validate_o12_runtime_payload + from .core import ProfileKey + schema_version = int(payload["schema_version"]) + if schema_version == 7: + validate_o12_runtime_payload(payload) + elif schema_version == 6: + validate_schema_v6_runtime_payload(payload) + else: + validate_compact_payload(payload) + side = str(payload["side"]).lower() + if expected_side is not None and side != str(expected_side).lower(): + raise ValueError( + f"calibration side {side!r} does not match requested side " + f"{str(expected_side).lower()!r}" + ) + quality = payload["quality"] + if quality.get("passed") is not True: + raise ValueError("calibration quality.passed must be true") + layout_id = ( + str(payload["layout_id"]) + if schema_version in {6, 7} + else infer_compact_payload_layout(payload) + ) + self.side = side + self.layout_id = layout_id + self.model = str(payload["model"]).upper() + self.profile_id = str( + payload.get("profile_id", f"G20/{side}/{layout_id}/v1") + ) + self.serial_number = str(payload["serial_number"]) + self.input_domain = str( + payload.get( + "curve_input_domain", + "command_u8" if schema_version == 4 else "", + ) + ) + if self.input_domain not in {"command_u8", "feedback_u8", "feedback_rad"}: + raise ValueError("calibration curve_input_domain is invalid") + if schema_version in {6, 7}: + self.command_names = tuple(str(value) for value in payload["command_names"]) + self.urdf_joint_names = tuple(str(name) for name in payload["joints"]) + self._motor_by_joint = { + name: int(payload["joints"][name]["motor_index"]) + for name in self.urdf_joint_names + } + registered = get_default_registry().get( + ProfileKey.parse(self.profile_id) + ) + self.feedback_name_aliases = dict( + registered.profile.command.feedback_name_aliases + ) + self.feedback_by_index = bool( + registered.profile.command.feedback_by_index + ) + else: + profile = get_hand_calibration_profile(side, layout_id) + self.command_names = G20_COMMAND_NAMES + self.urdf_joint_names = G20_URDF_JOINT_NAMES + self._motor_by_joint = { + name: int(profile.joint_specs[name].motor_index) + for name in self.urdf_joint_names + } + self.feedback_name_aliases = {} + self.feedback_by_index = False + self._curves = { + name: tuple( + float(value) + for value in payload["joints"][name]["angle_rad"] + ) + for name in self.urdf_joint_names + } + self._decreasing_curves = { + name: tuple( + float(value) + for value in payload["joints"][name].get( + "decreasing_rad", payload["joints"][name]["angle_rad"] + ) + ) + for name in self.urdf_joint_names + } + self._increasing_curves = { + name: tuple( + float(value) + for value in payload["joints"][name].get( + "increasing_rad", payload["joints"][name]["angle_rad"] + ) + ) + for name in self.urdf_joint_names + } + self._previous_by_motor: dict[int, float] = {} + self._direction_by_motor: dict[int, str] = {} + self.direction_deadband_u8 = 0.002 if schema_version == 7 else 0.5 + self._knots = { + name: tuple(float(value) for value in payload["joints"][name].get( + "curve_input_knots_rad", () + )) + for name in self.urdf_joint_names + } + self._raw_increasing_branch = { + name: str(payload["joints"][name].get( + "raw_increasing_curve_branch", "increasing" + )) + for name in self.urdf_joint_names + } + + @staticmethod + def _command_index(value: float) -> int: + command = float(value) + if not math.isfinite(command): + raise ValueError("calibrated command positions must be finite") + return max(0, min(255, int(math.floor(command + 0.5)))) + + def map_positions( + self, positions: Sequence[float], names: Sequence[str] = () + ) -> tuple[float, ...]: + values = tuple(float(value) for value in positions) + if names and not self.feedback_by_index: + if len(names) != len(values): + raise ValueError( + "JointState names and positions must have equal length" + ) + if len(set(names)) != len(names): + raise ValueError("JointState names must be unique") + by_name = dict(zip((str(name) for name in names), values)) + for alias, canonical in self.feedback_name_aliases.items(): + if alias in by_name and canonical not in by_name: + by_name[canonical] = by_name[alias] + missing = [name for name in self.command_names if name not in by_name] + if missing: + raise ValueError( + f"{self.model} feedback is missing named channels: " + + ",".join(missing) + ) + command = tuple(by_name[name] for name in self.command_names) + else: + if len(values) != len(self.command_names): + raise ValueError( + f"unnamed {self.model} feedback must contain exactly " + f"{len(self.command_names)} positions" + ) + command = values + indices = ( + () if self.input_domain == "feedback_rad" + else tuple(self._command_index(value) for value in command) + ) + direction_by_motor: dict[int, str | None] = {} + for motor, value in enumerate(command): + previous = self._previous_by_motor.get(motor) + direction = self._direction_by_motor.get(motor) + if previous is not None: + if value > previous + self.direction_deadband_u8: + direction = "increasing" + elif value < previous - self.direction_deadband_u8: + direction = "decreasing" + direction_by_motor[motor] = direction + result: list[float] = [] + for name in self.urdf_joint_names: + motor = self._motor_by_joint[name] + direction = direction_by_motor[motor] + if self.input_domain == "feedback_rad" and direction is not None: + raw_increasing = self._raw_increasing_branch[name] + direction = ( + raw_increasing + if direction == "increasing" + else "increasing" if raw_increasing == "decreasing" else "decreasing" + ) + curves = ( + self._increasing_curves + if direction == "increasing" + else self._decreasing_curves + if direction == "decreasing" + else self._curves + ) + if self.input_domain == "feedback_rad": + result.append(float(np.interp(command[motor], self._knots[name], curves[name]))) + else: + result.append(curves[name][indices[motor]]) + for motor, value in enumerate(command): + self._previous_by_motor[motor] = value + direction = direction_by_motor[motor] + if direction is not None: + self._direction_by_motor[motor] = direction + return tuple(result) + + +def load_calibrated_command_mapper( + calibration_file: str | Path, *, expected_side: str | None = None, input_kind="command" +) -> CalibratedCommandMapper: + path = Path(calibration_file).expanduser().resolve() + if not path.is_file(): + raise ValueError(f"calibration JSON does not exist: {path}") + payload = json.loads(path.read_text(encoding="utf-8")) + if path.name == "release_manifest.json" or payload.get("format") in {"unified_calibration_v1", "unified_calibration_v2", "unified_calibration_v3"}: + from .runtime.artifacts.reader import load_unified_mapper + return load_unified_mapper(path, expected_side=expected_side, input_kind=input_kind) + return CalibratedCommandMapper(payload, expected_side=expected_side) + + +def default_input_topic( + hand_type: str, input_domain: str, model: str = "G20" +) -> str: + side = str(hand_type).lower() + if side not in {"left", "right"}: + raise ValueError("hand_type must be left or right") + if input_domain == "feedback_u8": + return f"/{str(model).lower()}/cb_{side}_hand_state" + if input_domain == "command_u8": + return f"/{str(model).lower()}/cb_{side}_hand_control_cmd" + if input_domain == "feedback_rad": + return f"/{str(model).lower()}/{side}/joint_states" + if input_domain == "command_rad": + return f"/{str(model).lower()}/{side}/joint_cmd" + raise ValueError("calibration curve_input_domain is invalid") + + +class CalibratedJointStateBridge(Node): + def __init__(self) -> None: + super().__init__("calibrated_joint_state_bridge") + self.declare_parameter("hand_type", "right") + self.declare_parameter("calibration_file", "") + self.declare_parameter("input_topic", "") + self.declare_parameter("output_topic", "") + self.declare_parameter("input_kind", "command") + + hand_type = str(self.get_parameter("hand_type").value).lower() + if hand_type not in {"left", "right"}: + raise ValueError("hand_type must be left or right") + calibration_file = str(self.get_parameter("calibration_file").value) + if not calibration_file: + raise ValueError("calibration_file is required") + self.mapper = load_calibrated_command_mapper( + calibration_file, expected_side=hand_type, input_kind=str(self.get_parameter("input_kind").value) + ) + input_topic = str(self.get_parameter("input_topic").value).strip() + output_topic = str(self.get_parameter("output_topic").value).strip() + self.input_topic = input_topic or default_input_topic( + hand_type, self.mapper.input_domain, self.mapper.model + ) + self.output_topic = ( + output_topic + or f"/sim/mujoco/{self.mapper.model.lower()}/{hand_type}/joint_state" + ) + if self.output_topic in {self.input_topic, default_input_topic(hand_type, + "feedback_rad" if self.mapper.input_domain.endswith("rad") else "feedback_u8", self.mapper.model)}: + raise ValueError("mapped output must not overwrite the real SDK command/feedback topic") + self.publisher = self.create_publisher(JointState, self.output_topic, 10) + self.subscription = self.create_subscription( + JointState, self.input_topic, self._command_callback, 10 + ) + self._last_error = "" + self.get_logger().info( + f"loaded {self.mapper.profile_id} calibration for " + f"{self.mapper.serial_number}: " + f"{self.input_topic} ({self.mapper.input_domain}) -> " + f"{self.output_topic}" + ) + + def _command_callback(self, command: JointState) -> None: + try: + positions = self.mapper.map_positions(command.position, command.name) + except ValueError as error: + message = str(error) + if message != self._last_error: + self.get_logger().error(message) + self._last_error = message + return + self._last_error = "" + result = JointState() + result.header = command.header + result.name = list(self.mapper.urdf_joint_names) + result.position = list(positions) + self.publisher.publish(result) + + +def main(args: Sequence[str] | None = None) -> None: + rclpy.init(args=args) + node: CalibratedJointStateBridge | None = None + try: + node = CalibratedJointStateBridge() + rclpy.spin(node) + except KeyboardInterrupt: + pass + finally: + if node is not None: + node.destroy_node() + if rclpy.ok(): + rclpy.shutdown() + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/camera_timing.py b/src/linkerhand_calibration/linkerhand_calibration/camera_timing.py new file mode 100644 index 0000000..64966e1 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/camera_timing.py @@ -0,0 +1,217 @@ +"""Map camera frame clocks to host time before pairing images with feedback. + +The MVS frame counter timestamps exposure start. USB delivery/publication is +later. Clock latches bracket the device/host correspondence independently of +hand motion, images, or fitted calibration curves. +""" + +from dataclasses import asdict, dataclass +import json +import math +from pathlib import Path +import time + + +CAMERA_TIMING_POLICY = "mvs_latched_exposure_time_v1" +CLOCK_DRIFT_TOLERANCE_NS = 1_000_000 + + +@dataclass(frozen=True) +class ClockLatch: + device_tick: int + before_ns: int + after_ns: int + raw_before_ns: int | None = None + raw_after_ns: int | None = None + + @property + def midpoint_ns(self): + return (self.before_ns+self.after_ns)//2 + + @property + def half_width_ns(self): + return (self.after_ns-self.before_ns)/2 + + +class DeviceFrameClock: + """A nominal device clock with short, measured host-time brackets. + + A new latch is checked against the previous one before it can change the + mapping. This rejects wrong counter units, resets and host clock jumps. + Periodic updates bound accumulated drift; none depend on image delivery. + """ + + def __init__(self, ticks_per_second): + if not math.isfinite(ticks_per_second) or ticks_per_second <= 0: + raise ValueError("invalid camera clock frequency") + self.ticks_per_second = ticks_per_second + self.anchor = None + self.last_frame_tick = None + self.last_stamp_ns = None + self.refresh_interval_seconds = .5 + + def elapsed_ns(self, ticks): + return round(ticks*1_000_000_000/self.ticks_per_second) + + def update(self, latches): + if not latches or any(x.device_tick <= 0 or x.before_ns <= 0 + or not 0 <= x.after_ns-x.before_ns <= 2_000_000 for x in latches): + raise ValueError("camera clock latch is invalid or too uncertain") + previous = self.anchor or latches[0] + if self.anchor is None and latches[-1].before_ns-latches[0].after_ns < 50_000_000: + raise ValueError("camera clock units need an independent elapsed-time check") + for current in latches: + elapsed = self.elapsed_ns(current.device_tick-previous.device_tick) + host_elapsed = current.midpoint_ns-previous.midpoint_ns + tolerance = current.half_width_ns+previous.half_width_ns+CLOCK_DRIFT_TOLERANCE_NS + if elapsed < 0 or abs(elapsed-host_elapsed) > tolerance: + raise ValueError("camera/host clock discontinuity or counter unit mismatch") + # Refresh before measured phase drift spends the existing 1 ms + # continuity allowance. A fixed 0.5 s period repeatedly invalidates a + # smooth slewing host clock. Scheduling changes; admission never does. + current = max(latches, key=lambda x: x.midpoint_ns) + host_elapsed = current.midpoint_ns-previous.midpoint_ns + if host_elapsed >= 50_000_000: + drift = abs(host_elapsed-self.elapsed_ns(current.device_tick-previous.device_tick)) + rate = drift/host_elapsed + self.refresh_interval_seconds = max(.02, min(.5, + .25*CLOCK_DRIFT_TOLERANCE_NS/1e9/max(rate, 1e-12))) + self.anchor = min(latches, key=lambda x: x.half_width_ns) + + def timestamp(self, tick, *, received_ns, exposure_us): + if (self.anchor is None or not 0 <= received_ns-self.anchor.midpoint_ns <= 2_000_000_000 + or not math.isfinite(exposure_us) or exposure_us < 0): + raise ValueError("camera frame has no fresh clock or valid exposure") + if self.last_frame_tick is not None and tick <= self.last_frame_tick: + raise ValueError("camera frame counter reset or duplicate frame") + stamp = self.anchor.midpoint_ns+self.elapsed_ns(tick-self.anchor.device_tick)+round(exposure_us*500) + if stamp > received_ns+2_000_000 or (self.last_stamp_ns is not None and stamp <= self.last_stamp_ns): + raise ValueError("camera image time is future or out of order") + self.last_frame_tick, self.last_stamp_ns = tick, stamp + return stamp + + +class MvsCameraTiming: + """The camera-specific clock latch and its optional append-only journal.""" + + def __init__(self, camera, mvs, clock_ns, *, exposure_us, journal_path="", raw_clock_ns=None): + self.camera, self.mvs, self.clock_ns = camera, mvs, clock_ns + # CLOCK_MONOTONIC_RAW is independent of wall-clock synchronization. + # It is diagnostic evidence only, never a replacement ROS timestamp. + self.raw_clock_ns = raw_clock_ns or (lambda: time.clock_gettime_ns(time.CLOCK_MONOTONIC_RAW)) + self.exposure_us = exposure_us + self.frame_clock = None + self.last_stamp_ns = None + self.next_refresh = 0. + self.journal = None + if journal_path: + path = Path(journal_path) + path.parent.mkdir(parents=True, exist_ok=True) + self.journal = path.open("a", encoding="utf-8") + + def _integer(self, name): + value = self.mvs.MVCC_INTVALUE_EX() + status = self.camera.MV_CC_GetIntValueEx(name, value) + if status != 0: + raise ValueError(f"camera clock cannot read {name}:0x{status:08x}") + return int(value.nCurValue) + + def _latch(self): + raw_before = self.raw_clock_ns() + before = self.clock_ns() + status = self.camera.MV_CC_SetCommandValue("DeviceTimestampLatch") + if status != 0: + raise ValueError(f"camera clock latch failed:0x{status:08x}") + tick = self._integer("DeviceTimestamp") + after = self.clock_ns() + return ClockLatch(tick, before, after, raw_before, self.raw_clock_ns()) + + def _write(self, row): + if self.journal is not None: + self.journal.write(json.dumps(row, separators=(",", ":"))+"\n") + + def start(self): + # The installed USB camera firmware returns ticks/second for this + # feature (despite its XML unit label). Verify that interpretation + # against elapsed host time; do not assume it for another firmware. + self.frame_clock = DeviceFrameClock(self._integer("DeviceTimestampIncrement")) + latches = [] + for index in range(40): + if index: + time.sleep(.02) + latches.append(self._latch()) + valid = [x for x in latches if 0 <= x.after_ns-x.before_ns <= 2_000_000] + if len(valid) >= 8 and valid[-1].before_ns-valid[0].after_ns >= 50_000_000: + self._update(latches) + return + raise ValueError("camera clock has no bounded-latency startup latches") + + def _update(self, latches): + valid = [x for x in latches if 0 <= x.after_ns-x.before_ns <= 2_000_000] + if not valid: + # A delayed USB control transaction provides no new clock evidence. + # Keep the original two-second freshness bound while trying again. + self._write(dict(kind="camera_clock_latch_rejected", latches=[asdict(x) for x in latches])) + self.next_refresh = time.monotonic()+.02 + return + try: + self.frame_clock.update(valid) + except ValueError as error: + # Invalidation alone loses the transaction that failed. Preserve + # both clocks and the old anchor so drift, jumps and bad device + # counters can be distinguished without weakening the check. + self._write(dict(kind="camera_clock_sync_rejected", policy=CAMERA_TIMING_POLICY, + reason=str(error), ticks_per_second=self.frame_clock.ticks_per_second, + previous_anchor=asdict(self.frame_clock.anchor) if self.frame_clock.anchor else None, + latches=[asdict(x) for x in latches])) + if self.journal is not None: + self.journal.flush() + raise + self._write(dict(kind="camera_clock_sync", policy=CAMERA_TIMING_POLICY, + ticks_per_second=self.frame_clock.ticks_per_second, + refresh_interval_seconds=self.frame_clock.refresh_interval_seconds, + latches=[asdict(x) for x in latches], anchor=asdict(self.frame_clock.anchor))) + if self.journal is not None: + self.journal.flush() + # Startup may select a precise latch near the beginning of its window. + # That anchor has already spent part of the refresh budget. + anchor_age = (max(x.after_ns for x in latches)-self.frame_clock.anchor.midpoint_ns)/1e9 + self.next_refresh = time.monotonic()+max(0., self.frame_clock.refresh_interval_seconds-anchor_age) + + def refresh_if_due(self): + if self.frame_clock is None: + self.start() + elif time.monotonic() >= self.next_refresh: + self._update([self._latch() for _ in range(3)]) + + def invalidate(self, reason): + """Stop using an uncertain mapping until a new startup check succeeds.""" + self.frame_clock = None + self.next_refresh = 0. + self._write(dict(kind="camera_clock_invalidated", reason=str(reason), + last_stamp_ns=self.last_stamp_ns)) + if self.journal is not None: + self.journal.flush() + + def timestamp(self, info, received_ns): + if self.frame_clock is None: + raise ValueError("camera frame has no synchronized clock") + tick = (int(info.nDevTimeStampHigh)<<32)|int(info.nDevTimeStampLow) + # Auto-exposure preview uses the exact exposure-start timestamp when + # the SDK supplies no per-frame duration. Calibration fixes exposure. + measured_exposure = float(info.fExposureTime) + exposure = measured_exposure if measured_exposure > 0 else self.exposure_us + stamp = self.frame_clock.timestamp(tick, received_ns=received_ns, exposure_us=exposure) + if self.last_stamp_ns is not None and stamp <= self.last_stamp_ns: + raise ValueError("camera exposure time is not increasing after clock synchronization") + self.last_stamp_ns = stamp + self._write(dict(kind="camera_frame_time", frame_number=int(info.nFrameNum), + device_tick=tick, sdk_host_stamp_ms=int(info.nHostTimeStamp), + received_ns=received_ns, stamp_ns=stamp, exposure_us=exposure, + timestamp_reference="exposure_midpoint" if exposure else "exposure_start")) + return stamp + + def close(self): + if self.journal is not None: + self.journal.close() + self.journal = None diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/__init__.py new file mode 100644 index 0000000..c069e74 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/__init__.py @@ -0,0 +1,21 @@ +"""Compatibility adapters for one-release calibration migrations.""" + +from .config_v1 import ( + legacy_default_profile_key, + product_profile_key, + resolve_legacy_profile_alias, +) +from .defaults import ( + default_product_config_path, + default_three_camera_config_path, +) +from .paths import resolve_renamed_package_path + +__all__ = [ + "default_product_config_path", + "default_three_camera_config_path", + "legacy_default_profile_key", + "product_profile_key", + "resolve_legacy_profile_alias", + "resolve_renamed_package_path", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/config_v1.py b/src/linkerhand_calibration/linkerhand_calibration/compat/config_v1.py new file mode 100644 index 0000000..7699908 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/config_v1.py @@ -0,0 +1,47 @@ +"""Identity migration for deployed product configuration schemas.""" + +from __future__ import annotations + +from typing import Any, Mapping + +from ..core import ProfileKey + + +def product_profile_key(raw: Mapping[str, Any]) -> ProfileKey: + version = int(raw.get("schema_version", -1)) + if version in {2, 3}: + key = ProfileKey.parse(str(raw.get("profile_id", ""))) + for field, actual in ( + ("model", key.model), + ("side", key.side), + ("tag_layout", key.layout), + ): + configured = str(raw.get(field, "")).strip() + if configured and configured.lower() != actual.lower(): + raise ValueError(f"{field} differs from profile_id") + return key + if version != 1: + raise ValueError("product config schema_version must be 1, 2 or 3") + model = str(raw.get("model", "")).strip().upper() + side = str(raw.get("side", "")).strip().lower() + layout = str(raw.get("tag_layout", "")).strip().lower() + if not layout and (model, side) == ("G20", "right"): + layout = "g20_right_19" + return ProfileKey(model, side, layout, 1) + + +def legacy_default_profile_key() -> ProfileKey: + """Preserve the former no-argument executable for one release.""" + return ProfileKey("G20", "right", "g20_right_19", 1) + + +def resolve_legacy_profile_alias(key: ProfileKey) -> ProfileKey: + """Map retired layout identifiers to their reviewed physical profile.""" + if ( + key.model == "G20" + and key.side == "right" + and key.layout == "g20_right_15" + and key.revision == 1 + ): + return ProfileKey("G20", "right", "g20_right_19", 1) + return key diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/defaults.py b/src/linkerhand_calibration/linkerhand_calibration/compat/defaults.py new file mode 100644 index 0000000..07084d0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/defaults.py @@ -0,0 +1,16 @@ +"""One-release default selection for invocations without ``--config``.""" + +from pathlib import Path + +from ament_index_python.packages import get_package_share_directory + + +def default_product_config_path() -> Path: + share = Path(get_package_share_directory("linkerhand_calibration")) + return share / "config/g20_right_product.yaml" + + +def default_three_camera_config_path() -> Path: + """Resolve the installed calibration defaults through the ROS index.""" + share = Path(get_package_share_directory("linkerhand_calibration")) + return share / "config/three_camera_calibration.yaml" diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/__init__.py new file mode 100644 index 0000000..eab30d7 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/__init__.py @@ -0,0 +1,4 @@ +"""Legacy single-camera algorithms retained for one compatibility release.""" +from .session_v1 import uses_coupled_full_hand_zero_solver + +__all__ = ["uses_coupled_full_hand_zero_solver"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/session_v1.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/session_v1.py new file mode 100644 index 0000000..daa5103 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/session_v1.py @@ -0,0 +1,24 @@ +"""Version selection for replaying durable pre-v3 hardware sessions.""" + +from __future__ import annotations + +from typing import Any, Mapping + + +def uses_coupled_full_hand_zero_solver( + session_start: Mapping[str, Any], +) -> bool: + """Return the solver contract recorded by the legacy session header. + + Capabilities are not consulted by the live runtime. This adapter reads + the durable v1 header only so offline replay can reproduce an artifact + created before the independent thumb solver was introduced. + """ + capabilities = { + str(value) for value in session_start.get("capabilities", ()) + } + return ( + int(session_start.get("sample_schema_version", 1)) == 1 + and "palm_axis_side_channel_v2" in capabilities + and "palm_axis_relative_motion_v3" not in capabilities + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/thumb_core.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/thumb_core.py new file mode 100644 index 0000000..fd19fd5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy/thumb_core.py @@ -0,0 +1,638 @@ +"""Pure calibration math and command helpers. + +This module deliberately has no ROS imports so the geometry, fitting, and +output schema can be tested without a camera or a connected hand. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import math +from typing import Any, Iterable, Mapping, Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + + +COMMAND_NAMES: tuple[str, ...] = ( + "thumb_cmc_pitch", + "index_mcp_pitch", + "middle_mcp_pitch", + "ring_mcp_pitch", + "pinky_mcp_pitch", + "thumb_cmc_roll", + "index_mcp_roll", + "middle_mcp_roll", + "ring_mcp_roll", + "pinky_mcp_roll", + "thumb_cmc_yaw", + "reserved_11", + "reserved_12", + "reserved_13", + "reserved_14", + "thumb_mcp", + "index_pip", + "middle_pip", + "ring_pip", + "pinky_pip", +) + +BASELINE_COMMAND: tuple[int, ...] = ( + 255, + 255, + 255, + 255, + 255, + 255, + 193, + 148, + 105, + 42, + 245, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, +) + +PAIR_ROOT = "t0_t3" +PAIR_MCP = "t3_t4" +PAIR_IP = "t4_t5" +PAIR_NAMES: tuple[str, ...] = (PAIR_ROOT, PAIR_MCP, PAIR_IP) + +DIRECTION_DECREASING = "decreasing" +DIRECTION_INCREASING = "increasing" +DIRECTIONS: tuple[str, ...] = ( + DIRECTION_DECREASING, + DIRECTION_INCREASING, +) + +PHASE_ROOT = "root" +PHASE_TIP = "tip" + +JOINT_SPECS: dict[str, tuple[str, str, int]] = { + "thumb_cmc_pitch": (PHASE_ROOT, PAIR_ROOT, 0), + "thumb_mcp": (PHASE_TIP, PAIR_MCP, 15), + "thumb_ip": (PHASE_TIP, PAIR_IP, 15), +} + + +def build_command( + motor_index: int, + command_u8: int, + baseline: Sequence[int] = BASELINE_COMMAND, +) -> list[int]: + """Return one full G20 command with exactly one replaced motor slot.""" + if len(baseline) != 20: + raise ValueError("baseline must contain exactly 20 values") + values = [int(value) for value in baseline] + if any(value < 0 or value > 255 for value in values): + raise ValueError("baseline values must be in [0, 255]") + if motor_index not in (0, 5, 15): + raise ValueError( + "front thumb calibration only permits motor 0, 5 or 15" + ) + command_u8 = int(command_u8) + if command_u8 < 0 or command_u8 > 255: + raise ValueError("command_u8 must be in [0, 255]") + values[motor_index] = command_u8 + return values + + +def scan_targets( + repetitions: int = 3, + command_step: int = 1, +) -> list[tuple[int, str, int]]: + """Build repeated 255->0->255 scan targets on a bounded command grid.""" + if repetitions < 1: + raise ValueError("repetitions must be positive") + if command_step < 1 or command_step > 255: + raise ValueError("command_step must be in [1, 255]") + increasing = list(range(0, 256, command_step)) + if increasing[-1] != 255: + increasing.append(255) + decreasing = list(reversed(increasing)) + targets: list[tuple[int, str, int]] = [] + for cycle in range(repetitions): + targets.extend( + (cycle, DIRECTION_DECREASING, command) + for command in decreasing + ) + targets.extend( + (cycle, DIRECTION_INCREASING, command) + for command in increasing + ) + return targets + + +def normalize_quaternion_xyzw(values: Sequence[float]) -> np.ndarray: + quaternion = np.asarray(values, dtype=float) + if quaternion.shape != (4,) or not np.all(np.isfinite(quaternion)): + raise ValueError("quaternion must contain four finite xyzw values") + norm = float(np.linalg.norm(quaternion)) + if norm < 1e-12: + raise ValueError("quaternion norm is zero") + return quaternion / norm + + +def relative_quaternion_xyzw( + parent_camera_quaternion: Sequence[float], + child_camera_quaternion: Sequence[float], +) -> tuple[float, float, float, float]: + """Compute parent->child orientation from two camera->tag rotations.""" + parent = Rotation.from_quat(normalize_quaternion_xyzw(parent_camera_quaternion)) + child = Rotation.from_quat(normalize_quaternion_xyzw(child_camera_quaternion)) + quaternion = (parent.inv() * child).as_quat() + return tuple(float(value) for value in quaternion) + + +def image_plane_tag_quaternion_xyzw( + corners_xy: Sequence[Sequence[float]], +) -> tuple[float, float, float, float]: + """Estimate tag orientation about the optical axis from ordered corners.""" + corners = np.asarray(corners_xy, dtype=float) + if corners.shape != (4, 2) or not np.all(np.isfinite(corners)): + raise ValueError("corners_xy must contain four finite xy points") + # AprilTag corners 0->1 and 3->2 both follow the tag-local x axis. + # Average the two edges to reduce sub-pixel corner noise and perspective + # asymmetry. Image y points down, hence the minus sign for a right-handed + # camera-frame z rotation. + x_axis = (corners[1] - corners[0]) + (corners[2] - corners[3]) + if float(np.linalg.norm(x_axis)) < 1e-9: + raise ValueError("tag x-axis is degenerate") + angle = -math.atan2(float(x_axis[1]), float(x_axis[0])) + quaternion = Rotation.from_rotvec([0.0, 0.0, angle]).as_quat() + return tuple(float(value) for value in quaternion) + + +def robust_rotation_summary( + quaternions_xyzw: Sequence[Sequence[float]], +) -> tuple[tuple[float, float, float, float], float]: + """Return a robust orientation and maximum angular residual in radians.""" + if not quaternions_xyzw: + raise ValueError("at least one quaternion is required") + rotations = Rotation.from_quat( + np.asarray( + [normalize_quaternion_xyzw(value) for value in quaternions_xyzw], + dtype=float, + ) + ) + reference = rotations[0] + delta_vectors = (reference.inv() * rotations).as_rotvec() + median_delta = np.median(delta_vectors, axis=0) + robust = reference * Rotation.from_rotvec(median_delta) + residuals = (robust.inv() * rotations).magnitude() + maximum = float(np.max(residuals)) if residuals.size else 0.0 + return ( + tuple(float(value) for value in robust.as_quat()), + maximum, + ) + + +def rotation_spread_rad( + quaternions_xyzw: Sequence[Sequence[float]], +) -> float: + """Return the maximum geodesic residual around a robust orientation.""" + _, spread = robust_rotation_summary(quaternions_xyzw) + return spread + + +def rotation_rms_rad( + quaternions_xyzw: Sequence[Sequence[float]], + *, + outlier_threshold_rad: float | None = None, +) -> float: + """Return RMS geodesic noise around a robust orientation.""" + robust, _ = robust_rotation_summary(quaternions_xyzw) + reference = Rotation.from_quat(robust) + rotations = Rotation.from_quat( + np.asarray( + [normalize_quaternion_xyzw(value) for value in quaternions_xyzw], + dtype=float, + ) + ) + residuals = (reference.inv() * rotations).magnitude() + if outlier_threshold_rad is not None: + threshold = float(outlier_threshold_rad) + if threshold <= 0.0: + raise ValueError("outlier_threshold_rad must be positive") + residuals = residuals[residuals <= threshold] + if residuals.size == 0: + return float("inf") + return float(np.sqrt(np.mean(np.square(residuals)))) + + +def rotation_inlier_fraction( + quaternions_xyzw: Sequence[Sequence[float]], + *, + outlier_threshold_rad: float, +) -> float: + """Return the fraction close to the robust orientation.""" + threshold = float(outlier_threshold_rad) + if threshold <= 0.0: + raise ValueError("outlier_threshold_rad must be positive") + robust, _ = robust_rotation_summary(quaternions_xyzw) + reference = Rotation.from_quat(robust) + rotations = Rotation.from_quat( + np.asarray( + [normalize_quaternion_xyzw(value) for value in quaternions_xyzw], + dtype=float, + ) + ) + residuals = (reference.inv() * rotations).magnitude() + return float(np.mean(residuals <= threshold)) + + +def delta_rotation_vector( + reference_xyzw: Sequence[float], + observed_xyzw: Sequence[float], +) -> np.ndarray: + reference = Rotation.from_quat(normalize_quaternion_xyzw(reference_xyzw)) + observed = Rotation.from_quat(normalize_quaternion_xyzw(observed_xyzw)) + return (reference.inv() * observed).as_rotvec() + + +def fit_rotation_axis( + vectors: Sequence[Sequence[float]], + commands: Sequence[int], +) -> np.ndarray: + """Fit and orient the single rotational axis used by one motor sweep.""" + matrix = np.asarray(vectors, dtype=float) + command_values = np.asarray(commands, dtype=int) + if matrix.ndim != 2 or matrix.shape[1] != 3: + raise ValueError("vectors must have shape (N, 3)") + if command_values.shape != (matrix.shape[0],): + raise ValueError("commands must match vectors") + useful = np.linalg.norm(matrix, axis=1) > 1e-6 + if int(np.count_nonzero(useful)) < 3: + raise ValueError("insufficient non-zero rotations to fit an axis") + _, _, vh = np.linalg.svd(matrix[useful], full_matrices=False) + axis = vh[0] + projections = matrix @ axis + low = projections[command_values <= 16] + high = projections[command_values >= 239] + if low.size and high.size and float(np.median(low)) < float(np.median(high)): + axis = -axis + return axis / np.linalg.norm(axis) + + +def isotonic_nonincreasing(values: Sequence[float]) -> np.ndarray: + """Unweighted PAVA projection onto non-increasing values.""" + original = np.asarray(values, dtype=float) + if original.ndim != 1 or not np.all(np.isfinite(original)): + raise ValueError("values must be a finite vector") + negated = -original + levels: list[float] = [] + weights: list[int] = [] + starts: list[int] = [] + for index, value in enumerate(negated): + levels.append(float(value)) + weights.append(1) + starts.append(index) + while len(levels) >= 2 and levels[-2] > levels[-1]: + total_weight = weights[-2] + weights[-1] + merged = ( + levels[-2] * weights[-2] + levels[-1] * weights[-1] + ) / total_weight + levels[-2:] = [merged] + weights[-2:] = [total_weight] + starts.pop() + projected = np.empty_like(original) + for block_index, (level, start) in enumerate(zip(levels, starts)): + end = starts[block_index + 1] if block_index + 1 < len(starts) else len(original) + projected[start:end] = -level + return projected + + +def _record_rotation(record: Mapping[str, Any], pair: str) -> tuple[float, ...]: + rotations = record.get("relative_quaternion_xyzw", {}) + value = rotations.get(pair) + if value is None: + raise ValueError(f"sample record is missing {pair}") + return tuple(float(component) for component in value) + + +@dataclass(frozen=True) +class FitResult: + joints: dict[str, dict[str, Any]] + axes: dict[str, tuple[float, float, float]] + references: dict[str, tuple[float, float, float, float]] + ip_coupling: dict[str, float] + max_monotonic_correction_rad: float + max_hysteresis_rad: float + measurement_mode: str = "rotation" + trajectory_models: dict[str, Any] = field(default_factory=dict) + trajectory_quality: dict[str, Any] = field(default_factory=dict) + + def measure_from_reference( + self, + joint_name: str, + observed_quaternion_xyzw: Sequence[float], + reference_quaternion_xyzw: Sequence[float] | None = None, + ) -> float: + reference = ( + reference_quaternion_xyzw + if reference_quaternion_xyzw is not None + else self.references[joint_name] + ) + vector = delta_rotation_vector(reference, observed_quaternion_xyzw) + axis = np.asarray(self.axes[joint_name], dtype=float) + return float(vector @ axis) + + +def fit_calibration_curves(records: Iterable[Mapping[str, Any]]) -> FitResult: + """Fit six complete 256-entry curves from dense or sparse scan records.""" + samples = [ + dict(record) + for record in records + if record.get("kind", "sample") == "sample" + ] + if not samples: + raise ValueError("no scan records were provided") + + joint_results: dict[str, dict[str, Any]] = {} + axes: dict[str, tuple[float, float, float]] = {} + references: dict[str, tuple[float, float, float, float]] = {} + maximum_correction = 0.0 + maximum_hysteresis = 0.0 + + for joint_name, (phase, pair, motor_index) in JOINT_SPECS.items(): + phase_records = [record for record in samples if record.get("phase") == phase] + if not phase_records: + raise ValueError(f"no records for phase {phase}") + + cycle_references: dict[int, tuple[float, ...]] = {} + for record in phase_records: + if ( + record.get("direction") == DIRECTION_DECREASING + and int(record.get("command_u8", -1)) == 255 + ): + cycle_references.setdefault( + int(record["cycle"]), + _record_rotation(record, pair), + ) + cycles = sorted({int(record["cycle"]) for record in phase_records}) + if any(cycle not in cycle_references for cycle in cycles): + raise ValueError(f"{joint_name} is missing a command-255 cycle reference") + + vectors: list[np.ndarray] = [] + commands: list[int] = [] + indexed: list[tuple[Mapping[str, Any], np.ndarray]] = [] + for record in phase_records: + cycle = int(record["cycle"]) + vector = delta_rotation_vector( + cycle_references[cycle], + _record_rotation(record, pair), + ) + vectors.append(vector) + commands.append(int(record["command_u8"])) + indexed.append((record, vector)) + axis = fit_rotation_axis(vectors, commands) + axes[joint_name] = tuple(float(value) for value in axis) + references[joint_name] = robust_rotation_summary( + list(cycle_references.values()) + )[0] + + branch_values: dict[str, list[list[float]]] = { + direction: [[] for _ in range(256)] for direction in DIRECTIONS + } + for record, vector in indexed: + direction = str(record["direction"]) + command = int(record["command_u8"]) + branch_values[direction][command].append(float(vector @ axis)) + + fitted_branches: dict[str, list[float]] = {} + for direction in DIRECTIONS: + sample_commands = np.asarray( + [ + command + for command, values in enumerate(branch_values[direction]) + if values + ], + dtype=int, + ) + if ( + sample_commands.size < 3 + or int(sample_commands[0]) != 0 + or int(sample_commands[-1]) != 255 + ): + raise ValueError( + f"{joint_name}.{direction} requires at least three samples " + "including commands 0 and 255" + ) + raw = np.asarray( + [ + float(np.median(branch_values[direction][command])) + for command in sample_commands + ], + dtype=float, + ) + raw -= raw[-1] + projected_samples = isotonic_nonincreasing(raw) + projected_samples -= projected_samples[-1] + correction = float(np.max(np.abs(projected_samples - raw))) + maximum_correction = max(maximum_correction, correction) + projected = np.interp( + np.arange(256, dtype=float), + sample_commands.astype(float), + projected_samples, + ) + projected -= projected[255] + fitted_branches[direction] = [ + round(float(value), 8) for value in projected + ] + + hysteresis = float( + np.max( + np.abs( + np.asarray(fitted_branches[DIRECTION_DECREASING]) + - np.asarray(fitted_branches[DIRECTION_INCREASING]) + ) + ) + ) + maximum_hysteresis = max(maximum_hysteresis, hysteresis) + combined_curve = 0.5 * ( + np.asarray( + fitted_branches[DIRECTION_DECREASING], dtype=float + ) + + np.asarray( + fitted_branches[DIRECTION_INCREASING], dtype=float + ) + ) + combined_curve -= combined_curve[255] + joint_result: dict[str, Any] = { + "motor_index": motor_index, + "angle_rad": [ + round(float(value), 8) for value in combined_curve + ], + "decreasing_rad": fitted_branches[DIRECTION_DECREASING], + "increasing_rad": fitted_branches[DIRECTION_INCREASING], + } + if joint_name == "thumb_ip": + joint_result["passive"] = True + joint_results[joint_name] = joint_result + + mcp = joint_results["thumb_mcp"] + ip = joint_results["thumb_ip"] + x = np.asarray(mcp["angle_rad"], dtype=float) + y = np.asarray(ip["angle_rad"], dtype=float) + design = np.column_stack((x, np.ones_like(x))) + multiplier, offset = np.linalg.lstsq(design, y, rcond=None)[0] + predicted = multiplier * x + offset + residual_sum = float(np.sum((y - predicted) ** 2)) + total_sum = float(np.sum((y - np.mean(y)) ** 2)) + r_squared = 1.0 if total_sum < 1e-12 else 1.0 - residual_sum / total_sum + + return FitResult( + joints=joint_results, + axes=axes, + references=references, + ip_coupling={ + "multiplier": round(float(multiplier), 8), + "offset_rad": round(float(offset), 8), + "r_squared": round(float(r_squared), 8), + }, + max_monotonic_correction_rad=maximum_correction, + max_hysteresis_rad=maximum_hysteresis, + ) + + +def create_final_payload( + *, + serial_number: str, + fit: FitResult, + validation_errors_rad: Sequence[float], + passed: bool, + baseline: Sequence[int] = BASELINE_COMMAND, +) -> dict[str, Any]: + errors = np.abs(np.asarray(validation_errors_rad, dtype=float)) + mae = float(np.mean(errors)) if errors.size else float("nan") + p95 = float(np.percentile(errors, 95)) if errors.size else float("nan") + runtime_joints: dict[str, dict[str, Any]] = {} + for joint_name, joint in fit.joints.items(): + runtime_joint: dict[str, Any] = { + "motor_index": int(joint["motor_index"]), + "angle_rad": [ + round(float(value), 8) for value in joint["angle_rad"] + ], + } + if joint_name == "thumb_ip": + runtime_joint["passive"] = True + runtime_joints[joint_name] = runtime_joint + + payload = { + "schema_version": 2, + "model": "G20", + "side": "left", + "serial_number": str(serial_number), + "angle_unit": "rad", + "command_range": [0, 255], + "zero_command_u8": 255, + "baseline_command_u8": [int(value) for value in baseline], + "joints": runtime_joints, + "ip_coupling": { + "multiplier": fit.ip_coupling["multiplier"], + "offset_rad": fit.ip_coupling["offset_rad"], + }, + "quality": { + "passed": bool(passed), + "validation_mae_rad": None if not np.isfinite(mae) else round(mae, 8), + "validation_p95_rad": None if not np.isfinite(p95) else round(p95, 8), + }, + } + validate_final_payload(payload) + return payload + + +def maximum_non_target_drift_rad( + records: Iterable[Mapping[str, Any]], + fit: FitResult, +) -> float: + """Measure unintended active-joint motion during the two isolated scans.""" + samples = [ + dict(record) + for record in records + if record.get("kind", "sample") == "sample" + ] + maximum = 0.0 + checks = ( + (PHASE_ROOT, "thumb_mcp", PAIR_MCP), + (PHASE_ROOT, "thumb_ip", PAIR_IP), + (PHASE_TIP, "thumb_cmc_pitch", PAIR_ROOT), + ) + for phase, joint_name, pair in checks: + phase_records = [record for record in samples if record.get("phase") == phase] + for cycle in sorted({int(record["cycle"]) for record in phase_records}): + cycle_records = [ + record for record in phase_records if int(record["cycle"]) == cycle + ] + reference_record = next( + ( + record + for record in cycle_records + if record.get("direction") == DIRECTION_DECREASING + and int(record.get("command_u8", -1)) == 255 + ), + None, + ) + if reference_record is None: + continue + reference = _record_rotation(reference_record, pair) + axis = np.asarray(fit.axes[joint_name], dtype=float) + for record in cycle_records: + drift = abs( + float( + delta_rotation_vector( + reference, + _record_rotation(record, pair), + ) + @ axis + ) + ) + maximum = max(maximum, drift) + return maximum + + +def validate_final_payload(payload: Mapping[str, Any]) -> None: + """Validate the deliberately small runtime JSON schema.""" + if payload.get("schema_version") != 2: + raise ValueError("schema_version must be 2") + if payload.get("model") != "G20" or payload.get("side") != "left": + raise ValueError("payload must describe a left G20") + if payload.get("angle_unit") != "rad": + raise ValueError("angle_unit must be rad") + baseline = payload.get("baseline_command_u8") + if not isinstance(baseline, list) or len(baseline) != 20: + raise ValueError("baseline_command_u8 must contain 20 values") + joints = payload.get("joints") + if not isinstance(joints, Mapping) or set(joints) != set(JOINT_SPECS): + raise ValueError("payload must contain exactly the three thumb joints") + for joint_name, joint in joints.items(): + expected_motor = JOINT_SPECS[joint_name][2] + if int(joint.get("motor_index", -1)) != expected_motor: + raise ValueError(f"{joint_name} has the wrong motor index") + curve = joint.get("angle_rad") + if not isinstance(curve, list) or len(curve) != 256: + raise ValueError( + f"{joint_name}.angle_rad must contain 256 values" + ) + values = np.asarray(curve, dtype=float) + if not np.all(np.isfinite(values)): + raise ValueError( + f"{joint_name}.angle_rad contains non-finite values" + ) + if np.any(np.diff(values) > 1e-7): + raise ValueError( + f"{joint_name}.angle_rad must be non-increasing" + ) + if abs(float(values[255])) > 1e-6: + raise ValueError( + f"{joint_name}.angle_rad[255] must be zero" + ) + if joints["thumb_ip"].get("passive") is not True: + raise ValueError("thumb_ip must be marked passive") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/README.md b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/README.md new file mode 100644 index 0000000..71fc3de --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/README.md @@ -0,0 +1,14 @@ +# 历史兼容区 + +此目录保留旧格式读写、旧布局、历史数据诊断及必要的离线工具,不参与正式在线调度。 +四型号的 runner/node/pipeline 已由 `runtime/runner.py`、`runtime/session.py` 和 +`runtime/artifacts/finalization.py` 替代。只保留仍被历史工具调用的入口; +L6/O6 无调用的 pipeline 包装已删除。 + +旧独立断点实现、低速预检和在线节点已移除。旧发布函数已拒绝更新正式发布指针。 +这里生成的离线诊断文件不能作为标准 URDF 已验收的证据;正式回放使用 +`calibrate_hand --config --offline-raw `。 + +不要在此目录增加新型号。新型号提供 Profile、产品 YAML、原始 CAD/mesh;仅新 SDK 协议增加 Adapter。 +需要恢复已删除的历史实现时,使用工作区 +`calibration_output/refactor_backup.4WRWNn/` 中的归档,不要重新接入生产入口。 diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/__init__.py new file mode 100644 index 0000000..581de90 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/__init__.py @@ -0,0 +1 @@ +"""Read-only compatibility for archived sessions and diagnostic tools.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/__init__.py new file mode 100644 index 0000000..1962558 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/__init__.py @@ -0,0 +1,17 @@ +"""Model- and side-specific calibration policies.""" + +from linkerhand_calibration.compat.legacy_diagnostic_tools.models.registry import ( + EngineBindings, + ProfileRegistry, + RegisteredProfile, + get_default_registry, +) +from linkerhand_calibration.compat.legacy_diagnostic_tools.models.runtime_schema import validate_schema_v6_runtime_payload + +__all__ = [ + "EngineBindings", + "ProfileRegistry", + "RegisteredProfile", + "get_default_registry", + "validate_schema_v6_runtime_payload", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/__init__.py new file mode 100644 index 0000000..163d125 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/__init__.py @@ -0,0 +1,3 @@ +"""Compatibility imports for the G20 model package.""" +from linkerhand_calibration.models.g20 import register_profiles +__all__ = ["register_profiles"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/_adapter.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/_adapter.py new file mode 100644 index 0000000..d8976a2 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/_adapter.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20._adapter.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20._adapter") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/artifacts.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/artifacts.py new file mode 100644 index 0000000..6dfb06e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/artifacts.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.artifacts.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.artifacts") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/command_layout.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/command_layout.py new file mode 100644 index 0000000..37b1231 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/command_layout.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.command_layout.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.command_layout") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/golden_regression.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/golden_regression.py new file mode 100644 index 0000000..dd2ae98 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/golden_regression.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.golden_regression.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.golden_regression") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/legacy_11.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/legacy_11.py new file mode 100644 index 0000000..f93c02c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/legacy_11.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.legacy_11.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.legacy_11") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/motion.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/motion.py new file mode 100644 index 0000000..f352b61 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/motion.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.motion.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.motion") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/offline_replay.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/offline_replay.py new file mode 100644 index 0000000..efdf57a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/offline_replay.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.offline_replay.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.offline_replay") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/profile.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/profile.py new file mode 100644 index 0000000..949a142 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/profile.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.profile.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.profile") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/publication.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/publication.py new file mode 100644 index 0000000..3d54c81 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/publication.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.publication.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.publication") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/reporting_zh.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/reporting_zh.py new file mode 100644 index 0000000..aa89b75 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/reporting_zh.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.reporting_zh.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.reporting_zh") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/right_19.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/right_19.py new file mode 100644 index 0000000..f45ed5d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/right_19.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.right_19.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.right_19") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/runner.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/runner.py new file mode 100644 index 0000000..e0eb9a5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/runner.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.runner.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.runner") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/urdf_input.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/urdf_input.py new file mode 100644 index 0000000..c847a6b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/urdf_input.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.urdf_input.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.urdf_input") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/zero_policy.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/zero_policy.py new file mode 100644 index 0000000..dc3e231 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/zero_policy.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.zero_policy.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.zero_policy") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/zero_solver.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/zero_solver.py new file mode 100644 index 0000000..4703dbb --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/g20/zero_solver.py @@ -0,0 +1,4 @@ +"""Compatibility import for g20.zero_solver.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.zero_solver") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/__init__.py new file mode 100644 index 0000000..4fafcff --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/__init__.py @@ -0,0 +1,3 @@ +"""Compatibility imports for the L6 model package.""" +from linkerhand_calibration.models.l6 import register_profiles +__all__ = ["register_profiles"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/artifacts.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/artifacts.py new file mode 100644 index 0000000..f6acd96 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/artifacts.py @@ -0,0 +1,4 @@ +"""Compatibility import for l6.artifacts.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.l6.artifacts") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/fitting.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/fitting.py new file mode 100644 index 0000000..b8b63fa --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/fitting.py @@ -0,0 +1,4 @@ +"""Compatibility import for l6.fitting.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.l6.fitting") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/left_transfer.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/left_transfer.py new file mode 100644 index 0000000..ec98a53 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/left_transfer.py @@ -0,0 +1,4 @@ +"""Compatibility import for l6.left_transfer.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.l6.left_transfer") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/motion.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/motion.py new file mode 100644 index 0000000..023784f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/motion.py @@ -0,0 +1,4 @@ +"""Compatibility import for l6.motion.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.l6.motion") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/profile.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/profile.py new file mode 100644 index 0000000..eab1c91 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/profile.py @@ -0,0 +1,4 @@ +"""Compatibility import for l6.profile.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.l6.profile") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/runner.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/runner.py new file mode 100644 index 0000000..af4ad76 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/runner.py @@ -0,0 +1,4 @@ +"""Compatibility import for l6.runner.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.l6.runner") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/urdf.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/urdf.py new file mode 100644 index 0000000..2934e18 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/l6/urdf.py @@ -0,0 +1,4 @@ +"""Compatibility import for l6.urdf.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.l6.urdf") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/__init__.py new file mode 100644 index 0000000..cdc9cd5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/__init__.py @@ -0,0 +1,3 @@ +"""Compatibility imports for the O12 model package.""" +from linkerhand_calibration.models.o12 import register_profiles +__all__ = ["register_profiles"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/artifacts.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/artifacts.py new file mode 100644 index 0000000..da60673 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/artifacts.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.artifacts.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.artifacts") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/fitting.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/fitting.py new file mode 100644 index 0000000..00dd4f6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/fitting.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.fitting.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.fitting") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/health.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/health.py new file mode 100644 index 0000000..23d690e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/health.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.health.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.health") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/kinematics.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/kinematics.py new file mode 100644 index 0000000..7739a83 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/kinematics.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.kinematics.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.kinematics") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/motion.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/motion.py new file mode 100644 index 0000000..4a7e62b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/motion.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.motion.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.motion") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/observations.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/observations.py new file mode 100644 index 0000000..32a84bb --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/observations.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.observations.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.observations") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/pipeline.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/pipeline.py new file mode 100644 index 0000000..703015d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/pipeline.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.pipeline.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.pipeline") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/pnp.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/pnp.py new file mode 100644 index 0000000..d7e7e1e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/pnp.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.pnp.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.pnp") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/profile.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/profile.py new file mode 100644 index 0000000..d064948 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/profile.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.profile.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.profile") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/quality.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/quality.py new file mode 100644 index 0000000..a60ed52 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/quality.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.quality.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.quality") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/runner.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/runner.py new file mode 100644 index 0000000..e6e96bf --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/runner.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.runner.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.runner") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/urdf.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/urdf.py new file mode 100644 index 0000000..7b86352 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/urdf.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.urdf.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.urdf") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/zero.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/zero.py new file mode 100644 index 0000000..6a66340 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o12/zero.py @@ -0,0 +1,4 @@ +"""Compatibility import for o12.zero.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.zero") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/__init__.py new file mode 100644 index 0000000..ad4ea26 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/__init__.py @@ -0,0 +1,3 @@ +"""Compatibility imports for the O6 model package.""" +from linkerhand_calibration.models.o6 import register_profiles +__all__ = ["register_profiles"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/artifacts.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/artifacts.py new file mode 100644 index 0000000..cc88ab6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/artifacts.py @@ -0,0 +1,4 @@ +"""Compatibility import for o6.artifacts.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o6.artifacts") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/fitting.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/fitting.py new file mode 100644 index 0000000..5545612 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/fitting.py @@ -0,0 +1,4 @@ +"""Compatibility import for o6.fitting.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o6.fitting") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/left_transfer.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/left_transfer.py new file mode 100644 index 0000000..af7af37 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/left_transfer.py @@ -0,0 +1,4 @@ +"""Compatibility import for o6.left_transfer.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o6.left_transfer") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/profile.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/profile.py new file mode 100644 index 0000000..ec346a4 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/profile.py @@ -0,0 +1,4 @@ +"""Compatibility import for o6.profile.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o6.profile") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/runner.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/runner.py new file mode 100644 index 0000000..567844c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/runner.py @@ -0,0 +1,4 @@ +"""Compatibility import for o6.runner.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o6.runner") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/urdf.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/urdf.py new file mode 100644 index 0000000..c74e139 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/o6/urdf.py @@ -0,0 +1,4 @@ +"""Compatibility import for o6.urdf.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o6.urdf") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/registry.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/registry.py new file mode 100644 index 0000000..b7396d9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/registry.py @@ -0,0 +1,4 @@ +"""Compatibility import for the shared model registry.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.registry") diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/runtime_schema.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/runtime_schema.py new file mode 100644 index 0000000..8f7e438 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/models/runtime_schema.py @@ -0,0 +1,25 @@ +"""Dispatch model-specific runtime artifact validation by profile identity.""" + +from __future__ import annotations + +from typing import Any, Mapping + +from linkerhand_calibration.core import ProfileKey + + +def validate_schema_v6_runtime_payload(payload: Mapping[str, Any]) -> None: + key = ProfileKey.parse(str(payload.get("profile_id", ""))) + if key.model == "L6": + from linkerhand_calibration.compat.legacy_diagnostic_tools.models.l6.artifacts import validate_l6_runtime_payload + + validate_l6_runtime_payload(payload) + return + if key.model == "O6": + from linkerhand_calibration.compat.legacy_diagnostic_tools.models.o6.artifacts import validate_o6_runtime_payload + + validate_o6_runtime_payload(payload) + return + raise ValueError(f"schema v6 is unsupported for {key.profile_id}") + + +__all__ = ["validate_schema_v6_runtime_payload"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/progress.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/progress.py new file mode 100644 index 0000000..b2ff8d7 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/progress.py @@ -0,0 +1,251 @@ +"""Read-only renderers for old recorded status payloads, not live runners.""" + +from __future__ import annotations + +from typing import Any, Mapping + +from ...operator_report import ProgressEstimator +from ...runtime.reporting import reason_zh, render_progress_zh + +common_reason_zh = reason_zh +render_six_channel_progress_zh = render_progress_zh + +_L6_TASK_LABELS = { + "thumb_roll_top": "拇指 CMC roll(上方机位,ID6→ID7)", + "thumb_pitch_dip_front": "拇指 CMC pitch / DIP(正面机位,ID0→ID1→ID2)", + "pinky_pitch_dip_side": "小指 MCP pitch / DIP(侧面机位,ID3→ID4→ID5)", +} + + +def _l6_reason_zh( + status: Mapping[str, Any], *, model_name: str = "L6" +) -> tuple[str, str, str]: + return common_reason_zh(status, model_name=model_name) + + +def render_l6_progress_zh( + status: Mapping[str, Any], + estimator: ProgressEstimator | None = None, +) -> str: + """Render L6 progress in the same operator-oriented layout as G20.""" + return render_six_channel_progress_zh( + status, + task_labels=_L6_TASK_LABELS, + reason_renderer=_l6_reason_zh, + estimator=estimator, + ) + +_O6_TASK_LABELS = { + "thumb_yaw_top": "拇指 CMC yaw(上面机位,ID6→ID7)", + "thumb_pitch_ip_front": "拇指 CMC pitch / IP(正面机位,ID0→ID1→ID2)", + "pinky_pitch_dip_side": "小指 MCP pitch / DIP(侧面机位,ID3→ID4→ID5)", +} + + +def render_o6_progress_zh( + status: dict[str, Any], + estimator: ProgressEstimator | None = None, +) -> str: + return render_progress_zh( + status, + task_labels=_O6_TASK_LABELS, + reason_renderer=lambda value: reason_zh( + value, model_name="O6" + ), + estimator=estimator, + ) + +_O12_TASK_LABELS = { + "thumb_pitch_front": "拇指 CMC pitch(正面 ID0→ID1)", + "thumb_roll_front": "拇指 CMC roll(正面 ID0→ID1)", + "thumb_mcp_dip_front": "拇指 MCP / 被动 DIP(正面 ID1→ID2→ID3)", + "thumb_yaw_top": "拇指 CMC yaw(顶部 ID14→ID15)", + "pinky_chain_side": "小指 MCP / 被动 PIP/DIP(侧面 ID4→ID5→ID6→ID7)", + "middle_roll_front": "中指 MCP roll(正面 ID0→ID12 + 侧面 ID4→ID8)", + "middle_mcp_side": "中指 MCP pitch(侧面 ID4→ID8)", + "middle_pip_dip_side": "中指 PIP / 被动 DIP(侧面 ID8→ID9)", + "index_roll_front": "食指 MCP roll(正面 ID0→ID13 + 侧面 ID4→ID10)", + "index_mcp_side": "食指 MCP pitch(侧面 ID4→ID10)", + "index_pip_dip_side": "食指 PIP / 被动 DIP(侧面 ID10→ID11)", +} + + +def _o12_reason_zh(status): + reason = str(status.get("reason", "")) + if reason.startswith("sweep_quality_failed:"): + details = reason.split(":", 2)[-1] + if any( + item in details + for item in ("side_frames=", "side_bins=", "side_maximum_gap=") + ): + return ( + "O12-CROSS-VIEW-SAMPLING-104", + "侧摆任务的主视角数据已采到,但辅助侧面视角在本段轨迹内" + f"保留的时序覆盖不足:{details}。这不表示 Tag 被遮挡。", + "程序会保留已通过断点;重新启动后只重做该扫描单元。" + "若 Tag 持续可见,优先检查侧面 AprilTag 节点的发布频率和 CPU 调度。", + ) + if reason.startswith("mapping_preflight_no_target_motion:"): + task = reason.split(":", 1)[1] + return ( + "O12-MAPPING-301", + f"固定 SDK 映射点动时没有观察到目标关节运动:{task}。", + "检查对应 Tag、通道映射和机械连接;不要交换通道后强行继续。", + ) + if reason.startswith("mapping_preflight_wrong_feedback_direction:"): + task = reason.split(":", 1)[1] + return ( + "O12-MAPPING-302", + f"固定 SDK 映射点动的目标反馈方向不正确:{task}。", + "检查对应 SDK 通道和机械连接;不要交换通道后强行继续。", + ) + if reason.startswith("o12_active_motor_fault"): + return ( + "O12-HEALTH-201", + f"O12 返回活动电机故障:{status.get('error_faults', [])}。", + "检查对应电机的堵转、过流、过热或电机异常;排除后从断点启动。", + ) + if reason.startswith("o12_new_communication_fault"): + return ( + "O12-HEALTH-202", + f"运行中出现了新的 O12 通信异常:{status.get('error_faults', [])}。", + "检查 HCAN 线缆、供电和对应电机通信;程序已保持当前位置。", + ) + if reason.startswith("o12_feedback_stream_timeout"): + return ( + "O12-HEALTH-203", + "O12 命令触发反馈流中断超过 1 秒。", + "检查 HCAN 连接、SDK 节点和供电;恢复后从断点启动。", + ) + if reason.startswith("feedback_outside_registered_feedback_domain:"): + return ( + "O12-FEEDBACK-202", + "O12 反馈超出了已登记的物理反馈范围。", + "保持当前位置,检查诊断中的通道、反馈值和机械端点。", + ) + if reason == "calibration_node_status_timeout": + return ( + "O12-NODE-500", + "O12 标定节点已停止发布状态,运行栈将自动退出。", + "查看本次 calibration.log 中的 Python traceback,并从断点重启。", + ) + return reason_zh(status, model_name="O12") + + +def render_o12_progress_zh(status, estimator=None) -> str: + """Render O12 in the same operator-oriented layout as G20 and L6.""" + text = render_progress_zh( + status, + task_labels=_O12_TASK_LABELS, + reason_renderer=_o12_reason_zh, + estimator=estimator, + ) + temperature = ( + "直接温度回读" + if status.get("temperature_report_verified") + else "错误码 bit1 过热保护" + if status.get("temperature_fallback_active") + else "等待温度能力确认" + ) + resume = status.get("resume", {}) + resume_text = "" + if isinstance(resume, dict) and resume.get("used"): + resume_text = ( + "\n断点恢复:已复用 " + f"{int(resume.get('completed_unit_count', 0))} 个扫描单元;" + f"来源 {resume.get('source_session', '-')}" + ) + cross_view = status.get("roll_cross_view", {}) + cross_view_text = "" + if isinstance(cross_view, dict) and cross_view.get("active"): + recognized = "/".join( + f"ID{int(value)}" + for value in cross_view.get("recognized_tag_ids", ()) + ) or "无" + missing = "/".join( + f"ID{int(value)}" + for value in cross_view.get("unrecognized_tag_ids", ()) + ) or "无" + cross_view_text = ( + "\n侧摆双机位:侧面已识别 " + f"{recognized};未识别/不合格 {missing};联合 " + f"{int(cross_view.get('valid_frames', 0))}/" + f"{int(cross_view.get('total_frames', 0))} 帧(" + f"{float(cross_view.get('joint_frame_rate', 0.0)):.1%})" + ) + coupling = status.get("feedback_coupling", {}) + coupling_text = "" + if isinstance(coupling, dict) and coupling.get("active"): + stage = { + "training_observation": "训练采集", + "holdout_pending_full_sweep_validation": "第四轮整段验证", + "vendor_solver_motion_prior": "运动准备", + }.get(str(coupling.get("reference_kind", "")), "耦合观测") + coupling_text = ( + "\nO12耦合:" + f"{coupling.get('coupled_channel', '-')} 位移 " + f"{float(coupling.get('displacement_rad', 0.0)):.3f}/" + f"{float(coupling.get('hard_displacement_limit_rad', 0.0)):.3f} rad;" + f"{stage};vendor偏差 " + f"{float(coupling.get('residual_rad', 0.0)):.3f} rad(仅诊断)" + ) + auxiliary = status.get("auxiliary_tracking", {}) + auxiliary_text = "" + if isinstance(auxiliary, dict) and auxiliary.get("active"): + channels = list(auxiliary.get("channels", ())) + worst = max( + channels, + key=lambda item: float(item.get("error_rad", 0.0)), + default={}, + ) + stage = ( + "平滑过渡中" + if auxiliary.get("mode") == "transitioning" + else "已稳定保持" + if auxiliary.get("ready") + else "等待稳定" + ) + auxiliary_text = ( + "\nO12避让轴:" + f"{stage};最大偏差 {worst.get('channel', '-')}=" + f"{float(worst.get('error_rad', 0.0)):.3f} rad" + ) + locked_ids = list(status.get("locked_reference_tag_ids", ())) + locked_reference_text = "" + if locked_ids: + locked_reference_text = ( + "\n固定基准:" + + "/".join(f"ID{int(value)}" for value in locked_ids) + + " 已锁定,避让遮挡期间复用" + ) + error_health = str( + status.get("error_health_classification", "awaiting_error_report") + ) + if error_health == "historical_communication_latch": + channels = "/".join( + str(value) for value in status.get( + "confirmed_historical_communication_channels", () + ) + ) or "未知通道" + error_health_text = f"历史通信位已核验({channels})" + elif error_health == "confirming_historical_communication": + error_health_text = ( + "确认历史通信位 " + f"{int(status.get('error_report_matching_count', 0))}/3" + ) + elif error_health == "clear": + error_health_text = "正常" + else: + error_health_text = error_health + return ( + text + cross_view_text + coupling_text + auxiliary_text + + locked_reference_text + resume_text + ( + "\nO12安全:POSITION=" + f"{bool(status.get('position_mode_verified'))};" + f"错误码通道={bool(status.get('error_report_verified'))}" + f"({error_health_text});" + f"温度策略={temperature};速度倍率=" + f"{float(status.get('motion_speed_scale', 1.0)):.1f}x;" + f"控制发布={float(status.get('command_publish_hz', 0.0)):.1f} Hz" + ) + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/runner_helpers.py b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/runner_helpers.py new file mode 100644 index 0000000..850e2c0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/legacy_diagnostic_tools/runner_helpers.py @@ -0,0 +1,283 @@ +"""Read-only helpers retained for archived runner diagnostics; no live loop.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any, Mapping + +from ...product import ProductConfig, sha256_file +from ...runtime.engine import ACQUISITION_POLICY_VERSION + +STATUS_TIMEOUT_SECONDS = 90.0 +FITTING_STATUS_TIMEOUT_SECONDS = 600.0 + +def _status_timeout_seconds(status: Mapping[str, Any]) -> float: + """Return the watchdog deadline for the node's current phase. + + Motion and acquisition are expected to publish twice a second and retain + the strict transport watchdog. The final 3-D fit is intentionally a + synchronous, CPU-bound operation, so its executor cannot service the + status timer until the fit returns. The node publishes an explicit + FITTING status immediately before entering that operation; allow that + known phase enough time without weakening motion safety checks. + """ + if str(status.get("state", "")) == "FITTING": + return FITTING_STATUS_TIMEOUT_SECONDS + return STATUS_TIMEOUT_SECONDS + + +def _calibration_node_exited_before_status(log_path: Path) -> bool: + """Detect a launch child crash while the parent launch is still alive.""" + try: + with log_path.open("rb") as stream: + stream.seek(0, os.SEEK_END) + size = stream.tell() + stream.seek(max(0, size - 65536), os.SEEK_SET) + tail = stream.read().decode("utf-8", errors="replace") + except OSError: + return False + return ( + "[three_camera_calibration_node-" in tail + and "]: process has died" in tail + ) + +def _launch_command( + config: ProductConfig, + session: Path, + *, + resume_from: Path | None = None, + recalibration_scope: str = "full", +) -> list[str]: + values = { + "model": config.model, + "hand_type": config.side, + "tag_layout": config.tag_layout, + "serial_number": config.serial_number, + "can_interface": config.can_interface, + "session_dir": str(session), + "output_root": str(config.output_root), + "camera_extrinsics_file": str(config.camera_extrinsics), + "source_urdf_path": str(config.source_urdf), + "source_urdf_expected_sha256": config.source_urdf_sha256, + "camera_extrinsics_expected_sha256": config.camera_extrinsics_sha256, + "calibration_config_expected_sha256": config.calibration_config_sha256, + "tag_config_expected_sha256": config.tag_config_sha256, + "profile_config_expected_sha256": getattr( + config, "profile_config_sha256", "" + ), + "corrected_urdf_output_dir": str(session), + "calibration_config": str(config.calibration_config), + "tag_config": str(config.tag_config), + "commands_enabled": "true", + "start_cameras": "true", + "start_sdk": "true", + "record_bag": "false", + "validation_enabled": "false", + "recalibration_scope": recalibration_scope, + } + if resume_from is not None: + values["resume_raw_samples_path"] = str( + resume_from / "raw_samples.jsonl" + ) + for view, camera in config.cameras.items(): + values[f"{view}_camera_serial"] = camera["serial_number"] + values[f"{view}_camera_name"] = camera["camera_name"] + values[f"{view}_camera_info_url"] = camera["camera_info"] + return [ + "ros2", + "launch", + "linkerhand_calibration", + "unified_calibration.launch.py", + *(f"{name}:={value}" for name, value in values.items()), + ] + +def _automatic_resume_candidate(config: ProductConfig) -> Path | None: + """Return the newest compatible failed attempt, never a passed session. + + Do not trust only ``latest_attempt``. A process interrupted during the + device-only startup gate may have already moved that pointer while still + containing no ``session_start`` checkpoint. In that case walk backwards + to the preceding usable failed session instead of throwing away hours of + completed tasks. + """ + root = config.session_root + try: + resolved_root = root.resolve(strict=True) + except OSError: + return None + + candidates: list[Path] = [] + pointer = config.session_root / "latest_attempt" + if pointer.exists(): + try: + candidates.append(pointer.resolve(strict=True)) + except OSError: + pass + try: + candidates.extend( + sorted( + ( + path + for path in root.iterdir() + if path.is_dir() and not path.name.startswith("latest_") + ), + key=lambda path: path.name, + reverse=True, + ) + ) + except OSError: + return None + + passed_pointer = config.session_root / "latest_passed" + passed: Path | None = None + if passed_pointer.exists(): + try: + passed = passed_pointer.resolve(strict=True) + except OSError: + pass + + seen: set[Path] = set() + for unresolved in candidates: + try: + candidate = unresolved.resolve(strict=True) + except OSError: + continue + if candidate in seen: + continue + seen.add(candidate) + if candidate.parent != resolved_root or not candidate.is_dir(): + continue + # A failed attempt older than the current formal release is stale and + # must not seed a new independent calibration. + if passed is not None and candidate.name <= passed.name: + continue + raw_path = candidate / "raw_samples.jsonl" + if not raw_path.is_file(): + continue + summary_path = candidate / "calibration_summary_zh.json" + summary: dict[str, Any] | None = None + if summary_path.is_file(): + try: + loaded = json.loads(summary_path.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError): + continue + if not isinstance(loaded, dict) or loaded.get("result") != "FAIL": + continue + summary = loaded + hashes = summary.get("hashes", {}) + if not isinstance(hashes, Mapping): + continue + if ( + str(hashes.get("source_urdf_sha256", "")) + != config.source_urdf_sha256 + or str(hashes.get("camera_extrinsics_sha256", "")) + != config.camera_extrinsics_sha256 + ): + continue + start: dict[str, Any] | None = None + try: + with raw_path.open("r", encoding="utf-8") as stream: + for line in stream: + if not line.strip(): + continue + value = json.loads(line) + if ( + isinstance(value, dict) + and value.get("kind") == "session_start" + ): + start = value + break + except (OSError, json.JSONDecodeError): + continue + if ( + start is None + or start.get("acquisition_policy_version") + != ACQUISITION_POLICY_VERSION + or start.get("hand_type") != config.side + or start.get("tag_layout") != config.tag_layout + or start.get("source_urdf_sha256") + != config.source_urdf_sha256 + or ( + bool(start.get("protected_hashes")) + and dict(start.get("protected_hashes", {})) + != { + "source_urdf_sha256": config.source_urdf_sha256, + "camera_extrinsics_sha256": config.camera_extrinsics_sha256, + "calibration_config_sha256": config.calibration_config_sha256, + "tag_config_sha256": config.tag_config_sha256, + "profile_config_sha256": config.profile_config_sha256, + } + ) + ): + continue + if summary is None: + # Ctrl+C can terminate the ROS launch tree before the wrapper gets + # a chance to create calibration_summary_zh.json. The immutable + # checkpoint itself is enough to resume only after independently + # proving that its external geometry still matches the product. + try: + checkpoint_extrinsics = Path( + str(start["camera_extrinsics_file"]) + ).expanduser().resolve(strict=True) + if sha256_file(checkpoint_extrinsics) != ( + config.camera_extrinsics_sha256 + ): + continue + except (KeyError, OSError, ValueError): + continue + return candidate + return None + + +def _resolve_partial_base_session( + config: ProductConfig, base_session: str | Path | None +) -> Path: + """Validate the complete passed session that donates non-target tasks.""" + if base_session is None or not str(base_session).strip(): + raise ValueError( + "partial scope requires --base-session pointing to a passed " + "complete G20 right session" + ) + candidate = Path(base_session).expanduser().resolve(strict=True) + root = config.session_root.resolve() + if candidate.parent != root or not candidate.is_dir(): + raise ValueError( + "base session must resolve to a direct session directory under " + f"{root}" + ) + raw_path = candidate / "raw_samples.jsonl" + summary_path = candidate / "calibration_summary_zh.json" + payload_path = ( + candidate + / f"g20_right_{config.serial_number}_calibration.json" + ) + for required in (raw_path, summary_path, payload_path): + if not required.is_file(): + raise ValueError(f"base session is missing required artifact: {required}") + try: + summary = json.loads(summary_path.read_text(encoding="utf-8")) + except json.JSONDecodeError as error: + raise ValueError("base session summary is invalid JSON") from error + if ( + not isinstance(summary, dict) + or summary.get("result") != "PASS" + or not bool(summary.get("quality", {}).get("passed")) + ): + raise ValueError("base session is not a formally passed session") + hashes = summary.get("hashes", {}) + expected_hashes = { + "source_urdf_sha256": config.source_urdf_sha256, + "camera_extrinsics_sha256": config.camera_extrinsics_sha256, + "calibration_config_sha256": config.calibration_config_sha256, + } + if not isinstance(hashes, Mapping) or any( + str(hashes.get(name, "")) != expected + for name, expected in expected_hashes.items() + ): + raise ValueError( + "base session source URDF, camera extrinsics or calibration " + "configuration differs from the current product" + ) + return candidate diff --git a/src/linkerhand_calibration/linkerhand_calibration/compat/paths.py b/src/linkerhand_calibration/linkerhand_calibration/compat/paths.py new file mode 100644 index 0000000..375fad4 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/compat/paths.py @@ -0,0 +1,52 @@ +"""Path compatibility for immutable v1 product configurations.""" + +from __future__ import annotations + +from pathlib import Path + + +_LEGACY_SOURCE_PREFIX = Path("src/g20_thumb_apriltag_calibration") +_CURRENT_SOURCE_PREFIX = Path("src/linkerhand_calibration") + + +def _resolve_package_uri(value: str, workspace: Path) -> Path | None: + prefix = "package://" + if not value.startswith(prefix): + return None + package_name, separator, relative = value[len(prefix) :].partition("/") + if not separator or not package_name or not relative: + raise ValueError(f"invalid ROS package resource path: {value}") + workspace_candidate = (workspace / "src" / package_name / relative).resolve() + if workspace_candidate.exists(): + return workspace_candidate + try: + from ament_index_python.packages import get_package_share_directory + + package_share = Path(get_package_share_directory(package_name)) + except Exception: + return workspace_candidate + return (package_share / relative).resolve() + + +def resolve_renamed_package_path(value: str | Path, workspace: Path) -> Path: + """Resolve workspace paths, ROS package resources and the former prefix. + + Deployed v1 product YAML files are kept byte-for-byte stable because the + artifact paths participate in operational review. Existing paths always + win; package URIs prefer a source-workspace copy, and the rename mapping + is used only when the literal legacy path no longer exists. + """ + text = str(value).strip() + package_resource = _resolve_package_uri(text, workspace) + if package_resource is not None: + return package_resource + raw = Path(text).expanduser() + candidate = raw if raw.is_absolute() else workspace / raw + candidate = candidate.resolve() + if candidate.exists() or raw.is_absolute(): + return candidate + try: + suffix = raw.relative_to(_LEGACY_SOURCE_PREFIX) + except ValueError: + return candidate + return (workspace / _CURRENT_SOURCE_PREFIX / suffix).resolve() diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/__init__.py new file mode 100644 index 0000000..31fb5a6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/__init__.py @@ -0,0 +1,92 @@ +"""Hardware- and model-independent calibration kernel.""" + +from .domain import ( + AcquisitionPolicy, + ArtifactPolicy, + AcquisitionStatus, + CalibrationProfile, + CalibrationResult, + JointMapping, + JointLimitPolicy, + CalibrationStatus, + CommandLayout, + MeasurementPolicy, + MeasurementSpec, + MotionPolicy, + MotionStatus, + PauseStatus, + ProfileKey, + ProfileValidationError, + QualityPolicy, + ScopePolicy, + TagSpec, + TaskStatus, + TaskSpec, + ViewSpec, + VisionRigSpec, + ZeroSolvePolicy, + validate_profile, +) +from .domain.task import ( + DIRECTION_DECREASING, + DIRECTION_INCREASING, + DIRECTIONS, + PHASE_ROOT, + PHASE_TIP, +) +from .fitting import FitResult, isotonic_nonincreasing +from .geometry import ( + delta_rotation_vector, + fit_rotation_axis, + image_plane_tag_quaternion_xyzw, + normalize_quaternion_xyzw, + relative_quaternion_xyzw, + robust_rotation_summary, + rotation_inlier_fraction, + rotation_rms_rad, + rotation_spread_rad, +) + +__all__ = [ + "AcquisitionPolicy", + "ArtifactPolicy", + "AcquisitionStatus", + "CalibrationProfile", + "CalibrationResult", + "JointMapping", + "JointLimitPolicy", + "CalibrationStatus", + "CommandLayout", + "DIRECTION_DECREASING", + "DIRECTION_INCREASING", + "DIRECTIONS", + "FitResult", + "MeasurementPolicy", + "MeasurementSpec", + "MotionPolicy", + "MotionStatus", + "PauseStatus", + "PHASE_ROOT", + "PHASE_TIP", + "ProfileKey", + "ProfileValidationError", + "QualityPolicy", + "ScopePolicy", + "TagSpec", + "TaskStatus", + "TaskSpec", + "ViewSpec", + "VisionRigSpec", + "ZeroSolvePolicy", + "delta_rotation_vector", + "fit_rotation_axis", + "image_plane_tag_quaternion_xyzw", + "isotonic_nonincreasing", + "normalize_quaternion_xyzw", + "relative_quaternion_xyzw", + "robust_rotation_summary", + "rotation_inlier_fraction", + "rotation_rms_rad", + "rotation_spread_rad", + "validate_profile", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/__init__.py new file mode 100644 index 0000000..26ef89e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/__init__.py @@ -0,0 +1 @@ +"""Storage helpers shared by calibration artifact writers.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/evidence_journal.py b/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/evidence_journal.py new file mode 100644 index 0000000..ac3d153 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/evidence_journal.py @@ -0,0 +1,525 @@ +"""Indexed compressed storage for large calibration evidence records. + +The JSONL file remains the ordered, crash-safe journal. Small control records +stay inline. Large records are stored in independently compressed blocks and +the JSONL line contains the scalar resume index plus a content-bound reference. +Readers can either inspect that index or reconstruct the original record. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass +from functools import lru_cache +import hashlib +import json +import os +from pathlib import Path +import shutil +import zlib + + +FORMAT = "linkerhand_indexed_evidence_v1" +REFERENCE_KEY = "$evidence_record" +FIELDS_KEY = "$record_fields" +SCHEMA_KEY = "$record_schema" +CANONICAL_SHA256_KEY = "$record_canonical_sha256" +DEFAULT_THRESHOLD_BYTES = 16 * 1024 +MAXIMUM_BLOCK_BYTES = 4 * 1024 * 1024 +INDEXED_SCALAR_FIELDS = { + "kind", "profile_id", "serial_number", "task_name", "joint", + "observation_joint", "view", "image_stamp_ns", "cycle", "direction", + "segment_key", "attempt", "sample_phase", "passed", "status", + "motion_version", "session_epoch", "reference_path_index", + "observer_preparation_id", "preparation_witness_joint", "tag_role", + "motor_index", "steady_index", + "steady_target", "command_u8", "command_rad", "feedback_u8", + "feedback_rad", "command_index", "branch_revision", +} +DETAILED_RECORD_KINDS = { + "motion_branch_observation", "image_observation_frame", + "pnp_candidate_frame", "pnp_branch_event", "joint_sample", + "secondary_joint_sample", "joint_zero_sample", + "visual_motion_observation", "diagnostic_observation_frame", +} +CANONICAL_INDEX_KINDS = { + "motion_branch_observation", "motion_branch_initialization", + "image_observation_frame", "pnp_candidate_frame", "joint_zero_sample", + "joint_zero_motion_reference_verified", "parent_reference_verified", + "observer_preparation_decision", "observer_preparation_segment_complete", + "observer_preparation_excursion_started", "observer_preparation_cancelled_before_excursion", + "capture_scope_extension", "capture_observation_revision", + "passed_tasks_reused", "passed_pose_models_restored", "staged_pose_models_restored", + "resume_verification", "joint_zero_recovery", "visual_motion_observation", + "visual_motion_settled", "task_observation_state", +} + + +@dataclass(frozen=True, slots=True) +class EvidenceRecordReference: + offset: int + compressed_length: int + block_sha256: str + record_offset: int + record_length: int + record_sha256: str + archive: str = "" + + @classmethod + def from_mapping(cls, value): + common = {"version", "offset", "compressed_length", "block_sha256", + "record_offset", "record_length", "record_sha256"} + version = value.get("version") + if ((version == 1 and set(value) != common) + or (version == 2 and set(value) != common | {"archive"}) + or version not in {1, 2}): + raise ValueError("invalid_compressed_evidence_reference") + integers = [value[key] for key in ("offset", "compressed_length", "record_offset", "record_length")] + if any(type(item) is not int or item < 0 for item in integers) or integers[1] < 1 or integers[3] < 1: + raise ValueError("invalid_compressed_evidence_reference") + archive = value.get("archive", "") + if archive and (Path(archive).name != archive or archive in {".", ".."}): + raise ValueError("invalid_compressed_evidence_reference") + return cls(*(value[key] for key in ( + "offset", "compressed_length", "block_sha256", "record_offset", + "record_length", "record_sha256")), archive) + + def as_mapping(self): + value = {"version": 2 if self.archive else 1, "offset": self.offset, + "compressed_length": self.compressed_length, "block_sha256": self.block_sha256, + "record_offset": self.record_offset, "record_length": self.record_length, + "record_sha256": self.record_sha256} + if self.archive: + value["archive"] = self.archive + return value + + +def manifest_path(journal_path: str | Path) -> Path: + path = Path(journal_path) + return path.with_name(path.stem + ".storage.json") + + +def archive_path(journal_path: str | Path) -> Path: + path = Path(journal_path) + return path.with_name(path.stem + ".evidence.zlib") + + +def initialize_evidence_journal(journal_path: str | Path, *, + threshold_bytes=DEFAULT_THRESHOLD_BYTES, compression_level=1) -> None: + """Enable indexed storage for a new journal without changing old captures.""" + journal = Path(journal_path) + marker = manifest_path(journal) + if marker.exists(): + payload = json.loads(marker.read_text(encoding="utf-8")) + if payload.get("format") != FORMAT: + raise ValueError("unsupported_evidence_journal_format") + return + if journal.exists() and journal.stat().st_size: + raise ValueError("indexed_evidence_requires_new_or_migrated_journal") + journal.parent.mkdir(parents=True, exist_ok=True) + if type(compression_level) is not int or not 1 <= compression_level <= 9: + raise ValueError("invalid_evidence_compression_level") + from .storage import atomic_write_json + atomic_write_json(marker, { + "format": FORMAT, + "archive": archive_path(journal).name, + "codec": f"zlib_level_{compression_level}_independent_blocks", + "compression_level": compression_level, + "envelope_fields": "archive_bound_v2", + "field_schemas": {}, + "large_record_threshold_bytes": int(threshold_bytes), + "maximum_uncompressed_block_bytes": MAXIMUM_BLOCK_BYTES, + }) + _journal_configuration.cache_clear() + + +@lru_cache(maxsize=128) +def _journal_configuration(journal_path: str) -> dict | None: + marker = manifest_path(journal_path) + if not marker.is_file(): + return None + try: + value = json.loads(marker.read_text(encoding="utf-8")) + except (OSError, ValueError, TypeError): + return None + return value if value.get("format") == FORMAT else None + + +def is_indexed_journal(journal_path: str | Path) -> bool: + return _journal_configuration(str(Path(journal_path).resolve())) is not None + + +def _resume_index(record: Mapping) -> dict: + return {key: record[key] for key in INDEXED_SCALAR_FIELDS if key in record + and (record[key] is None or isinstance(record[key], (str, int, float, bool)))} + + +def _schema_identity(fields) -> str: + return hashlib.sha256(json.dumps(list(fields), separators=(",", ":")).encode()).hexdigest()[:16] + + +@lru_cache(maxsize=512) +def _schema_fields(journal_path: str | Path, identity: str): + marker = _journal_configuration(str(Path(journal_path).resolve())) or {} + fields = marker.get("field_schemas", {}).get(identity) + if not isinstance(fields, list) or not all(isinstance(field, str) for field in fields): + raise ValueError("compressed_evidence_schema_missing") + if _schema_identity(fields) != identity: + raise ValueError("compressed_evidence_schema_changed") + return tuple(fields) + + +def _envelope(record: Mapping, reference, schema_identity) -> dict: + indexed = _resume_index(record) + if REFERENCE_KEY in indexed or FIELDS_KEY in indexed or SCHEMA_KEY in indexed: + raise ValueError("calibration_record_uses_reserved_storage_field") + # record_sha256 binds the complete archived object. Repeating its field + # names in every one-line resume index added tens of MB without adding an + # independent integrity check. + result = {REFERENCE_KEY: reference, SCHEMA_KEY: schema_identity, **indexed} + if record.get("kind") in CANONICAL_INDEX_KINDS: + result[CANONICAL_SHA256_KEY] = hashlib.sha256(json.dumps(record, sort_keys=True, + separators=(",", ":"), allow_nan=False).encode()).hexdigest() + return result + + +def _write_all(stream, payload: bytes) -> None: + written = stream.write(payload) + if written != len(payload): + raise OSError("incomplete_evidence_archive_write") + + +def append_indexed_records(journal_path: str | Path, records: Iterable[Mapping], *, durable: bool) -> None: + """Append records in order; evidence is durable before its references.""" + journal = Path(journal_path) + marker = _journal_configuration(str(journal.resolve())) + if marker is None: + raise ValueError("unsupported_evidence_journal_format") + threshold = int(marker["large_record_threshold_bytes"]) + compression_level = int(marker.get("compression_level", 1)) + if not 1 <= compression_level <= 9: + raise ValueError("invalid_evidence_compression_level") + prepared = [] + imported = {} + for record in records: + if REFERENCE_KEY in record or FIELDS_KEY in record or SCHEMA_KEY in record: + raise ValueError("calibration_record_uses_reserved_storage_field") + reference = getattr(record, "reference", None) + field_names = getattr(record, "field_names", None) + fields = tuple(record) if field_names is None else tuple(field_names) + schema_identity = _schema_identity(fields) + if isinstance(reference, EvidenceRecordReference): + imported[len(prepared)] = (record, schema_identity) + line = None + else: + line = json.dumps(record, ensure_ascii=False, separators=(",", ":")).encode("utf-8") + prepared.append((record, line, schema_identity, fields)) + if not prepared: + return + + schemas = dict(marker.get("field_schemas", {})) + changed = False + for _, _, identity, fields in prepared: + existing = schemas.get(identity) + if existing is not None and tuple(existing) != fields: + raise ValueError("compressed_evidence_schema_collision") + if existing is None: + schemas[identity] = list(fields) + changed = True + if changed: + marker = {**marker, "field_schemas": schemas} + from .storage import atomic_write_json + atomic_write_json(manifest_path(journal), marker) + _journal_configuration.cache_clear() + + evidence = archive_path(journal) + evidence.parent.mkdir(parents=True, exist_ok=True) + output: list[bytes | None] = [None] * len(prepared) + for index, (record, schema_identity) in imported.items(): + envelope = _linked_envelope(journal, record, schema_identity) + output[index] = json.dumps(envelope, ensure_ascii=False, + separators=(",", ":")).encode("utf-8") + with evidence.open("ab") as archive: + large: list[tuple[int, Mapping, bytes, str]] = [] + size = 0 + + def flush_block(): + nonlocal large, size + if not large: + return + block = b"".join(line for _, _, line, _ in large) + compressed = zlib.compress(block, compression_level) + offset = archive.tell() + _write_all(archive, compressed) + block_digest = hashlib.sha256(compressed).hexdigest() + local = 0 + for index, record, line, schema_identity in large: + reference = { + "version": 1, "offset": offset, + "compressed_length": len(compressed), + "block_sha256": block_digest, + "record_offset": local, "record_length": len(line), + "record_sha256": hashlib.sha256(line).hexdigest(), + } + output[index] = json.dumps(_envelope(record, reference, schema_identity), + ensure_ascii=False, separators=(",", ":")).encode("utf-8") + local += len(line) + large, size = [], 0 + + for index, (record, line, schema_identity, _) in enumerate(prepared): + if line is None: + continue + if len(line) < threshold and record.get("kind") not in DETAILED_RECORD_KINDS: + output[index] = line + continue + if large and size + len(line) > MAXIMUM_BLOCK_BYTES: + flush_block() + large.append((index, record, line, schema_identity)) + size += len(line) + flush_block() + archive.flush() + if durable: + os.fsync(archive.fileno()) + + with journal.open("ab") as stream: + _write_all(stream, b"\n".join(output) + b"\n") + stream.flush() + if durable: + os.fsync(stream.fileno()) + + +def _linked_envelope(destination: Path, record, schema_identity) -> dict: + """Hard-link an immutable source archive and retain its indexed row.""" + reference = record.reference + source_archive = (record.path.parent / reference.archive + if reference.archive else archive_path(record.path)) + stat = source_archive.stat() + identity = hashlib.sha256( + f"{stat.st_dev}:{stat.st_ino}:{stat.st_size}".encode()).hexdigest()[:20] + target = destination.parent / f"imported_evidence_{identity}.zlib" + if target.exists(): + if not os.path.samefile(source_archive, target): + raise ValueError("imported_evidence_identity_collision") + else: + try: + os.link(source_archive, target) + except OSError as error: + if error.errno != getattr(os, "EXDEV", 18): + raise + shutil.copy2(source_archive, target) + directory = os.open(destination.parent, os.O_RDONLY) + try: + os.fsync(directory) + finally: + os.close(directory) + linked = EvidenceRecordReference(reference.offset, reference.compressed_length, + reference.block_sha256, reference.record_offset, reference.record_length, + reference.record_sha256, target.name) + result = {REFERENCE_KEY: linked.as_mapping(), SCHEMA_KEY: schema_identity, **record.metadata} + if record.canonical_sha256: + result[CANONICAL_SHA256_KEY] = record.canonical_sha256 + return result + + +def sync_indexed_journal(journal_path: str | Path) -> None: + """Order the persistence barrier so a durable reference is never dangling.""" + evidence = archive_path(journal_path) + if evidence.exists(): + with evidence.open("rb") as stream: + os.fsync(stream.fileno()) + with Path(journal_path).open("rb") as stream: + os.fsync(stream.fileno()) + + +@lru_cache(maxsize=8) +def _read_block(path: str, offset: int, length: int, digest: str) -> bytes: + with Path(path).open("rb") as stream: + stream.seek(offset) + compressed = stream.read(length) + if len(compressed) != length or hashlib.sha256(compressed).hexdigest() != digest: + raise ValueError("compressed_evidence_block_changed") + try: + return zlib.decompress(compressed) + except zlib.error as error: + raise ValueError("compressed_evidence_block_invalid") from error + + +def evidence_record_bytes(journal_path: str | Path, reference: Mapping) -> bytes: + reference = (reference if isinstance(reference, EvidenceRecordReference) + else EvidenceRecordReference.from_mapping(reference)) + journal_path = Path(journal_path) + evidence = (journal_path.parent / reference.archive + if reference.archive else archive_path(journal_path)) + block = _read_block(str(evidence.resolve()), reference.offset, + reference.compressed_length, reference.block_sha256) + start, length = reference.record_offset, reference.record_length + raw = block[start:start + length] + if len(raw) != length or hashlib.sha256(raw).hexdigest() != reference.record_sha256: + raise ValueError("compressed_evidence_record_changed") + return raw + + +def decode_envelope(journal_path: str | Path, envelope: Mapping, decoder): + if REFERENCE_KEY not in envelope: + return envelope + value = decoder.loads(evidence_record_bytes(journal_path, envelope[REFERENCE_KEY])) + expected_fields = (envelope.get(FIELDS_KEY) if FIELDS_KEY in envelope + else _schema_fields(journal_path, envelope[SCHEMA_KEY]) if SCHEMA_KEY in envelope else None) + if (not isinstance(value, dict) or expected_fields is not None + and tuple(value) != tuple(expected_fields)): + raise ValueError("compressed_evidence_record_shape_changed") + return value + + +def compact_existing_journal(source_path: str | Path, *, replace=False) -> dict: + """Stream a legacy journal into indexed storage and verify every record. + + With ``replace=True`` the original path is swapped only after the compact + copy has passed record-content verification. The archive contains every + externalized record in full; no observation or diagnostic field is lost. + """ + source = Path(source_path).resolve() + if not source.is_file(): + raise FileNotFoundError(source) + source_is_indexed = is_indexed_journal(source) + source_marker = (json.loads(manifest_path(source).read_text(encoding="utf-8")) + if source_is_indexed else {}) + compact = source.with_name(source.name + ".compacting") + compact_archive = archive_path(compact) + for path in (compact, compact_archive, manifest_path(compact)): + if path.exists(): + path.unlink() + # Closed checkpoints favor disk footprint. Live capture remains level 1 so + # evidence persistence cannot stall the control loop. + initialize_evidence_journal(compact, compression_level=6) + + source_digest = hashlib.sha256() + record_count = 0 + batch = [] + try: + from ...core.geometry.frozen_evidence import EvidenceDecoder + decoder = EvidenceDecoder(verify_hashes=False) + with source.open("rb") as stream: + for number, line in enumerate(stream, 1): + source_digest.update(line) + if not line.strip(): + continue + try: + row = decoder.loads(line) + if REFERENCE_KEY in row: + row = decode_envelope(source, row, decoder) + except json.JSONDecodeError as error: + raise ValueError(f"invalid calibration JSONL at line {number}") from error + if not isinstance(row, dict): + raise ValueError(f"calibration JSONL record is not an object at line {number}") + batch.append(row) + record_count += 1 + if len(batch) == 256: + append_indexed_records(compact, batch, durable=False) + batch.clear() + append_indexed_records(compact, batch, durable=False) + sync_indexed_journal(compact) + + # Stream verification keeps the migration bounded even for multi-GB captures. + left_decoder, right_decoder = (EvidenceDecoder(verify_hashes=False) for _ in range(2)) + with source.open("rb") as left, compact.open("rb") as right: + right_lines = (line for line in right if line.strip()) + verified = 0 + for left_line in left: + if not left_line.strip(): + continue + try: + right_line = next(right_lines) + except StopIteration as error: + raise ValueError("compacted_evidence_record_count_changed") from error + left_row = left_decoder.loads(left_line) + if REFERENCE_KEY in left_row: + left_row = decode_envelope(source, left_row, left_decoder) + envelope = right_decoder.loads(right_line) + right_row = decode_envelope(compact, envelope, right_decoder) + if left_row != right_row: + raise ValueError("compacted_evidence_differs_from_source") + verified += 1 + try: + next(right_lines) + except StopIteration: + pass + else: + raise ValueError("compacted_evidence_record_count_changed") + if verified != record_count: + raise ValueError("compacted_evidence_record_count_changed") + def file_sha256(path): + with Path(path).open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + compact_digest = file_sha256(compact) + archive_digest = file_sha256(compact_archive) + result = { + "format": FORMAT, "source": str(source), + "source_sha256": source_digest.hexdigest(), + "source_bytes": source.stat().st_size, + "record_count": record_count, + "compact_journal_bytes": compact.stat().st_size, + "compressed_evidence_bytes": compact_archive.stat().st_size, + "compact_journal_sha256": compact_digest, + "compressed_evidence_sha256": archive_digest, + "semantic_verification": "passed", + } + if replace: + final_archive = archive_path(source) + final_manifest = manifest_path(source) + backup = source.with_name(source.name + ".uncompressed-backup") + backup_archive = final_archive.with_name(final_archive.name + ".backup") + backup_manifest = final_manifest.with_name(final_manifest.name + ".backup") + if backup.exists() or backup_archive.exists() or backup_manifest.exists(): + raise FileExistsError("compact journal destination already exists") + if not source_is_indexed and (final_archive.exists() or final_manifest.exists()): + raise FileExistsError("compact journal destination already exists") + marker = json.loads(manifest_path(compact).read_text(encoding="utf-8")) + marker["archive"] = final_archive.name + marker.update({key: result[key] for key in ("source_sha256", "source_bytes", "record_count")}) + if source_marker: + marker["lineage_source_sha256"] = source_marker.get( + "lineage_source_sha256", source_marker.get("source_sha256")) + marker["lineage_source_bytes"] = source_marker.get( + "lineage_source_bytes", source_marker.get("source_bytes")) + from .storage import atomic_write_json + try: + if source_is_indexed: + final_archive.replace(backup_archive) + final_manifest.replace(backup_manifest) + compact_archive.replace(final_archive) + source.replace(backup) + compact.replace(source) + if (file_sha256(source) != compact_digest + or file_sha256(final_archive) != archive_digest): + raise ValueError("installed_compact_journal_verification_failed") + atomic_write_json(final_manifest, marker) + _journal_configuration.cache_clear() + except Exception: + final_manifest.unlink(missing_ok=True) + if backup.exists(): + if source.exists(): + source.replace(compact) + backup.replace(source) + if final_archive.exists(): + final_archive.replace(compact_archive) + if source_is_indexed: + if backup_archive.exists(): + backup_archive.replace(final_archive) + if backup_manifest.exists(): + backup_manifest.replace(final_manifest) + raise + backup.unlink() + backup_archive.unlink(missing_ok=True) + backup_manifest.unlink(missing_ok=True) + manifest_path(compact).unlink(missing_ok=True) + _journal_configuration.cache_clear() + result["installed"] = True + return result + except Exception: + _journal_configuration.cache_clear() + compact.unlink(missing_ok=True) + compact_archive.unlink(missing_ok=True) + manifest_path(compact).unlink(missing_ok=True) + raise diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/storage.py b/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/storage.py new file mode 100644 index 0000000..9f9dc35 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/artifacts/storage.py @@ -0,0 +1,135 @@ +"""Crash-safe session storage for hardware calibration.""" + +from __future__ import annotations + +import json +import os +from pathlib import Path +from typing import Any, Iterable, Mapping + + +def atomic_write_json(path: str | Path, payload: Mapping[str, Any]) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_suffix(destination.suffix + ".tmp") + with temporary.open("w", encoding="utf-8") as stream: + json.dump(payload, stream, ensure_ascii=False, indent=2) + stream.write("\n") + stream.flush() + os.fsync(stream.fileno()) + os.replace(temporary, destination) + + +def append_jsonl(path: str | Path, payload: Mapping[str, Any]) -> None: + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + from .evidence_journal import is_indexed_journal, append_indexed_records + if is_indexed_journal(destination): + append_indexed_records(destination, (payload,), durable=True) + return + line = json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + with destination.open("a", encoding="utf-8") as stream: + stream.write(line + "\n") + stream.flush() + os.fsync(stream.fileno()) + + +def append_jsonl_many( + path: str | Path, payloads: Iterable[Mapping[str, Any]], *, durable: bool = True, +) -> None: + """Append one ordered batch, durable by default. + + Continuous observations may defer fsync until a reference/checkpoint, + pause, or explicit sync_jsonl barrier. They are still flushed before + returning; only complete, durable scan units can authorize resume. + """ + destination = Path(path) + destination.parent.mkdir(parents=True, exist_ok=True) + payloads = tuple(payloads) + from .evidence_journal import is_indexed_journal, append_indexed_records + if is_indexed_journal(destination): + append_indexed_records(destination, payloads, durable=durable) + return + lines = [ + json.dumps(payload, ensure_ascii=False, separators=(",", ":")) + for payload in payloads + ] + if not lines: + return + with destination.open("a", encoding="utf-8") as stream: + stream.write("\n".join(lines) + "\n") + stream.flush() + if durable: + os.fsync(stream.fileno()) + + +def sync_jsonl(path: str | Path) -> None: + """Persist all previously flushed records before hashing or publishing.""" + from .evidence_journal import is_indexed_journal, sync_indexed_journal + if is_indexed_journal(path): + sync_indexed_journal(path) + return + with Path(path).open("rb") as stream: + os.fsync(stream.fileno()) + + +def load_jsonl(path: str | Path) -> list[dict[str, Any]]: + source = Path(path) + if not source.exists(): + return [] + records: list[dict[str, Any]] = [] + from .evidence_journal import REFERENCE_KEY, decode_envelope + from ..geometry.frozen_evidence import EvidenceDecoder + decoder = EvidenceDecoder() + with source.open("r", encoding="utf-8") as stream: + lines = stream.readlines() + nonempty_lines = [ + index for index, line in enumerate(lines, 1) if line.strip() + ] + last_nonempty_line = nonempty_lines[-1] if nonempty_lines else 0 + for line_number, line in enumerate(lines, 1): + if not line.strip(): + continue + try: + value = json.loads(line) + except json.JSONDecodeError as error: + if line_number == last_nonempty_line: + break + raise ValueError( + f"{source}:{line_number}: invalid JSONL record" + ) from error + if not isinstance(value, dict): + raise ValueError(f"{source}:{line_number}: record must be an object") + if REFERENCE_KEY in value: + value = decode_envelope(source, value, decoder) + records.append(value) + return records + + +def load_json(path: str | Path) -> dict[str, Any] | None: + source = Path(path) + if not source.exists(): + return None + with source.open("r", encoding="utf-8") as stream: + value = json.load(stream) + if not isinstance(value, dict): + raise ValueError(f"{source} must contain a JSON object") + return value + + +def completed_scan_keys( + records: Iterable[Mapping[str, Any]], +) -> set[tuple[str, int, str, int]]: + keys: set[tuple[str, int, str, int]] = set() + for record in records: + if record.get("kind", "sample") != "sample": + continue + keys.add( + ( + str(record["phase"]), + int(record["cycle"]), + str(record["direction"]), + int(record["command_u8"]), + ) + ) + return keys diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/__init__.py new file mode 100644 index 0000000..3af428e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/__init__.py @@ -0,0 +1,65 @@ +"""Calibration domain types.""" + +from .profile import ( + AcquisitionPolicy, + ArtifactPolicy, + CalibrationProfile, + CommandLayout, + MeasurementPolicy, + MeasurementSpec, + MotionPolicy, + ProfileKey, + ProfileValidationError, + QualityPolicy, + ScopePolicy, + TagSpec, + TaskSpec, + ViewSpec, + VisionRigSpec, + ZeroSolvePolicy, + JointZeroSpec, + KnownBaselineGeometry, + JointLimitPolicy, + validate_profile, +) +from .result import CalibrationResult, JointMapping +from .reference import JointZeroReference, JointZeroSample +from .status import ( + AcquisitionStatus, + CalibrationStatus, + MotionStatus, + PauseStatus, + TaskStatus, +) + +__all__ = [ + "AcquisitionPolicy", + "ArtifactPolicy", + "AcquisitionStatus", + "CalibrationProfile", + "CalibrationResult", + "JointMapping", + "JointZeroReference", + "JointZeroSample", + "JointZeroSpec", + "KnownBaselineGeometry", + "JointLimitPolicy", + "CalibrationStatus", + "CommandLayout", + "MeasurementPolicy", + "MeasurementSpec", + "MotionPolicy", + "MotionStatus", + "ProfileKey", + "ProfileValidationError", + "PauseStatus", + "QualityPolicy", + "ScopePolicy", + "TagSpec", + "TaskStatus", + "TaskSpec", + "ViewSpec", + "VisionRigSpec", + "ZeroSolvePolicy", + "validate_profile", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/capture_plan.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/capture_plan.py new file mode 100644 index 0000000..8c3edbb --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/capture_plan.py @@ -0,0 +1,214 @@ +"""One immutable partition contract for acquisition, fitting and release. + +Cycle IDs are evidence identities, not display ordinals. Optional training +never renumbers the independent validation cycle or changes its command grid. +""" + +from dataclasses import asdict, dataclass, replace +import hashlib +import json + + +PLAN_VERSION = "capture_plan_v1" +FIXED = "fixed" +ADAPTIVE = "adaptive_2_to_3" +STAGED = "staged_2_to_3" +TASKWISE_STAGED = "taskwise_staged_2_to_3" +TASKWISE_TWO_ROUND = "taskwise_2_plus_1" +RAW_JOINT = "raw_joint_2_plus_1" +RAW_FEEDBACK = "raw_feedback_3_plus_1" +FEEDBACK_RAW_PROTOCOL = "raw_feedback_images_v1" +RAW_PROTOCOL = "raw_joint_images_v2" +LEGACY_RAW_PROTOCOL = "raw_joint_images_v1" +STAGED_POLICIES = frozenset((STAGED, TASKWISE_STAGED)) +PREPARATION_POLICIES = STAGED_POLICIES | {TASKWISE_TWO_ROUND} +LEGACY_TRAINING = (0, 1, 2) +LEGACY_HOLDOUT = 3 + + +def raw_joint_capture(profile): + return profile.quality.training_policy == RAW_JOINT + + +def raw_feedback_capture(profile): + return profile.quality.training_policy == RAW_FEEDBACK + + +def evidence_digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), + allow_nan=False).encode()).hexdigest() + + +@dataclass(frozen=True) +class TaskPartition: + task_key: str + training: tuple[int, ...] + holdout: int + command_training: tuple[int, ...] + command_holdout: int + + @property + def motion_cycles(self): + return (*self.training, self.holdout) + + def cycles(self, phase): + return ((*self.command_training, self.command_holdout) + if phase == "steady" else self.motion_cycles) + + +@dataclass(frozen=True) +class CapturePlan: + policy: str + command_capture_mode: str + tasks: tuple[TaskPartition, ...] + motion_contract_json: str + + @classmethod + def from_profile(cls, profile): + tasks = tuple(task_partition(profile, task) for task in profile.motion.tasks) + # JSON normalization keeps equality stable across checkpoint round trips. + from .sampling import command_nodes + motion = {"unit": profile.command.unit, "motion": asdict(profile.motion), + "nodes": {task.key: {"training": command_nodes(profile, task), + "holdout": command_nodes(profile, task, holdout=True)} for task in profile.motion.tasks}} + # Auxiliary observer excursions produce no scan/partition identities. + # Their full paths are protected by preparation_contract instead; old + # completed units and training partitions keep their original hashes. + motion['motion'].pop('observer_preparations') + if not profile.motion.preparation_witnesses: + motion["motion"].pop("preparation_witnesses") # Historical plan hashes stay unchanged. + return cls(profile.quality.training_policy, profile.acquisition.command_capture_mode, tasks, + json.dumps(motion, sort_keys=True, separators=(",", ":"), allow_nan=False)) + + def task(self, key): + return next(task for task in self.tasks if task.task_key == key) + + def as_dict(self, *, legacy_raw=False): + version = (("capture_plan_v6_raw_joint" if legacy_raw else "capture_plan_v7_raw_joint") if self.policy == RAW_JOINT else + "capture_plan_v5" if self.policy == TASKWISE_TWO_ROUND else + "capture_plan_v3" if self.policy == TASKWISE_STAGED else + "capture_plan_v2" if self.policy == STAGED else + "capture_plan_v8_raw_feedback" if self.policy == RAW_FEEDBACK else PLAN_VERSION) + result = {"version": version, "policy": self.policy, + "command_capture_mode": self.command_capture_mode, + "motion_contract": json.loads(self.motion_contract_json), + "tasks": {t.task_key: {"training_cycles": list(t.training), + "holdout_cycle": t.holdout, + "command_training_cycles": list(t.command_training), + "command_holdout_cycle": t.command_holdout} for t in self.tasks}} + if self.policy in STAGED_POLICIES: + result["stages"] = [ + {"name": name, "cycle": cycle, "tasks": [t.task_key for t in self.tasks + if cycle in t.motion_cycles]} + for name, cycle in (("first_training", 0), ("second_training", 1), + ("supplement", 2), ("validation", 3))] + if self.policy == TASKWISE_STAGED: + result["schedule"] = ( + "first_whole_hand_pass_then_taskwise_second_pass_with_immediate_supplement_then_validation" + ) + if self.policy == TASKWISE_TWO_ROUND: + result["schedule"] = "each_task_two_training_rounds_then_independent_validation" + result["preparation_recovery"] = { + "policy": "dependency_ordered_task_deferral_v2", + "maximum_revisits": 1, + "preserve_task_round_order": True, + "incomplete_capture_blocks_publication": True, + } + if self.policy == RAW_FEEDBACK: + result["observation_protocol"] = { + "version": FEEDBACK_RAW_PROTOCOL, + "online_geometry_authorization": False, + "motion_training_cycles": [0, 1, 2], "motion_holdout_cycle": 3, + "command_training_cycle": 4, "command_holdout_cycle": 5, + "maximum_unit_recaptures": 1, + "incomplete_capture_blocks_publication": True, + } + if self.policy == RAW_JOINT: + result["schedule"] = "each_task_two_training_rounds_then_independent_validation" + result["observation_protocol"] = { + "version": LEGACY_RAW_PROTOCOL if legacy_raw else RAW_PROTOCOL, + "online_geometry_authorization": False, + "maximum_unit_recaptures": 1, + "recapture_order": "queue_tail" if legacy_raw else "immediate", + "incomplete_capture_blocks_publication": True, + } + if not legacy_raw: + result["observation_protocol"].update(hardware_stall_retries=1, + stall_retry_delay_seconds=3.0, motion_progress_scope="direction_active_time") + return result + + @property + def sha256(self): + return evidence_digest(self.as_dict()) + + +def task_for_joint(profile, joint): + donor = profile.measurement.transferred_motion_sources.get(joint, joint) + secondary = {source: primary for primary, source in profile.measurement.cross_view_sources.items()} + donor = secondary.get(donor, donor) + for task in profile.motion.tasks: + if donor in task.joints: + return task + raise ValueError(f"capture_plan_joint_has_no_task:{joint}") + + +def task_partition(profile, task=None, *, joint=None): + if joint is not None: + task = task_for_joint(profile, joint) + key = getattr(task, "key", task) + default = (LEGACY_TRAINING[:2] if profile.quality.training_policy in PREPARATION_POLICIES | {RAW_JOINT} + else profile.quality.training_cycles) + training = tuple(profile.quality.task_training_cycles.get(key, default)) + holdout = profile.quality.holdout_cycle + separate = profile.acquisition.command_capture_mode == "separate" + return TaskPartition(key, training, holdout, (holdout + 1,) if separate else training, + holdout + 2 if separate else holdout) + + +def training_cycles(profile, task=None, *, joint=None): + return task_partition(profile, task, joint=joint).training + + +def select_task_training(profile, task_key, cycles): + cycles = tuple(cycles) + if task_key not in {t.key for t in profile.motion.tasks}: + raise ValueError("capture_plan_unknown_task") + if cycles not in (LEGACY_TRAINING, LEGACY_TRAINING[:2]): + raise ValueError("capture_plan_invalid_training_partition") + if profile.quality.training_policy in {TASKWISE_TWO_ROUND, RAW_JOINT}: + if cycles != LEGACY_TRAINING[:2]: + raise ValueError("taskwise_two_round_cannot_add_training") + return profile + if (cycles != tuple(profile.quality.training_cycles) + and profile.quality.training_policy not in {ADAPTIVE, *STAGED_POLICIES}): + raise ValueError("capture_plan_fixed_training_cannot_change") + selections = {**profile.quality.task_training_cycles, task_key: cycles} + return replace(profile, quality=replace(profile.quality, task_training_cycles=selections)) + + +def configure_training(profile, policy): + if policy not in {FIXED, ADAPTIVE, *STAGED_POLICIES, TASKWISE_TWO_ROUND, RAW_JOINT, RAW_FEEDBACK}: + raise ValueError("unknown_training_policy") + if policy == RAW_FEEDBACK and (profile.command_based_release + or profile.acquisition.command_capture_mode != "separate" + or profile.artifacts.output_schema_version < 3 + or tuple(profile.quality.training_cycles) != LEGACY_TRAINING + or profile.quality.holdout_cycle != LEGACY_HOLDOUT): + raise ValueError("raw_feedback_requires_separate_feedback_v3_profile") + if policy == RAW_JOINT and profile.key.profile_id != 'O30/right/o30_right_18/v1': + raise ValueError("raw_joint_capture_requires_o30_profile") + if profile.artifacts.output_schema_version in {2, 3} and ( + tuple(profile.quality.training_cycles) != LEGACY_TRAINING + or profile.quality.holdout_cycle != LEGACY_HOLDOUT): + raise ValueError("production_partition_requires_versioned_training_policy") + if policy in {ADAPTIVE, *STAGED_POLICIES, TASKWISE_TWO_ROUND, RAW_JOINT} and (profile.artifacts.output_schema_version < 3 + or not profile.command_based_release + or profile.acquisition.command_capture_mode != "interleaved" + or tuple(profile.quality.training_cycles) != LEGACY_TRAINING + or profile.quality.holdout_cycle != LEGACY_HOLDOUT): + raise ValueError("adaptive_training_requires_measured_interleaved_command_release") + # Fixed two-round collection uses the ordinary task-contiguous scheduler. + # Its partition is derived by task_partition, not an executed journal + # decision. Keep the reusable profile serializable for the launched node. + return replace(profile, quality=replace(profile.quality, + training_policy=policy, task_training_cycles={})) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/measurement.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/measurement.py new file mode 100644 index 0000000..cbb27a9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/measurement.py @@ -0,0 +1,72 @@ +"""Shared measurement and curve contracts; no hardware or model defaults.""" +from __future__ import annotations +from dataclasses import dataclass +from typing import Any, Mapping + +@dataclass(frozen=True) +class JointSpec: + name: str + motor_index: int + active: bool + view: str | None + parent_role: str | None + child_role: str | None + source_joint: str | None = None + zero_kind: str | None = None + # Keep the physical axis-line gate only when that line contributes to a + # released URDF zero/axis decision. Curve-only passive measurements may + # retain the monocular line residual as a diagnostic while their image + # trajectory, relative rotation, synchronisation and holdout gates remain + # release-critical. + pose_axis_line_required: bool = True + + @property + def measured(self) -> bool: + return self.source_joint is None + + +@dataclass(frozen=True) +class SweepSpec: + view: str + motor_index: int + joints: tuple[str, ...] + task_name: str = "" + auxiliary_commands: tuple[tuple[int, int], ...] = () + validation_only: bool = False + + @property + def key(self) -> str: + if self.task_name: + return self.task_name + return f"{self.view}:motor{self.motor_index}:{','.join(self.joints)}" + + +@dataclass(frozen=True) +class PalmAxisObserver: + """Non-blocking direction observation attached to an existing task. + + This is deliberately not a ``JointSpec``: it has no curve, endpoint or + retry semantics. The camera callback records it only while both Tags are + visible during the named sweep. + """ + + source_name: str + task_name: str + view: str + parent_role: str + child_role: str + model_joint: str + motor_index: int + + +@dataclass(frozen=True) +class JointCurveFit: + angle_rad: tuple[float, ...] + decreasing_rad: tuple[float, ...] + increasing_rad: tuple[float, ...] + circle: Mapping[str, Any] + maximum_monotonic_correction_rad: float + maximum_hysteresis_rad: float + quality: Mapping[str, float] + zero_offset_rad: float = 0.0 + diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/motion_path.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/motion_path.py new file mode 100644 index 0000000..39aa349 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/motion_path.py @@ -0,0 +1,78 @@ +"""Declared multi-channel paths and durable scan identities. + +Only paths own interpolation. Every observation retains its own motor channel; +the scalar path coordinate is never a joint measurement or a new zero. +""" + +from dataclasses import dataclass +import math + + +@dataclass(frozen=True) +class MotionSegment: + key: str + start_commands: tuple[tuple[int, float], ...] + end_commands: tuple[tuple[int, float], ...] + joints: tuple[str, ...] + + @property + def moving_channels(self): + end = dict(self.end_commands) + return tuple(i for i, value in self.start_commands if end[i] != value) + + @property + def command_index(self): + return self.moving_channels[0] + + @property + def start(self): + return dict(self.start_commands)[self.command_index] + + @property + def end(self): + return dict(self.end_commands)[self.command_index] + + @property + def direction(self): + return "increasing" if self.end > self.start else "decreasing" + + def commands_at(self, value, *, quantize=False): + fraction = (value-self.start)/(self.end-self.start) + if not math.isfinite(fraction) or not -1e-9 <= fraction <= 1+1e-9: + raise ValueError("motion segment coordinate outside declared path") + end = dict(self.end_commands) + values = {i: start+(end[i]-start)*fraction for i, start in self.start_commands} + return {i: float(round(v)) for i, v in values.items()} if quantize else values + + +def task_segments(task): + if task.segments: + return task.segments + return tuple(MotionSegment("", ((task.command_index, start),), + ((task.command_index, end),), task.joints) + for start, end in ((task.start_value, task.end_value), (task.end_value, task.start_value))) + + +def task_segment(task, key): + for segment in task.segments: + if segment.key == key: + return segment + raise ValueError(f"unknown motion segment:{task.key}:{key}") + + +def task_channels(task): + return tuple(sorted({i for segment in task_segments(task) for i in segment.moving_channels})) + + +def scan_identity(task, cycle, direction, segment_key=""): + base = (task, cycle, direction) + return (*base, segment_key) if segment_key else base + + +def record_scan_identity(row): + return scan_identity(row.get("task_name"), row.get("cycle"), row.get("direction"), + row.get("segment_key", "")) + + +def segment_metadata(key): + return {"segment_key": key} if key else {} diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/profile.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/profile.py new file mode 100644 index 0000000..26d4c6c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/profile.py @@ -0,0 +1,1055 @@ +"""Typed, hardware-independent calibration profile contracts.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import math +from pathlib import PurePath +from typing import Mapping +from .motion_path import MotionSegment + + +ACQUISITION_POLICY_VERSION = "unified_engine_v8_all_view_images" + + +@dataclass(frozen=True, order=True) +class ProfileKey: + """Stable identity for one independently reviewed hand profile.""" + + model: str + side: str + layout: str + revision: int = 1 + + def __post_init__(self) -> None: + object.__setattr__(self, "model", str(self.model).strip().upper()) + object.__setattr__(self, "side", str(self.side).strip().lower()) + object.__setattr__(self, "layout", str(self.layout).strip().lower()) + object.__setattr__(self, "revision", int(self.revision)) + if not self.model or not self.side or not self.layout: + raise ValueError("profile identity fields must be non-empty") + if self.side not in {"left", "right"}: + raise ValueError("profile side must be left or right") + if self.revision < 1: + raise ValueError("profile revision must be positive") + + @property + def profile_id(self) -> str: + return f"{self.model}/{self.side}/{self.layout}/v{self.revision}" + + @classmethod + def parse(cls, value: str) -> "ProfileKey": + parts = str(value).strip().split("/") + if len(parts) != 4 or not parts[3].startswith("v"): + raise ValueError( + "profile_id must be MODEL/side/layout/vREVISION" + ) + return cls(parts[0], parts[1], parts[2], int(parts[3][1:])) + + +@dataclass(frozen=True) +class CommandLayout: + """Command channels, joint bindings, and the reviewed baseline pose.""" + + names: tuple[str, ...] + baseline_u8: tuple[int, ...] + command_index_by_joint: Mapping[str, int] + disabled_indices: frozenset[int] = frozenset() + # Calibration names are allowed to stay model-neutral while the source + # URDF keeps any vendor/side prefixes (for example ``rh_``). + urdf_joint_by_joint: Mapping[str, str] = field(default_factory=dict) + # Older SDKs occasionally published a wrong label for a physically stable + # channel. Aliases are accepted only at the declared channel index. + feedback_name_aliases: Mapping[str, str] = field(default_factory=dict) + # SDK speed commands are not necessarily one value per position channel. + # This mapping makes that protocol detail explicit in a profile. + speed_slot_by_command_index: Mapping[int, int] = field(default_factory=dict) + # Physical-angle SDKs use these fields. ``baseline_u8`` remains the + # deployed compatibility contract for legacy byte-command profiles. + unit: str = "u8" + baseline: tuple[float, ...] = () + lower_bounds: tuple[float, ...] = () + upper_bounds: tuple[float, ...] = () + # Position feedback is an observation, not a command. Servo tracking, + # encoder quantisation, and the vendor's zero offset may put a valid + # observation just outside the safe command envelope. Physical-angle + # profiles can therefore register a separate feedback envelope; legacy + # profiles default to the command envelope. + feedback_lower_bounds: tuple[float, ...] = () + feedback_upper_bounds: tuple[float, ...] = () + feedback_by_index: bool = False + # Signed derivative of the URDF coordinate with respect to native SDK + # feedback, in fixed channel order. It is a product contract, not inferred + # by swapping channels after observing motion. + sdk_to_joint_direction: tuple[int, ...] = () + maximum_velocity: tuple[float, ...] = () + + @property + def joint_directions(self) -> tuple[int, ...]: + return self.sdk_to_joint_direction or (-1,) * self.command_count + + @property + def command_count(self) -> int: + return len(self.names) + + @property + def baseline_values(self) -> tuple[float, ...]: + source = self.baseline if self.baseline else self.baseline_u8 + return tuple(float(value) for value in source) + + @property + def minimum_values(self) -> tuple[float, ...]: + return ( + tuple(float(value) for value in self.lower_bounds) + if self.lower_bounds + else (0.0,) * self.command_count + ) + + @property + def maximum_values(self) -> tuple[float, ...]: + return ( + tuple(float(value) for value in self.upper_bounds) + if self.upper_bounds + else (255.0,) * self.command_count + ) + + @property + def minimum_feedback_values(self) -> tuple[float, ...]: + return ( + tuple(float(value) for value in self.feedback_lower_bounds) + if self.feedback_lower_bounds + else self.minimum_values + ) + + @property + def maximum_feedback_values(self) -> tuple[float, ...]: + return ( + tuple(float(value) for value in self.feedback_upper_bounds) + if self.feedback_upper_bounds + else self.maximum_values + ) + + def normalize(self, index: int, value: float) -> float: + lower = self.minimum_values[int(index)] + upper = self.maximum_values[int(index)] + if not math.isfinite(float(value)) or upper <= lower: + raise ValueError("command value or bounds are invalid") + return (float(value) - lower) / (upper - lower) + + def denormalize(self, index: int, progress: float) -> float: + lower = self.minimum_values[int(index)] + upper = self.maximum_values[int(index)] + phase = float(progress) + if not math.isfinite(phase) or not 0.0 <= phase <= 1.0: + raise ValueError("normalized command progress must be in [0, 1]") + return lower + phase * (upper - lower) + + +@dataclass(frozen=True) +class TagSpec: + role: str + tag_id: int + fixed_reference: bool = False + link: str | None = None + size_m: float = 0.016 + + +@dataclass(frozen=True) +class ViewSpec: + name: str + tags: tuple[TagSpec, ...] + + +@dataclass(frozen=True) +class VisionRigSpec: + """Any number of named views and their Tag roles.""" + + views: tuple[ViewSpec, ...] + common_frame: str + extrinsic_reference_view: str + extrinsics_quality_limits: Mapping[str, float] = field( + default_factory=dict + ) + minimum_capture_counts: Mapping[str, int] = field(default_factory=dict) + + @property + def view_names(self) -> tuple[str, ...]: + return tuple(view.name for view in self.views) + + @property + def tag_ids(self) -> frozenset[int]: + return frozenset(tag.tag_id for view in self.views for tag in view.tags) + + +@dataclass(frozen=True) +class ModelPreparation: + """Independent parent-Tag image authorization at this task's holding pose.""" + + joint: str + command: tuple[float, ...] + approach_commands: tuple[tuple[float, ...], ...] + + +@dataclass(frozen=True) +class ObserverPreparationPlan: + """Finite, ordered observation actions; completed actions survive restarts.""" + + actions: tuple[ModelPreparation, ...] + + +@dataclass(frozen=True) +class ParentReferenceSpec: + """Independent sources for a held Tag pose and its local hinge geometry.""" + + pose_joint: str + geometry_joint: str + + +@dataclass(frozen=True) +class TaskSpec: + key: str + view: str + command_index: int + joints: tuple[str, ...] + auxiliary_commands: tuple[tuple[int, float], ...] = () + validation_only: bool = False + start_u8: int = 255 + end_u8: int = 0 + preflight_speed_u8: int | None = None + formal_speed_u8: int | None = None + start: float | None = None + end: float | None = None + preflight_speed: float | None = None + formal_speed: float | None = None + preparation_groups: tuple[tuple[int, ...], ...] = () + entry_waypoints: tuple[tuple[tuple[int, float], ...], ...] = () + segments: tuple["MotionSegment", ...] = () + exit_waypoints: tuple[tuple[tuple[int, float], ...], ...] = () + model_preparations: tuple[ModelPreparation, ...] = () + parent_reference: ParentReferenceSpec | None = None + + @property + def start_value(self) -> float: + return float(self.start_u8 if self.start is None else self.start) + + @property + def end_value(self) -> float: + return float(self.end_u8 if self.end is None else self.end) + + +@dataclass(frozen=True) +class ReferenceWaypoint: + key: str + command: tuple[float, ...] + tag_ids_by_view: Mapping[str, tuple[int, ...]] + + +@dataclass(frozen=True) +class JointZeroSpec: + """A reviewed full-hand pose at which one joint's baseline is visible.""" + + task_key: str + command: tuple[float, ...] + approach_commands: tuple[tuple[float, ...], ...] = () + evidence_scope: str = "arrival" + + +@dataclass(frozen=True) +class KnownBaselineGeometry: + """Independent CAD angle at the measured baseline, never an SDK prior.""" + + cad_angle_rad: float + uncertainty_rad: float + evidence_source: str + + +@dataclass(frozen=True) +class MotionPolicy: + """Reviewed motion tasks and optional safe waypoint sequences.""" + + tasks: tuple[TaskSpec, ...] + preparation_waypoints_u8: tuple[tuple[int, ...], ...] = () + safe_return_waypoints_u8: tuple[tuple[int, ...], ...] = () + speed_parameters: Mapping[str, float] = field(default_factory=dict) + precheck_sweeps: bool = False + steady_command_checkpoints: bool = False + return_groups: tuple[tuple[int, ...], ...] = () + resume_verification_waypoints: tuple[ReferenceWaypoint, ...] = () + joint_zero_references: Mapping[str, JointZeroSpec] = field(default_factory=dict) + # Target joint -> bounded upstream excitation at its clearance posture. + # These images only authorize preparation; they never enter formal fitting. + preparation_witnesses: Mapping[str, ModelPreparation] = field(default_factory=dict) + # Independent rigid-pair observation; a common ancestor moves while the + # recipient hinge stays at zero. Never a replacement for accepted scans. + observer_preparations: Mapping[str, ModelPreparation | ObserverPreparationPlan] = field(default_factory=dict) + + +@dataclass(frozen=True) +class MeasurementSpec: + joint: str + kind: str + view: str | None + parent_role: str | None + child_role: str | None + validation_source: str | None = None + # Some measured trajectories publish only a dynamic curve while their + # static URDF zero/axis remains CAD- or mimic-owned. For those joints a + # monocular 3-D axis-line residual is useful diagnostic evidence, but it + # must not reject an otherwise clean image/SO(3) trajectory merely because + # the hand was placed at a different valid position in the camera view. + pose_axis_line_required: bool = True + observer_pose_policy: str = "frozen_parent_v1" + + +@dataclass(frozen=True) +class MeasurementPolicy: + measurements: Mapping[str, MeasurementSpec] + cross_view_sources: Mapping[str, str] = field(default_factory=dict) + image_curve_joints: frozenset[str] = frozenset() + directional_zero: bool = False + cross_view_roll_curve: bool = False + stable_cross_view_cone_bias: bool = False + candidate_selection_tasks: frozenset[str] = frozenset() + input_domain: str = "" + # Explicit motion reuse, independent of legacy zero/mimic transfer policy. + # Recipients keep their own SDK channel and cannot become measured donors. + transferred_motion_sources: Mapping[str, str] = field(default_factory=dict) + release_basis: str = "feedback_and_command" + + +@dataclass(frozen=True) +class ZeroSolvePolicy: + active_joints: frozenset[str] + passive_joints: frozenset[str] + direct_zero_joints: tuple[str, ...] + axis_joints: tuple[str, ...] + mechanical_endpoint_joints: frozenset[str] + post_solve_endpoint_joints: frozenset[str] + mimic_source_by_joint: Mapping[str, str] + cad_frozen_joints: frozenset[str] + # ``upper_at_end`` means TaskSpec.end_u8 is the trusted source-URDF upper + # physical endpoint. The measured travel then defines the electrical + # zero and corrected [0, travel] coordinate range. + endpoint_anchor_by_joint: Mapping[str, str] = field(default_factory=dict) + fitted_mimic_joints: frozenset[str] = frozenset() + # Passive coupling is not necessarily representable by the linear URDF + # ``mimic`` element. Profiles must opt in explicitly before a nonlinear + # runtime/MuJoCo relation may be published. + coupling_model_by_joint: Mapping[str, str] = field(default_factory=dict) + transferred_zero_sources: Mapping[str, str] = field(default_factory=dict) + transferred_mimic_sources: Mapping[str, str] = field(default_factory=dict) + # Geometry policy only; no Python callback/import strings are permitted. + spatial: Mapping[str, object] = field(default_factory=dict) + known_baseline_geometry: Mapping[str, KnownBaselineGeometry] = field(default_factory=dict) + # User-accepted CAD q=0 at physical baseline, not a measured geometry prior. + cad_zero_assumptions: Mapping[str, str] = field(default_factory=dict) + + +@dataclass(frozen=True) +class QualityPolicy: + training_cycles: tuple[int, ...] + holdout_cycle: int | None + hard_threshold_keys: frozenset[str] + retry_metric_scope: Mapping[str, str] = field(default_factory=dict) + isolated_holdout: bool = False + training_policy: str = "fixed" + # Runtime selections are journal-derived, never guessed from missing rows. + task_training_cycles: Mapping[str, tuple[int, ...]] = field(default_factory=dict) + + +@dataclass(frozen=True) +class AcquisitionPolicy: + """Cross-model runtime safety and retained-data acceptance contract.""" + + policy_version: str = ACQUISITION_POLICY_VERSION + mapping_probe_maximum_rad: float = 0.0 + automatic_rescan_limit: int = 1 + minimum_valid_samples: int = 40 + minimum_bins: int = 32 + maximum_unobserved_fraction: float = 1.0 / 16.0 + legacy_minimum_span_01: float = 240.0 / 255.0 + physical_first_cycle_minimum_span_01: float = 0.85 + physical_repeat_minimum_fraction: float = 0.90 + stall_timeout_seconds: float = 2.0 + feedback_stale_seconds: float = 1.0 + fixed_reference_minimum_frames: int = 10 + fixed_reference_maximum_drift_px: float = 5.0 + fixed_reference_confirmation_frames: int = 10 + fixed_reference_mode: str = "tag_pose" + require_endpoint_observations: bool = False + endpoint_tolerance_01: float = 2.0 / 255.0 + steady_training_nodes: int = 9 + command_capture_mode: str = "interleaved" + steady_extra_training_nodes: Mapping[str, tuple[float, ...]] = field(default_factory=dict) + steady_minimum_samples: int = 3 + steady_window_seconds: float = 0.2 + steady_timeout_seconds: float = 2.0 + joint_zero_timeout_seconds: float = 2.0 + motion_model_scope: str = "session" + # Native position bytes may have endpoint dead zones or a nonlinear servo + # response. Only a declared common scale can turn command travel into an + # expected encoder displacement before calibration has measured the map. + feedback_travel_matches_command: bool = True + minimum_significant_request_u8: float = 2.0 + motion_observation: str = "feedback" + visual_stale_seconds: float = 1.0 + visual_minimum_motion_px: float = 1.0 + visual_stability_px: float = 0.35 + visual_zero_tolerance_px: float = 1.0 + + +def observation_streams(profile, task): + """Primary and declared secondary views of each measured joint.""" + for name in task.joints: + yield "joint", name, profile.measurement.measurements[name] + secondary = profile.measurement.cross_view_sources.get(name) + if secondary is not None: + yield "observation_joint", name, profile.measurement.measurements[secondary] + + +@dataclass(frozen=True) +class RetainedCadScope: + """Explicit partial capture with unmeasured, unchanged CAD ancestors.""" + + reason: str + root_anchor_joints: tuple[str, ...] + orientation_anchor_joint: str + directed_base_axis_joints: tuple[str, ...] = () + + +@dataclass(frozen=True) +class ScopePolicy: + calibrate_joints: Mapping[str, frozenset[str]] + frozen_joints: Mapping[str, frozenset[str]] + default_scope: str = "full" + retained_cad_scopes: Mapping[str, RetainedCadScope] = field(default_factory=dict) + + def selected_joints(self, scope: str) -> frozenset[str]: + try: + return self.calibrate_joints[str(scope)] + except KeyError as error: + raise ValueError(f"unsupported calibration scope: {scope}") from error + + +@dataclass(frozen=True) +class ArtifactPolicy: + output_schema_version: int + calibration_filename: str + corrected_urdf_filename: str + protected_input_fields: frozenset[str] + publication_pointer: str = "latest_passed" + session_compatibility_tokens: frozenset[str] = frozenset() + publish_corrected_urdf: bool = False + directional_command_joints: frozenset[str] = frozenset() + + +@dataclass(frozen=True) +class JointLimitPolicy: + """An explicit interpretation of CAD limits, separate from SDK safety. + + Independent safety bounds, when known, are in original CAD coordinates. + Their absence never means that a calibrated motion envelope is a hardware + safety certificate. + """ + + source_limits: str + evidence_source: str + independent_safety_limits_cad_rad: tuple[float, float] | None = None + safety_evidence_source: str = "" + + +@dataclass(frozen=True) +class CalibrationProfile: + key: ProfileKey + namespace: str + command: CommandLayout + vision: VisionRigSpec + motion: MotionPolicy + measurement: MeasurementPolicy + zero: ZeroSolvePolicy + quality: QualityPolicy + scope: ScopePolicy + artifacts: ArtifactPolicy + acquisition: AcquisitionPolicy = field(default_factory=AcquisitionPolicy) + sdk_adapter: str = "legacy_byte_sdk" + urdf_authorized_fields: Mapping[str, frozenset[str]] = field( + default_factory=dict + ) + # Per-URDF-joint provenance used by partial calibration artifacts. + # Known values are: measured_static_dynamic, measured_dynamic_cad_static, + # transferred_static_dynamic, transferred_dynamic_cad_static, cad_nominal, + # and mimic_nominal. + joint_coverage: Mapping[str, str] = field(default_factory=dict) + urdf_limit_policies: Mapping[str, JointLimitPolicy] = field(default_factory=dict) + + @property + def retained_joints(self) -> frozenset[str]: + if self.scope.default_scope in self.scope.retained_cad_scopes: + return self.scope.frozen_joints[self.scope.default_scope] + return frozenset() + + @property + def command_based_release(self) -> bool: + return self.measurement.release_basis == "steady_command" + + @property + def vision_motion(self) -> bool: + return self.acquisition.motion_observation == "vision" + + @property + def curve_input_domain(self) -> str: + return self.measurement.input_domain or f"feedback_{self.command.unit}" + + +class ProfileValidationError(ValueError): + """Raised before hardware startup when a profile is internally unsafe.""" + + +def _transfer_channel(profile: CalibrationProfile, joint: str) -> int | None: + """Resolve a declared channel without inventing a recipient binding.""" + seen = set() + while joint not in profile.command.command_index_by_joint: + if joint in seen or joint not in profile.zero.mimic_source_by_joint: + return None + seen.add(joint) + joint = profile.zero.mimic_source_by_joint[joint] + return profile.command.command_index_by_joint[joint] + + +def _validate_observation_strategy(profile: CalibrationProfile, errors: list[str]) -> None: + zero, command = profile.zero, profile.command + transfers = profile.measurement.transferred_motion_sources + observed = {joint for task in profile.motion.tasks if not task.validation_only + for joint in task.joints if joint in profile.measurement.measurements + and profile.measurement.measurements[joint].view is not None + and profile.measurement.measurements[joint].kind != "axis_cross_view_validation"} + all_joints = zero.active_joints | zero.passive_joints + for target, source in transfers.items(): + if target not in all_joints or source not in all_joints or source not in observed or target == source: + errors.append(f"motion transfer requires a known recipient and directly observed donor:{target}") + continue + if target in observed or source in transfers: + errors.append(f"motion transfer cannot replace observations or chain donors:{target}") + if (target in zero.active_joints) != (source in zero.active_joints): + errors.append(f"motion transfer must preserve active/passive joint type:{target}") + if target in zero.passive_joints: + parent = zero.mimic_source_by_joint.get(target) + donor_parent = zero.mimic_source_by_joint.get(source) + if parent is None or donor_parent is None or transfers.get(parent, parent) != donor_parent: + errors.append(f"motion transfer must preserve mimic parent correspondence:{target}") + target_channel, source_channel = _transfer_channel(profile, target), _transfer_channel(profile, source) + channels = (target_channel, source_channel) + values = (command.baseline_values, command.minimum_values, + command.maximum_values, command.joint_directions, + command.minimum_feedback_values, command.maximum_feedback_values) + if any(index is None or index < 0 or index in command.disabled_indices + or any(index >= len(row) for row in values) for index in channels): + errors.append(f"motion transfer requires valid enabled SDK bindings:{target}") + elif any(row[target_channel] != row[source_channel] for row in values): + errors.append(f"motion transfer requires equal SDK ranges, baseline and sign:{target}") + if target in zero.direct_zero_joints: + errors.append(f"motion recipient cannot claim a directly observed zero:{target}") + if target in zero.transferred_zero_sources and zero.transferred_zero_sources[target] != source: + errors.append(f"motion and zero transfer donors differ:{target}") + for joint, reason in zero.cad_zero_assumptions.items(): + if joint not in all_joints or not isinstance(reason, str) or not reason.strip(): + errors.append(f"CAD zero assumption requires a known joint and explicit reason:{joint}") + if joint in zero.direct_zero_joints or joint in zero.known_baseline_geometry \ + or joint in zero.transferred_zero_sources: + errors.append(f"CAD zero assumption conflicts with another zero source:{joint}") + for joint in zero.transferred_zero_sources: + if joint in zero.known_baseline_geometry or joint in zero.direct_zero_joints: + errors.append(f"transferred zero conflicts with another zero source:{joint}") + + +def validate_profile(profile: CalibrationProfile) -> None: + """Hard-check all cross-policy references before hardware is enabled.""" + errors: list[str] = [] + from .capture_plan import configure_training, select_task_training + try: + configure_training(profile, profile.quality.training_policy) + for key, cycles in profile.quality.task_training_cycles.items(): + select_task_training(profile, key, cycles) + except ValueError as error: + errors.append(str(error)) + command = profile.command + baseline = command.baseline_values + if profile.measurement.release_basis not in {"feedback_and_command", "steady_command"}: + errors.append("unsupported measurement release basis") + if profile.command_based_release and (profile.artifacts.output_schema_version != 3 + or profile.acquisition.command_capture_mode != "interleaved" + or profile.measurement.cross_view_sources + or profile.measurement.transferred_motion_sources + or profile.zero.passive_joints): + errors.append("steady command release requires independent active v3 joints and interleaved acquisition") + if not command.names or len(command.names) != len(baseline): + errors.append("command names and baseline must be non-empty and aligned") + if len(set(command.names)) != len(command.names): + errors.append("command names must be unique") + if command.unit not in {"u8", "rad"}: + errors.append("command unit must be u8 or rad") + if profile.curve_input_domain not in {f"feedback_{command.unit}", f"command_{command.unit}"}: + errors.append("curve input must explicitly identify native command or feedback coordinates") + if (len(command.joint_directions) != command.command_count + or any(value not in {-1, 1} for value in command.joint_directions) + or (command.unit == "rad" and not command.sdk_to_joint_direction)): + errors.append("native SDK directions must explicitly bind every physical-angle channel") + if command.unit == "u8" and any(value < 0 or value > 255 for value in baseline): + errors.append("baseline command values must be in [0, 255]") + if ( + len(command.minimum_values) != command.command_count + or len(command.maximum_values) != command.command_count + ): + errors.append("command bounds must align with command names") + elif any( + not math.isfinite(lower) + or not math.isfinite(upper) + or lower >= upper + or not lower <= value <= upper + for lower, upper, value in zip( + command.minimum_values, command.maximum_values, baseline + ) + ): + errors.append("command bounds or baseline values are invalid") + if ( + len(command.minimum_feedback_values) != command.command_count + or len(command.maximum_feedback_values) != command.command_count + ): + errors.append("feedback bounds must align with command names") + elif any( + not math.isfinite(feedback_lower) + or not math.isfinite(feedback_upper) + or feedback_lower >= feedback_upper + for feedback_lower, feedback_upper, command_lower, command_upper in zip( + command.minimum_feedback_values, + command.maximum_feedback_values, + command.minimum_values, + command.maximum_values, + ) + ): + errors.append( + "feedback bounds must be finite and ordered in feedback coordinates" + ) + indices = set(range(command.command_count)) + if command.maximum_velocity and (len(command.maximum_velocity) != command.command_count + or any(not math.isfinite(v) or v <= 0 for v in command.maximum_velocity)): + errors.append("per-channel velocity limits must be finite, positive and complete") + if not set(command.disabled_indices).issubset(indices): + errors.append("disabled command index is out of range") + if any(index not in indices for index in command.command_index_by_joint.values()): + errors.append("joint command index is out of range") + if command.urdf_joint_by_joint: + if not set(command.command_index_by_joint).issubset( + command.urdf_joint_by_joint + ): + errors.append("every commanded joint must map to a URDF joint") + urdf_names = tuple(command.urdf_joint_by_joint.values()) + if len(set(urdf_names)) != len(urdf_names): + errors.append("URDF joint mappings must be unique") + if any( + index not in indices or slot < 0 + for index, slot in command.speed_slot_by_command_index.items() + ): + errors.append("speed-slot mapping is invalid") + if any( + not str(alias).strip() or canonical not in command.names + for alias, canonical in command.feedback_name_aliases.items() + ): + errors.append("feedback name alias is not part of the command schema") + + view_names = profile.vision.view_names + if not view_names or len(set(view_names)) != len(view_names): + errors.append("vision views must be non-empty and unique") + if profile.vision.extrinsic_reference_view not in view_names: + errors.append("extrinsic reference view is not declared") + tag_ids = [tag.tag_id for view in profile.vision.views for tag in view.tags] + tag_roles = [tag.role for view in profile.vision.views for tag in view.tags] + if any(not math.isfinite(tag.size_m) or tag.size_m <= 0 for view in profile.vision.views for tag in view.tags): + errors.append("Tag side lengths must be finite positive meters") + if len(set(tag_ids)) != len(tag_ids): + errors.append("Tag IDs must be unique across views") + if len(set(tag_roles)) != len(tag_roles): + errors.append("Tag roles must be unique across views") + if not any( + tag.fixed_reference for view in profile.vision.views for tag in view.tags + ): + errors.append("at least one fixed reference Tag is required") + + task_keys = [task.key for task in profile.motion.tasks] + reference_keys = set() + for waypoint in profile.motion.resume_verification_waypoints: + if not waypoint.key or waypoint.key in reference_keys or "/" in waypoint.key: + errors.append("reference waypoint keys must be nonempty, unique and contain no slash") + reference_keys.add(waypoint.key) + if len(waypoint.command) != command.command_count or any( + not math.isfinite(v) or not lo <= v <= hi for v, lo, hi in + zip(waypoint.command, command.minimum_values, command.maximum_values)): + errors.append("reference waypoint command outside declared domain") + if any(i < len(waypoint.command) and waypoint.command[i] != command.baseline_values[i] + for i in command.disabled_indices): + errors.append("reference waypoint must keep disabled channels at baseline") + if not waypoint.tag_ids_by_view or any(view not in view_names or not ids or not set(ids) <= { + tag.tag_id for rig_view in profile.vision.views if rig_view.name == view for tag in rig_view.tags + if not tag.fixed_reference} for view, ids in waypoint.tag_ids_by_view.items()): + errors.append("reference waypoint must name observed moving Tags in their declared views") + if not profile.measurement.candidate_selection_tasks <= set(task_keys): + errors.append("candidate selection references an unknown motion task") + if not task_keys or len(set(task_keys)) != len(task_keys): + errors.append("motion task keys must be non-empty and unique") + measurement_names = set(profile.measurement.measurements) + for task in profile.motion.tasks: + if task.view not in view_names: + errors.append(f"task {task.key} uses an unknown view") + if task.command_index not in indices: + errors.append(f"task {task.key} command index is out of range") + continue + if not task.joints or not set(task.joints).issubset(measurement_names): + errors.append(f"task {task.key} references unknown measurements") + if any(index not in indices for index, _ in task.auxiliary_commands): + errors.append(f"task {task.key} auxiliary index is out of range") + elif any( + not command.minimum_values[index] <= float(value) <= command.maximum_values[index] + for index, value in task.auxiliary_commands + ): + errors.append(f"task {task.key} auxiliary command is out of range") + lower = command.minimum_values[task.command_index] + upper = command.maximum_values[task.command_index] + if not lower <= task.start_value <= upper or not lower <= task.end_value <= upper: + errors.append(f"task {task.key} sweep endpoint is out of range") + if task.start_value == task.end_value: + errors.append(f"task {task.key} sweep endpoints must differ") + grouped = [index for group in task.preparation_groups for index in group] + if any(not group for group in task.preparation_groups) or len(grouped) != len(set(grouped)) or not set(grouped) <= indices: + errors.append(f"task {task.key} preparation groups must contain unique valid channels") + if any(task.command_index in group for group in task.preparation_groups[:-1]): + errors.append(f"task {task.key} measured channel must move after avoidance channels") + segment_keys = set() + for segment in task.segments: + starts, ends = dict(segment.start_commands), dict(segment.end_commands) + if (not segment.key or segment.key in segment_keys or set(starts) != set(ends) + or len(starts) != len(segment.start_commands) or len(ends) != len(segment.end_commands) + or not starts or not set(starts) <= indices-command.disabled_indices): + errors.append(f"task {task.key} has an invalid segment identity or channels") + continue + segment_keys.add(segment.key) + if any(not math.isfinite(v) or not command.minimum_values[i] <= v <= command.maximum_values[i] + for i, v in (*segment.start_commands, *segment.end_commands)): + errors.append(f"task {task.key} segment commands are outside domain") + moving = {i for i in starts if starts[i] != ends[i]} + signs = {1 if ends[i] > starts[i] else -1 for i in moving} + if not moving or len(signs) != 1: + errors.append(f"task {task.key} segment must move channels in one native direction") + if (not segment.joints or not set(segment.joints) <= set(task.joints) + or any(_transfer_channel(profile, j) not in moving for j in segment.joints)): + errors.append(f"task {task.key} segment observations must follow moving channels") + if task.segments and segment_keys == {s.key for s in task.segments}: + if set().union(*(set(s.joints) for s in task.segments)) != set(task.joints): + errors.append(f"task {task.key} segments must cover every observed joint") + for previous, following in zip(task.segments, task.segments[1:]): + if dict(previous.end_commands) != dict(following.start_commands): + errors.append(f"task {task.key} segment path must be continuous") + if dict(task.segments[-1].end_commands) != dict(task.segments[0].start_commands): + errors.append(f"task {task.key} segment cycle must be closed") + if task.parent_reference is not None: + reference = task.parent_reference + earlier = {name for previous in profile.motion.tasks[:profile.motion.tasks.index(task)] + for name in previous.joints} + if (task.model_preparations or len(task.joints) != 1 + or profile.acquisition.motion_model_scope != "task" + or not {reference.pose_joint, reference.geometry_joint} <= earlier): + errors.append(f"task {task.key} parent reference requires earlier measured sources and task scope") + elif all(name in measurement_names for name in (*task.joints, reference.pose_joint, reference.geometry_joint)): + child = profile.measurement.measurements[task.joints[0]] + if any(profile.measurement.measurements[name].child_role != child.parent_role + or profile.measurement.measurements[name].view != child.view + for name in (reference.pose_joint, reference.geometry_joint)): + errors.append(f"task {task.key} parent reference must identify the same physical parent Tag") + for preparation in task.model_preparations: + if profile.acquisition.motion_model_scope != "task" or preparation.joint not in measurement_names: + errors.append(f"task {task.key} image preparation needs a measured joint and task model scope") + continue + spec = profile.measurement.measurements[preparation.joint] + roots = {profile.measurement.measurements[j].parent_role for j in task.joints if j in measurement_names} + if spec.child_role not in roots or preparation.joint in task.joints or not preparation.approach_commands: + errors.append(f"task {task.key} image preparation must authorize a parent Tag") + for pose in (*preparation.approach_commands, preparation.command): + if len(pose) != command.command_count or any(not math.isfinite(v) or not lo <= v <= hi + for v, lo, hi in zip(pose, command.minimum_values, command.maximum_values)): + errors.append(f"task {task.key} image preparation command outside domain") + if preparation.command not in {spec.command for spec in profile.motion.joint_zero_references.values() + if spec.task_key == task.key}: + errors.append(f"task {task.key} image preparation must finish at its declared zero pose") + channel = _transfer_channel(profile, preparation.joint) + if any(i != channel and v != preparation.command[i] + for pose in preparation.approach_commands for i, v in enumerate(pose) + if i < len(preparation.command)): + errors.append(f"task {task.key} image preparation must move only its observed parent joint") + for waypoint in (*task.entry_waypoints, *task.exit_waypoints): + if not waypoint or len({i for i, _ in waypoint}) != len(waypoint) or any( + i not in indices or i in command.disabled_indices or not math.isfinite(v) + or not command.minimum_values[i] <= v <= command.maximum_values[i] for i, v in waypoint): + errors.append(f"task {task.key} has an invalid entry waypoint") + for speed in (task.preflight_speed_u8, task.formal_speed_u8): + if speed is not None and not 0 <= speed <= 255: + errors.append(f"task {task.key} speed is out of range") + if command.unit == "rad" and ( + task.formal_speed is None or not math.isfinite(float(task.formal_speed)) or float(task.formal_speed) <= 0.0 + ): + errors.append(f"task {task.key} physical speed must be positive") + for name, spec in profile.measurement.measurements.items(): + if name != spec.joint: + errors.append(f"measurement mapping key differs for {name}") + if spec.view is not None and spec.view not in view_names: + errors.append(f"measurement {name} uses an unknown view") + if spec.view is not None: + roles = {tag.role for view in profile.vision.views if view.name == spec.view for tag in view.tags} + if spec.parent_role not in roles or spec.child_role not in roles or spec.parent_role == spec.child_role: + errors.append(f"measurement {name} must reference distinct parent/child Tags in its view") + for primary, validation in profile.measurement.cross_view_sources.items(): + if primary not in measurement_names or validation not in measurement_names: + errors.append("cross-view measurement source is unknown") + return_indices = [index for group in profile.motion.return_groups for index in group] + if any(not group for group in profile.motion.return_groups) or len(return_indices) != len(set(return_indices)) or not set(return_indices) <= indices: + errors.append("return groups must contain unique valid channels") + + zero = profile.zero + for name, reference in profile.motion.joint_zero_references.items(): + if reference.evidence_scope not in {"arrival", "path"}: + errors.append(f"invalid zero approach evidence scope:{name}") + if reference.evidence_scope == "path": + if len(reference.approach_commands) < 2: + errors.append(f"path evidence needs at least two declared approach poses:{name}") + elif all(len(pose) == command.command_count + for pose in (reference.command, *reference.approach_commands)): + moving = {i for i, value in enumerate(reference.approach_commands[-1]) + if value != reference.command[i]} + if any(value != reference.command[i] for pose in reference.approach_commands + for i, value in enumerate(pose) if i not in moving): + errors.append(f"path evidence must preserve the final arrival holding pose:{name}") + task = next((t for t in profile.motion.tasks if t.key == reference.task_key), None) + if task is None or name not in task.joints: + errors.append(f"zero reference must precede an observing task:{name}") + continue + for pose in (reference.command, *reference.approach_commands): + if len(pose) != command.command_count or any(not math.isfinite(v) or not lo <= v <= hi + for v, lo, hi in zip(pose, command.minimum_values, command.maximum_values)): + errors.append(f"zero reference command outside declared domain:{name}") + elif any(pose[i] != command.baseline_values[i] for i in command.disabled_indices): + errors.append(f"zero reference moves a disabled channel:{name}") + if len(reference.command) == command.command_count: + channel = _transfer_channel(profile, name) + if channel is None: + errors.append(f"zero reference has no motor channel:{name}") + continue + if reference.command[channel] != command.baseline_values[channel]: + errors.append(f"zero reference must use joint baseline, not task start:{name}") + if profile.artifacts.output_schema_version >= 3 and (not reference.approach_commands + or len(reference.approach_commands[-1]) != command.command_count + or reference.approach_commands[-1][channel] == reference.command[channel]): + errors.append(f"zero reference requires an explicit nonzero final arrival:{name}") + first_task = next((t.key for t in profile.motion.tasks if name in t.joints), None) + if first_task != reference.task_key: + errors.append(f"zero reference must precede first training task:{name}") + for name, geometry in zero.known_baseline_geometry.items(): + if name not in zero.active_joints | zero.passive_joints or not geometry.evidence_source.strip(): + errors.append(f"known baseline requires a joint and evidence source:{name}") + if not math.isfinite(geometry.cad_angle_rad) or not 0 <= geometry.uncertainty_rad <= math.radians(1): + errors.append(f"known baseline geometry is invalid or uncertain:{name}") + if zero.active_joints & zero.passive_joints: + errors.append("active and passive joints must be disjoint") + all_joints = zero.active_joints | zero.passive_joints + _validate_observation_strategy(profile, errors) + if not zero.active_joints.issubset(command.command_index_by_joint): + errors.append("every active joint must bind to a command channel") + if not set(zero.direct_zero_joints).issubset(zero.active_joints): + errors.append("direct zero targets must be active joints") + if not set(zero.axis_joints).issubset(all_joints): + errors.append("axis targets must be known joints") + if not zero.mechanical_endpoint_joints.issubset(zero.active_joints): + errors.append("mechanical endpoint targets must be active joints") + if not zero.post_solve_endpoint_joints.issubset(zero.active_joints): + errors.append("post-solve endpoint targets must be active joints") + if not set(zero.mimic_source_by_joint).issubset(zero.passive_joints): + errors.append("mimic targets must be passive joints") + if not set(zero.mimic_source_by_joint.values()).issubset(all_joints): + errors.append("mimic sources must be known joints") + if not set(zero.endpoint_anchor_by_joint).issubset(zero.active_joints): + errors.append("endpoint anchors must target active joints") + if not set(zero.endpoint_anchor_by_joint.values()).issubset( + { + "upper_at_end", + "lower_at_start", + "zero_at_start", + "cad_range_center", + } + ): + errors.append("endpoint anchor policy is unsupported") + if not zero.fitted_mimic_joints.issubset(zero.passive_joints): + errors.append("fitted mimic targets must be passive joints") + for transfers, targets, donors, label in ( + (zero.transferred_zero_sources, zero.active_joints, set(zero.direct_zero_joints), "zero"), + (zero.transferred_mimic_sources, zero.passive_joints, zero.fitted_mimic_joints, "mimic"), + ): + if not set(transfers) <= targets or not set(transfers.values()) <= donors or any(k == v for k, v in transfers.items()): + errors.append(f"{label} transfer requires distinct known recipients and measured donors") + if not zero.fitted_mimic_joints.issubset(zero.mimic_source_by_joint): + errors.append("fitted mimic target has no source mapping") + if not set(zero.coupling_model_by_joint).issubset( + zero.mimic_source_by_joint + ): + errors.append("coupling model target has no source mapping") + if not set(zero.coupling_model_by_joint.values()).issubset( + { + "linear_mimic", + "quadratic_runtime", + "direction_aware_knots", + "vendor_o12_polynomial", + } + ): + errors.append("coupling model policy is unsupported") + + scopes = set(profile.scope.calibrate_joints) + if profile.scope.default_scope not in scopes: + errors.append("default scope is not declared") + if scopes != set(profile.scope.frozen_joints): + errors.append("scope calibration and frozen mappings must align") + for name in scopes: + selected = profile.scope.calibrate_joints[name] + frozen = profile.scope.frozen_joints[name] + if selected & frozen or selected | frozen != zero.active_joints: + errors.append(f"scope {name} must partition all active joints") + for name, policy in profile.scope.retained_cad_scopes.items(): + if (name not in scopes or name == "full" or not policy.reason.strip() + or not profile.scope.frozen_joints.get(name)): + errors.append(f"retained CAD scope must explicitly name excluded active joints:{name}") + anchors = set(policy.root_anchor_joints) | {policy.orientation_anchor_joint} + if (not policy.root_anchor_joints or not anchors <= profile.scope.calibrate_joints.get(name, ()) + or not set(policy.directed_base_axis_joints) <= anchors): + errors.append(f"partial base pose must use declared measured anchors:{name}") + retained = profile.retained_joints + if retained: + measured = {joint for task in profile.motion.tasks for joint in task.joints} + if (not profile.command_based_release or measured != zero.active_joints - retained + or retained & (set(profile.measurement.measurements) | set(profile.urdf_authorized_fields) + | set(profile.urdf_limit_policies) | set(zero.direct_zero_joints) + | set(zero.cad_zero_assumptions) | set(zero.known_baseline_geometry))): + errors.append("partial capture must preserve excluded CAD joints without claiming measurements or zeros") + + artifacts = profile.artifacts + if artifacts.output_schema_version < 1: + errors.append("artifact schema version must be positive") + if artifacts.directional_command_joints and (artifacts.output_schema_version != 3 + or not artifacts.directional_command_joints <= profile.measurement.measurements.keys()): + errors.append("directional command curves require measured v3 joints") + for target, source in profile.measurement.transferred_motion_sources.items(): + if (target in artifacts.directional_command_joints) != (source in artifacts.directional_command_joints): + errors.append("transferred command curves must retain their source direction policy") + for label, filename in ( + ("calibration", artifacts.calibration_filename), + ("corrected URDF", artifacts.corrected_urdf_filename), + ("publication pointer", artifacts.publication_pointer), + ): + if not filename or PurePath(filename).name != filename: + errors.append(f"{label} filename must not contain a directory") + if not profile.namespace.startswith("/"): + errors.append("runtime namespace must be absolute") + if not str(profile.sdk_adapter).strip(): + errors.append("SDK adapter name must be non-empty") + valid_urdf_fields = { + "origin.rpy", "limit.lower", "limit.upper", + "mimic.multiplier", "mimic.offset", + } + if not set().union(*profile.urdf_authorized_fields.values(), set()).issubset( + valid_urdf_fields + ): + errors.append("URDF authorization contains an unsupported field") + for name, policy in profile.urdf_limit_policies.items(): + if name not in all_joints or not isinstance(policy, JointLimitPolicy): + errors.append(f"URDF limit policy requires a known movable joint:{name}") + continue + if policy.source_limits != "calibrated_motion_envelope" or not policy.evidence_source.strip(): + errors.append(f"URDF motion envelope requires explicit source-limit interpretation:{name}") + if not {"limit.lower", "limit.upper"} <= set(profile.urdf_authorized_fields.get(name, ())): + errors.append(f"URDF motion envelope lacks limit authorization:{name}") + bounds = policy.independent_safety_limits_cad_rad + if bounds is None: + if policy.safety_evidence_source: + errors.append(f"URDF safety evidence has no independent bounds:{name}") + elif (len(bounds) != 2 or not all(math.isfinite(v) for v in bounds) + or bounds[0] >= bounds[1] or not policy.safety_evidence_source.strip()): + errors.append(f"URDF independent safety bounds require finite limits and evidence:{name}") + acquisition = profile.acquisition + if acquisition.motion_observation not in {"feedback", "vision"}: + errors.append("motion observation must be feedback or vision") + if profile.vision_motion and not profile.command_based_release: + errors.append("visual motion requires independent steady-command release") + for key in ("visual_stale_seconds", "visual_minimum_motion_px", "visual_stability_px", "visual_zero_tolerance_px"): + if not math.isfinite(getattr(acquisition, key)) or getattr(acquisition, key) <= 0: + errors.append(f"visual motion threshold must be finite and positive:{key}") + if acquisition.visual_minimum_motion_px <= 2*acquisition.visual_stability_px: + errors.append("visual motion witness must exceed twice the stability noise") + if not isinstance(acquisition.feedback_travel_matches_command, bool): + errors.append("feedback travel correspondence must be a boolean") + if (not math.isfinite(acquisition.minimum_significant_request_u8) + or not 2.0 <= acquisition.minimum_significant_request_u8 <= 255.0): + errors.append("minimum significant u8 request must be finite and in [2, 255]") + if acquisition.motion_model_scope not in {"session", "task"}: + errors.append("motion model scope must be session or task") + if acquisition.fixed_reference_mode not in {"tag_pose", "stationary_image"}: + errors.append("fixed reference mode must be tag_pose or stationary_image") + if acquisition.fixed_reference_mode == "stationary_image" and profile.artifacts.output_schema_version < 3: + errors.append("stationary image references require version 3 measured geometry") + if acquisition.command_capture_mode not in {"interleaved", "separate"}: + errors.append("unsupported command capture mode") + task_by_key = {task.key: task for task in profile.motion.tasks} + for key, values in acquisition.steady_extra_training_nodes.items(): + task = task_by_key.get(key) + if task is None or any(not math.isfinite(value) or not min(task.start_value, task.end_value) < value < max(task.start_value, task.end_value) for value in values): + errors.append(f"extra steady nodes must lie inside a declared task:{key}") + if acquisition.steady_training_nodes < 3 or acquisition.steady_minimum_samples < 3: + errors.append("steady mapping requires at least three nodes and three images per node") + if not acquisition.steady_timeout_seconds <= acquisition.joint_zero_timeout_seconds <= 10.0: + errors.append("joint zero capture timeout must be between the steady timeout and 10 seconds") + if not 0 < acquisition.steady_window_seconds < acquisition.steady_timeout_seconds <= 2.0: + errors.append("steady acquisition must have a finite stability window and <=2 second wait") + if acquisition.policy_version != ACQUISITION_POLICY_VERSION: + errors.append("unsupported acquisition policy version") + if acquisition.automatic_rescan_limit != 1: + errors.append("unified engine requires exactly one automatic rescan") + if acquisition.minimum_valid_samples < 40 or acquisition.minimum_bins < 32: + errors.append("acquisition sample and bin minima are too small") + if not 0.0 < acquisition.maximum_unobserved_fraction <= 1.0 / 16.0: + errors.append("maximum unobserved travel must not exceed 1/16") + if command.unit == "rad" and not 0.0 < acquisition.mapping_probe_maximum_rad <= math.radians(3.0): + errors.append("physical-angle profiles require a <=3 degree mapping probe") + if command.unit == "u8" and acquisition.mapping_probe_maximum_rad != 0.0: + errors.append("legacy profiles must not request a radian mapping probe") + if acquisition.feedback_stale_seconds <= 0.0: + errors.append("feedback stale timeout must be positive") + if not all(math.isfinite(float(value)) and float(value) > 0 for value in ( + acquisition.feedback_stale_seconds, acquisition.stall_timeout_seconds, + acquisition.fixed_reference_maximum_drift_px, + )): + errors.append("safety timeouts and reference drift must be finite and positive") + if not 0 <= acquisition.endpoint_tolerance_01 < 0.5: + errors.append("endpoint observation tolerance must be in [0, 0.5)") + if acquisition.fixed_reference_minimum_frames < 10: + errors.append("fixed reference locking requires at least ten frames") + if acquisition.fixed_reference_confirmation_frames < 10: + errors.append("fixed reference movement requires ten confirming frames") + if profile.joint_coverage: + valid_coverage = { + "measured_static_dynamic", + "measured_dynamic_cad_static", + "transferred_static_dynamic", + "transferred_dynamic_cad_static", + "cad_nominal", + "mimic_nominal", + } + if set(profile.joint_coverage) != all_joints: + errors.append("joint coverage must describe every profile joint") + if not set(profile.joint_coverage.values()).issubset(valid_coverage): + errors.append("joint coverage contains an unsupported status") + + if errors: + raise ProfileValidationError("; ".join(errors)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/reference.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/reference.py new file mode 100644 index 0000000..b514c8a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/reference.py @@ -0,0 +1,249 @@ +"""Immutable visual baselines, acquired once before each joint's training.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, replace +import math +import re +from typing import Mapping, Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + + +@dataclass(frozen=True) +class JointZeroPose: + quaternion_xyzw: tuple[float, ...] + translation_xyz_m: tuple[float, ...] + + @classmethod + def from_mapping(cls, row): + q, t = tuple(row["quaternion_xyzw"]), tuple(row["translation_xyz_m"]) + if (len(q) != 4 or len(t) != 3 or not np.all(np.isfinite(q+t)) + or not np.isclose(np.linalg.norm(q), 1, atol=1e-5)): + raise ValueError("joint_zero_pose_invalid") + return cls(q, t) + + +@dataclass(frozen=True) +class JointZeroSample: + sample_id: str + view: str + image_stamp_ns: int + relative_quaternion_xyzw: tuple[float, ...] + relative_translation_xyz_m: tuple[float, ...] + command: tuple[float, ...] + feedback: tuple[float, ...] + arrival_directions: tuple[str, ...] + parent_pose_common: JointZeroPose + child_pose_common: JointZeroPose + + @classmethod + def from_row(cls, row, unit): + return cls(f"{row['view']}:{int(row['image_stamp_ns'])}", row["view"], + int(row["image_stamp_ns"]), tuple(row["relative_quaternion_xyzw"]), + tuple(row["relative_translation_xyz_m"]), tuple(row[f"command_vector_{unit}"]), + tuple(row.get(f"state_{unit}") or ()), tuple(row.get("command_direction_by_index", ())), + JointZeroPose.from_mapping(row["parent_pose_common"]), JointZeroPose.from_mapping(row["child_pose_common"])) + + +@dataclass(frozen=True) +class JointZeroBranchReference: + """A moving physical Tag's immutable pre-zero motion authorization.""" + + view: str + tag_role: str + branch_revision: int + motion_evidence_id: str + + def __post_init__(self): + if (not self.view or not self.tag_role or type(self.branch_revision) is not int + or self.branch_revision < 1 or not isinstance(self.motion_evidence_id, str) + or re.fullmatch(r"[0-9a-f]{64}", self.motion_evidence_id) is None): + raise ValueError("joint_zero_motion_evidence_invalid") + + +@dataclass(frozen=True) +class JointZeroReference: + joint: str + task_key: str + baseline_command: float + channel: int + session_epoch: int + motion_version: int + samples: tuple[JointZeroSample, ...] + branch_references: tuple[JointZeroBranchReference, ...] = () + + def quaternion(self, view): + rotations = Rotation.from_quat([s.relative_quaternion_xyzw for s in self.samples if s.view == view]) + return rotations.mean().as_quat() + + def input_reference(self, view, *, feedback=False): + values = [(s.feedback if feedback else s.command)[self.channel] + for s in self.samples if s.view == view] + if not values: + raise ValueError(f"joint_zero_missing_view:{self.joint}:{view}") + return float(np.median(values)) + + def as_record(self): + return {"kind": "joint_zero_reference", **asdict(self)} + + @classmethod + def from_record(cls, row): + for sample in row["samples"]: + if sample["sample_id"] != f"{sample['view']}:{int(sample['image_stamp_ns'])}": + raise ValueError(f"joint_zero_image_identity_invalid:{row['joint']}") + samples = tuple(JointZeroSample(**{**s, + "parent_pose_common": JointZeroPose.from_mapping(s["parent_pose_common"]), + "child_pose_common": JointZeroPose.from_mapping(s["child_pose_common"]), + **{key: tuple(s[key]) for key in ("relative_quaternion_xyzw", "relative_translation_xyz_m", + "command", "feedback", "arrival_directions")}}) for s in row["samples"]) + return cls(str(row["joint"]), str(row["task_key"]), float(row["baseline_command"]), + int(row["channel"]), int(row["session_epoch"]), int(row["motion_version"]), samples, + tuple(JointZeroBranchReference(**item) for item in row.get("branch_references", ()))) + + +def joint_zero_moving_roles(profile, joint): + """Physical roles that require motion evidence for this joint's zero.""" + names = (joint, profile.measurement.cross_view_sources.get(joint)) + roles = set() + for name in names: + if name is None: + continue + measurement = profile.measurement.measurements[name] + for view in profile.vision.views: + if view.name == measurement.view: + roles.update((view.name, tag.role) for tag in view.tags + if tag.role in (measurement.parent_role, measurement.child_role) and not tag.fixed_reference) + return roles + + +def _branch_references(profile, joint, rows): + allowed = joint_zero_moving_roles(profile, joint) + result, observed = {}, {} + for row in rows: + for item in row.get("pnp_observation_evidence", {}).values(): + key = (row["view"], item.get("tag_role")) + diagnostics = item.get("candidate_diagnostics", {}) + verified, identity = diagnostics.get("motion_evidence_verified"), diagnostics.get("motion_evidence_id") + observed.setdefault(key, []).append((verified, identity)) + if not identity and verified is not True: + continue # Legacy image confirmation remains readable as legacy. + if (key not in allowed or verified is not True or item.get("pose_source") not in { + "current_image", "image_constrained_current_image"} + or diagnostics.get("observation_stamp_ns") != row["image_stamp_ns"] + or diagnostics.get("branch_status") != "tracking"): + raise ValueError(f"joint_zero_motion_evidence_unconfirmed:{joint}") + reference = JointZeroBranchReference(*key, diagnostics.get("branch_revision"), identity) + if key in result and result[key] != reference: + raise ValueError(f"joint_zero_motion_evidence_changed:{joint}") + result[key] = reference + for key, reference in result.items(): + required = sum(row["view"] == key[0] for row in rows) + if len(observed[key]) != required or any( + verified is not True or identity != reference.motion_evidence_id for verified, identity in observed[key]): + raise ValueError(f"joint_zero_motion_evidence_incomplete:{joint}") + return tuple(result[key] for key in sorted(result)) + + +def _validate_branch_bindings(profile, reference): + keys = [(item.view, item.tag_role) for item in reference.branch_references] + if len(set(keys)) != len(keys) or not set(keys) <= joint_zero_moving_roles(profile, reference.joint): + raise ValueError(f"joint_zero_motion_evidence_binding_invalid:{reference.joint}") + + +def build_joint_zero_reference(profile, joint, rows: Sequence[Mapping], *, session_epoch, motion_version): + spec = profile.motion.joint_zero_references[joint] + task = next(t for t in profile.motion.tasks if t.key == spec.task_key) + from ..fitting.motion_fit import channel_for_joint + channel = channel_for_joint(profile, joint) + views = {profile.measurement.measurements[joint].view} + secondary = profile.measurement.cross_view_sources.get(joint) + if secondary: + views.add(profile.measurement.measurements[secondary].view) + if session_epoch < 1 or motion_version < 1: + raise ValueError(f"joint_zero_session_version_invalid:{joint}") + # Incomplete windows are checked by the control timer repeatedly. Check + # their image coverage before constructing and validating every pose. + minimum = profile.acquisition.fixed_reference_minimum_frames + for view in views: + count = len({int(row["image_stamp_ns"]) for row in rows if row["view"] == view}) + if count < minimum: + measurements = [profile.measurement.measurements[n] for n in (joint, secondary) if n is not None] + roles = {role for m in measurements if m.view == view for role in (m.parent_role, m.child_role)} + ids = [t.tag_id for v in profile.vision.views if v.name == view for t in v.tags if t.role in roles] + raise ValueError(f"joint_zero_samples_missing:{joint}:{view}:required_tags={ids}:{count}/{minimum}") + samples = tuple(JointZeroSample.from_row(row, profile.command.unit) for row in rows) + for sample in samples: + if sample.image_stamp_ns < 1 or sample.sample_id != f"{sample.view}:{sample.image_stamp_ns}": + raise ValueError(f"joint_zero_image_identity_invalid:{joint}") + if len(sample.relative_quaternion_xyzw) != 4 or not np.isclose(np.linalg.norm(sample.relative_quaternion_xyzw), 1, atol=1e-5): + raise ValueError(f"joint_zero_rotation_invalid:{joint}") + parent, child = sample.parent_pose_common, sample.child_pose_common + rp, rc = Rotation.from_quat(parent.quaternion_xyzw), Rotation.from_quat(child.quaternion_xyzw) + if ((Rotation.from_quat(sample.relative_quaternion_xyzw).inv()*rp.inv()*rc).magnitude() > 1e-7 + or not np.allclose(rp.inv().apply(np.asarray(child.translation_xyz_m)-parent.translation_xyz_m), + sample.relative_translation_xyz_m, atol=1e-8, rtol=0)): + raise ValueError(f"joint_zero_relative_pose_inconsistent:{joint}") + for view in views: + selected = [s for s in samples if s.view == view] + rotations = Rotation.from_quat([s.relative_quaternion_xyzw for s in selected]) + if np.max((rotations.mean().inv()*rotations).magnitude()) > math.radians(1): + raise ValueError(f"joint_zero_not_stable:{joint}:{view}") + identities = [(s.view, s.sample_id) for s in samples] + if len(set(identities)) != len(identities): + raise ValueError(f"duplicate_joint_zero_image:{joint}") + for sample in samples: + if sample.view not in views or sample.command != spec.command: + raise ValueError(f"joint_zero_pose_differs:{joint}") + if not profile.vision_motion and (len(sample.feedback) != profile.command.command_count or not np.all(np.isfinite(sample.feedback))): + raise ValueError(f"joint_zero_feedback_invalid:{joint}") + if len(sample.arrival_directions) != profile.command.command_count: + raise ValueError(f"joint_zero_arrival_missing:{joint}") + if spec.approach_commands: + before = spec.approach_commands[-1][channel] + expected = "increasing" if spec.command[channel] > before else "decreasing" + if sample.arrival_directions[channel] != expected: + raise ValueError(f"joint_zero_arrival_changed:{joint}") + return JointZeroReference(joint, spec.task_key, profile.command.baseline_values[channel], + channel, session_epoch, motion_version, samples, _branch_references(profile, joint, rows)) + + +def read_joint_zero_references(profile, records): + """Reject invented, repeated or late baselines in online and offline inputs.""" + result = {} + first_training_stamp = {} + for row in records: + if row.get("kind") in {"joint_sample", "secondary_joint_sample"}: + name = row.get("joint", row.get("observation_joint")) + stamp = int(row["image_stamp_ns"]) + first_training_stamp[name] = min(first_training_stamp.get(name, stamp), stamp) + if row.get("kind") != "joint_zero_reference": + continue + reference = JointZeroReference.from_record(row) + name = reference.joint + if name in result or name not in profile.motion.joint_zero_references: + raise ValueError(f"duplicate_or_unknown_joint_zero:{name}") + spec = profile.motion.joint_zero_references[name] + if (not 0 <= reference.channel < profile.command.command_count or reference.task_key != spec.task_key + or reference.baseline_command != profile.command.baseline_values[reference.channel]): + raise ValueError(f"joint_zero_contract_changed:{name}") + # Revalidate the complete stored evidence, not just an averaged quaternion. + rows = [{"view": s.view, "image_stamp_ns": s.image_stamp_ns, + "relative_quaternion_xyzw": s.relative_quaternion_xyzw, + "relative_translation_xyz_m": s.relative_translation_xyz_m, + f"command_vector_{profile.command.unit}": s.command, f"state_{profile.command.unit}": s.feedback, + "command_direction_by_index": s.arrival_directions, + "parent_pose_common": asdict(s.parent_pose_common), "child_pose_common": asdict(s.child_pose_common)} + for s in reference.samples] + checked = build_joint_zero_reference(profile, name, rows, + session_epoch=reference.session_epoch, motion_version=reference.motion_version) + _validate_branch_bindings(profile, reference) + checked = replace(checked, branch_references=reference.branch_references) + if checked.channel != reference.channel: + raise ValueError(f"joint_zero_channel_changed:{name}") + result[name] = checked + for name, reference in result.items(): + if name in first_training_stamp and max(s.image_stamp_ns for s in reference.samples) >= first_training_stamp[name]: + raise ValueError(f"joint_zero_not_before_training:{name}") + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/result.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/result.py new file mode 100644 index 0000000..2689b59 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/result.py @@ -0,0 +1,105 @@ +"""Frozen numerical results, independent of a serializer or SDK transport.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import math +from typing import TYPE_CHECKING, Mapping, Sequence + +import numpy as np + +if TYPE_CHECKING: + from .measurement import JointCurveFit + from ..fitting.coupling import RelativeMimicEvidence + from ..fitting.spatial import ZeroSolveResult + + +@dataclass(frozen=True) +class CalibrationResult: + """Training-frozen measurements and parameters consumed by every writer. + + output_mappings is the primary geometry/replay domain, explicitly labeled + by each JointMapping. Optional feedback diagnostics never supply geometry. + + This is not a publication certificate: the final serialized URDF must + still pass independent spatial replay and structural authorization. + """ + + curves: Mapping[str, JointCurveFit] + output_mappings: Mapping[str, JointMapping] + zero_offsets_rad: Mapping[str, float] + zero_method_by_joint: Mapping[str, str] + standard_mimic_evidence: Mapping[str, RelativeMimicEvidence] + holdout_errors_rad: Mapping[str, tuple[float, ...]] + spatial_zero: ZeroSolveResult + cross_view_metrics: Mapping = field(default_factory=dict) + reference_inputs: Mapping[str, float] = field(default_factory=dict) + command_mappings: Mapping[str, JointMapping] = field(default_factory=dict) + command_holdout_metrics: Mapping = field(default_factory=dict) + command_applicability: Mapping = field(default_factory=dict) + joint_zero_references: Mapping = field(default_factory=dict) + mimic_approximations: Mapping = field(default_factory=dict) + feedback_diagnostics: Mapping = field(default_factory=dict) + + +@dataclass(frozen=True) +class JointMapping: + """SDK input -> output URDF coordinate; branches use raw SDK direction. + + Coordinate/sign choices belong to fitting. Writers may round numbers but + must not rebase, reverse, clip or refit this result. + """ + + joint: str + motor_index: int + input_domain: str + knots: tuple[float, ...] + angle_rad: tuple[float, ...] + increasing_rad: tuple[float, ...] + decreasing_rad: tuple[float, ...] + transferred_from: str | None = None + + def __post_init__(self) -> None: + if not self.joint or self.motor_index < 0: + raise ValueError("mapping requires a joint and a valid SDK channel") + if self.input_domain not in {"feedback_rad", "command_rad", "feedback_u8", "command_u8"}: + raise ValueError("mapping requires an explicit SDK input domain") + x = np.asarray(self.knots, dtype=float) + if x.ndim != 1 or x.size < 2 or not np.all(np.isfinite(x)) or np.any(np.diff(x) <= 0): + raise ValueError("mapping knots must be finite and strictly increasing") + for branch in (self.angle_rad, self.increasing_rad, self.decreasing_rad): + y = np.asarray(branch, dtype=float) + if y.shape != x.shape or not np.all(np.isfinite(y)): + raise ValueError("mapping curve must align with its native knots") + d = np.diff(y) + if not (np.all(d >= -1e-9) or np.all(d <= 1e-9)): + raise ValueError("mapping curve must be monotonic") + + @property + def bounds_rad(self) -> tuple[float, float]: + values = self.angle_rad + self.increasing_rad + self.decreasing_rad + return min(values), max(values) + + def evaluate(self, value: float, direction: str = "") -> float: + if direction not in {"", "increasing", "decreasing"}: + raise ValueError("invalid native SDK direction") + if not math.isfinite(value) or not self.knots[0] <= value <= self.knots[-1]: + raise ValueError(f"SDK input outside fitted support:{self.joint}:{value}") + branch = getattr(self, direction + "_rad") if direction else self.angle_rad + # Commands become actual wire bytes. Feedback can be interpolated + # between CAN receipts at an image's exposure time and stays continuous. + if self.input_domain == "command_u8": + value = math.floor(value + 0.5) + return float(np.interp(value, self.knots, branch)) + + +def evaluate_mappings( + mappings: Mapping[str, JointMapping], sdk_values: Sequence[float], + directions: Mapping[str, str], +) -> dict[str, float]: + result = {} + for joint, mapping in mappings.items(): + if joint != mapping.joint or mapping.motor_index >= len(sdk_values): + raise ValueError("mapping/SDK vector contract differs") + result[joint] = mapping.evaluate(float(sdk_values[mapping.motor_index]), directions.get(joint, "")) + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/sample_schema.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/sample_schema.py new file mode 100644 index 0000000..a39bddd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/sample_schema.py @@ -0,0 +1,192 @@ +"""Canonical command/feedback schema for calibration observations. + +The hand command and its measured motor feedback are different physical +domains. Durable samples always retain both. Fitting code may still use the +historical ``command_u8`` key, but it is created only as an explicit projection +of a canonical record at the fitting boundary. +""" + +from __future__ import annotations + +import math +from typing import Any, Iterable, Literal, Mapping + +import numpy as np + + +SAMPLE_KINDS = frozenset( + { + 'sample', + 'baseline_hold_sample', + 'steady_command_sample', + 'palm_axis_sample', + } +) + +FitDomain = Literal['default', 'requested', 'feedback'] + + +class SampleDataContractError(ValueError): + """A calibration observation mixes or omits command domains.""" + + +def _finite_u8(value: Any, field: str, *, integral: bool) -> int | float: + try: + number = float(value) + except (TypeError, ValueError) as error: + raise SampleDataContractError( + f'DATA-CONTRACT-701:{field} must be numeric' + ) from error + if not math.isfinite(number) or not 0.0 <= number <= 255.0: + raise SampleDataContractError( + f'DATA-CONTRACT-701:{field} must be finite and in [0, 255]' + ) + if integral: + rounded = int(round(number)) + if not math.isclose(number, rounded, rel_tol=0.0, abs_tol=1.0e-9): + raise SampleDataContractError( + f'DATA-CONTRACT-701:{field} must be an integer command' + ) + return rounded + return number + + +def explicit_domain_value( + source: Mapping[str, Any], domain: Literal['requested', 'feedback'] +) -> int | float: + """Read and validate one explicitly named domain from any observation.""" + field = ( + 'requested_command_u8' if domain == 'requested' else 'feedback_u8' + ) + if field not in source or source[field] is None: + raise SampleDataContractError( + f'DATA-CONTRACT-701:observation is missing explicit {field}' + ) + return _finite_u8(source[field], field, integral=domain == 'requested') + + +def canonical_sample_record( + source: Mapping[str, Any], + *, + allow_legacy_command: bool = False, +) -> dict[str, Any]: + """Return one durable, unambiguous calibration observation. + + ``allow_legacy_command`` is restricted to importing historical sessions + and unit fixtures. New online observations must provide both explicit + fields and therefore cannot silently reinterpret ``command_u8``. + """ + record = dict(source) + kind = str(record.get('kind', '')) + if not kind and allow_legacy_command: + # Old in-memory steady-curve fixtures predate durable sample kinds. + # This adapter is never enabled by the new online/import contract. + kind = 'steady_command_sample' + record['kind'] = kind + if kind not in SAMPLE_KINDS: + raise SampleDataContractError( + f'DATA-CONTRACT-701:unsupported calibration sample kind {kind!r}' + ) + + requested = record.get('requested_command_u8') + feedback = record.get('feedback_u8') + legacy = record.get('command_u8') + if requested is None or feedback is None: + if not allow_legacy_command or legacy is None: + missing = [ + name + for name, value in ( + ('requested_command_u8', requested), + ('feedback_u8', feedback), + ) + if value is None + ] + raise SampleDataContractError( + 'DATA-CONTRACT-701:' + f'{kind} is missing explicit {",".join(missing)}' + ) + # Historical in-memory records used requested commands for settled + # checkpoints and feedback bins for dense/baseline/palm observations. + if requested is None: + requested = legacy + if feedback is None: + feedback = legacy + + record.pop('command_u8', None) + record['requested_command_u8'] = explicit_domain_value( + {'requested_command_u8': requested}, 'requested' + ) + record['feedback_u8'] = explicit_domain_value( + {'feedback_u8': feedback}, 'feedback' + ) + return record + + +def fitting_sample_record( + source: Mapping[str, Any], + *, + domain: FitDomain = 'default', + allow_legacy_command: bool = False, + snap_requested_endpoints: bool = False, +) -> dict[str, Any]: + """Project a canonical sample into the legacy curve-fitter interface.""" + record = canonical_sample_record( + source, allow_legacy_command=allow_legacy_command + ) + kind = str(record['kind']) + selected = domain + if selected == 'default': + selected = ( + 'requested' if kind == 'steady_command_sample' else 'feedback' + ) + if selected not in {'requested', 'feedback'}: + raise SampleDataContractError( + f'DATA-CONTRACT-701:unsupported fitting domain {domain!r}' + ) + requested = int(record['requested_command_u8']) + if selected == 'requested' or ( + snap_requested_endpoints and requested in {0, 255} + ): + index = requested + else: + index = int( + np.clip(np.rint(float(record['feedback_u8'])), 0, 255) + ) + record['command_u8'] = index + return record + + +def fitting_sample_records( + records: Iterable[Mapping[str, Any]], + *, + domain: FitDomain = 'default', + allow_legacy_command: bool = False, + snap_requested_endpoints: bool = False, +) -> list[dict[str, Any]]: + """Project several canonical samples into one explicit fitting domain.""" + return [ + fitting_sample_record( + record, + domain=domain, + allow_legacy_command=allow_legacy_command, + snap_requested_endpoints=snap_requested_endpoints, + ) + for record in records + ] + + +def validate_sample_records( + records: Iterable[Mapping[str, Any]], + *, + allow_legacy_command: bool = False, +) -> None: + """Validate a collection without changing its representation.""" + for index, record in enumerate(records): + try: + canonical_sample_record( + record, allow_legacy_command=allow_legacy_command + ) + except SampleDataContractError as error: + raise SampleDataContractError( + f'{error};record_index={index}' + ) from error diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/sampling.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/sampling.py new file mode 100644 index 0000000..a2ddcbf --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/sampling.py @@ -0,0 +1,32 @@ +"""The declared command nodes used by acquisition and fitting alike.""" + +import numpy as np + + +def command_training_cycles(profile, task=None, *, joint=None): + from .capture_plan import task_partition + return task_partition(profile, task, joint=joint).command_training + + +def command_holdout_cycle(profile): + from .capture_plan import task_partition + return task_partition(profile).command_holdout + + +def command_nodes(profile, task, *, holdout=False): + lo, hi = sorted((task.start_value, task.end_value)) + train = np.linspace(lo, hi, profile.acquisition.steady_training_nodes) + train = np.unique(np.r_[train, profile.acquisition.steady_extra_training_nodes.get(task.key, ())]) + if profile.artifacts.output_schema_version >= 3: + from .motion_path import task_channels + baselines = [profile.command.baseline_values[i] for i in task_channels(task)] + if any(not lo <= baseline <= hi for baseline in baselines): + raise ValueError(f"baseline_outside_calibrated_support:{task.key}") + train = np.unique(np.r_[train, baselines]) + if task.segments: + boundaries = [v for s in task.segments for i, v in (*s.start_commands, *s.end_commands)] + train = np.unique(np.r_[train, boundaries]) + values = np.r_[lo, (train[:-1]+train[1:])/2, hi] if holdout else train + if profile.command.unit == "u8": + values = np.floor(values+.5) + return tuple(sorted(set(float(v) for v in values))) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/status.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/status.py new file mode 100644 index 0000000..2a81cc6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/status.py @@ -0,0 +1,85 @@ +"""Model-independent progress and failure status contracts.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +from typing import Any, Mapping + + +@dataclass(frozen=True) +class TaskStatus: + key: str = "" + label: str = "" + cycle: int | None = None + cycle_count: int = 4 + direction: str = "" + capture_stage: str = "motion" + required_tag_ids_by_view: Mapping[str, tuple[int, ...]] = field( + default_factory=dict + ) + segment_key: str = "" + segment_commands: Mapping[str, tuple[float, float]] = field(default_factory=dict) + + +@dataclass(frozen=True) +class MotionStatus: + channel: str = "" + command: float | None = None + feedback: float | None = None + unit: str = "" + speed: float | None = None + + +@dataclass(frozen=True) +class AcquisitionStatus: + valid_samples: int = 0 + minimum_samples: int = 40 + coverage_01: float = 0.0 + bins: int = 0 + maximum_gap: int = 0 + retry_count: int = 0 + warnings: tuple[str, ...] = () + + +@dataclass(frozen=True) +class PauseStatus: + code: str = "" + reason: str = "" + suggestion: str = "" + details: Mapping[str, Any] = field(default_factory=dict) + + +@dataclass(frozen=True) +class CalibrationStatus: + """Stable payload rendered by the one common product runner.""" + + schema_version: int = 1 + state: str = "WAIT_DEVICE" + phase: str = "" + overall_progress_01: float = 0.0 + estimated_remaining_seconds: float | None = None + reference_locked: bool = False + reference_message: str = "" + task: TaskStatus = field(default_factory=TaskStatus) + recognized_tag_ids: tuple[int, ...] = () + missing_tag_ids: tuple[int, ...] = () + rejected_tag_ids: tuple[int, ...] = () + motion: MotionStatus = field(default_factory=MotionStatus) + acquisition: AcquisitionStatus = field(default_factory=AcquisitionStatus) + resume: Mapping[str, Any] = field(default_factory=dict) + hardware: Mapping[str, Any] = field(default_factory=dict) + pause: PauseStatus = field(default_factory=PauseStatus) + log_path: str = "" + outputs: Mapping[str, str] = field(default_factory=dict) + + def as_dict(self) -> dict[str, Any]: + return asdict(self) + + +__all__ = [ + "AcquisitionStatus", + "CalibrationStatus", + "MotionStatus", + "PauseStatus", + "TaskStatus", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/domain/task.py b/src/linkerhand_calibration/linkerhand_calibration/core/domain/task.py new file mode 100644 index 0000000..87d4e16 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/domain/task.py @@ -0,0 +1,19 @@ +"""Shared task direction vocabulary.""" + +DIRECTION_DECREASING = "decreasing" +DIRECTION_INCREASING = "increasing" +DIRECTIONS: tuple[str, ...] = ( + DIRECTION_DECREASING, + DIRECTION_INCREASING, +) + +PHASE_ROOT = "root" +PHASE_TIP = "tip" + +__all__ = [ + "DIRECTION_DECREASING", + "DIRECTION_INCREASING", + "DIRECTIONS", + "PHASE_ROOT", + "PHASE_TIP", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/__init__.py new file mode 100644 index 0000000..2bdcb99 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/__init__.py @@ -0,0 +1,19 @@ +"""Pure curve and axis fitting.""" + +from .curve import FitResult, isotonic_nonincreasing +from .coupling import ( + CouplingFit, LinearMimicFit, PairedJointObservation, RelativeMimicEvidence, + curve_travel_rad, fit_coupling_model, fit_standard_mimic, fit_relative_standard_mimic, +) +from .rotation_curve import RotationCurve, RotationObservation, fit_rotation_curve + +__all__ = [ + "CouplingFit", + "FitResult", + "curve_travel_rad", + "fit_coupling_model", + "isotonic_nonincreasing", + "LinearMimicFit", "PairedJointObservation", "RelativeMimicEvidence", + "fit_standard_mimic", "fit_relative_standard_mimic", + "RotationCurve", "RotationObservation", "fit_rotation_curve", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/anchored_mapping.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/anchored_mapping.py new file mode 100644 index 0000000..30afd8c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/anchored_mapping.py @@ -0,0 +1,22 @@ +"""Training-only monotonic projection with an exact, already observed zero.""" + +import math +import numpy as np + +from .curve import isotonic_nonincreasing + + +def anchored_mean(knots, increasing, decreasing, baseline, sign): + x = np.asarray(knots, dtype=float) + values = (np.asarray(increasing) + decreasing) / 2 + indices = np.flatnonzero(np.isclose(x, baseline, atol=1e-9, rtol=0)) + if len(indices) != 1: + raise ValueError("baseline_requires_an_observed_training_knot") + i = int(indices[0]) + oriented = values * sign + left = np.minimum(-isotonic_nonincreasing(-oriented[:i]), 0) if i else [] + right = np.maximum(-isotonic_nonincreasing(-oriented[i+1:]), 0) if i+1 < len(x) else [] + fitted = np.r_[left, 0.0, right] * sign + if np.max(np.abs(fitted-values)) > math.radians(1): + raise ValueError("baseline_constraint_inconsistent_with_training") + return tuple(float(v) for v in fitted) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/circle_geometry.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/circle_geometry.py new file mode 100644 index 0000000..a3951b3 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/circle_geometry.py @@ -0,0 +1,144 @@ +"""Generic circular statistics and robust image-plane circle fitting.""" +from __future__ import annotations +import math +from typing import Sequence +import numpy as np +from scipy.optimize import least_squares + +def wrap_angle_rad(angle_rad: float) -> float: + """Wrap one finite angle to [-pi, pi).""" + angle = float(angle_rad) + if not math.isfinite(angle): + raise ValueError("angle must be finite") + return (angle + math.pi) % (2.0 * math.pi) - math.pi + + +def signed_angle_difference_rad(angle_rad: float, reference_rad: float) -> float: + """Return the wrapped signed rotation from reference to angle.""" + return wrap_angle_rad(float(angle_rad) - float(reference_rad)) + + +def circular_mean_rad(angles_rad: Sequence[float]) -> float: + """Return the circular mean of at least one finite angle.""" + angles = np.asarray(angles_rad, dtype=float) + if angles.ndim != 1 or angles.size == 0 or not np.all(np.isfinite(angles)): + raise ValueError("angles_rad must contain finite angles") + vector = complex( + float(np.mean(np.cos(angles))), + float(np.mean(np.sin(angles))), + ) + if abs(vector) < 1.0e-12: + raise ValueError("angles do not have a unique circular mean") + return wrap_angle_rad(math.atan2(vector.imag, vector.real)) + + +def circular_median_rad(angles_rad: Sequence[float]) -> float: + """Return a robust circular median around the circular mean.""" + angles = np.asarray(angles_rad, dtype=float) + reference = circular_mean_rad(angles) + deltas = np.asarray( + [signed_angle_difference_rad(value, reference) for value in angles], + dtype=float, + ) + return wrap_angle_rad(reference + float(np.median(deltas))) + + +def circular_std_rad(angles_rad: Sequence[float]) -> float: + """Return circular standard deviation in radians.""" + angles = np.asarray(angles_rad, dtype=float) + if angles.ndim != 1 or angles.size == 0 or not np.all(np.isfinite(angles)): + raise ValueError("angles_rad must contain finite angles") + resultant = float( + math.hypot( + float(np.mean(np.cos(angles))), + float(np.mean(np.sin(angles))), + ) + ) + resultant = min(1.0, max(1.0e-15, resultant)) + return math.sqrt(max(0.0, -2.0 * math.log(resultant))) + + +def maximum_pairwise_angle_difference_rad( + angles_rad: Sequence[float], +) -> float: + """Return the largest wrapped distance between any two angles.""" + angles = [float(value) for value in angles_rad] + if not angles or not all(math.isfinite(value) for value in angles): + raise ValueError("angles_rad must contain finite angles") + return max( + ( + abs(signed_angle_difference_rad(left, right)) + for index, left in enumerate(angles) + for right in angles[index + 1:] + ), + default=0.0, + ) + + +def _fit_circle(points_xy: np.ndarray) -> tuple[np.ndarray, float]: + """Fit a geometric circle with robust nonlinear least squares.""" + points = np.asarray(points_xy, dtype=float) + if points.ndim != 2 or points.shape[1] != 2 or len(points) < 3: + raise ValueError("circle fit requires at least three 2D points") + origin = np.mean(points, axis=0) + centered = points - origin + matrix = np.column_stack( + (2.0 * centered[:, 0], 2.0 * centered[:, 1], np.ones(len(points))) + ) + rhs = np.sum(np.square(centered), axis=1) + solution, _, rank, _ = np.linalg.lstsq(matrix, rhs, rcond=None) + if rank < 3: + raise ValueError("trajectory points are degenerate") + centre0 = solution[:2] + origin + radius0_squared = ( + float(solution[2]) + float(np.dot(solution[:2], solution[:2])) + ) + if radius0_squared <= 0.0: + raise ValueError("trajectory circle radius is invalid") + radius0 = math.sqrt(radius0_squared) + + def residual(parameters: np.ndarray) -> np.ndarray: + centre = parameters[:2] + radius = parameters[2] + return np.linalg.norm(points - centre, axis=1) - radius + + initial_error = residual(np.asarray([*centre0, radius0], dtype=float)) + robust_scale = max( + 0.25, + 1.4826 + * float( + np.median( + np.abs(initial_error - float(np.median(initial_error))) + ) + ), + ) + result = least_squares( + residual, + np.asarray([*centre0, radius0], dtype=float), + loss="soft_l1", + f_scale=robust_scale, + max_nfev=1000, + ) + centre = np.asarray(result.x[:2], dtype=float) + radius = float(abs(result.x[2])) + if not result.success or not np.all(np.isfinite(centre)): + raise ValueError("trajectory circle optimization failed") + if not math.isfinite(radius) or radius <= 0.0: + raise ValueError("trajectory circle radius is invalid") + return centre, radius + + +def _trajectory_arc_rad(points_xy: np.ndarray, centre_xy: np.ndarray) -> float: + angles = np.mod( + np.arctan2( + points_xy[:, 1] - centre_xy[1], + points_xy[:, 0] - centre_xy[0], + ), + 2.0 * math.pi, + ) + if len(angles) < 2: + return 0.0 + angles = np.sort(angles) + gaps = np.diff(np.r_[angles, angles[0] + 2.0 * math.pi]) + return float(2.0 * math.pi - np.max(gaps)) + diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_mapping.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_mapping.py new file mode 100644 index 0000000..99e80d7 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_mapping.py @@ -0,0 +1,168 @@ +"""Steady command calibration against independently observed Tag angles. + +Feedback is NOT a command label and is never the target of this regression. +The visual reference/axis was frozen by the continuous training acquisition. +""" + +from dataclasses import asdict, replace +import math +import numpy as np + +from ..domain.result import JointMapping +from ..urdf.acceptance import angular_metrics +from .curve import isotonic_nonincreasing +from .spatial import measure_joint_curve_observation +from ..domain.sampling import command_nodes, command_training_cycles, command_holdout_cycle +from ..domain.motion_path import task_channels + + +def fit_command_mappings(profile, fit, records_by_joint): + mappings, metrics, applicability = fit_command_observations(profile, fit.curves, records_by_joint, + channels={name: mapping.motor_index for name, mapping in fit.output_mappings.items()}, + reference_inputs=fit.reference_inputs, zero_references=fit.joint_zero_references) + return replace(fit, command_mappings=mappings, command_holdout_metrics=metrics, + command_applicability=applicability) + + +def fit_command_training(profile, curves, records_by_joint, *, channels, reference_inputs, zero_references): + """Fit stable command labels to angles measured in frozen visual frames.""" + mappings, metrics, applicability = {}, {}, {} + holdout_cycle = command_holdout_cycle(profile) + for joint in sorted(channels): + donor = joint if profile.artifacts.output_schema_version >= 3 else profile.zero.transferred_zero_sources.get(joint, joint) + rows = records_by_joint.get(donor, ()) + if not rows or any(r.get("sample_phase") != "steady" for r in rows): + raise ValueError(f"steady_command_observations_missing:{joint}") + training_cycles = command_training_cycles(profile, joint=donor) + if any(r["cycle"] not in training_cycles for r in rows): + raise ValueError("command_training_received_nontraining_data") + curve = curves[donor] + gauge = 0.0 + # Byte curves already carry their shared coordinate reference. Native + # curves retain the arbitrary observed Tag reference in fit.curves. + if profile.command.unit != "u8" and profile.artifacts.output_schema_version < 3: + gauge = float(np.interp(reference_inputs[donor], curve.circle["input_knots"], curve.angle_rad)) + observed = {r["sample_id"]: measure_joint_curve_observation(curve, + quaternion_xyzw=r.get("relative_quaternion_xyzw"), + image_relative_xy_px=r.get("image_relative_xy_px"))-gauge for r in rows} + if len(observed) != len(rows): + raise ValueError("duplicate steady visual image") + channel = channels[joint] + source_channel = channels[donor] + branches = {} + maximum_correction = 0.0 + directional = joint in profile.artifacts.directional_command_joints + task = next(t for t in profile.motion.tasks if donor in t.joints) + from .command_sampling import declared_training_nodes + knots = declared_training_nodes(profile, task, rows) + sign = profile.command.joint_directions[source_channel] + if profile.artifacts.output_schema_version >= 3 and not profile.command_based_release: + sign = 1 if curve.angle_rad[-1] > curve.angle_rad[0] else -1 + for direction in ("increasing", "decreasing"): + values = [] + for knot in knots: + medians = [] + for cycle in training_cycles: + selected = [r for r in rows if r["cycle"] == cycle and r["direction"] == direction + and math.isclose(float(r["steady_target"]), knot, abs_tol=1e-9)] + if len(selected) < profile.acquisition.steady_minimum_samples: + raise ValueError(f"steady_training_incomplete:{joint}:{cycle}:{direction}:{knot}") + for r in selected: + if not math.isclose(float(r[f"command_{profile.command.unit}"]), knot, abs_tol=1e-9): + raise ValueError("steady observation captured during command motion") + medians.append(float(np.median([observed[r["sample_id"]] for r in selected]))) + values.append(float(np.median(medians))) + values = np.asarray(values) + projected = -sign*isotonic_nonincreasing(-sign*values) + maximum_correction = max(maximum_correction, float(np.max(np.abs(projected-values)))) + if maximum_correction > math.radians(1): + raise ValueError(f"steady_command_not_monotonic:{joint}:{direction}") + branches[direction] = tuple(float(v) for v in projected) + if directional: + from .anchored_mapping import anchored_mean + branches = {direction: anchored_mean(knots, values, values, + zero_references[joint].baseline_command, sign) + for direction, values in branches.items()} + mean = tuple((a+b)/2 for a, b in zip(branches["increasing"], branches["decreasing"])) + if profile.artifacts.output_schema_version >= 3: + from .anchored_mapping import anchored_mean + mean = anchored_mean(knots, branches["increasing"], branches["decreasing"], + zero_references[joint].baseline_command, sign) + mapping = JointMapping(joint, channel, f"command_{profile.command.unit}", knots, + mean, branches["increasing"], branches["decreasing"], donor if donor != joint else None) + mappings[joint] = mapping + metrics[joint] = {"maximum_monotonic_correction_rad": maximum_correction, + "independently_measured": donor == joint, "source_joint": donor, + "training_cycles": list(training_cycles), "holdout_cycle": holdout_cycle, + "training_sample_ids": sorted(r["sample_id"] for r in rows)} + training = [r for r in rows if r["cycle"] in training_cycles] + vectors = np.asarray([r[f"command_vector_{profile.command.unit}"] for r in training]) + held = {str(i): float(np.median(vectors[:, i])) for i in range(profile.command.command_count) + if i not in task_channels(task)} + for i, value in held.items(): + if np.max(np.abs(vectors[:, int(i)]-value)) > 1e-8: + raise ValueError(f"scan_changed_multiple_command_channels:{donor}:{i}") + applicability[joint] = {"task": task.key, "held_command_values": held, + "scope": "declared_multi_channel_path" if task.segments else "single_channel_at_declared_pose", "arbitrary_multiaxis_validated": False, + "branch_initialization": "recorded_baseline_then_endpoint_resets" if task.segments else "full_range_endpoint_reset"} + if task.segments: + applicability[joint]["motion_segments"] = [asdict(s) for s in task.segments] + if directional: + applicability[joint].update(command_mapping="directional", direction_source="raw_sdk_input", + interior_reversals_validated=False) + return mappings, metrics, applicability + + +def validate_command_training(profile, curves, mappings, metrics, records_by_joint, *, reference_inputs): + """Evaluate independent images against already frozen frames and mappings.""" + holdout_cycle = command_holdout_cycle(profile) + accepted = {} + for joint, mapping in mappings.items(): + donor = metrics[joint]["source_joint"] + curve = curves[donor] + rows = records_by_joint.get(donor, ()) + if not rows or any(r["cycle"] != holdout_cycle or r.get("sample_phase") != "steady" for r in rows): + raise ValueError(f"steady_holdout_incomplete:{joint}") + ids = [r["sample_id"] for r in rows] + trained = set(metrics[joint]["training_sample_ids"]) | set(curve.circle.get("training_sample_ids", ())) + if len(ids) != len(set(ids)) or trained.intersection(ids): + raise ValueError("command_holdout_image_identity_overlaps_training") + task = next(t for t in profile.motion.tasks if donor in t.joints) + for direction in ("increasing", "decreasing"): + for knot in command_nodes(profile, task, holdout=True): + if sum(r["direction"] == direction and math.isclose(float(r["steady_target"]), knot, abs_tol=1e-9) + for r in rows) < profile.acquisition.steady_minimum_samples: + raise ValueError(f"steady_holdout_incomplete:{joint}:{direction}:{knot}") + gauge = (float(np.interp(reference_inputs[donor], curve.circle["input_knots"], curve.angle_rad)) + if profile.command.unit != "u8" and profile.artifacts.output_schema_version < 3 else 0.) + directional = joint in profile.artifacts.directional_command_joints + errors = [mapping.evaluate(float(r[f"command_{profile.command.unit}"]), + r["direction"] if directional or profile.artifacts.output_schema_version < 3 else "") + - measure_joint_curve_observation(curve, quaternion_xyzw=r.get("relative_quaternion_xyzw"), + image_relative_xy_px=r.get("image_relative_xy_px")) + gauge for r in rows] + quality = angular_metrics(errors) + if not quality.passed: + raise ValueError(f"steady_command_holdout_failed:{joint}:{quality}") + accepted[joint] = {**metrics[joint], **asdict(quality)} + if profile.artifacts.output_schema_version >= 3: + branches = {direction: angular_metrics([error for error, row in zip(errors, rows) + if row["direction"] == direction]) for direction in ("increasing", "decreasing")} + if not all(value.passed for value in branches.values()): + raise ValueError(f"command_curve_direction_holdout_failed:{joint}") + accepted[joint]["by_direction"] = {key: asdict(value) for key, value in branches.items()} + return accepted + + +def fit_command_observations(profile, curves, records_by_joint, *, channels, reference_inputs, zero_references): + training, validation = {}, {} + for name, rows in records_by_joint.items(): + cycles = command_training_cycles(profile, joint=name) + holdout = command_holdout_cycle(profile) + if any(row["cycle"] not in (*cycles, holdout) for row in rows): + raise ValueError("command_observation_outside_capture_plan") + training[name] = [row for row in rows if row["cycle"] in cycles] + validation[name] = [row for row in rows if row["cycle"] == holdout] + mappings, metrics, applicability = fit_command_training(profile, curves, training, + channels=channels, reference_inputs=reference_inputs, zero_references=zero_references) + return mappings, validate_command_training(profile, curves, mappings, metrics, validation, + reference_inputs=reference_inputs), applicability diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_motion.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_motion.py new file mode 100644 index 0000000..9c07067 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_motion.py @@ -0,0 +1,114 @@ +"""Command-certified motion with an independent, non-blocking feedback diagnostic. + +Moving images determine only a hinge frame. Stable commanded poses train the +control curves. A fourth cycle never contributes to either training stage. +""" + +from dataclasses import asdict, dataclass, replace +import numpy as np + +from ..domain.measurement import JointCurveFit +from ..urdf.acceptance import angular_metrics +from .command_mapping import fit_command_training as train_commands, validate_command_training +from ..domain.capture_plan import training_cycles, LEGACY_TRAINING, LEGACY_HOLDOUT +from ..domain.sampling import command_training_cycles, command_holdout_cycle +from .motion_fit import channel_for_joint, joint_input_direction +from .observed_motion import image_identity +from .rotation_curve import RotationObservation, fit_rotation_frame, fit_rotation_curve + + +def rotation_observations(rows, domain): + return [RotationObservation(image_identity(row), float(row[domain]), + tuple(row['relative_quaternion_xyzw']), int(row['cycle']), str(row['direction'])) for row in rows] + + +def feedback_diagnostic(rows, *, domain, sign, reference, cycles=LEGACY_TRAINING, holdout_cycle=LEGACY_HOLDOUT): + result = {'required_for_release': False, 'input_domain': domain, 'training_cycles': list(cycles), + 'holdout_cycle': holdout_cycle, 'extrapolation': 'reject'} + try: + if any(row.get(domain) is None or not np.isfinite(row[domain]) for row in rows): + raise ValueError('position_feedback_missing_or_invalid') + observations = rotation_observations(rows, domain) + curve = fit_rotation_curve([r for r in observations if r.cycle in cycles], + input_domain=domain, sdk_to_joint_direction=sign, reference_xyzw=reference, + training_cycles=cycles, holdout_cycle=holdout_cycle) + held = [r for r in observations if r.cycle == holdout_cycle] + supported = [r for r in held if curve.knots[0] <= r.input_value <= curve.knots[-1]] + outside = [r for r in held if not curve.knots[0] <= r.input_value <= curve.knots[-1]] + quality = angular_metrics(curve.holdout_errors(supported)) if supported else None + metrics = {**asdict(quality), 'passed': quality.passed} if quality else None + result.update(status='passed' if held and not outside and metrics and metrics['passed'] else 'incomplete_or_inaccurate', + training_support=[curve.knots[0], curve.knots[-1]], holdout_samples=len(held), + outside_training_support=len(outside), outside_image_ids=[r.sample_id for r in outside], + supported_holdout_metrics=metrics, mapping={**asdict(curve), + "training_sample_ids": sorted(curve.training_sample_ids)}) + except (ValueError, TypeError) as error: + result.update(status='unavailable', reason=str(error)) + return result + + +@dataclass(frozen=True) +class CommandMotionFit: + observed_curves: dict + coordinate_curves: dict + mappings: dict + command_metrics: dict + applicability: dict + reference_inputs: dict + feedback_diagnostics: dict + + @property + def holdout_errors_rad(self): + # Command errors are retained with their per-direction metrics. + return {} + + @property + def cross_view_metrics(self): + return {} + + +def fit_command_training(profile, source_model, sweep, steady, references): + """Training-only motion API. Passing a holdout image is a contract error.""" + if set(sweep) != set(steady) or set(sweep) != set(references): + raise ValueError('command_motion_observation_coverage_differs') + frames = {} + channels = {name: channel_for_joint(profile, name) for name in sweep} + for name, rows in sweep.items(): + cycles = training_cycles(profile, joint=name) + if any(row['cycle'] not in cycles for row in rows): + raise ValueError('motion_training_received_nontraining_data') + view = profile.measurement.measurements[name].view + frames[name] = fit_rotation_frame(rotation_observations(rows, f'command_{profile.command.unit}'), + sdk_to_joint_direction=joint_input_direction(profile, source_model, name), + reference_xyzw=references[name].quaternion(view), training_cycles=cycles) + inputs = {name: references[name].baseline_command for name in frames} + mappings, metrics, applicability = train_commands(profile, frames, steady, + channels=channels, reference_inputs=inputs, zero_references=references) + curves = {} + for name, mapping in mappings.items(): + curves[name] = JointCurveFit(mapping.angle_rad, mapping.decreasing_rad, mapping.increasing_rad, + {**frames[name].circle, 'input_domain': mapping.input_domain, 'input_knots': mapping.knots, + 'mapping_training_sample_ids': metrics[name]['training_sample_ids']}, + metrics[name]["maximum_monotonic_correction_rad"], + float(np.max(np.abs(np.array(mapping.increasing_rad)-mapping.decreasing_rad))), {}) + return CommandMotionFit(curves, curves, mappings, metrics, applicability, inputs, {}) + + +def fit_command_motion(profile, source_model, sweep, steady, references, *, frozen_motion=None): + train_sweep = {name: [r for r in rows if r['cycle'] in training_cycles(profile, joint=name)] + for name, rows in sweep.items()} + train_steady = {name: [r for r in rows if r['cycle'] in command_training_cycles(profile, joint=name)] + for name, rows in steady.items()} + motion = frozen_motion or fit_command_training(profile, source_model, train_sweep, train_steady, references) + held = {name: [r for r in rows if r['cycle'] == command_holdout_cycle(profile)] + for name, rows in steady.items()} + metrics = validate_command_training(profile, motion.coordinate_curves, + motion.mappings, motion.command_metrics, held, reference_inputs=motion.reference_inputs) + diagnostics = {} + for name, rows in sweep.items(): + view = profile.measurement.measurements[name].view + diagnostics[name] = feedback_diagnostic(rows, + domain=f'feedback_{profile.command.unit}', sign=joint_input_direction(profile, source_model, name), + reference=references[name].quaternion(view), cycles=training_cycles(profile, joint=name), + holdout_cycle=profile.quality.holdout_cycle) + return replace(motion, command_metrics=metrics, feedback_diagnostics=diagnostics) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_sampling.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_sampling.py new file mode 100644 index 0000000..77165c8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_sampling.py @@ -0,0 +1,149 @@ +"""Training-only reduction of static command knots with immutable evidence. + +The continuous curve chooses where to stop, never supplies a static command +angle. Every retained static knot is measured afresh in both directions. The +original independent validation grid and all publication gates remain intact. +""" + +import hashlib +import json +import math + +import numpy as np + +from ..domain.sampling import command_nodes +from ..domain.profile import observation_streams +from .rotation_curve import RotationObservation, fit_rotation_curve +from ..domain.motion_path import record_scan_identity, segment_metadata +from ..domain.capture_plan import training_cycles + + +SAMPLING_POLICY = "training_shape_static_knots_v1" +MAXIMUM_REMOVAL_ERROR_RAD = math.radians(.25) + + +def digest(value): + return hashlib.sha256(json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest() + + +def training_sources(profile, task, records): + cycles = training_cycles(profile, task) + streams = {(field, name, spec.view) for field, name, spec in observation_streams(profile, task)} + latest = {} + for row in records: + if row.get("task_name") == task.key and row.get("cycle") in cycles and row.get("direction"): + key = record_scan_identity(row) + latest[key] = max(latest.get(key, 0), int(row.get("attempt", 1))) + result = [] + for row in records: + if (row.get("task_name") != task.key or row.get("cycle") not in cycles + or row.get("sample_phase", "sweep") != "sweep" or "relative_quaternion_xyzw" not in row): + continue + if int(row.get("attempt", 1)) != latest.get(record_scan_identity(row)): + continue + for field, name, view in sorted(streams): + if row.get(field) == name and row.get("view") == view: + result.append({"field": field, "joint": name, "view": view, "cycle": row["cycle"], + "direction": row["direction"], "image_stamp_ns": row["image_stamp_ns"], + **segment_metadata(row.get("segment_key", "")), + "input": float(row[f"{'command' if profile.command_based_release else 'feedback'}_{profile.command.unit}"]), + "quaternion": list(row["relative_quaternion_xyzw"])}) + return sorted(result, key=lambda row: (row["field"], row["joint"], row["view"], row["image_stamp_ns"])) + + +def reduced_knots(grid, curves, mandatory): + """Shortest path through the original grid; each omitted knot is bounded.""" + grid, values = np.asarray(grid), np.asarray(curves) + paths = {0: (0,)} + for end in range(1, len(grid)): + candidates = [] + for start, path in paths.items(): + if any(start < index < end for index in mandatory): + continue + fraction = (grid[start:end+1]-grid[start])/(grid[end]-grid[start]) + prediction = values[:, start, None] + (values[:, end]-values[:, start])[:, None]*fraction + if np.max(np.abs(prediction-values[:, start:end+1])) <= MAXIMUM_REMOVAL_ERROR_RAD: + candidates.append((*path, end)) + paths[end] = min(candidates, key=lambda path: (len(path), path)) + return tuple(float(grid[index]) for index in paths[len(grid)-1]) + + +def build_sampling_plan(profile, task, records): + sources = training_sources(profile, task, records) + grid = command_nodes(profile, task) + knots, reason = grid, "full_grid_insufficient_training_shape" + curves = [] + if task.segments: + reason = "segmented_motion_preserves_full_per_joint_grid" + else: + try: + for field, name, spec in observation_streams(profile, task): + rows = [row for row in sources if (row["field"], row["joint"], row["view"]) == (field, name, spec.view)] + observations = [RotationObservation(f"{row['view']}:{row['image_stamp_ns']}", row["input"], + tuple(row["quaternion"]), row["cycle"], row["direction"]) for row in rows] + fitted = fit_rotation_curve(observations, input_domain=f"{'command' if profile.command_based_release else 'feedback'}_{profile.command.unit}", + sdk_to_joint_direction=profile.command.joint_directions[task.command_index], + training_cycles=training_cycles(profile, task), holdout_cycle=profile.quality.holdout_cycle) + if fitted.maximum_monotonic_correction_rad > MAXIMUM_REMOVAL_ERROR_RAD: + raise ValueError("training_shape_noisy") + for branch in (fitted.increasing_rad, fitted.decreasing_rad): + curves.append(np.interp(grid, fitted.knots, branch)) + mandatory_values = {grid[0], grid[-1], grid[len(grid)//2], + profile.command.baseline_values[task.command_index], + *profile.acquisition.steady_extra_training_nodes.get(task.key, ())} + mandatory = {i for i, value in enumerate(grid) if value in mandatory_values} + knots = reduced_knots(grid, curves, mandatory) + reason = "training_shape_bounded" if len(knots) < len(grid) else "full_grid_required_by_training_shape" + except (ValueError, KeyError, TypeError, np.linalg.LinAlgError) as error: + reason = "full_grid:" + str(error) + plan = {"kind": "command_sampling_plan", "policy": SAMPLING_POLICY, "task_name": task.key, + "training_nodes": list(knots), "validation_nodes": list(command_nodes(profile, task, holdout=True)), + "source_sha256": digest(sources), "source_count": len(sources), "training_cycles": list(training_cycles(profile, task)), + "maximum_removal_error_rad": MAXIMUM_REMOVAL_ERROR_RAD, "reason": reason} + return {**plan, "plan_sha256": digest(plan)} + + +def declared_training_nodes(profile, task, records): + """Read a plan in complete journals or self-contained individual units.""" + declarations = set() + for row in records: + if row.get("task_name") != task.key: + continue + if row.get("kind") == "command_sampling_plan": + if digest({k: v for k, v in row.items() if k != "plan_sha256"}) != row.get("plan_sha256"): + raise ValueError("command_sampling_plan_hash_changed") + declarations.add(tuple(row["training_nodes"])) + elif row.get("sample_phase") == "steady" and "steady_training_nodes" in row: + declarations.add(tuple(row["steady_training_nodes"])) + if len(declarations) > 1: + raise ValueError("command_sampling_plan_conflict") + if not declarations: + return command_nodes(profile, task) + nodes = next(iter(declarations)) + allowed = set(command_nodes(profile, task)) + if (len(nodes) < 3 or tuple(sorted(set(nodes))) != nodes or not set(nodes) <= allowed + or nodes[0] != min(allowed) or nodes[-1] != max(allowed)): + raise ValueError("command_sampling_nodes_invalid") + return nodes + + +def validate_sampling_plans(profile, records): + plans = {} + for row in records: + if row.get("kind") == "command_sampling_plan": + task = next(task for task in profile.motion.tasks if task.key == row["task_name"]) + if row != build_sampling_plan(profile, task, records): + raise ValueError("command_sampling_training_evidence_changed") + if task.key in plans and plans[task.key] != row: + raise ValueError("command_sampling_plan_conflict") + plans[task.key] = row + required = any(row.get("command_sampling_policy") == SAMPLING_POLICY for row in records) + for row in records: + if row.get("sample_phase") != "steady" or "steady_target" not in row: + continue + plan = plans.get(row["task_name"]) + if required or "sampling_plan_sha256" in row: + if (plan is None or row.get("sampling_plan_sha256") != plan["plan_sha256"] + or list(row.get("steady_training_nodes", ())) != plan["training_nodes"]): + raise ValueError("command_sampling_sample_unbound") + return plans diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_support.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_support.py new file mode 100644 index 0000000..8ecaf6d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/command_support.py @@ -0,0 +1,77 @@ +"""Training-only support for the physically shared turnaround endpoints. + +The last incoming command owns the turnaround image. An unobserved outgoing +endpoint is a continuity constraint, never a second independent measurement. +Interior parameters and endpoints with actual directional evidence stay free. +""" +import numpy as np + + +TURNAROUND_POLICY = 'observed_turnaround_continuity_v1' + + +def compile_turnaround_constraints(bundle): + constraints = {} + for name, columns in bundle.curve_columns.items(): + channel = bundle.channels[name] + indices = sorted({int(index) for role, data in bundle.observations.items() + if any(joint.name == bundle.cad_names[name] for joint in bundle.chains[role]) + for index in data[0]}) + if not indices: + continue + commands = bundle.commands[indices, channel] + directions = bundle.directions[indices, channel] + for node in (0, len(bundle.knots[name])-1): + for recipient in (0, 1): + column = int(columns[recipient, node]) + # Unknown startup history observes the common endpoint; it + # does not independently identify the outgoing branch. + at_endpoint = commands == bundle.knots[name][node] + if column < 0 or np.any(at_endpoint & (directions == recipient)): + continue + donor = 1-recipient + sources = [bundle.rows[index] for index in indices + if bundle.commands[index, channel] == bundle.knots[name][node] + and bundle.directions[index, channel] == donor] + if not sources: + continue + constraints.setdefault(name, []).append(dict(node=node, recipient=recipient, + donor=donor, column=column, command=float(bundle.knots[name][node]), + source_sample_ids=sorted({f"{row['view']}:{row['image_stamp_ns']}" for row in sources}), + source_cycles=sorted({row['cycle'] for row in sources}))) + return constraints + + +def validate_turnaround_mapping(mapping, support): + """Read-back must preserve the saved constraint, including its sources.""" + if support is None: # Historical artifacts retain their old contract. + return + if support.get('policy') != TURNAROUND_POLICY or not isinstance(support.get('constraints'), list): + raise ValueError('invalid_turnaround_support:' + mapping.joint) + endpoints = support.get('endpoints', ()) + if (len(endpoints) != 2 or [row.get('command') for row in endpoints] + != [mapping.knots[0], mapping.knots[-1]]): + raise ValueError('invalid_turnaround_endpoints:' + mapping.joint) + for endpoint in endpoints: + if not endpoint.get('samples') or any( + sample.get('cycle') not in (0, 1) or not isinstance(sample.get('id'), str) + or not sample['id'] or sample.get('direction') not in ('', 'increasing', 'decreasing') + for sample in endpoint['samples']): + raise ValueError('invalid_turnaround_samples:' + mapping.joint) + branches = (mapping.increasing_rad, mapping.decreasing_rad) + seen = set() + for row in support['constraints']: + node, recipient, donor = row['node'], row['recipient'], row['donor'] + if (node not in (0, len(mapping.knots)-1) or recipient not in (0, 1) + or donor != 1-recipient or (node, recipient) in seen + or row['command'] != mapping.knots[node] + or not row['source_sample_ids'] or not row['source_cycles'] + or not set(row['source_cycles']) <= {0, 1} + or abs(branches[recipient][node]-branches[donor][node]) > 1e-10): + raise ValueError('turnaround_mapping_differs_from_evidence:' + mapping.joint) + seen.add((node, recipient)) + endpoint = endpoints[0 if node == 0 else 1] + observed = {sample['id'] for sample in endpoint['samples'] + if sample['direction'] == ('increasing', 'decreasing')[donor]} + if not observed.intersection(row['source_sample_ids']): + raise ValueError('turnaround_source_not_observed:' + mapping.joint) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/coupling.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/coupling.py new file mode 100644 index 0000000..0e4313d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/coupling.py @@ -0,0 +1,388 @@ +"""Model-independent active/passive joint coupling fitting.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Protocol, Sequence + +import numpy as np +from scipy.optimize import least_squares + + +class DirectionalCurve(Protocol): + decreasing_rad: Sequence[float] + increasing_rad: Sequence[float] + + +@dataclass(frozen=True) +class LinearMimicFit: + """The one relationship that a standard URDF can actually serialize.""" + + source_joint: str + target_joint: str + multiplier: float + offset_rad: float + offset_observed: bool + training_cycles: tuple[int, ...] + residuals_rad: tuple[float, ...] + + +@dataclass(frozen=True) +class PairedJointObservation: + """Two independent visual angles from the same image and frozen mounts.""" + + sample_id: str + cycle: int + direction: str + source_rad: float + target_rad: float + + +@dataclass(frozen=True) +class RelativeMimicEvidence: + fit: LinearMimicFit + # Nuisance phase between the two frozen visual references, NOT a URDF zero. + installation_phase_rad: float + training_sample_ids: tuple[str, ...] + holdout_sample_ids: tuple[str, ...] + holdout_errors_rad: tuple[float, ...] + + +def fit_relative_standard_mimic( + source_joint: str, target_joint: str, + observations: Sequence[PairedJointObservation], *, cad_offset_rad: float, +) -> RelativeMimicEvidence: + """Fit a standard linear mimic from paired visual motion, not SDK priors. + + Unknown mounting angles make the absolute passive intercept unobservable. + A training-only nuisance phase aligns the *visual references*, while the + published CAD intercept is preserved. It cannot be re-estimated on holdout + or used as an origin/mimic correction. Both directions share one slope. + """ + rows = tuple(observations) + identities = [row.sample_id for row in rows] + if any(not value for value in identities) or len(set(identities)) != len(identities): + raise ValueError("paired mimic image identities are missing or duplicated") + if any(row.cycle not in (0, 1, 2, 3) or row.direction not in {"increasing", "decreasing"} + or not math.isfinite(row.source_rad) or not math.isfinite(row.target_rad) + for row in rows): + raise ValueError("invalid paired mimic observation") + for cycle in range(4): + for direction in ("increasing", "decreasing"): + if sum(row.cycle == cycle and row.direction == direction for row in rows) < 40: + raise ValueError(f"missing paired mimic observations: {target_joint}:{cycle}:{direction}") + training = tuple(row for row in rows if row.cycle != 3) + holdout = tuple(row for row in rows if row.cycle == 3) + relative_fit = fit_standard_mimic(source_joint, target_joint, + [row.source_rad for row in training], [row.target_rad for row in training], + cycles=[row.cycle for row in training], offset_rad=None, offset_observable=True) + errors = tuple(relative_fit.multiplier * row.source_rad + relative_fit.offset_rad - row.target_rad + for row in holdout) + # Final-file FK remains a separate mandatory gate; this is the prerequisite + # that a single standard mimic can even explain the independent motion. + for label, residuals in (("training", relative_fit.residuals_rad), ("holdout", errors)): + degrees = np.rad2deg(np.abs(residuals)) + if np.mean(degrees) > 1 or np.percentile(degrees, 95) > 2 or np.max(degrees) > 3: + raise ValueError( + f"standard_urdf_mimic_not_expressive:joint={target_joint}:phase={label}:" + f"mae_deg={np.mean(degrees):.6f}:p95_deg={np.percentile(degrees, 95):.6f}:" + f"maximum_deg={np.max(degrees):.6f}; 标准 URDF 线性 mimic 表达能力不足或观测不一致" + ) + if not math.isfinite(cad_offset_rad): + raise ValueError("passive CAD offset must be finite") + fit = LinearMimicFit(source_joint, target_joint, relative_fit.multiplier, + float(cad_offset_rad), False, (0, 1, 2), relative_fit.residuals_rad) + return RelativeMimicEvidence(fit, relative_fit.offset_rad, + tuple(row.sample_id for row in training), tuple(row.sample_id for row in holdout), errors) + + +def fit_standard_mimic( + source_joint: str, + target_joint: str, + active_rad: Sequence[float], + passive_rad: Sequence[float], + *, + cycles: Sequence[int], + offset_rad: float | None, + offset_observable: bool = False, + multiplier_bounds: tuple[float, float] | None = None, +) -> LinearMimicFit: + """Fit actual synchronous observations, never a vendor-generated curve. + + A static offset is fixed to the CAD/coordinate-conversion value unless an + independent datum makes it observable. Unknown tag mounting cannot justify + fitting an intercept. Numerical fitting is training-only; the serialized + URDF and independent fourth cycle decide acceptance afterwards. + """ + x, y = np.asarray(active_rad, dtype=float), np.asarray(passive_rad, dtype=float) + identifiers = np.asarray(cycles) + if x.ndim != 1 or x.shape != y.shape or x.shape != identifiers.shape or x.size < 40: + raise ValueError("mimic fitting requires at least 40 aligned observations") + if not np.all(np.isfinite(x)) or not np.all(np.isfinite(y)): + raise ValueError("mimic observations must be finite") + if not np.all(np.isin(identifiers, (0, 1, 2))) or set(identifiers.tolist()) != {0, 1, 2}: + raise ValueError("mimic fitting requires three training cycles; holdout is forbidden") + if not source_joint or not target_joint or source_joint == target_joint: + raise ValueError("mimic source and target must be distinct") + if float(np.ptp(x)) <= math.radians(1.0): + raise ValueError("mimic source travel is not observable") + if offset_rad is None: + if not offset_observable: + raise ValueError("unobservable passive static offset must retain CAD") + design, rhs = np.column_stack((x, np.ones_like(x))), y + else: + if not math.isfinite(float(offset_rad)): + raise ValueError("fixed mimic offset must be finite") + design, rhs = x[:, None], y - float(offset_rad) + initial, _, rank, _ = np.linalg.lstsq(design, rhs, rcond=None) + if rank != design.shape[1]: + raise ValueError("mimic parameters are not independently observable") + residual = rhs - design @ initial + scale = max(math.radians(0.1), 1.4826 * float(np.median(np.abs(residual - np.median(residual))))) + bounds = (-np.inf, np.inf) + if multiplier_bounds is not None: + if (offset_rad is None or len(multiplier_bounds) != 2 + or not all(math.isfinite(v) for v in multiplier_bounds) + or multiplier_bounds[0] >= multiplier_bounds[1]): + raise ValueError("bounded mimic requires a fixed offset and a finite feasible interval") + bounds = multiplier_bounds + initial = np.clip(initial, *bounds) + solution = least_squares(lambda parameters: design @ parameters - rhs, + initial, loss="soft_l1", f_scale=scale, bounds=bounds) + if not solution.success or not np.all(np.isfinite(solution.x)): + raise ValueError("linear mimic fit failed") + multiplier = float(solution.x[0]) + offset = float(solution.x[1]) if offset_rad is None else float(offset_rad) + return LinearMimicFit(source_joint, target_joint, multiplier, offset, + offset_rad is None, (0, 1, 2), tuple(float(v) for v in (multiplier*x + offset - y))) + + +def fit_range_bounded_mimic(source_joint, target_joint, active_rad, passive_rad, *, + cycles, parent_range, child_range): + """Best robust affine approximation within the unchanged joint limits. + + Optimize the two child angles at the parent's endpoints. Bounding those + two values guarantees that the entire affine motion stays in the child's + interval, including tiny negative baseline excursions. The intercept is + approximation error at baseline, NOT an observed physical zero correction. + """ + initial_fit = fit_standard_mimic(source_joint, target_joint, active_rad, passive_rad, + cycles=cycles, offset_rad=0.0) + for interval in (parent_range, child_range): + if (len(interval) != 2 or not all(math.isfinite(v) for v in interval) + or interval[0] >= interval[1]): + raise ValueError("invalid_mimic_motion_interval") + x, y = np.asarray(active_rad, dtype=float), np.asarray(passive_rad, dtype=float) + lower, upper = parent_range + fraction = (x - lower) / (upper - lower) + design = np.column_stack((1 - fraction, fraction)) + residual = np.asarray(initial_fit.residuals_rad) + scale = max(math.radians(0.1), 1.4826 * float(np.median(np.abs(residual - np.median(residual))))) + initial = np.clip(np.asarray(parent_range) * initial_fit.multiplier, *child_range) + solution = least_squares(lambda endpoints: design @ endpoints - y, initial, + loss="soft_l1", f_scale=scale, bounds=child_range) + if not solution.success or not np.all(np.isfinite(solution.x)): + raise ValueError("bounded_affine_mimic_fit_failed") + multiplier = float((solution.x[1] - solution.x[0]) / (upper - lower)) + offset = float(solution.x[0] - multiplier * lower) + return LinearMimicFit(source_joint, target_joint, multiplier, offset, False, + (0, 1, 2), tuple(float(v) for v in multiplier*x + offset - y)) + + +@dataclass(frozen=True) +class CouplingFit: + source_joint: str + target_joint: str + model: str + coefficients: tuple[float, ...] + urdf_mimic_multiplier: float + urdf_mimic_policy: str + cycle_coefficients: tuple[tuple[float, ...], ...] + maximum_cycle_range: float + maximum_cycle_prediction_range_rad: float + residual_rms_rad: float + residual_p95_rad: float + residual_max_rad: float + + @property + def multiplier(self) -> float: + return float(self.coefficients[0]) + + @property + def cycle_multipliers(self) -> tuple[float, ...]: + return tuple(float(values[0]) for values in self.cycle_coefficients) + + @property + def mujoco_polycoef(self) -> tuple[float, ...]: + return (0.0, *self.coefficients, *(0.0,) * (5 - len(self.coefficients))) + + +def curve_travel_rad(fit: DirectionalCurve) -> float: + """Return the mean travel of the decreasing and increasing curves.""" + decreasing = np.asarray(fit.decreasing_rad, dtype=float) + increasing = np.asarray(fit.increasing_rad, dtype=float) + if decreasing.size < 2 or increasing.size < 2: + raise ValueError("directional curves require at least two knots") + travel = 0.5 * ( + float(decreasing[0] - decreasing[-1]) + + float(increasing[0] - increasing[-1]) + ) + if not math.isfinite(travel) or travel <= 0.0: + raise ValueError("fitted travel must be finite and positive") + return travel + + +def _coupling_regression( + active: Sequence[float], passive: Sequence[float], *, degree: int +) -> tuple[tuple[float, ...], np.ndarray]: + x = np.asarray(active, dtype=float) + y = np.asarray(passive, dtype=float) + if x.shape != y.shape or x.ndim != 1 or x.size < 16: + raise ValueError("coupling curves must be aligned finite vectors") + if not np.all(np.isfinite(x)) or not np.all(np.isfinite(y)): + raise ValueError("coupling curves must be finite") + if degree not in {1, 2}: + raise ValueError("coupling degree must be one or two") + if float(x @ x) <= 1.0e-9: + raise ValueError("active coupling source has insufficient travel") + design = np.column_stack([x ** power for power in range(1, degree + 1)]) + initial = np.linalg.lstsq(design, y, rcond=None)[0] + scale = max( + math.radians(0.25), + float(np.median(np.abs(y - design @ initial))), + ) + fitted = least_squares( + lambda value: y - design @ value, + np.asarray(initial, dtype=float), + loss="soft_l1", + f_scale=scale, + ) + if not fitted.success or not np.all(np.isfinite(fitted.x)): + raise ValueError("robust through-origin coupling regression failed") + coefficients = tuple(float(value) for value in fitted.x) + grid = np.linspace(0.0, float(np.max(x)), 256) + derivative = np.full_like(grid, coefficients[0]) + if degree == 2: + derivative += 2.0 * coefficients[1] * grid + if float(np.min(derivative)) < -1.0e-7: + raise ValueError("coupling model is not monotonic") + return coefficients, y - design @ fitted.x + + +def fit_coupling_model( + source_joint: str, + target_joint: str, + active_fit: DirectionalCurve, + passive_fit: DirectionalCurve, + *, + model: str, + cycle_curve_pairs: Sequence[ + tuple[Sequence[float], Sequence[float]] + ] = (), + minimum_multiplier: float = 0.5, + maximum_multiplier: float = 1.5, + maximum_cycle_range: float = 0.03, + maximum_cycle_prediction_range_rad: float = math.radians(1.0), + maximum_residual_p95_rad: float = math.radians(2.0), + maximum_residual_rad: float = math.radians(3.0), +) -> CouplingFit: + """Fit a profile-selected coupling primitive with release-grade metrics.""" + supported = {"linear_mimic", "quadratic_runtime", "direction_aware_knots"} + if model not in supported: + raise ValueError(f"unsupported coupling model: {model}") + source_travel = curve_travel_rad(active_fit) + target_travel = curve_travel_rad(passive_fit) + endpoint_multiplier = float(target_travel / source_travel) + if model == "direction_aware_knots": + if not minimum_multiplier <= endpoint_multiplier <= maximum_multiplier: + raise ValueError( + f"{target_joint} coupling endpoint ratio is outside " + f"[{minimum_multiplier}, {maximum_multiplier}]" + ) + return CouplingFit( + source_joint, target_joint, model, (endpoint_multiplier,), + endpoint_multiplier, "endpoint_linear_fallback", (), + 0.0, 0.0, 0.0, 0.0, 0.0, + ) + + degree = 1 if model == "linear_mimic" else 2 + active = np.concatenate(( + np.asarray(active_fit.decreasing_rad, dtype=float), + np.asarray(active_fit.increasing_rad, dtype=float), + )) + passive = np.concatenate(( + np.asarray(passive_fit.decreasing_rad, dtype=float), + np.asarray(passive_fit.increasing_rad, dtype=float), + )) + coefficients, residual = _coupling_regression(active, passive, degree=degree) + multiplier = coefficients[0] + if not minimum_multiplier <= multiplier <= maximum_multiplier: + raise ValueError( + f"{target_joint} coupling linear term is outside " + f"[{minimum_multiplier}, {maximum_multiplier}]" + ) + cycle_coefficients = tuple( + _coupling_regression(source, target, degree=degree)[0] + for source, target in cycle_curve_pairs + ) + cycle_multipliers = tuple(values[0] for values in cycle_coefficients) + cycle_range = ( + 0.0 if len(cycle_multipliers) < 2 + else float(max(cycle_multipliers) - min(cycle_multipliers)) + ) + if cycle_range > maximum_cycle_range: + raise ValueError( + f"{target_joint} coupling linear-term cycle range exceeds " + f"{maximum_cycle_range}" + ) + cycle_prediction_range = 0.0 + if len(cycle_coefficients) >= 2: + grid = np.linspace(0.0, float(np.max(active)), 256) + predictions = np.asarray([ + sum(value * grid ** (index + 1) for index, value in enumerate(values)) + for values in cycle_coefficients + ]) + cycle_prediction_range = float(np.max(np.ptp(predictions, axis=0))) + if cycle_prediction_range > maximum_cycle_prediction_range_rad: + raise ValueError( + f"{target_joint} coupling cycle prediction range exceeds limit" + ) + absolute = np.abs(residual) + rms = float(np.sqrt(np.mean(np.square(residual)))) + p95 = float(np.percentile(absolute, 95.0)) + maximum = float(np.max(absolute)) + if p95 > maximum_residual_p95_rad or maximum > maximum_residual_rad: + raise ValueError( + "coupling_residual_exceeds:" + f"joint={target_joint}:model={model}:" + f"linear_term={multiplier:.6f}:" + f"p95_deg={math.degrees(p95):.3f}:" + f"maximum_deg={math.degrees(maximum):.3f}:" + f"p95_limit_deg={math.degrees(maximum_residual_p95_rad):.3f}:" + f"maximum_limit_deg={math.degrees(maximum_residual_rad):.3f}" + ) + return CouplingFit( + source_joint=source_joint, + target_joint=target_joint, + model=model, + coefficients=coefficients, + urdf_mimic_multiplier=( + multiplier if model == "linear_mimic" else endpoint_multiplier + ), + urdf_mimic_policy=( + "exact_linear" if model == "linear_mimic" + else "endpoint_linear_fallback" + ), + cycle_coefficients=cycle_coefficients, + maximum_cycle_range=cycle_range, + maximum_cycle_prediction_range_rad=cycle_prediction_range, + residual_rms_rad=rms, + residual_p95_rad=p95, + residual_max_rad=maximum, + ) + + +__all__ = ["CouplingFit", "DirectionalCurve", "curve_travel_rad", "fit_coupling_model", + "LinearMimicFit", "fit_standard_mimic", "PairedJointObservation", + "RelativeMimicEvidence", "fit_relative_standard_mimic"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/curve.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/curve.py new file mode 100644 index 0000000..98d4f90 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/curve.py @@ -0,0 +1,70 @@ +"""Model-independent curve fitting result and monotonic projection.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Any, Sequence + +import numpy as np + +from ..geometry import delta_rotation_vector + + +def isotonic_nonincreasing(values: Sequence[float]) -> np.ndarray: + """Unweighted PAVA projection onto non-increasing values.""" + original = np.asarray(values, dtype=float) + if original.ndim != 1 or not np.all(np.isfinite(original)): + raise ValueError("values must be a finite vector") + negated = -original + levels: list[float] = [] + weights: list[int] = [] + starts: list[int] = [] + for index, value in enumerate(negated): + levels.append(float(value)) + weights.append(1) + starts.append(index) + while len(levels) >= 2 and levels[-2] > levels[-1]: + total_weight = weights[-2] + weights[-1] + merged = ( + levels[-2] * weights[-2] + levels[-1] * weights[-1] + ) / total_weight + levels[-2:] = [merged] + weights[-2:] = [total_weight] + starts.pop() + projected = np.empty_like(original) + for block_index, (level, start) in enumerate(zip(levels, starts)): + end = ( + starts[block_index + 1] + if block_index + 1 < len(starts) + else len(original) + ) + projected[start:end] = -level + return projected + + +@dataclass(frozen=True) +class FitResult: + joints: dict[str, dict[str, Any]] + axes: dict[str, tuple[float, float, float]] + references: dict[str, tuple[float, float, float, float]] + ip_coupling: dict[str, float] + max_monotonic_correction_rad: float + max_hysteresis_rad: float + measurement_mode: str = "rotation" + trajectory_models: dict[str, Any] = field(default_factory=dict) + trajectory_quality: dict[str, Any] = field(default_factory=dict) + + def measure_from_reference( + self, + joint_name: str, + observed_quaternion_xyzw: Sequence[float], + reference_quaternion_xyzw: Sequence[float] | None = None, + ) -> float: + reference = ( + reference_quaternion_xyzw + if reference_quaternion_xyzw is not None + else self.references[joint_name] + ) + vector = delta_rotation_vector(reference, observed_quaternion_xyzw) + axis = np.asarray(self.axes[joint_name], dtype=float) + return float(vector @ axis) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/frozen.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/frozen.py new file mode 100644 index 0000000..cf548dc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/frozen.py @@ -0,0 +1,60 @@ +"""Explicit JSON transport for immutable numerical training objects. + +Only a fixed registry of calibration value types can be reconstructed. There +is no pickle, dynamic import or executable object in a persisted model. +""" + +from dataclasses import fields, is_dataclass +import math + +import numpy as np +from scipy.spatial.transform import Rotation + + +def encode(value): + if isinstance(value, Rotation): + return {"$type": "Rotation", "value": value.as_quat().tolist()} + if isinstance(value, np.ndarray): + return {"$type": "array", "value": value.tolist()} + if isinstance(value, np.generic): + return encode(value.item()) + if is_dataclass(value): + return {"$type": type(value).__name__, "fields": { + field.name: encode(getattr(value, field.name)) for field in fields(value)}} + if isinstance(value, dict): + return {"$type": "mapping", "items": [[encode(k), encode(value[k])] for k in sorted(value, key=repr)]} + if isinstance(value, (tuple, list, frozenset, set)): + values = sorted(value) if isinstance(value, (set, frozenset)) else value + return {"$type": type(value).__name__, "items": [encode(item) for item in values]} + if isinstance(value, float) and not math.isfinite(value): + raise ValueError("frozen_training_nonfinite_value") + if value is None or isinstance(value, (str, int, float, bool)): + return value + raise TypeError(f"unsupported_frozen_training_type:{type(value).__name__}") + + +def decode(value): + if not isinstance(value, dict): + return value + kind = value.get("$type") + if kind == "Rotation": + return Rotation.from_quat(value["value"]) + if kind == "array": + return np.asarray(value["value"], dtype=float) + if kind == "mapping": + return {decode(k): decode(v) for k, v in value["items"]} + sequences = {"tuple": tuple, "list": list, "set": set, "frozenset": frozenset} + if kind in sequences: + return sequences[kind](decode(item) for item in value["items"]) + from . import command_motion, tag_installation + from .spatial_solver import stages, solve, types + from ..domain import measurement, result + registry = {name: cls for module in (command_motion, tag_installation, stages, solve, + types, measurement, result) for name, cls in vars(module).items() + if isinstance(cls, type) and is_dataclass(cls)} + if kind not in registry: + raise ValueError(f"unknown_frozen_training_type:{kind}") + cls = registry[kind] + if set(value["fields"]) != {field.name for field in fields(cls)}: + raise ValueError("frozen_training_fields_changed") + return cls(**{key: decode(item) for key, item in value["fields"].items()}) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/image_curve.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/image_curve.py new file mode 100644 index 0000000..3175618 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/image_curve.py @@ -0,0 +1,74 @@ +"""Training-frozen angular phase of an observed image-plane circle. + +Only use this primitive where the Profile declares the projected circle +observable. Final standard-URDF SE(3) replay remains mandatory: a good image +circle alone cannot certify physical angles in an oblique projection. +""" + +import math + +import numpy as np + +from ..domain.measurement import JointCurveFit +from .circle_geometry import _fit_circle, _trajectory_arc_rad +from .trajectory_geometry import _fit_joint_curve + + +def image_phase(point, circle): + point, centre, reference = (np.asarray(value, dtype=float) for value in + (point, circle["center_xy_px"], circle["reference_xy_px"])) + vector = point - centre + if point.shape != (2,) or not np.all(np.isfinite(point)) or np.linalg.norm(vector) < 1e-9: + raise ValueError("invalid image trajectory observation") + return float(circle["orientation_sign"]) * math.atan2( + float(reference[0]*vector[1] - reference[1]*vector[0]), float(reference @ vector)) + + +def fit_joint_image_curve(records, *, zero_command_u8=255, + canonical_zero_direction="decreasing", maximum_radial_rms_px=2., + maximum_radial_p95_px=3.5, minimum_radius_px=20., minimum_arc_rad=math.radians(15)): + samples = list(records) + if not samples or any(int(row["cycle"]) not in {0, 1, 2} for row in samples): + raise ValueError("image curve requires training observations only") + points = np.asarray([row["image_relative_xy_px"] for row in samples], dtype=float) + if points.shape != (len(samples), 2) or not np.all(np.isfinite(points)): + raise ValueError("image curve requires finite two-dimensional observations") + centre, radius = _fit_circle(points) + radial = np.linalg.norm(points-centre, axis=1)-radius + quality = {"radial_rms_px": float(np.sqrt(np.mean(radial**2))), + "radial_p95_px": float(np.percentile(np.abs(radial), 95)), + "radius_px": radius, "arc_rad": float(_trajectory_arc_rad(points, centre))} + if (quality["radial_rms_px"] > maximum_radial_rms_px + or quality["radial_p95_px"] > maximum_radial_p95_px + or radius < minimum_radius_px or quality["arc_rad"] < minimum_arc_rad): + raise ValueError("image_trajectory_not_observable") + # One observed reference for all training directions/cycles. Choose it + # near nominal baseline, then interpolate a single coordinate gauge. + indices = [index for index, row in enumerate(samples) + if canonical_zero_direction is None or row["direction"] == canonical_zero_direction] + if not indices: + raise ValueError("canonical image direction is missing") + index = min(indices, key=lambda i: abs(int(samples[i]["command_u8"])-zero_command_u8)) + reference = points[index]-centre + reference /= np.linalg.norm(reference) + circle = {"space": "image_2d", "center_xy_px": centre.tolist(), + "reference_xy_px": reference.tolist(), "orientation_sign": 1., "radius_px": radius, + "training_cycles": sorted({int(row["cycle"]) for row in samples}), + "input_domain": "feedback_u8", "input_knots": list(range(256)), + "zero_command_u8": int(zero_command_u8)} + values = np.asarray([image_phase(point, circle) for point in points]) + commands = np.asarray([int(row["command_u8"]) for row in samples]) + trend = float((commands-np.mean(commands)) @ (values-np.mean(values))) + if abs(trend) < 1e-12: + raise ValueError("image motion direction is not observable") + if trend > 0: + values = -values + circle["orientation_sign"] = -1. + curves, correction, hysteresis = _fit_joint_curve(samples, values, preserve_direction_offset=True) + reference_angle = float(curves["angle_rad" if canonical_zero_direction is None else canonical_zero_direction+"_rad"][int(zero_command_u8)]) + turn = reference_angle / circle["orientation_sign"] + rotation = np.array([[math.cos(turn), -math.sin(turn)], [math.sin(turn), math.cos(turn)]]) + circle["reference_xy_px"] = (rotation @ reference).tolist() + curves = {name: tuple(float(value-reference_angle) for value in values) for name, values in curves.items()} + return JointCurveFit(curves["angle_rad"], curves["decreasing_rad"], curves["increasing_rad"], + circle, correction, hysteresis, quality) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/mimic_approximation.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/mimic_approximation.py new file mode 100644 index 0000000..5beeb85 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/mimic_approximation.py @@ -0,0 +1,107 @@ +"""Training-only URDF approximations, separate from exact JSON lookup tables.""" + +from dataclasses import dataclass, replace +import math + +from .coupling import LinearMimicFit, fit_standard_mimic, fit_range_bounded_mimic +from .observed_motion import paired_visual_observations + + +@dataclass(frozen=True) +class MimicApproximation: + output_fit: LinearMimicFit + training_sample_ids: tuple[str, ...] + holdout_sample_ids: tuple[str, ...] + holdout_errors_rad: tuple[float, ...] + transferred_from_joint: str | None = None + multiplier_bounds: tuple[float, float] | None = None + parent_range_rad: tuple[float, float] | None = None + child_range_rad: tuple[float, float] | None = None + + def in_cad_coordinates(self, offsets): + from dataclasses import replace + if self.parent_range_rad is not None: + raise ValueError("affine_approximation_intercept_is_not_a_physical_zero") + fit = self.output_fit + # The offset is supported by the TWO baseline geometry datums. + return replace(fit, offset_rad=offsets[fit.target_joint]-fit.multiplier*offsets[fit.source_joint], + offset_observed=True) + + +def shared_zero_multiplier_bounds(parent_range, child_range): + """Intersect endpoint constraints for q_child = a*q_parent. + + These ranges come from training support or mechanical bounds, never from + holdout observations. Neither measured curve nor joint range is modified. + """ + lower, upper = -math.inf, math.inf + if any(len(interval) != 2 or not all(math.isfinite(v) for v in interval) + or interval[0] >= interval[1] for interval in (parent_range, child_range)): + raise ValueError("invalid_mimic_motion_interval") + for endpoint in parent_range: + if endpoint == 0: + if not child_range[0] <= 0 <= child_range[1]: + raise ValueError("mimic_range_excludes_shared_zero") + continue + values = sorted(value / endpoint for value in child_range) + lower, upper = max(lower, values[0]), min(upper, values[1]) + if not math.isfinite(lower) or not math.isfinite(upper) or lower >= upper: + raise ValueError("no_feasible_shared_zero_mimic") + return lower, upper + + +def fit_mimic_approximations(model, curves, records, *, output_ranges=None, affine=False): + result = {} + for name, joint in model.joints.items(): + parent = joint.mimic_joint + if parent is None or name not in curves or parent not in curves: + continue + rows = paired_visual_observations(records[parent], records[name], curves[parent], curves[name]) + for cycle in range(4): + for direction in ("increasing", "decreasing"): + if sum(r.cycle == cycle and r.direction == direction for r in rows) < 40: + raise ValueError(f"paired_mimic_observations_missing:{name}:{cycle}:{direction}") + training = [r for r in rows if r.cycle != 3] + holdout = [r for r in rows if r.cycle == 3] + bounds = None + arguments = dict(source_joint=parent, target_joint=name, + active_rad=[r.source_rad for r in training], passive_rad=[r.target_rad for r in training], + cycles=[r.cycle for r in training]) + if affine: + if output_ranges is None: + raise ValueError("affine_mimic_requires_training_motion_ranges") + fit = fit_range_bounded_mimic(**arguments, + parent_range=output_ranges[parent], child_range=output_ranges[name]) + else: + bounds = None if output_ranges is None else shared_zero_multiplier_bounds( + output_ranges[parent], output_ranges[name]) + fit = fit_standard_mimic(**arguments, offset_rad=0.0, multiplier_bounds=bounds) + if not math.isfinite(fit.multiplier) or fit.multiplier == 0: + raise ValueError(f"invalid_mimic_approximation:{name}") + result[name] = MimicApproximation(fit, tuple(r.sample_id for r in training), + tuple(r.sample_id for r in holdout), + tuple(fit.multiplier*r.source_rad + fit.offset_rad - r.target_rad for r in holdout), + multiplier_bounds=bounds, + parent_range_rad=tuple(output_ranges[parent]) if affine else None, + child_range_rad=tuple(output_ranges[name]) if affine else None) + return result + + +def fit_bounded_mimic_approximations(profile, model, fit, records): + """Fit the URDF affine fallback after training establishes both ranges. + + Only independently observed pairs are fitted; explicit donor expansion is + performed afterwards. JSON continues to use the independent nonlinear maps. + """ + ranges = {} + for name, mapping in fit.output_mappings.items(): + joint = model.joints[name] + if name in profile.urdf_limit_policies or joint.mimic_joint is None: + command = fit.command_mappings[name] + ranges[name] = (min(0, mapping.bounds_rad[0], command.bounds_rad[0]), + max(0, mapping.bounds_rad[1], command.bounds_rad[1])) + else: + delta = fit.zero_offsets_rad[name] + ranges[name] = (joint.lower - delta, joint.upper - delta) + return replace(fit, mimic_approximations=fit_mimic_approximations( + model, fit.curves, records, output_ranges=ranges, affine=True)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/motion_fit.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/motion_fit.py new file mode 100644 index 0000000..61f7f3f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/motion_fit.py @@ -0,0 +1,139 @@ +"""Profile-selected native measurement primitives and coordinate gauges. + +The curve reference is only a coordinate choice. CAD zero is solved later +from independently observed spatial axes; neither SDK zero nor an endpoint +is treated as a mechanical datum. +""" + +from dataclasses import dataclass, replace +from typing import Mapping + +import numpy as np + +from ..domain.measurement import JointCurveFit +from ..urdf.acceptance import angular_metrics +from .coupling import fit_relative_standard_mimic +from .observed_motion import ( + compare_native_views, fit_byte_observed_motion, fit_native_observed_rotation, + paired_visual_observations, +) + + +@dataclass(frozen=True) +class MotionFit: + observed_curves: Mapping[str, JointCurveFit] + coordinate_curves: Mapping[str, JointCurveFit] + holdout_errors_rad: Mapping[str, tuple[float, ...]] + mimic_evidence: Mapping + cross_view_metrics: Mapping + reference_inputs: Mapping[str, float] + + +def channel_for_joint(profile, joint): + seen = set() + while joint not in profile.command.command_index_by_joint: + if joint in seen or joint not in profile.zero.mimic_source_by_joint: + raise ValueError(f"measured joint has no SDK source:{joint}") + seen.add(joint) + joint = profile.zero.mimic_source_by_joint[joint] + return profile.command.command_index_by_joint[joint] + + +def joint_input_direction(profile, source_model, joint): + """A passive measurement follows its declared CAD mimic chain's sign.""" + sign, current, seen = 1, joint, set() + while current not in profile.command.command_index_by_joint: + if current in seen: + raise ValueError("cyclic mimic input binding") + seen.add(current) + cad = source_model.joints[current] + if cad.mimic_joint != profile.zero.mimic_source_by_joint.get(current) or cad.mimic_multiplier == 0: + raise ValueError(f"invalid measured mimic input binding:{current}") + sign *= 1 if cad.mimic_multiplier > 0 else -1 + current = cad.mimic_joint + return sign * profile.command.joint_directions[profile.command.command_index_by_joint[current]] + + +def native_coordinate_curve(curve, baseline): + """Choose one training-supported gauge, never extend a fitted domain. + + Both directional branches subtract the SAME reference, retaining actual + backlash. If nominal baseline lies outside observed support, the nearest + measured input is the reference and is explicitly recorded as such. + """ + inputs = curve.circle["input_knots"] + reference_input = float(np.clip(baseline, inputs[0], inputs[-1])) + reference_angle = float(np.interp(reference_input, inputs, curve.angle_rad)) + branches = {name: tuple(float(value - reference_angle) for value in getattr(curve, name)) + for name in ("angle_rad", "increasing_rad", "decreasing_rad")} + return replace(curve, **branches, circle={**curve.circle, + "coordinate_reference_input": reference_input, + "coordinate_reference_angle_rad": reference_angle}), reference_input + + +def fit_profile_motion(profile, source_model, records_by_joint, *, cross_view_records=None, zero_references=None): + expected = {name for name, spec in profile.measurement.measurements.items() + if spec.view is not None and spec.kind != "axis_cross_view_validation"} + if set(records_by_joint) != expected: + raise ValueError("fitting observations differ from the Profile") + if any(profile.measurement.measurements[name].kind not in {"relative_rotation", "urdf_axis_chain", "curve"} for name in expected): + raise ValueError("measurement primitive is not implemented in this pipeline") + mimic_sources = {name: profile.zero.mimic_source_by_joint[name] for name in profile.zero.fitted_mimic_joints} + if profile.artifacts.output_schema_version >= 3: + if set(zero_references or {}) != expected: + raise ValueError("joint_zero_references_incomplete") + observed, holdout, evidence, references = {}, {}, {}, {} + for name, rows in sorted(records_by_joint.items()): + view = profile.measurement.measurements[name].view + reference = zero_references[name] + observed[name], holdout[name] = fit_native_observed_rotation(rows, + input_domain=profile.curve_input_domain, + input_to_joint_direction=joint_input_direction(profile, source_model, name), + reference_xyzw=reference.quaternion(view), joint=name, view=view) + references[name] = reference.input_reference(view, feedback=True) + coordinates = observed + elif profile.command.unit == "u8": + observed, holdout, evidence = fit_byte_observed_motion(records_by_joint, + source_model=source_model, mimic_sources=mimic_sources, + baseline_by_joint={name: profile.command.baseline_values[channel_for_joint(profile, name)] for name in expected}, + direction_by_joint={name: joint_input_direction(profile, source_model, name) for name in expected}, + image_curve_joints=profile.measurement.image_curve_joints, input_domain=profile.curve_input_domain) + coordinates = observed + references = {name: float(profile.command.baseline_values[channel_for_joint(profile, name)]) + for name in observed} + else: + observed, coordinates, holdout, evidence, references = {}, {}, {}, {}, {} + for name, rows in sorted(records_by_joint.items()): + curve, errors = fit_native_observed_rotation(rows, input_domain=profile.curve_input_domain, + input_to_joint_direction=joint_input_direction(profile, source_model, name), + joint=name, view=profile.measurement.measurements[name].view) + observed[name], holdout[name] = curve, errors + coordinates[name], references[name] = native_coordinate_curve(curve, + profile.command.baseline_values[channel_for_joint(profile, name)]) + for target, source in mimic_sources.items(): + cad = source_model.joints[target] + if cad.mimic_joint != source: + raise ValueError(f"mimic source differs from CAD:{target}") + evidence[target] = fit_relative_standard_mimic(source, target, + paired_visual_observations(records_by_joint[source], records_by_joint[target], + observed[source], observed[target]), cad_offset_rad=cad.mimic_offset) + secondary = cross_view_records or {} + if set(secondary) != set(profile.measurement.cross_view_sources): + raise ValueError("required cross-view observations are incomplete") + metrics = {} + for name, rows in secondary.items(): + curve, errors = fit_native_observed_rotation(rows, input_domain=profile.curve_input_domain, + input_to_joint_direction=joint_input_direction(profile, source_model, name), + reference_xyzw=(zero_references[name].quaternion(rows[0]["view"]) + if profile.artifacts.output_schema_version >= 3 else None), + joint=name, view=profile.measurement.measurements[ + profile.measurement.cross_view_sources[name]].view) + if "input_knots" not in observed[name].circle: + raise ValueError("cross-view comparison requires native input knots") + comparison = compare_native_views(observed[name], curve) + if comparison.get("direction_disagrees", False): + raise ValueError(f"cross-view motion direction disagrees:{name}") + quality = angular_metrics(errors) + metrics[name] = {**comparison, "holdout_mae_deg": quality.mae_deg, + "holdout_p95_deg": quality.p95_deg, "holdout_max_deg": quality.maximum_deg} + return MotionFit(observed, coordinates, holdout, evidence, metrics, references) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/motion_transfer.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/motion_transfer.py new file mode 100644 index 0000000..4566e99 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/motion_transfer.py @@ -0,0 +1,111 @@ +"""Apply explicit donor policies without creating recipient observations. + +Motion curves, absolute zeros and URDF approximations have separate provenance. +Only the numerical mappings are expanded; training and holdout evidence remain +attached to the joints that were actually observed. +""" + +from dataclasses import replace + +from ..domain.profile import CalibrationProfile, validate_profile +from ..domain.result import CalibrationResult, JointMapping +from .motion_fit import channel_for_joint + + +def transferred_mapping(profile: CalibrationProfile, mapping: JointMapping, + target: str) -> JointMapping: + return replace(mapping, joint=target, motor_index=channel_for_joint(profile, target), + transferred_from=mapping.joint) + + +def expand_profile_transfers(profile: CalibrationProfile, fit: CalibrationResult) -> CalibrationResult: + """Copy frozen fits once, after all measured command holdouts have passed.""" + transfers = profile.measurement.transferred_motion_sources + if not transfers: + return fit + validate_profile(profile) + outputs, commands = dict(fit.output_mappings), dict(fit.command_mappings) + offsets, methods = dict(fit.zero_offsets_rad), dict(fit.zero_method_by_joint) + approximations = dict(fit.mimic_approximations) + for target, source in transfers.items(): + if target in outputs or target in commands or target in fit.curves or target in fit.joint_zero_references: + raise ValueError(f"motion_transfer_cannot_replace_existing_result:{target}") + if source not in fit.curves or source not in outputs or source not in commands: + raise ValueError(f"motion_transfer_requires_fitted_donor:{target}:{source}") + for mappings in (outputs, commands): + donor = mappings[source] + if donor.joint != source or donor.transferred_from is not None \ + or donor.motor_index != channel_for_joint(profile, source): + raise ValueError(f"motion_transfer_requires_direct_donor_binding:{source}") + mappings[target] = transferred_mapping(profile, donor, target) + # Dynamic similarity does not authorize copying an absolute CAD zero. + if profile.zero.transferred_zero_sources.get(target) == source and source in offsets: + offsets[target] = offsets[source] + methods[target] = "transferred_static_zero_on_own_cad" + # Historical fitted approximations remain transferable for replay. + # Current measured fitting emits no mimic fit; each recipient keeps its CAD coupling. + if target in profile.zero.passive_joints and approximations: + if source not in fit.mimic_approximations: + raise ValueError(f"motion_transfer_requires_paired_donor_mimic:{target}:{source}") + donor = fit.mimic_approximations[source] + approximations[target] = replace(donor, + output_fit=replace(donor.output_fit, target_joint=target, + source_joint=profile.zero.mimic_source_by_joint[target]), + transferred_from_joint=source) + return replace(fit, output_mappings=outputs, command_mappings=commands, + zero_offsets_rad=offsets, zero_method_by_joint=methods, mimic_approximations=approximations) + + +def validate_mapping_provenance(profile: CalibrationProfile, fit: CalibrationResult) -> None: + """Require every published table to be measured or an exact authorized copy.""" + validate_profile(profile) + transfers = profile.measurement.transferred_motion_sources + observed = set(fit.curves) + if observed & transfers.keys(): + raise ValueError("independent_release_contains_transferred_or_unknown_joints") + expected = observed | transfers.keys() + for mappings in (fit.output_mappings, fit.command_mappings): + if set(mappings) != expected: + raise ValueError("independent_release_contains_transferred_or_unknown_joints") + for name, mapping in mappings.items(): + if mapping.joint != name or mapping.motor_index != channel_for_joint(profile, name): + raise ValueError(f"mapping_sdk_binding_differs:{name}") + source = transfers.get(name) + if source is None: + if mapping.transferred_from is not None: + raise ValueError("independent_release_contains_transferred_or_unknown_joints") + elif source not in observed or mappings[source].transferred_from is not None \ + or mapping != transferred_mapping(profile, mappings[source], name): + raise ValueError(f"mapping_differs_from_declared_donor:{name}") + for name, approximation in fit.mimic_approximations.items(): + source = transfers.get(name) + if source is None: + if approximation.transferred_from_joint is not None: + raise ValueError(f"undeclared_mimic_transfer:{name}") + elif source not in fit.mimic_approximations: + raise ValueError(f"missing_donor_mimic_approximation:{name}") + else: + donor = fit.mimic_approximations[source] + expected_approximation = replace(donor, output_fit=replace(donor.output_fit, + target_joint=name, source_joint=profile.zero.mimic_source_by_joint[name]), + transferred_from_joint=source) + if approximation != expected_approximation: + raise ValueError(f"mimic_differs_from_declared_donor:{name}") + + +def validate_zero_provenance(profile: CalibrationProfile, fit: CalibrationResult) -> None: + """Keep accepted premises and explicit zero copies true in the final plan.""" + offsets, methods = fit.zero_offsets_rad, fit.zero_method_by_joint + for name in profile.zero.cad_zero_assumptions: + if offsets.get(name) != 0.0 or methods.get(name) != "assumed_source_cad_zero": + raise ValueError(f"assumed_cad_zero_differs_from_profile:{name}") + for name, geometry in profile.zero.known_baseline_geometry.items(): + if offsets.get(name) != geometry.cad_angle_rad \ + or methods.get(name) != "independent_known_baseline_geometry": + raise ValueError(f"known_baseline_geometry_differs_from_profile:{name}") + for target, source in profile.zero.transferred_zero_sources.items(): + if profile.measurement.transferred_motion_sources.get(target) != source: + continue + if source not in offsets or offsets.get(target) != offsets[source] \ + or methods.get(target) != "transferred_static_zero_on_own_cad": + raise ValueError(f"transferred_zero_differs_from_declared_donor:{target}") diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/observed_motion.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/observed_motion.py new file mode 100644 index 0000000..b10aa98 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/observed_motion.py @@ -0,0 +1,156 @@ +"""Shared visual motion fitting and independently paired standard mimics.""" + +from __future__ import annotations + +from typing import Any, Mapping + +from .coupling import PairedJointObservation, fit_relative_standard_mimic +from .spatial import fit_rotation_joint_curve, measure_joint_curve_observation, joint_curve_holdout_errors +from .image_curve import fit_joint_image_curve +from ..urdf.acceptance import angular_metrics +from ..domain.measurement import JointCurveFit +from .rotation_curve import RotationObservation, fit_rotation_curve +from .rotation_diagnostics import RotationHoldoutFailure, rotation_holdout_diagnostic + + +def image_identity(row: Mapping[str, Any]) -> str: + identity = str(row.get("sample_id", "")) + if not identity and row.get("view") and row.get("image_stamp_ns") is not None: + identity = f"{row['view']}:{int(row['image_stamp_ns'])}" + if not identity: + raise ValueError("visual fitting requires recorded image identity") + return identity + + +def paired_visual_observations(source_rows, target_rows, source_fit, target_fit): + def indexed(rows): + output = {} + for row in rows: + identity = image_identity(row) + if identity in output: + raise ValueError("duplicated paired visual image identity") + output[identity] = row + return output + source, target = indexed(source_rows), indexed(target_rows) + output = [] + for identity in sorted(source.keys() & target.keys()): + a, b = source[identity], target[identity] + if (a["cycle"], a["direction"]) != (b["cycle"], b["direction"]): + raise ValueError("paired visual image has different cycle/direction") + output.append(PairedJointObservation(identity, int(a["cycle"]), str(a["direction"]), + measure_joint_curve_observation(source_fit, quaternion_xyzw=a.get("relative_quaternion_xyzw"), + image_relative_xy_px=a.get("image_relative_xy_px")), + measure_joint_curve_observation(target_fit, quaternion_xyzw=b.get("relative_quaternion_xyzw"), + image_relative_xy_px=b.get("image_relative_xy_px")))) + return output + + +def fit_native_observed_rotation(rows, *, input_domain, input_to_joint_direction, + reference_xyzw=None, joint=None, view=None): + """Native-coordinate 3+1 hinge primitive with the shared geometric result. + + The metadata carries real knots, not a synthetic byte command domain. + Scalar angle zero is only a fixed Tag reference, never a CAD datum. + """ + import numpy as np + observations = [RotationObservation(image_identity(row), float(row[input_domain]), + tuple(row["relative_quaternion_xyzw"]), int(row["cycle"]), str(row["direction"])) + for row in rows] + for direction in ("increasing", "decreasing"): + if sum(row.cycle == 3 and row.direction == direction for row in observations) < 40: + raise ValueError("holdout requires 40 images in each direction") + fitted = fit_rotation_curve([row for row in observations if row.cycle != 3], + input_domain=input_domain, sdk_to_joint_direction=input_to_joint_direction, + reference_xyzw=reference_xyzw) + holdout = [row for row in observations if row.cycle == 3] + errors = fitted.holdout_errors(holdout) + metrics = angular_metrics(errors) + if not metrics.passed: + raise RotationHoldoutFailure(rotation_holdout_diagnostic( + fitted, holdout, errors, metrics, joint=joint, view=view)) + hysteresis = float(np.max(np.abs(np.asarray(fitted.increasing_rad) - fitted.decreasing_rad))) + curve = JointCurveFit(fitted.angle_rad, fitted.decreasing_rad, fitted.increasing_rad, + {"space": "relative_rotation_3d", "input_domain": input_domain, "input_knots": fitted.knots, + "reference_quaternion_xyzw": fitted.reference_xyzw, "axis_xyz": fitted.axis_xyz, + "training_cycles": [0, 1, 2], "training_sample_ids": sorted(fitted.training_sample_ids)}, + fitted.maximum_monotonic_correction_rad, hysteresis, {"sample_count": float(len(observations)), + "holdout_mae_deg": metrics.mae_deg, "holdout_p95_deg": metrics.p95_deg, + "holdout_max_deg": metrics.maximum_deg}) + return curve, errors + + +def compare_native_views(primary, secondary): + """Diagnostic comparison in their common physical input interval. + + Neither curve is replaced or recalibrated from the other view. Absolute + mount phase differs between Tags, so centre each frozen branch for this + diagnostic alone; final file FK validates the actual fixed mounts. + """ + import numpy as np + a, b = primary.circle["input_knots"], secondary.circle["input_knots"] + lower, upper = max(a[0], b[0]), min(a[-1], b[-1]) + if upper <= lower: + raise ValueError("cross-view native input supports do not overlap") + inputs = np.linspace(lower, upper, 65) + left = np.interp(inputs, a, primary.angle_rad) + right = np.interp(inputs, b, secondary.angle_rad) + if (left[-1] - left[0]) * (right[-1] - right[0]) <= 0: + return {"direction_disagrees": 1.0} + result = {"travel_difference_rad": abs(float(np.ptp(left) - np.ptp(right)))} + for field in ("angle_rad", "increasing_rad", "decreasing_rad"): + x = np.interp(inputs, a, getattr(primary, field)) + y = np.interp(inputs, b, getattr(secondary, field)) + delta = (x - np.mean(x)) - (y - np.mean(y)) + result[f"{field}_rms_difference_rad"] = float(np.sqrt(np.mean(delta ** 2))) + return result + + +def fit_byte_observed_motion(records_by_joint, *, source_model, mimic_sources, + baseline_by_joint=None, image_curve_joints=(), input_domain="feedback_u8", direction_by_joint=None): + """3+1 frozen-reference byte-domain hinge fit; no per-cycle re-zeroing.""" + curves, errors = {}, {} + for joint, rows in sorted(records_by_joint.items()): + # The retained byte primitive calls its abscissa command_u8. Adapt a + # PRIVATE numerical input, never overwrite the captured command. + rows = [dict(row, command_u8=int(round(float(row[input_domain])))) for row in rows] + ids = [image_identity(row) for row in rows] + if len(set(ids)) != len(ids): + raise ValueError(f"duplicate visual fitting image:{joint}") + for cycle in range(4): + for direction in ("increasing", "decreasing"): + if sum(int(row["cycle"]) == cycle and row["direction"] == direction for row in rows) < 40: + raise ValueError(f"missing bidirectional visual samples:{joint}:{cycle}:{direction}") + training = [row for row in rows if int(row["cycle"]) in {0, 1, 2}] + holdout = [row for row in rows if int(row["cycle"]) == 3] + baseline = int((baseline_by_joint or {}).get(joint, 255)) + primitive = fit_joint_image_curve if joint in image_curve_joints else fit_rotation_joint_curve + curve = primitive(training, zero_command_u8=baseline, canonical_zero_direction=None) + from dataclasses import replace + sign = int((direction_by_joint or {}).get(joint, -1)) + if sign not in {-1, 1}: + raise ValueError("byte SDK direction must be explicitly signed") + if sign == 1: + circle = dict(curve.circle) + if circle["space"] == "image_2d": + circle["orientation_sign"] = -float(circle["orientation_sign"]) + else: + circle["axis_xyz"] = [-float(v) for v in circle["axis_xyz"]] + # The legacy primitive chooses an arbitrary axis orientation with + # a negative input slope. Reorient BOTH the observation axis and + # every branch to the declared SDK direction, never just the table. + curve = replace(curve, circle=circle, **{field: tuple(-v for v in getattr(curve, field)) + for field in ("angle_rad", "increasing_rad", "decreasing_rad")}) + curve = replace(curve, circle={**curve.circle, "input_domain": input_domain, "input_knots": tuple(range(256))}) + residuals = joint_curve_holdout_errors(curve, holdout, zero_command_u8=baseline) + if not angular_metrics(residuals).passed: + raise ValueError(f"independent_rotation_holdout_failed:{joint}") + curves[joint], errors[joint] = curve, residuals + evidence = {} + for target, source in mimic_sources.items(): + cad = source_model.joints[target] + if cad.mimic_joint != source: + raise ValueError(f"mimic source differs from CAD:{target}") + evidence[target] = fit_relative_standard_mimic(source, target, + paired_visual_observations(records_by_joint[source], records_by_joint[target], curves[source], curves[target]), + cad_offset_rad=cad.mimic_offset) + return curves, errors, evidence diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_draft.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_draft.py new file mode 100644 index 0000000..8bf3294 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_draft.py @@ -0,0 +1,322 @@ +"""Approximate command curves using the existing CAD image objective. + +Drafts estimate supported internal zeros. Unobserved root frames and declared +CAD leaf zeros remain explicit premises, never arbitrary measured offsets. +""" +from collections import defaultdict +from dataclasses import replace +from itertools import product + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..domain.capture_plan import task_for_joint +from ..geometry.tag_pose.motion_evidence import _axis +from ..geometry.tag_pose.urdf_command_images import UrdfCommandImages, pose_vector +from .motion_fit import joint_input_direction + +UPRIGHT_SPLAY_JOINTS = frozenset(finger+'_mcp_roll' for finger in ('index', 'middle', 'ring', 'pinky')) +UPRIGHT_SPLAY_REFERENCE = 'operator_defined_upright_splay_baseline' + + +def define_upright_splay_zero(profile, model): + """Use the operator's upright baseline as a definition, not a measurement.""" + if (profile.key.model != 'O30' or profile.key.side != 'right' + or not UPRIGHT_SPLAY_JOINTS <= profile.zero.active_joints): + raise ValueError('draft_upright_splay_requires_o30_right_four_fingers') + for name in UPRIGHT_SPLAY_JOINTS: + finger = name.split('_')[0] + positions = [model.link_transform(profile.command.urdf_joint_by_joint.get(joint, joint), + zero_offsets={}, joint_angles={}, independent_mimic_angles=True)[:3, 3] + for joint in (finger+'_mcp_pitch', finger+'_pip')] + direction = positions[1]-positions[0] + if not np.allclose(direction/np.linalg.norm(direction), [0., 0., 1.], atol=1e-6): + raise ValueError('draft_source_zero_is_not_upright:' + name) + assumptions = dict(profile.zero.cad_zero_assumptions) + assumptions.update({name: UPRIGHT_SPLAY_REFERENCE for name in UPRIGHT_SPLAY_JOINTS}) + return replace(profile, zero=replace(profile.zero, cad_zero_assumptions=assumptions)) + + +def draft_training_coverage(completed_units, units): + """Audit accepted directions without borrowing from independent validation.""" + completed = set(completed_units) + coverage = {} + for task in sorted({unit.task_key for unit in units}): + cycles = {} + for cycle in (0, 1): + expected = {unit.identity for unit in units if unit.task_key == task and unit.cycle == cycle} + accepted = expected & completed + cycles[cycle] = dict(expected_units=len(expected), accepted_units=len(accepted), + complete=bool(expected) and accepted == expected) + complete = [cycle for cycle, row in cycles.items() if row['complete']] + coverage[task] = dict(cycles=cycles, complete_cycles=complete, + initialization_cycle=complete[0] if complete else None) + return coverage + + +def draft_targets(profile, selected=None): + """Report the requested whole-hand result independently of partial output.""" + target_ranges = set(profile.zero.active_joints) + retained_leaves = set(profile.zero.cad_zero_assumptions) + target_zeros = target_ranges-retained_leaves + measured_ranges = set() if selected is None else set(selected.zero.active_joints) + measured_zeros = set() if selected is None else measured_ranges-set(selected.zero.cad_zero_assumptions) + defined_zeros = set() if selected is None else {name for name, reason in + selected.zero.cad_zero_assumptions.items() if reason == UPRIGHT_SPLAY_REFERENCE} + return dict(zero_target_joints=sorted(target_zeros), range_target_joints=sorted(target_ranges), + retained_leaf_zero_joints=sorted(retained_leaves), estimated_zero_joints=sorted(measured_zeros), + defined_zero_joints=sorted(defined_zeros), + estimated_range_joints=sorted(measured_ranges), + missing_zero_joints=sorted(target_zeros-measured_zeros-defined_zeros), + missing_range_joints=sorted(target_ranges-measured_ranges), + full_target_covered=(target_zeros <= measured_zeros | defined_zeros and target_ranges <= measured_ranges)) + + +def draft_profile(profile, model, completed_units, units, training): + """One complete training cycle supports a draft, with observed ancestors.""" + coverage = draft_training_coverage(completed_units, units) + tasks = {task for task, row in coverage.items() if row['complete_cycles']} + names = {name for task in profile.motion.tasks if task.key in tasks for name in task.joints} + cad_names = {name: profile.command.urdf_joint_by_joint.get(name, name) for name in names} + observed = set(cad_names.values()) + names = frozenset(name for name in names if all(j.kind == 'fixed' or j.name in observed + for j in model._chain(cad_names[name]))) + if not names: + raise ValueError('draft_no_complete_ancestor_supported_training') + from ...profiles.observations import compile_tag_links + links = compile_tag_links(profile, model) + observed = {cad_names[name] for name in names} + visible = {role for row in training for role in row.get('tags', {})} + roles = {role for role, link in links.items() if role in visible and (link == model.root_link or all( + j.kind == 'fixed' or j.name in observed + for j in model._chain(model.parent_joint_by_child[link])))} + # Fixed tags belong to the root, which has no parent joint. + views = tuple(replace(view, tags=tuple(tag for tag in view.tags + if tag.fixed_reference or tag.role in roles)) for view in profile.vision.views) + assumptions = {name: reason for name, reason in profile.zero.cad_zero_assumptions.items() if name in names} + for name, observer in profile.zero.spatial.get('offset_observer_joint', {}).items(): + if name in names and observer not in names: + assumptions[name] = 'partial_missing_zero_observer:' + observer + roots = [name for name in names if not any(j.kind != 'fixed' + for j in model._chain(cad_names[name])[:-1])] + # With only one root chain, rotating palm and root zero together leaves + # every image identical. Fix that gauge, while fitting the internal zeros. + if len(roots) == 1: + assumptions[roots[0]] = 'partial_single_root_zero_unobservable_without_palm_reference' + selected = replace(profile, + zero=replace(profile.zero, active_joints=names, + cad_zero_assumptions=assumptions), + motion=replace(profile.motion, tasks=tuple(task for task in profile.motion.tasks + if task.key in tasks and set(task.joints) <= names)), + vision=replace(profile.vision, views=views)) + required = {profile.measurement.measurements[name].child_role for name in names} + if not required <= roles: + raise ValueError('draft_required_training_tags_missing:' + str(sorted(required-roles))) + return selected + + +class DraftCommandImages(UrdfCommandImages): + """Shared image objective, with exact repeated-pose least-squares reduction.""" + + # Numerical stopping for an explicitly uncertified draft; release angular, + # image, observability and final-file acceptance limits remain independent. + solver_ftol = 1e-5 + + def __init__(self, profile, model, extrinsics, rows, tag_links, *, initialization_cycles=None, + training_initialization=None): + super().__init__(profile, model, extrinsics, rows, tag_links) + self.training_initialization = training_initialization + self.initialization_cycles = (dict(initialization_cycles) if initialization_cycles is not None + else {task.key: 0 for task in profile.motion.tasks}) + if any(self.initialization_cycles.get(task.key) not in (0, 1) for task in profile.motion.tasks): + raise ValueError('draft_initialization_training_cycle_required') + self.original_observations = self.observations + self.observations, weights, within_group_error = {}, [], 0. + local_names = {cad: name for name, cad in self.cad_names.items()} + for role, (indices, pixels, matrices, objects) in self.original_observations.items(): + channels = [self.channels[local_names[joint.name]] for joint in self.chains[role] + if joint.kind != 'fixed'] + groups = defaultdict(list) + for position, index in enumerate(indices): + key = (tuple(self.commands[index, channels]), tuple(self.directions[index, channels]), + matrices[position].tobytes()) + groups[key].append(position) + representatives, means = [], [] + for positions in groups.values(): + mean = pixels[positions].mean(axis=0) + within_group_error += float(np.sum((pixels[positions]-mean)**2)) + representatives.append(positions[0]) + means.append(mean) + weights.extend([np.sqrt(len(positions))]*8) + self.observations[role] = (indices[representatives], np.asarray(means), + matrices[representatives], objects) + self.residual_weights = np.asarray(weights) + self.within_group_error = within_group_error + self.original_residual_count = sum(len(data[0])*8 for data in self.original_observations.values()) + + def residual(self, parameters): + # sum ||prediction - pixel_i||² = n ||prediction - mean||² + scatter. + # Keep scatter in the objective, including the solver stopping test. + return np.r_[super().residual(parameters)*self.residual_weights, + np.sqrt(self.within_group_error), np.zeros(7)] + + def jacobian(self, parameters): + weighted = super().jacobian(parameters)*self.residual_weights[:, None] + return np.vstack((weighted, np.zeros((8, len(parameters))))) + + def original_residual(self, parameters): + predicted = self.project_observations(parameters, self.commands, self.directions, self.original_observations) + return np.concatenate([(predicted[role]-data[1]).ravel() + for role, data in self.original_observations.items()]) + + def audit_root_directions(self): + """Reject opposite SDK signs for CAD-parallel roots, before fitting zeros. + + Only complete training cycles enter this check. Both planar candidates + and both scan directions are retained; an ambiguous axis is not a + direction correction. Nothing here changes commands or chooses a pose. + """ + roots = [name for name in self.profile.zero.spatial.get('root_anchor_joints', ()) + if name in self.joints] + axes = {} + for name in roots: + spec = self.profile.measurement.measurements[name] + task = task_for_joint(self.profile, name) + channel = self.channels[name] + observed = [] + for direction in range(2): + indices = self.motion_indices(name, direction, self.initialization_cycles[task.key]) + if len(indices) < 3: + continue + for branch in (0, 1): + _, poses = self.motion_poses(indices, spec.child_role, branch) + axis, phase = _axis(Rotation.from_matrix(np.asarray(poses)[:, :3, :3])) + if abs(phase[-1]-phase[0]) < np.radians(15): + continue + observed.append(axis*np.sign(phase[-1]-phase[0]) + *joint_input_direction(self.profile, self.model, name)) + axes[name] = observed + comparisons = [] + for i, first in enumerate(roots): + a, _ = self.model.axis_line(self.cad_names[first], zero_offsets={}, joint_angles={}) + for second in roots[i+1:]: + b, _ = self.model.axis_line(self.cad_names[second], zero_offsets={}, joint_angles={}) + if abs(a @ b) < .999 or not axes[first] or not axes[second]: + continue + dots = np.asarray(axes[first]) @ np.asarray(axes[second]).T * np.sign(a @ b) + comparisons.append(dict(joints=[first, second], minimum_cosine=float(dots.min()), + maximum_cosine=float(dots.max()), reversed_for_all_candidates=bool(dots.max() < -.5))) + return dict(training_only=True, validation_used=False, comparisons=comparisons, + passed=not any(row['reversed_for_all_candidates'] for row in comparisons)) + + def initialize(self, branches): + roles = sorted(self.tags) + if len(branches) != min(6, len(roles)) or any(b not in (0, 1) for b in branches): + raise ValueError('draft_initialization_seed_invalid') + branch_by_role = {role: branches[min(i, len(branches)-1)] for i, role in enumerate(roles)} + initial = np.zeros(len(self.scale)) + lines = {} + for name in self.joints: + task = task_for_joint(self.profile, name) + spec = self.profile.measurement.measurements[name] + channel = self.channels[name] + sign = joint_input_direction(self.profile, self.model, name) + for direction in range(2): + indices = self.motion_indices(name, direction, self.initialization_cycles[task.key]) + if len(indices) < 3: + raise ValueError('draft_directional_training_missing:' + name) + indices, poses = self.motion_poses(indices, spec.child_role, branch_by_role[spec.child_role]) + axis, phase = _axis(Rotation.from_matrix(poses[:, :3, :3])) + if (phase[-1]-phase[0])*sign < 0: + axis, phase = -axis, -phase + commands = self.commands[indices, channel] + phase -= np.interp(self.profile.command.baseline_values[channel], commands, phase) + self.set_initial_curve(initial, name, direction, np.interp(self.knots[name], commands, phase)) + if direction == 0: + turns = poses[:, :3, :3] @ poses[0, :3, :3].T + blocks = np.eye(3)-turns + target = poses[:, :3, 3]-np.einsum('nij,j->ni', turns, poses[0, :3, 3]) + lines[name] = (axis, np.linalg.lstsq(blocks.reshape(-1, 3), target.ravel(), rcond=1e-6)[0], indices[0]) + angles = self.joint_angles(initial, self.commands, self.directions) + cad_axes, axes, cad_points, points = [], [], [], [] + for name, (axis, point, index) in lines.items(): + cad_axis, cad_point = self.model.axis_line(self.cad_names[name], zero_offsets={}, + joint_angles={joint: values[index] for joint, values in angles.items()}, independent_mimic_angles=True) + cad_axes.append(cad_axis); axes.append(axis) + cad_points.append(cad_point); points.append(point) + if np.linalg.matrix_rank(np.asarray(cad_axes), tol=.01) < 2: + raise ValueError('draft_initialization_requires_nonparallel_observed_axes') + rotation, _ = Rotation.align_vectors(np.asarray(axes), np.asarray(cad_axes)) + blocks = np.asarray([np.eye(3)-np.outer(axis, axis) for axis in axes]) + targets = np.einsum('nij,nj->ni', blocks, np.asarray(points)-rotation.apply(cad_points)) + initial[:3] = rotation.as_rotvec() + initial[3:6] = np.linalg.lstsq(blocks.reshape(-1, 3), targets.ravel(), rcond=1e-6)[0] + if self.training_initialization is not None: + hint = self.training_initialization + initial[:6] = hint['palm'] + for name, mapping in hint['mappings'].items(): + if name not in self.joints: + continue + if name in self.zero_columns: + initial[self.zero_columns[name]] = hint['offsets'][name] + for direction, values in enumerate((mapping.increasing_rad, mapping.decreasing_rad)): + self.set_initial_curve(initial, name, direction, + np.interp(self.knots[name], mapping.knots, values)) + transforms = self.link_poses(initial, self.commands, self.directions) + for role, column in self.mount_columns.items(): + index = self.observations[role][0][0] + initial[column:column+6] = pose_vector(np.linalg.inv(transforms[self.tag_links[role]][index]) + @ self._pose(index, role, branch_by_role[role])) + self._initialization_costs[tuple(branches)] = self._refine_mount_guesses(initial, transforms, + observations=self.original_observations) + return initial + + +def fit_draft(bundle, candidate_completed=lambda _row: None): + """Training-only representative; image precision is reported, not certified.""" + candidates, audit = [], [] + seed_width = min(6, len(bundle.tags)) + for seed in product((0, 1), repeat=seed_width): + row = dict(seed=list(seed), converged=False) + try: + fit = bundle.fit(seed) + if not fit.success or not np.all(np.isfinite(fit.x)) or not np.all(np.isfinite(fit.fun)): + raise ValueError('draft_optimizer_did_not_converge') + bundle.output_mappings(fit.x) + residual = bundle.original_residual(fit.x) if hasattr(bundle, 'original_residual') else fit.fun + errors = np.sqrt(np.mean(np.sum(residual.reshape(-1, 4, 2)**2, axis=-1), axis=-1)) + row.update(converged=True, coordinate_rms_px=float(np.sqrt(np.mean(residual**2))), + tag_rms_p95_px=float(np.percentile(errors, 95)), maximum_tag_rms_px=float(errors.max()), + original_image_precision_passed=bool(errors.max() <= 1.5), + evaluations=int(fit.nfev+fit.initialization_evaluations)) + candidates.append((row, fit.x.copy())) + except (ValueError, np.linalg.LinAlgError) as error: + row['reason'] = str(error) + audit.append(row) + candidate_completed(row) + # A reviewable draft needs a bounded representative search, not a + # release claim that all geometric alternatives have been excluded. + if len(candidates) == 4: + break + if not candidates: + raise ValueError('draft_no_converged_training_candidate') + selected, parameters = min(candidates, key=lambda pair: pair[0]['coordinate_rms_px']) + jacobian = bundle.jacobian(parameters)*bundle.scale[None, :] + _u, singular, vectors = np.linalg.svd(jacobian, full_matrices=jacobian.shape[0] < jacobian.shape[1]) + rows = getattr(bundle, 'original_residual_count', jacobian.shape[0]) + rank = int(np.count_nonzero(singular > singular[0]*max(rows, jacobian.shape[1])*np.finfo(float).eps)) + nullspace = vectors[rank:] + unresolved = [name for name, column in bundle.zero_columns.items() + if len(nullspace) and np.linalg.norm(nullspace[:, column]) > 1e-6] + if unresolved: + raise ValueError('draft_estimated_zero_unobservable:' + ','.join(unresolved)) + zeros = {name: dict(estimated_deg=float(np.degrees(bundle.zero_offsets(parameters)[name])), + candidate_spread_deg=float(np.degrees(np.ptp([bundle.zero_offsets(value)[name] + for _, value in candidates])))) for name in bundle.zero_columns} + return parameters, dict(selected_seed=selected['seed'], selection='minimum_training_coordinate_rms', + validation_used_for_selection=False, precision_certified=False, candidates=audit, + solver_stopping_ftol=getattr(bundle, 'solver_ftol', 1e-9), + candidate_search_policy='uncertified_draft_up_to_four_converged_v1', + initializations_evaluated=len(audit), available_initializations=2**seed_width, + candidate_search_exhaustive=len(audit) == 2**seed_width, + estimated_zeros=zeros, local_parameter_rank=rank, parameter_count=len(bundle.scale)), candidates diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_fit.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_fit.py new file mode 100644 index 0000000..254a99c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_fit.py @@ -0,0 +1,176 @@ +"""Training-only candidate sets for the CAD-constrained image graph.""" +from dataclasses import dataclass + +import numpy as np + +from ..geometry.tag_pose.finger_chain_images import chain_candidate_seeds + + +@dataclass(frozen=True) +class RawJointCandidate: + seed: tuple + parameters: np.ndarray + covariance: np.ndarray + rms_px: float + + def __post_init__(self): + for field in ('parameters', 'covariance'): + value = np.array(getattr(self, field), copy=True) + value.flags.writeable = False + object.__setattr__(self, field, value) + + +@dataclass(frozen=True) +class RawJointFit: + candidates: tuple[RawJointCandidate, ...] + representative: int + uncertainty: dict + training_audit: tuple + training_selection: dict | None = None + + +def physical_outputs(bundle, parameters): + """Physical quantities only: differing installation poses are not vetoes.""" + offsets = bundle.zero_offsets(parameters) + values = bundle.mappings(parameters) + zeros = np.asarray([offsets[name] for name in bundle.joints]) + # Absolute angles retain covariance between the zero and command curve. + commands = np.concatenate([(values[name]+offsets[name]).ravel() for name in bundle.joints]) + axes, points = [], [] + probes = [list(bundle.profile.command.baseline_values)] + for name, channel in bundle.channels.items(): + for knot in bundle.knots[name]: + probe = probes[0].copy(); probe[channel] = knot; probes.append(probe) + probes = np.asarray(probes) + fk_points, fk_rotations = [], [] + for direction in (0, 1): + poses = bundle.link_poses(parameters, probes, np.full(probes.shape, direction)) + if direction == 0: + for name in bundle.joints: + joint = bundle.model.joints[bundle.cad_names[name]] + frame = poses[joint.parent][0] @ joint.origin + axes.append(frame[:3, :3] @ joint.axis) + points.append(frame[:3, 3]) + for link in sorted(set(bundle.tag_links.values())): + fk_points.extend(poses[link][:, :3, 3]) + fk_rotations.extend(poses[link][:, :3, :3].reshape(-1, 9)) + return dict(zero_rad=zeros, command_rad=commands, axis=np.asarray(axes), + axis_point_m=np.asarray(points), fk_point_m=np.asarray(fk_points), + fk_rotation=np.asarray(fk_rotations)) + + +def candidate_uncertainty(bundle, candidate): + from .raw_joint_uncertainty import physical_intervals + return physical_outputs(bundle, candidate.parameters), physical_intervals(bundle, candidate) + + +def certify_candidate_union(bundle, candidates): + if not candidates: + raise ValueError('raw_joint_no_training_candidate') + evaluated = [candidate_uncertainty(bundle, candidate) for candidate in candidates] + limits = dict(zero_rad=np.radians(1), command_rad=np.radians(1), + axis=2*np.sin(np.radians(3)/2), axis_point_m=.0015, + fk_point_m=.003, fk_rotation=2*np.sqrt(2)*np.sin(np.radians(1)/2)) + audit, failures, radii = {}, [], {} + for key, limit in limits.items(): + values = np.asarray([item[0][key] for item in evaluated]) + widths = np.asarray([item[1][key] for item in evaluated]) + radii[key] = [] + for first in range(len(candidates)): + difference = values-values[first] + if difference.ndim == 3: + difference = np.linalg.norm(difference, axis=-1) + else: + difference = np.abs(difference) + radii[key].append(float(np.max(difference+widths))) + # Choose a physical minimax representative only AFTER forming the union. + # Pixel scores and installation uniqueness never choose the exported zero. + representative = int(np.argmin(np.max(np.asarray([np.asarray(radii[k])/v + for k, v in limits.items()]), axis=0))) + for key, limit in limits.items(): + radius = radii[key][representative] + audit[key] = dict(maximum_union_radius=radius, limit=float(limit), passed=bool(radius <= limit)) + if radius > limit: + failures.append(key) + values = np.asarray([item[0][key] for item in evaluated]) + widths = np.asarray([item[1][key] for item in evaluated]) + difference = values-values[representative] + difference = np.linalg.norm(difference,axis=-1) if difference.ndim == 3 else np.abs(difference) + affected = np.flatnonzero(np.max(difference+widths,axis=0) > limit) + if key in {'zero_rad','axis','axis_point_m'}: + names = {bundle.joints[int(index)] for index in affected} + elif key == 'command_rad': + labels = [name for name in bundle.joints for _ in range(2*len(bundle.knots[name]))] + names = {labels[int(index)] for index in affected} + else: + probes = 1+sum(len(nodes) for nodes in bundle.knots.values()) + links = sorted(set(bundle.tag_links.values())) + affected_links = {links[(int(index)//probes)%len(links)] for index in affected} + names = {name for name in bundle.joints if bundle.model.joints[bundle.cad_names[name]].child in affected_links} + audit[key]['affected_joints'] = sorted(names) + audit[key]['required_observations'] = [dict(joint=name, + task=next(task.key for task in bundle.profile.motion.tasks if name in task.joints), + view=bundle.profile.measurement.measurements[name].view, + tag_roles=[bundle.profile.measurement.measurements[name].parent_role, + bundle.profile.measurement.measurements[name].child_role], + need=('bidirectional_steady_command_support' if key == 'command_rad' else + 'simultaneous_link_observations_with_distinct_axis_or_held_pose_geometry'), + repeat_identical_trajectory_automatically=False) for name in sorted(names)] + if any(abs(v) > np.radians(20) for candidate in candidates + for v in bundle.zero_offsets(candidate.parameters).values()): + failures.append('absolute_zero_exceeds_20deg') + audit['passed'] = not failures + audit['failures'] = failures + audit['scope'] = 'training_command_grid_and_single_joint_fk; not_arbitrary_multiaxis' + return audit, representative + + +def fit_raw_joint_candidates(bundle, *, cancelled=lambda: False, candidate_completed=lambda _row: None, + workers=1): + """The existing 64 seeds / 200 evaluations; validation is not an input.""" + from concurrent.futures import ThreadPoolExecutor + if type(workers) is not int or not 1 <= workers <= 4: + raise ValueError('raw_joint_worker_budget_invalid') + candidates, audit = [], [] + def solve(seed): + if cancelled(): + raise ValueError('operator_abort:no_artifact_publication') + row = dict(seed=list(seed), converged=False, accepted_for_uncertainty=False) + try: + fit = bundle.fit(seed) + row.update(converged=bool(fit.success), evaluations=int(fit.nfev)+fit.initialization_evaluations, + joint_evaluations=int(fit.nfev), initialization_evaluations=fit.initialization_evaluations, + rms_px=float(np.sqrt(np.mean(fit.fun**2)))) + if not fit.success: + raise ValueError('optimizer_budget_exhausted') + from ..geometry.tag_pose.parameters import DEFAULT_POSE_TRACKING_PARAMETERS + errors = np.sqrt(np.mean(fit.fun.reshape(-1, 4, 2)**2, axis=(1, 2))*2) + row['maximum_training_tag_rms_px'] = float(np.max(errors)) + if np.max(errors) > DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px: + row['training_excluded'] = 'declared_image_reprojection_limit' + return None, row + covariance = bundle.covariance(fit) + bundle.output_mappings(fit.x) # Reject nonmonotonic physical curves. + candidate = RawJointCandidate(tuple(seed), fit.x, covariance, row['rms_px']) + row['accepted_for_uncertainty'] = True + except (ValueError, np.linalg.LinAlgError) as error: + # Failure to initialize/converge cannot prove an alternative false. + row['unresolved_reason'] = str(error) + candidate = None + return candidate, row + with ThreadPoolExecutor(max_workers=workers) as pool: + for candidate, row in pool.map(solve, chain_candidate_seeds()): + if candidate is not None: + candidates.append(candidate) + audit.append(row) + candidate_completed(row) + if any(not row['accepted_for_uncertainty'] and not row.get('training_excluded') for row in audit): + raise ValueError('raw_joint_unresolved_training_candidates:see_raw_joint_training.json') + from .raw_joint_selection import reject_training_distinguishable_candidates + candidates, selection = reject_training_distinguishable_candidates(bundle, tuple(candidates)) + excluded = {tuple(seed) for seed in selection.get('excluded_seeds', ())} + for row in audit: + if tuple(row['seed']) in excluded: + row.update(accepted_for_uncertainty=False, training_excluded='paired_training_loss_holm') + uncertainty, representative = certify_candidate_union(bundle, candidates) + return RawJointFit(candidates, representative, uncertainty, tuple(audit), selection) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_selection.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_selection.py new file mode 100644 index 0000000..c60b203 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_selection.py @@ -0,0 +1,80 @@ +"""Training-only rejection of distinguishable image hypotheses. + +Repeated holds and optimizer seeds are not independent observations. Compare +one median paired loss per distinct command/direction pose, with the existing +0.03 px resolution margin and Holm familywise correction. Survivors, including +physically different tied solutions, all proceed to covariance propagation. +""" +from collections import defaultdict + +import numpy as np +from scipy.stats import ttest_1samp, wilcoxon + +from ..geometry.tag_pose.image_model_selection import holm_adjusted_probabilities +from ..geometry.tag_pose.parameters import DEFAULT_REPROJECTION_TIE_PX + + +def _families(bundle, candidates): + families = [] + for index, candidate in enumerate(candidates): + for family in families: + if all(np.max(np.abs(candidate.parameters-candidates[other].parameters)/bundle.scale) <= 1e-5 + for other in family): + family.append(index) + break + else: + families.append([index]) + return families + + +def _probability(differences): + if len(differences) < 6 or not np.all(np.isfinite(differences)) or np.mean(differences) <= 0: + return 1. + if np.ptp(differences) < 1e-12: + return 2.**-len(differences) + mean = float(ttest_1samp(differences,0.,alternative='greater').pvalue) + rank = float(wilcoxon(differences,alternative='greater',zero_method='wilcox').pvalue) + return max(mean,rank) if np.isfinite(mean) and np.isfinite(rank) else 1. + + +def reject_training_distinguishable_candidates(bundle, candidates): + if not candidates: + return (), dict(policy='training_paired_pose_losses_holm_v1', families=[], comparisons=[]) + families = _families(bundle,candidates) + anchor = min(range(len(candidates)),key=lambda i:candidates[i].rms_px) + predictions = [bundle.project_observations(c.parameters,bundle.commands,bundle.directions,bundle.observations) + for c in candidates] + probabilities, comparisons = [], [] + for family_index,family in enumerate(families): + if anchor in family: + continue + for role,(indices,measured,_matrices,_objects) in bundle.observations.items(): + base = np.sqrt(np.mean(np.sum((predictions[anchor][role]-measured)**2,axis=2),axis=1)) + # Only commanded ancestors move this role. Other fingers' repeated + # holds cannot multiply the evidence for its installation branch. + ancestors = {joint.name for joint in bundle.chains[role]} + channels = sorted(bundle.channels[name] for name in bundle.joints if bundle.cad_names[name] in ancestors) + strata = defaultdict(list) + for local,index in enumerate(indices): + key = tuple((float(bundle.commands[index,ch]),int(bundle.directions[index,ch])) for ch in channels) + strata[key].append(local) + pvalues = [] + for member in family: + other = np.sqrt(np.mean(np.sum((predictions[member][role]-measured)**2,axis=2),axis=1)) + losses = other**2-(base+DEFAULT_REPROJECTION_TIE_PX)**2 + differences = np.asarray([np.median(losses[items]) for items in strata.values()]) + pvalues.append(_probability(differences)) + index = len(comparisons) + probabilities.append((index,max(pvalues))) + comparisons.append(dict(family=family_index,role=role,pose_strata=len(strata), + probability=max(pvalues))) + excluded = set() + for index,adjusted in holm_adjusted_probabilities(probabilities): + comparisons[index]['holm_probability'] = adjusted + if adjusted < .01: + excluded.update(families[comparisons[index]['family']]) + retained = tuple(c for i,c in enumerate(candidates) if i not in excluded) + return retained, dict(policy='training_paired_pose_losses_holm_v1', + training_comparison_anchor=list(candidates[anchor].seed), pixel_margin=DEFAULT_REPROJECTION_TIE_PX, + familywise_alpha=.01, families=[[list(candidates[i].seed) for i in family] for family in families], + excluded_seeds=[list(candidates[i].seed) for i in sorted(excluded)], comparisons=comparisons) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_uncertainty.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_uncertainty.py new file mode 100644 index 0000000..8093541 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_uncertainty.py @@ -0,0 +1,91 @@ +"""Exact first derivatives of physical outputs, including full covariance.""" +import numpy as np + +from ..geometry.tag_pose.urdf_command_images import rigid, right_jacobian, skew + + +def angle_derivatives(bundle, commands, directions): + derivatives = {} + width = len(bundle.scale) + for name, channel in bundle.channels.items(): + jac = np.zeros((len(commands), width)) + if name in bundle.zero_columns: + jac[:, bundle.zero_columns[name]] = 1. + weights = bundle.curve_weights(name, commands[:,channel], directions[:,channel]) + for direction in range(2): + for node, column in enumerate(bundle.curve_columns[name][direction]): + if column >= 0: + jac[:,column] += weights[:,direction,node] + derivatives[bundle.cad_names[name]] = jac + return derivatives + + +def pose_derivatives(bundle, parameters, commands, directions): + poses = bundle.link_poses(parameters, commands, directions) + angles = angle_derivatives(bundle, commands, directions) + shape = (len(commands), 3, len(parameters)) + position, rotation = np.zeros(shape), np.zeros(shape) + position[:,:,3:6] = np.eye(3) + rotation[:,:,:3] = rigid(parameters[:6])[:3,:3] @ right_jacobian(parameters[:3]) + jacobians = {bundle.model.root_link: (position, rotation)} + frames = {} + for chain in bundle.chains.values(): + for joint in chain: + if joint.child in jacobians: + continue + parent_position, parent_rotation = jacobians[joint.parent] + frame = poses[joint.parent] @ joint.origin + displacement = frame[:,:3,3]-poses[joint.parent][:,:3,3] + point = parent_position-skew(displacement) @ parent_rotation + angular = parent_rotation.copy() + if joint.kind != 'fixed': + axis = frame[:,:3,:3] @ joint.axis + angular += axis[:,:,None]*angles[joint.name][:,None,:] + frames[joint.name] = (point, -skew(axis) @ parent_rotation) + jacobians[joint.child] = point, angular + return poses, jacobians, frames + + +def physical_intervals(bundle, candidate): + parameters, covariance = candidate.parameters, candidate.covariance + def interval(jac): + # Scalar or vector three-sigma radius, preserving every correlation. + shape = jac.shape[:-1] + flat = jac.reshape(-1, len(parameters)) + from scipy.sparse import csr_matrix + sparse = csr_matrix(flat) + variance = np.asarray(sparse.multiply(sparse @ covariance).sum(axis=1)).ravel().reshape(shape) + return 3*np.sqrt(np.maximum(variance, 0.).sum(axis=-1) if len(shape)>1 else np.maximum(variance, 0.)) + zeros = np.zeros((len(bundle.joints), len(parameters))) + commands = [] + for i, name in enumerate(bundle.joints): + if name in bundle.zero_columns: + zeros[i,bundle.zero_columns[name]] = 1. + for direction in (0, 1): + basis = bundle.curve_weights(name, bundle.knots[name], + np.full(len(bundle.knots[name]), direction)) + for weights in basis: + row = zeros[i].copy() + for column, weight in zip(bundle.curve_columns[name].ravel(), weights.ravel()): + if column >= 0: + row[column] += weight + commands.append(row) + result = dict(zero_rad=interval(zeros), command_rad=interval(np.asarray(commands))) + probes = [list(bundle.profile.command.baseline_values)] + for name, channel in bundle.channels.items(): + for knot in bundle.knots[name]: + probe = probes[0].copy(); probe[channel] = knot; probes.append(probe) + probes = np.asarray(probes) + points, rotations = [], [] + for direction in (0,1): + poses, jacobians, frames = pose_derivatives(bundle, parameters, probes, np.full(probes.shape, direction)) + if direction == 0: + result['axis_point_m'] = interval(np.asarray([frames[bundle.cad_names[n]][0][0] for n in bundle.joints])) + result['axis'] = interval(np.asarray([frames[bundle.cad_names[n]][1][0] for n in bundle.joints])) + for link in sorted(set(bundle.tag_links.values())): + point, angular = jacobians[link] + points.extend(interval(point).tolist()) + # ||dR||_F = sqrt(2)||angular velocity||, exact rotation metric. + rotations.extend((np.sqrt(2)*interval(angular)).tolist()) + result['fk_point_m'], result['fk_rotation'] = np.asarray(points), np.asarray(rotations) + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_update.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_update.py new file mode 100644 index 0000000..28274e4 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_update.py @@ -0,0 +1,88 @@ +"""Constrained batch updates of the existing image objective, without motion. + +The caller supplies the new batch's camera geometry and immutable reference +parameters. Unselected joints and tag installations cannot move in the fit. +""" +import numpy as np +from scipy.optimize import least_squares + + +def check_update_zero_observability(bundle, parameters, active, joints): + """Reject zero gauges, conditional on the explicitly frozen reference.""" + jacobian = bundle.jacobian(parameters)[:, active]*bundle.scale[active] + _, singular, vectors = np.linalg.svd(jacobian, + full_matrices=jacobian.shape[0] < jacobian.shape[1]) + rows = getattr(bundle, 'original_residual_count', jacobian.shape[0]) + rank = int(np.count_nonzero(singular > singular[0]*max(rows, len(active))*np.finfo(float).eps)) + nullspace = vectors[rank:] + positions = {column: i for i, column in enumerate(active)} + unresolved = [name for name in joints if name in bundle.zero_columns + and (bundle.zero_columns[name] not in positions or (len(nullspace) + and np.linalg.norm(nullspace[:, positions[bundle.zero_columns[name]]]) > 1e-6))] + if unresolved: + raise ValueError('batch_update_zero_unobservable:' + ','.join(unresolved)) + return rank + + +def transfer_parameters(source, parameters, target): + """Copy semantic parameters; array positions may differ between scopes.""" + result = np.zeros(len(target.scale)) + result[:6] = parameters[:6] + for name, columns in target.curve_columns.items(): + if not np.array_equal(source.knots[name], target.knots[name]): + raise ValueError('batch_update_training_knots_changed:' + name) + mask = columns >= 0 + original = source.curve_columns[name] + if not np.array_equal(mask, original >= 0): + raise ValueError('batch_update_baseline_changed:' + name) + result[columns[mask]] = parameters[original[mask]] + for name, column in target.zero_columns.items(): + result[column] = source.zero_offsets(parameters)[name] + for role, column in target.mount_columns.items(): + if source.tag_links[role] != target.tag_links[role]: + raise ValueError('batch_update_tag_link_changed:' + role) + original = source.mount_columns[role] + result[column:column+6] = parameters[original:original+6] + return result + + +def fit_joint_update(bundle, initial, joints, mount_roles, *, fit_palm=True): + """Use the shared bounded solver while keeping the reference hand fixed.""" + if not set(joints) <= set(bundle.joints) or not set(mount_roles) <= set(bundle.tags): + raise ValueError('batch_update_scope_invalid') + columns = list(range(6)) if fit_palm else [] + for name in joints: + if name in bundle.zero_columns: + columns.append(bundle.zero_columns[name]) + columns.extend(bundle.curve_columns[name][bundle.curve_columns[name] >= 0]) + for role in mount_roles: + start = bundle.mount_columns[role] + columns.extend(range(start, start+6)) + proposed = np.asarray(sorted(set(columns)), dtype=int) + # Unobserved increments cannot acquire invented travel through optimizer + # drift. Retain their input values and report that they were not fitted. + supported = np.linalg.norm(bundle.jacobian(initial)[:, proposed], axis=0) > 1e-8 + active = proposed[supported] + if not len(active): + raise ValueError('batch_update_no_observed_parameters') + def unpack(values): + parameters = initial.copy() + parameters[active] = values + return parameters + options = dict(bundle.solver_options) + lower, upper = options.pop('bounds') + fit = least_squares(lambda x: bundle.residual(unpack(x)), initial[active], + jac=lambda x: bundle.solver_jacobian(unpack(x))[:, active], + bounds=(lower[active], upper[active]), x_scale=bundle.scale[active], + max_nfev=100, ftol=bundle.solver_ftol, **options) + parameters = unpack(fit.x) + rank = check_update_zero_observability(bundle, parameters, active, joints) + derived = {row['column'] for rows in getattr(bundle, 'turnaround_constraints', {}).values() for row in rows} + audit = dict(converged=bool(fit.success), evaluations=int(fit.nfev), + coordinate_rms_px=float(np.sqrt(np.mean(bundle.original_residual(parameters)**2))), + active_columns=active.tolist(), + derived_turnaround_columns=sorted(derived.intersection(proposed.tolist())), + unobserved_retained_columns=[int(column) for column in proposed[~supported] if column not in derived], + validation_used=False, fixed_cad_axes=True, conditional_parameter_rank=rank, + observability_condition='unselected_joints_and_tag_mounts_fixed') + return parameters, audit diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_validation.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_validation.py new file mode 100644 index 0000000..ad2b410 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/raw_joint_validation.py @@ -0,0 +1,141 @@ +"""Independent per-image angles; shared geometry and command maps stay frozen. + +Images with the same observation layout are evaluated together. Their angle +variables remain separate blocks, so vectorization shares no measurements and +cannot turn the third round into a geometry or mapping fit. +""" +from collections import defaultdict +from dataclasses import asdict + +import numpy as np +from scipy.optimize import least_squares +from scipy.sparse import coo_matrix +from scipy.spatial.transform import Rotation + +from ..domain.motion_path import task_segment +from ..urdf.acceptance import angular_metrics +from ..urdf.tag_acceptance import POSITION_P95_LIMIT_M +from ..geometry.tag_pose.parameters import DEFAULT_POSE_TRACKING_PARAMETERS +from ..geometry.tag_pose.ippe import square_object_points + + +def _groups(bundle, rows): + training_ids = {(r['view'], r['image_stamp_ns']) for r in bundle.rows} + matrices = {r['view']: np.asarray(r['camera_matrix']) for r in bundle.rows} + tasks = {task.key: task for task in bundle.profile.motion.tasks} + seen, groups = set(), defaultdict(list) + for row in rows: + if row.get('sample_phase') != 'steady' or row.get('accepted_sample_window_open') is not True: + continue + identity = row['view'], row['image_stamp_ns'] + if identity in training_ids or identity in seen or row.get('cycle') != 3: + raise ValueError('raw_joint_holdout_not_independent') + seen.add(identity) + if not np.array_equal(row['camera_matrix'], matrices.get(row['view'])): + raise ValueError('raw_joint_holdout_intrinsics_changed') + task = tasks[row['task_name']] + segment = task_segment(task, row['segment_key']) if row.get('segment_key') else None + roles = tuple(role for role, (view, _) in bundle.tags.items() + if view == row['view'] and role in row.get('tags', {})) + ancestors = {joint.name for role in roles for joint in bundle.chains[role]} + names = tuple(name for name in (segment.joints if segment else task.joints) + if bundle.cad_names[name] in ancestors) + if roles: + groups[row['view'], names, roles].append(row) + return groups + + +def _measure_group(bundle, candidate, rows, names, roles, cancelled): + count, width = len(rows), len(names) + commands = np.asarray([row['command_vector'] for row in rows]) + directions = bundle._directions(rows) + observations = {} + for role in roles: + pixels = np.asarray([row['tags'][role]['corners_xy'] for row in rows], dtype=float) + if pixels.shape != (count,4,2) or not np.all(np.isfinite(pixels)): + raise ValueError('raw_joint_holdout_corners_invalid') + observations[role] = (np.arange(count), pixels, + np.asarray([row['camera_matrix'] for row in rows]), square_object_points(bundle.tags[role][1].size_m)) + def corrections(values): + matrix = values.reshape(count,width) + return {name: matrix[:,index] for index,name in enumerate(names)} + def residual(values): + if cancelled(): + raise ValueError('operator_abort:no_artifact_publication') + predicted = bundle.project_observations(candidate.parameters, commands, directions, + observations, corrections(values)) + return np.concatenate([(predicted[role]-data[1]).ravel() for role,data in observations.items()]) + forward = residual(np.zeros(count*width)).reshape(len(roles),count,8) + if not width: + return None, forward, forward, None, None, None + # Every image's pixels depend only on that image's active angle variables. + row_indices = np.arange(len(roles)*count*8) + columns = np.tile(np.repeat(np.arange(count),8),len(roles)) + sparsity = coo_matrix((np.ones(len(row_indices)*width), + (np.repeat(row_indices,width), (columns[:,None]*width+np.arange(width)).ravel())), + shape=(len(row_indices),count*width)).tocsr() + fit = least_squares(residual, np.zeros(count*width), jac_sparsity=sparsity, + max_nfev=20, ftol=1e-9, xtol=1e-9, gtol=1e-8, + tr_options=dict(atol=1e-12,btol=1e-12)) + if not fit.success: + raise ValueError('raw_joint_holdout_angle_measurement_failed') + local_jac = np.zeros((count,len(roles)*8,width)) + for role_index in range(len(roles)): + indices = role_index*count*8+np.arange(count*8).reshape(count,8) + for column in range(width): + selected = fit.jac[indices, (np.arange(count)*width+column)[:,None]] + local_jac[:,role_index*8:(role_index+1)*8,column] = ( + selected.toarray() if hasattr(selected, 'toarray') else np.asarray(selected)) + information = np.einsum('nki,nkj->nij',local_jac,local_jac) + eigen = np.linalg.eigvalsh(information) + if np.any(eigen[:,0] <= np.maximum(1.,eigen[:,-1])*np.finfo(float).eps*width): + raise ValueError('raw_joint_holdout_angle_unobservable') + measured = fit.fun.reshape(len(roles),count,8) + variance = np.maximum(.03**2,np.sum(measured**2,axis=(0,2))/max(1,len(roles)*8-width)) + confidence = 3*np.sqrt(np.diagonal(np.linalg.inv(information),axis1=1,axis2=2)*variance[:,None]) + predicted_poses = bundle.link_poses(candidate.parameters,commands,directions) + measured_poses = bundle.link_poses(candidate.parameters,commands,directions,corrections(fit.x)) + return fit.x.reshape(count,width), forward, measured, confidence, predicted_poses, measured_poses + + +def validate_raw_joint_candidate(bundle, candidate, rows, *, cancelled=lambda: False, + report_joints=None): + names_to_report = tuple(bundle.joints if report_joints is None else report_joints) + if not names_to_report or not set(names_to_report) <= set(bundle.joints): + raise ValueError('raw_joint_holdout_report_scope_invalid') + angles, positions, rotations = defaultdict(list), defaultdict(list), defaultdict(list) + primary_counts, pixels, forward_pixels, uncertainty = defaultdict(int), [], [], [] + for (view,names,roles), group in _groups(bundle,rows).items(): + values, forward, measured, confidence, predicted, observed = _measure_group( + bundle,candidate,group,names,roles,cancelled) + forward_pixels.extend(np.sqrt(np.mean(forward**2,axis=2)*2).ravel().tolist()) + pixels.extend(np.sqrt(np.mean(measured**2,axis=2)*2).ravel().tolist()) + if values is None: + continue + uncertainty.extend(confidence.ravel().tolist()) + for column,name in enumerate(names): + angles[name].extend(values[:,column].tolist()) + if bundle.profile.measurement.measurements[name].view == view: + primary_counts[name] += len(group) + link = bundle.model.joints[bundle.cad_names[name]].child + a,b = predicted[link],observed[link] + positions[name].extend(np.linalg.norm(a[:,:3,3]-b[:,:3,3],axis=1).tolist()) + rotations[name].extend(Rotation.from_matrix(a[:,:3,:3].transpose(0,2,1)@b[:,:3,:3]).magnitude().tolist()) + reports = {} + for name in names_to_report: + if primary_counts[name] < bundle.profile.acquisition.minimum_valid_samples: + raise ValueError('raw_joint_holdout_measurements_missing:'+name) + angular,orientation = angular_metrics(angles[name]),angular_metrics(rotations[name]) + position = float(np.percentile(positions[name],95)) + reports[name] = dict(angular=asdict(angular),orientation=asdict(orientation), + position_p95_m=position,samples=len(angles[name]),primary_samples=primary_counts[name], + passed=angular.passed and orientation.passed and position <= POSITION_P95_LIMIT_M) + passed = (bool(reports) and all(r['passed'] for r in reports.values()) + and max(uncertainty,default=np.inf) <= np.radians(1) + and max(pixels,default=np.inf) <= DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px) + return dict(passed=bool(passed),joints=reports, + maximum_measurement_confidence_rad=max(uncertainty,default=None), + maximum_measurement_reprojection_px=max(pixels,default=None), + frozen_forward_reprojection_p95_px=float(np.percentile(forward_pixels,95)) if forward_pixels else None, + holdout_cycle=3,shared_parameters_updated=False, + policy='frozen_forward_commands_and_independent_image_angles_v1') diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/rotation_curve.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/rotation_curve.py new file mode 100644 index 0000000..775cf33 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/rotation_curve.py @@ -0,0 +1,214 @@ +"""Native-domain hinge measurements with a single training-frozen Tag frame. + +This primitive measures *relative* motion. Its arbitrary reference angle is +not a CAD zero; spatial calibration must supply that separate datum. Neither +holdout observations nor SDK endpoints are allowed to set that datum. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + +from .curve import isotonic_nonincreasing +from ..domain.capture_plan import LEGACY_TRAINING, LEGACY_HOLDOUT + + +@dataclass(frozen=True) +class RotationObservation: + sample_id: str + input_value: float + quaternion_xyzw: tuple[float, float, float, float] + cycle: int + direction: str + + +@dataclass(frozen=True) +class RotationCurve: + input_domain: str + knots: tuple[float, ...] + increasing_rad: tuple[float, ...] + decreasing_rad: tuple[float, ...] + reference_xyzw: tuple[float, float, float, float] + axis_xyz: tuple[float, float, float] + sdk_to_joint_direction: int + training_sample_ids: frozenset[str] + maximum_monotonic_correction_rad: float = 0.0 + training_cycles: tuple[int, ...] = LEGACY_TRAINING + holdout_cycle: int = LEGACY_HOLDOUT + + @property + def angle_rad(self) -> tuple[float, ...]: + return tuple((a + b) / 2 for a, b in zip(self.increasing_rad, self.decreasing_rad)) + + def predict(self, value: float, direction: str) -> float: + if direction not in {"increasing", "decreasing"}: + raise ValueError("curve direction must be a native SDK direction") + if not math.isfinite(value) or not self.knots[0] <= value <= self.knots[-1]: + raise ValueError("input outside measured curve domain") + return float(np.interp(value, self.knots, getattr(self, direction + "_rad"))) + + def measure(self, quaternion_xyzw: Sequence[float]) -> tuple[float, float]: + relative = Rotation.from_quat(self.reference_xyzw).inv() * _rotation(quaternion_xyzw) + vector = relative.as_rotvec() + axis = np.asarray(self.axis_xyz) + angle = float(vector @ axis) + predicted = Rotation.from_rotvec(axis * angle) + off_axis_error = float((predicted.inv() * relative).magnitude()) + return angle, off_axis_error + + def holdout_errors(self, observations: Sequence[RotationObservation]) -> tuple[float, ...]: + _validate_observations(observations, cycles={self.holdout_cycle}) + if any(row.sample_id in self.training_sample_ids for row in observations): + raise ValueError("holdout image identity overlaps training") + reference = Rotation.from_quat(self.reference_xyzw) + axis = np.asarray(self.axis_xyz) + # Full SO(3) residual, not just its projection onto the fitted axis: + # a slipped/tilted Tag cannot pass by retaining a plausible scalar angle. + return tuple(float(((reference * Rotation.from_rotvec( + axis * self.predict(row.input_value, row.direction) + )).inv() * _rotation(row.quaternion_xyzw)).magnitude()) for row in observations) + + +def _rotation(quaternion: Sequence[float]) -> Rotation: + values = np.asarray(quaternion, dtype=float) + if values.shape != (4,) or not np.all(np.isfinite(values)) or np.linalg.norm(values) < 1e-12: + raise ValueError("Tag quaternion must be finite and nondegenerate") + return Rotation.from_quat(values) + + +def common_directional_input_support(values, directions) -> tuple[float, float]: + """Training-only support shared by fitting and live acquisition checks.""" + inputs = np.asarray(values, dtype=float) + if inputs.ndim != 1 or len(inputs) != len(directions) or not np.all(np.isfinite(inputs)): + raise ValueError("directional SDK inputs must be finite matching vectors") + if any(direction not in {"increasing", "decreasing"} for direction in directions): + raise ValueError("invalid SDK support direction") + supports = [] + for direction in ("increasing", "decreasing"): + selected = inputs[np.asarray([value == direction for value in directions], dtype=bool)] + if not selected.size: + raise ValueError("both directional SDK supports are required") + supports.append((float(np.min(selected)), float(np.max(selected)))) + lower, upper = max(s[0] for s in supports), min(s[1] for s in supports) + if upper <= lower: + raise ValueError("directional SDK supports do not overlap") + return lower, upper + + +def _validate_observations(rows: Sequence[RotationObservation], *, cycles: set[int]) -> None: + if not rows: + raise ValueError("rotation observations are missing") + ids = [row.sample_id for row in rows] + if not all(ids) or len(set(ids)) != len(ids): + raise ValueError("rotation image identities must be nonempty and unique") + for row in rows: + if row.cycle not in cycles or row.direction not in {"increasing", "decreasing"}: + raise ValueError("rotation cycle/direction is outside the requested data partition") + if not math.isfinite(row.input_value): + raise ValueError("rotation input must be finite") + _rotation(row.quaternion_xyzw) + + +def fit_rotation_curve( + observations: Sequence[RotationObservation], *, input_domain: str, + sdk_to_joint_direction: int, knot_count: int = 65, + reference_xyzw: Sequence[float] | None = None, + training_cycles: tuple[int, ...] = LEGACY_TRAINING, + holdout_cycle: int = LEGACY_HOLDOUT, +) -> RotationCurve: + """Fit three complete training cycles without integerizing physical inputs. + + A fixed reference and axis are learned once. The two branches keep their + measured hysteresis; per-cycle/per-direction recentering is forbidden. + The resulting support is the common observed native-input interval. + """ + if input_domain not in {"feedback_rad", "command_rad", "feedback_u8", "command_u8"}: + raise ValueError("an explicit native SDK input domain is required") + if sdk_to_joint_direction not in {-1, 1} or knot_count < 32: + raise ValueError("invalid direction or curve knot count") + if len(training_cycles) < 2 or holdout_cycle in training_cycles: + raise ValueError("at least two independent training cycles and an isolated holdout are required") + _validate_observations(observations, cycles=set(training_cycles)) + required = {(cycle, direction) for cycle in training_cycles for direction in ("increasing", "decreasing")} + groups = {(row.cycle, row.direction) for row in observations} + if groups != required: + raise ValueError("complete declared bidirectional training cycles are required") + for cycle, direction in required: + if sum(row.cycle == cycle and row.direction == direction for row in observations) < 40: + raise ValueError("each training direction requires 40 unique observations") + inputs = np.asarray([row.input_value for row in observations]) + if input_domain.endswith("u8") and (np.min(inputs) < 0 or np.max(inputs) > 255): + raise ValueError("byte observations are outside the SDK domain") + frame = fit_rotation_frame(observations, sdk_to_joint_direction=sdk_to_joint_direction, + reference_xyzw=reference_xyzw, training_cycles=training_cycles) + reference = Rotation.from_quat(frame.reference_xyzw) + axis = np.asarray(frame.axis_xyz) + angles = (reference.inv() * Rotation.from_quat([r.quaternion_xyzw for r in observations])).as_rotvec() @ axis + lower, upper = common_directional_input_support(inputs, [row.direction for row in observations]) + knots = np.linspace(lower, upper, knot_count) + branches = {} + maximum_correction = 0.0 + for direction in ("increasing", "decreasing"): + mask = np.asarray([row.direction == direction for row in observations]) + x, y = inputs[mask], angles[mask] + order = np.argsort(x, kind="stable") + unique, starts = np.unique(x[order], return_index=True) + # Median repeated encoder observations before projecting monotonically. + medians = np.asarray([np.median(group) for group in np.split(y[order], starts[1:])]) + projected = -sdk_to_joint_direction * isotonic_nonincreasing(-sdk_to_joint_direction * medians) + maximum_correction = max(maximum_correction, float(np.max(np.abs(projected - medians)))) + branches[direction] = tuple(float(v) for v in np.interp(knots, unique, projected)) + return RotationCurve(input_domain, tuple(float(v) for v in knots), + branches["increasing"], branches["decreasing"], tuple(reference.as_quat()), + tuple(axis), sdk_to_joint_direction, frozenset(row.sample_id for row in observations), maximum_correction, + tuple(training_cycles), holdout_cycle) + + +@dataclass(frozen=True) +class VisualRotationFrame: + """Training-only hinge frame, independent of any SDK-to-angle regression.""" + reference_xyzw: tuple[float, ...] + axis_xyz: tuple[float, ...] + training_sample_ids: tuple[str, ...] + training_cycles: tuple[int, ...] = LEGACY_TRAINING + + @property + def circle(self): + return {"space": "relative_rotation_3d", "reference_quaternion_xyzw": self.reference_xyzw, + "axis_xyz": self.axis_xyz, "training_cycles": list(self.training_cycles), + "training_sample_ids": self.training_sample_ids} + + +def fit_rotation_frame(observations, *, sdk_to_joint_direction, reference_xyzw=None, + training_cycles=LEGACY_TRAINING): + _validate_observations(observations, cycles=set(training_cycles)) + for cycle in training_cycles: + for direction in ("increasing", "decreasing"): + if sum(r.cycle == cycle and r.direction == direction for r in observations) < 40: + raise ValueError("visual frame requires 40 training images per cycle/direction") + if sdk_to_joint_direction not in {-1, 1}: + raise ValueError("visual frame requires a signed physical direction") + inputs = np.asarray([row.input_value for row in observations]) + rotations = Rotation.from_quat([row.quaternion_xyzw for row in observations]) + # Use one observed reference, never assert that its input is a CAD zero. + reference = rotations[int(np.argmin(inputs))] if reference_xyzw is None else _rotation(reference_xyzw) + vectors = (reference.inv() * rotations).as_rotvec() + _, singular, vh = np.linalg.svd(vectors, full_matrices=False) + if not singular.size or singular[0] < math.radians(1): + raise ValueError("hinge rotation is not observable") + axis = vh[0] + angles = vectors @ axis + trend = float((inputs - np.mean(inputs)) @ (angles - np.mean(angles))) + if abs(trend) <= 1e-12: + raise ValueError("SDK/visual motion direction is not observable") + if math.copysign(1, trend) != sdk_to_joint_direction: + axis, angles = -axis, -angles + if np.ptp(angles) >= math.pi - math.radians(1): + raise ValueError("hinge travel exceeds this rotation primitive's unambiguous interval") + return VisualRotationFrame(tuple(reference.as_quat()), tuple(axis), + tuple(sorted(row.sample_id for row in observations)), tuple(training_cycles)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/rotation_diagnostics.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/rotation_diagnostics.py new file mode 100644 index 0000000..3279b31 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/rotation_diagnostics.py @@ -0,0 +1,78 @@ +"""Explain a failed frozen rotation holdout without changing its acceptance.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Sequence + +from ..urdf.acceptance import ErrorMetrics, angular_metrics +from .rotation_curve import RotationCurve, RotationObservation + + +@dataclass(frozen=True) +class RotationHoldoutSample: + sample_id: str + cycle: int + direction: str + input_value: float + full_so3_error_deg: float + axial_error_deg: float + off_axis_error_deg: float + + +@dataclass(frozen=True) +class RotationHoldoutDiagnostic: + joint: str | None + view: str | None + input_domain: str + full_so3: ErrorMetrics + axial: ErrorMetrics + off_axis: ErrorMetrics + worst_sample: RotationHoldoutSample + training_cycles: tuple[int, ...] = (0, 1, 2) + holdout_cycle: int = 3 + + +class RotationHoldoutFailure(ValueError): + """A rejected rotation fit with serializable, read-only sample evidence.""" + + def __init__(self, diagnostics: RotationHoldoutDiagnostic): + self.diagnostics = diagnostics + metrics = diagnostics.full_so3 + super().__init__( + "independent_rotation_holdout_failed:" + f"joint={diagnostics.joint or 'unknown'}:view={diagnostics.view or 'unknown'}:" + f"mae_deg={metrics.mae_deg:.6f}:p95_deg={metrics.p95_deg:.6f}:" + f"max_deg={metrics.maximum_deg:.6f}") + + +def rotation_holdout_diagnostic( + fitted: RotationCurve, + observations: Sequence[RotationObservation], + errors_rad: Sequence[float], + metrics: ErrorMetrics, + *, + joint: str | None, + view: str | None, +) -> RotationHoldoutDiagnostic: + """Describe the existing failed fit; never fit, re-zero or filter samples. + + Axial error compares projected log angles. Off-axis error measures the + observed rotation's departure from the frozen hinge axis. These explain + different effects; their magnitudes are not additive SO(3) components. + Only the original full SO(3) metrics determine acceptance. + """ + measurements = [fitted.measure(row.quaternion_xyzw) for row in observations] + axial = [angle - fitted.predict(row.input_value, row.direction) + for row, (angle, _) in zip(observations, measurements)] + off_axis = [error for _, error in measurements] + worst_index = max(range(len(errors_rad)), key=errors_rad.__getitem__) + worst = observations[worst_index] + return RotationHoldoutDiagnostic( + joint, view, fitted.input_domain, metrics, + angular_metrics(axial), angular_metrics(off_axis), + RotationHoldoutSample( + worst.sample_id, worst.cycle, worst.direction, worst.input_value, + math.degrees(errors_rad[worst_index]), math.degrees(axial[worst_index]), + math.degrees(off_axis[worst_index]))) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/session.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/session.py new file mode 100644 index 0000000..e5913ca --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/session.py @@ -0,0 +1,242 @@ +"""Profile-selected geometry/curve/mimic fitting, with no model imports.""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +import math +from pathlib import Path +from typing import Mapping + +from ..domain.profile import CalibrationProfile, validate_profile +from ..domain.result import CalibrationResult, JointMapping +from ..domain.capture_plan import (CapturePlan, ADAPTIVE, STAGED, TASKWISE_STAGED, TASKWISE_TWO_ROUND, + training_cycles) +from ..urdf.kinematics import UrdfKinematicModel +from .motion_fit import channel_for_joint, fit_profile_motion, joint_input_direction +from .spatial import ZeroCalibrationProfile, fit_joint_axis_measurement, solve_urdf_zero_offsets, with_depth_free_axis_projection + + +@dataclass(frozen=True) +class SpatialHandContract: + side: str + layout_id: str + active_joints: tuple[str, ...] + reference_finger: str = "" + palm_orientation_sources: Mapping[str, str] = field(default_factory=dict) + minimum_palm_orientation_sources: int = 0 + stable_cross_view_cone_bias: bool = False + + +def compile_spatial_profile(profile: CalibrationProfile) -> ZeroCalibrationProfile: + data = profile.zero.spatial + allowed = {"root_anchor_joints", "axis_parent_joint", "phase_parent_joint", + "offset_observer_joint", "base_pose_strategy", "orientation_anchor_joint", + "directed_base_axis_joints", "depth_free_axis_projection", "axis_order", + "same_view_axis_pair_by_offset", + "parallel_root_pattern", + "accept_validated_zero_in_confidence_interval"} + if not data or set(data) - allowed: + raise ValueError("spatial observation graph is missing or has unsupported fields") + direct = tuple(profile.zero.direct_zero_joints) + observers = dict(data.get("offset_observer_joint", {})) + if set(observers) != set(direct): + raise ValueError("every required zero must have an explicit observable axis/phase datum") + axes = tuple(data.get("axis_order", profile.zero.axis_joints)) + if set(axes) != set(profile.zero.axis_joints) or len(set(axes)) != len(axes): + raise ValueError("spatial axis order differs from declared observations") + # Coordinate descent must solve an upstream zero before the downstream + # phase that depends on it. The declaration of required zeros is a set of + # requirements, not an optimization order (O6 used pitch before yaw). + if not set(direct) <= set(axes): + raise ValueError("spatial zero has no position in the declared axis order") + direct = tuple(name for name in axes if name in direct) + return ZeroCalibrationProfile( + hand=SpatialHandContract(profile.key.side, profile.key.layout, tuple(profile.zero.active_joints - profile.retained_joints), + stable_cross_view_cone_bias=profile.measurement.stable_cross_view_cone_bias), + direct_zero_joints=direct, axis_joints=axes, + inherited_zero_joints={} if profile.artifacts.output_schema_version >= 3 else dict(profile.zero.transferred_zero_sources), + inherited_static_zero_joints={} if profile.artifacts.output_schema_version >= 3 else dict(profile.zero.transferred_zero_sources), + constrained_circle_joints=frozenset(axes), + root_anchor_joints=frozenset(data.get("root_anchor_joints", ())), + axis_parent_joint=dict(data.get("axis_parent_joint", {})), + phase_parent_joint=dict(data.get("phase_parent_joint", {})), + offset_observer_joint=observers, + same_view_axis_pair_by_offset={name: tuple(pair) for name, pair in data.get("same_view_axis_pair_by_offset", {}).items()}, + fixed_direct_zero_offsets_rad={name: value.cad_angle_rad for name, value in profile.zero.known_baseline_geometry.items() + if name in direct}, static_output_zero_offsets_rad={}, + base_pose_strategy=str(data.get("base_pose_strategy", "full_hand")), + orientation_anchor_joint=data.get("orientation_anchor_joint"), + directed_base_axis_joints=frozenset(data.get("directed_base_axis_joints", ())), + accept_validated_zero_in_confidence_interval=bool(data.get("accept_validated_zero_in_confidence_interval", False)), + parallel_root_pattern=bool(data.get("parallel_root_pattern", False)), + independent_observed_motion=profile.artifacts.output_schema_version >= 3) + + +def build_axis_observations(profile, model, geometry_records, motion, zero_profile, *, include_holdout=True): + """Build only the axis observations present in the declared partition.""" + measured = profile.artifacts.output_schema_version >= 3 + geometry_domain = f"command_{profile.command.unit}" if profile.command_based_release else profile.curve_input_domain + observations = [] + plan = CapturePlan.from_profile(profile) + phase = "steady" if profile.command_based_release else "sweep" + for cycle in sorted({c for part in plan.tasks for c in part.cycles(phase)}): + if not include_holdout and cycle in { + part.command_holdout if phase == "steady" else part.holdout for part in plan.tasks}: + continue + by_joint = {} + for joint in zero_profile.axis_joints: + task = next(task for task in profile.motion.tasks if joint in task.joints) + if cycle not in plan.task(task.key).cycles(phase): + continue + rows = geometry_records[joint] + if profile.command_based_release: + rows = [dict(row, input_value=float(row[geometry_domain]), + state_values=row[f"state_{profile.command.unit}"]) for row in rows] + elif profile.command.unit == "rad": + rows = [dict(row, input_value=float(row[profile.curve_input_domain]), state_values=row["state_rad"]) + for row in rows] + else: + rows = [dict(row, command_u8=int(round(float(row[profile.curve_input_domain])))) for row in rows] + parent = zero_profile.phase_parent_joint.get(joint) + if parent is not None and parent not in by_joint: + if (cycle != plan.task(task.key).holdout + and profile.quality.training_policy in {ADAPTIVE, STAGED, TASKWISE_STAGED, TASKWISE_TWO_ROUND}): + continue # No same-cycle parent observation: do not fabricate a geometric sample. + raise ValueError("spatial axis order must place phase parents first") + task = next(task for task in profile.motion.tasks if joint in task.joints) + baseline = (motion.reference_inputs[joint] if measured else task.start_value if profile.command.unit == "rad" + else profile.command.baseline_values[channel_for_joint(profile, joint)]) + axis = fit_joint_axis_measurement(joint, rows, cycle=cycle, zero_command_u8=baseline, + input_to_joint_direction=joint_input_direction(profile, model, joint), + constrained_circle_joints=zero_profile.constrained_circle_joints, + view_normal_common_xyz=rows[0]["view_normal_common_xyz"], + canonical_zero_direction="decreasing", + axis_common_constraint=None if parent is None else by_joint[parent].axis_common_xyz, + separate_axial_residual=True, + condition_command_field=f"command_vector_{profile.command.unit}" if profile.command_based_release else None) + if profile.zero.spatial.get("depth_free_axis_projection", False): + axis = with_depth_free_axis_projection(axis, rows[0]["camera_center_common_xyz_m"]) + observations.append(axis) + by_joint[joint] = axis + return observations + + +def fit_profile_calibration(profile: CalibrationProfile, source_urdf: Path, records_by_joint, + *, cross_view_records=None, zero_references=None, steady_records=None, motion_fitted=lambda _motion: None, + frozen_training=None) -> CalibrationResult: + """Shared native-domain motion, spatial zero and standard mimic fit. + + No mechanical endpoint or range-centre fallback can replace a requested + but unobservable spatial zero. The fourth cycle never updates the fit. + """ + if profile.artifacts.output_schema_version >= 3: + validate_profile(profile) + if profile.zero.endpoint_anchor_by_joint: + raise ValueError("unverified mechanical endpoints cannot define CAD zeros") + required_pose_fields = {"parent_pose_common", "child_pose_common", + "relative_translation_xyz_m", "view_normal_common_xyz", + "camera_center_common_xyz_m", f"state_{profile.command.unit}"} + for joint in profile.zero.axis_joints: + rows = records_by_joint.get(joint, ()) + if not rows or any(not required_pose_fields.issubset(row) for row in rows): + raise ValueError(f"spatial calibration requires identified common-frame pose observations:{joint}") + model = UrdfKinematicModel(source_urdf) + if profile.retained_joints: + from ..urdf.partial_scope import require_profile_held_pose + from ...profiles.observations import compile_tag_links + links = compile_tag_links(profile, model) + for name, rows in records_by_joint.items(): + spec = profile.measurement.measurements[name] + for row in rows: + for role in (spec.parent_role, spec.child_role): + require_profile_held_pose(profile, model, row[f"command_vector_{profile.command.unit}"], links[role]) + zero_profile = compile_spatial_profile(profile) + if profile.command_based_release: + from .command_motion import fit_command_motion + motion = fit_command_motion(profile, model, records_by_joint, steady_records or {}, zero_references or {}, + frozen_motion=None if frozen_training is None else frozen_training["motion"]) + geometry_records = steady_records + geometry_domain = f"command_{profile.command.unit}" + else: + motion = fit_profile_motion(profile, model, records_by_joint, cross_view_records=cross_view_records, + zero_references=zero_references) + geometry_records = records_by_joint + geometry_domain = profile.curve_input_domain + for joint in profile.zero.axis_joints: + if not geometry_records.get(joint) or any(not required_pose_fields.issubset(row) + for row in geometry_records[joint]): + raise ValueError(f"spatial calibration requires identified geometry poses:{joint}") + motion_fitted(motion) + curves = motion.coordinate_curves + measured = profile.artifacts.output_schema_version >= 3 + baseline_geometry = {name: value.cad_angle_rad for name, value in profile.zero.known_baseline_geometry.items()} + if measured: + baseline_geometry.update({name: 0.0 for name in profile.zero.cad_zero_assumptions}) + spatial_curves = {name: replace(curve, circle={**curve.circle, + "known_cad_baseline_rad": baseline_geometry[name]}) + if measured and name in baseline_geometry and name not in zero_profile.direct_zero_joints + else curve for name, curve in curves.items()} + observations = build_axis_observations(profile, model, geometry_records, motion, zero_profile) + plan = CapturePlan.from_profile(profile) + geometry_training = tuple(sorted({cycle for part in plan.tasks for cycle in + (part.command_training if profile.command_based_release else part.training)})) + geometry_holdout = (plan.tasks[0].command_holdout if profile.command_based_release else profile.quality.holdout_cycle) + zero = solve_urdf_zero_offsets(source_urdf=source_urdf, measurements=observations, + curves=spatial_curves, motor_by_joint={joint: channel_for_joint(profile, joint) for joint in curves}, + zero_profile=zero_profile, training_cycles=geometry_training, validation_cycle=geometry_holdout, + allow_partial_training_cycles=profile.quality.training_policy in {ADAPTIVE, STAGED, TASKWISE_STAGED, TASKWISE_TWO_ROUND}, + frozen_training=None if frozen_training is None else frozen_training["zero"], + maximum_offset_rad=math.radians(20), finger_maximum_offset_rad=math.radians(20), + maximum_validation_mae_rad=math.radians(1), maximum_validation_p95_rad=math.radians(2), + maximum_validation_error_rad=math.radians(3), maximum_confidence_half_width_rad=math.radians(1), + maximum_pose_axis_line_rms_m=0.0015) + if not zero.passed: + raise ValueError("spatial_zero_not_observable_or_inaccurate:" + str(zero.failure_reasons)) + offsets = {name: float(zero.direct_offsets_rad[name]) for name in profile.zero.direct_zero_joints} + methods = {name: "urdf_serial_axis_geometry" for name in offsets} + if measured: + for name, datum in profile.zero.known_baseline_geometry.items(): + offsets[name], methods[name] = datum.cad_angle_rad, "independent_known_baseline_geometry" + for name in profile.zero.cad_zero_assumptions: + offsets[name], methods[name] = 0.0, "assumed_source_cad_zero" + mappings = {name: JointMapping(name, channel_for_joint(profile, name), geometry_domain, + tuple(curve.circle["input_knots"]), curve.angle_rad, curve.increasing_rad, curve.decreasing_rad) + for name, curve in curves.items()} + return CalibrationResult(curves, mappings, offsets, methods, {}, motion.holdout_errors_rad, zero, + motion.cross_view_metrics, motion.reference_inputs, joint_zero_references=dict(zero_references), + command_mappings=motion.mappings if profile.command_based_release else {}, + command_holdout_metrics=motion.command_metrics if profile.command_based_release else {}, + command_applicability=motion.applicability if profile.command_based_release else {}, + feedback_diagnostics=motion.feedback_diagnostics if profile.command_based_release else {}) + for name in profile.zero.active_joints - offsets.keys() - profile.zero.transferred_zero_sources.keys(): + if name not in profile.zero.cad_frozen_joints: + raise ValueError(f"active static zero has no measured or CAD-retention policy:{name}") + offsets[name], methods[name] = 0.0, "source_cad_zero_profile_excluded" + for target, donor in profile.zero.transferred_zero_sources.items(): + offsets[target] = offsets[donor] + methods[target] = "transferred_static_zero_on_own_cad" + mappings = {} + for joint, channel in profile.command.command_index_by_joint.items(): + if joint not in profile.zero.active_joints: + continue + donor = profile.zero.transferred_zero_sources.get(joint, joint) + curve = curves[donor] + knots = tuple(curve.circle.get("input_knots", range(256))) + branches = (curve.angle_rad, curve.increasing_rad, curve.decreasing_rad) + if profile.command.unit == "u8": + # Legacy primitive tables may extend to 0/255. Publish only the + # intersection actually measured in both training directions. + import numpy as np + training = records_by_joint[donor] + support = [[float(r[profile.curve_input_domain]) for r in training + if r["cycle"] in training_cycles(profile, joint=donor) and r["direction"] == direction] + for direction in ("increasing", "decreasing")] + lo, hi = math.ceil(max(min(s) for s in support)), math.floor(min(max(s) for s in support)) + knots = tuple(float(v) for v in range(lo, hi+1)) + branches = tuple(tuple(float(v) for v in np.interp(knots, range(256), values)) for values in branches) + mappings[joint] = JointMapping(joint, channel, profile.curve_input_domain, knots, + *branches, + donor if donor != joint else None) + return CalibrationResult(motion.observed_curves, mappings, offsets, methods, + motion.mimic_evidence, motion.holdout_errors_rad, zero, + motion.cross_view_metrics, motion.reference_inputs) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial.py new file mode 100644 index 0000000..eb2f687 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial.py @@ -0,0 +1,47 @@ +"""Stable spatial API; numerical implementations live in spatial_solver.""" + +from .spatial_solver.types import ZeroCalibrationProfile as ZeroCalibrationProfile +from .spatial_solver.geometry_helpers import circle_direction_is_constrained as circle_direction_is_constrained +from .spatial_solver.geometry_helpers import select_cross_view_roll_direction_source as select_cross_view_roll_direction_source +from .spatial_solver.geometry_helpers import ZERO_REFERENCE_MAXIMUM_DISTANCE_U8 as ZERO_REFERENCE_MAXIMUM_DISTANCE_U8 +from .spatial_solver.geometry_helpers import AXIS_POINT_MINIMUM_ROTATION_RAD as AXIS_POINT_MINIMUM_ROTATION_RAD +from .spatial_solver.geometry_helpers import AXIS_POINT_IMAGE_PLANE_MAXIMUM_OBLIQUITY_RAD as AXIS_POINT_IMAGE_PLANE_MAXIMUM_OBLIQUITY_RAD +from .spatial_solver.geometry_helpers import AXIS_POINT_RESIDUAL_SCALE_M as AXIS_POINT_RESIDUAL_SCALE_M +from .spatial_solver.geometry_helpers import ZERO_MINIMUM_AXIS_CONE_RAD as ZERO_MINIMUM_AXIS_CONE_RAD +from .spatial_solver.geometry_helpers import _zero_sensitive_axis_error_rad as _zero_sensitive_axis_error_rad +from .spatial_solver.geometry_helpers import _axis_cone_mismatch_rad as _axis_cone_mismatch_rad +from .spatial_solver.geometry_helpers import _vector as _vector +from .spatial_solver.geometry_helpers import _pose_matrix as _pose_matrix +from .spatial_solver.geometry_helpers import _relative_rotation as _relative_rotation +from .spatial_solver.rotation_curves import _reference_group_key as _reference_group_key +from .spatial_solver.rotation_curves import _canonical_reference_records as _canonical_reference_records +from .spatial_solver.rotation_curves import _spatial_input as _spatial_input +from .spatial_solver.rotation_curves import _interpolate_reference_rotation as _interpolate_reference_rotation +from .spatial_solver.rotation_curves import _near_zero_records as _near_zero_records +from .spatial_solver.rotation_curves import _baseline_reference as _baseline_reference +from .spatial_solver.rotation_curves import baseline_hysteresis_by_cycle_rad as baseline_hysteresis_by_cycle_rad +from .spatial_solver.rotation_curves import fit_rotation_joint_curve as fit_rotation_joint_curve +from .spatial_solver.rotation_curves import measure_rotation_joint_observation as measure_rotation_joint_observation +from .spatial_solver.rotation_curves import measure_joint_curve_observation as measure_joint_curve_observation +from .spatial_solver.rotation_curves import rotation_curve_holdout_errors as rotation_curve_holdout_errors +from .spatial_solver.rotation_curves import joint_curve_holdout_errors as joint_curve_holdout_errors +from .spatial_solver.types import JointAxisMeasurement as JointAxisMeasurement +from .spatial_solver.types import PalmOrientationMeasurement as PalmOrientationMeasurement +from .spatial_solver.geometry_helpers import PALM_AXIS_INCREMENT_COMMAND_SEPARATION_U8 as PALM_AXIS_INCREMENT_COMMAND_SEPARATION_U8 +from .spatial_solver.geometry_helpers import PALM_AXIS_INCREMENT_MINIMUM_ROTATION_RAD as PALM_AXIS_INCREMENT_MINIMUM_ROTATION_RAD +from .spatial_solver.geometry_helpers import PALM_AXIS_INCREMENT_MINIMUM_PAIR_COUNT as PALM_AXIS_INCREMENT_MINIMUM_PAIR_COUNT +from .spatial_solver.geometry_helpers import PALM_AXIS_INCREMENT_CONSENSUS_PERCENTILE as PALM_AXIS_INCREMENT_CONSENSUS_PERCENTILE +from .spatial_solver.axis_observations import _incremental_common_rotation_axis as _incremental_common_rotation_axis +from .spatial_solver.axis_observations import fit_partial_palm_orientation_measurement as fit_partial_palm_orientation_measurement +from .spatial_solver.axis_observations import fit_partial_palm_orientation_measurements as fit_partial_palm_orientation_measurements +from .spatial_solver.axis_lines import with_depth_free_axis_projection as with_depth_free_axis_projection +from .spatial_solver.axis_lines import cross_view_side_line_source as cross_view_side_line_source +from .spatial_solver.axis_lines import axis_line_uses_depth_free_interpretation_plane as axis_line_uses_depth_free_interpretation_plane +from .spatial_solver.axis_lines import refit_axis_line_group_with_shared_radius as refit_axis_line_group_with_shared_radius +from .spatial_solver.axis_lines import maximum_axis_line_cycle_spread_m as maximum_axis_line_cycle_spread_m +from .spatial_solver.axis_lines import axis_line_cycle_rms_m as axis_line_cycle_rms_m +from .spatial_solver.axis_lines import _fit_axis_point_from_pose_trajectory as _fit_axis_point_from_pose_trajectory +from .spatial_solver.axis_observations import fit_joint_axis_measurement as fit_joint_axis_measurement +from .spatial_solver.types import ZeroSolveResult as ZeroSolveResult +from .spatial_solver.geometry_helpers import _angles_from_state as _angles_from_state +from .spatial_solver.solve import solve_urdf_zero_offsets as solve_urdf_zero_offsets diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/__init__.py new file mode 100644 index 0000000..d40bebb --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/__init__.py @@ -0,0 +1 @@ +"""Shared spatial mathematics; import the stable spatial facade for public APIs.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/acceptance.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/acceptance.py new file mode 100644 index 0000000..58e8151 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/acceptance.py @@ -0,0 +1,187 @@ +"""Unchanged spatial acceptance gates and public result assembly.""" + +from __future__ import annotations + +import math + +import numpy as np + +from .stages import ( + AcceptanceDecision, + CycleEvidence, + GeometryEvidence, + HoldoutEvidence, + LineEvidence, + ObservabilityEvidence, + OffsetLimits, + TrainingFit, + ZeroProblem, + ZeroSolveOptions, +) +from .types import ZeroSolveResult + + +def decide_training_acceptance(*, cycles, fit, geometry_evidence, limits, observability, options, problem): + """All training gates shared by early stopping and final acceptance.""" + profile = problem.profile + common_mode = (float(np.median([fit.training_offsets[name] for name in limits.product_finger_rolls])) + if profile.parallel_root_pattern and limits.product_finger_rolls else 0.) + failures = {} + for name, limit, diagnostic_limit in zip(profile.direct_zero_joints, + limits.offset_limits, limits.diagnostic_offset_limits): + if name in problem.fixed_offsets: + continue + checked = problem.output_offsets.get(name, fit.training_offsets[name]) + if name in limits.product_finger_rolls: + checked -= common_mode + if abs(checked) > limit + math.radians(.01): + failures[name] = "zero_offset_exceeds_configured_limit" + if abs(checked) >= diagnostic_limit - math.radians(.01): + failures[name] = "zero_offset_reached_diagnostic_bound" + if limits.product_finger_rolls and abs(common_mode) > options.maximum_offset_rad + math.radians(.01): + failures["finger_mcp_roll_common_mode"] = "zero_offset_exceeds_configured_limit" + if profile.parallel_root_pattern and profile.base_pose_strategy == "full_hand": + if observability.observability_rank < observability.observability_parameter_count: + failures["palm_and_static_zero"] = "zero_observation_jacobian_rank_deficient" + elif observability.observability_condition_number > options.maximum_observability_condition_number: + failures["palm_and_static_zero"] = "zero_observation_jacobian_ill_conditioned" + for name in cycles.inconsistent_cycles: + failures[name] = "zero_offset_cycle_difference_too_large" + for name in cycles.insignificant_large: + failures[name] = "zero_offset_not_statistically_significant" + if options.maximum_confidence_half_width_rad is not None: + for name, width in cycles.confidence_half_widths.items(): + if width > options.maximum_confidence_half_width_rad: + failures[name] = "zero_offset_confidence_interval_too_wide" + failures.update(geometry_evidence.observation_failures) + return AcceptanceDecision(finger_roll_common_mode=common_mode, failure_reasons=failures, + passed=cycles.cycle_consistent and not failures) + + +def decide_acceptance( + *, cycles: CycleEvidence, fit: TrainingFit, geometry_evidence: GeometryEvidence, + holdout: HoldoutEvidence, limits: OffsetLimits, observability: ObservabilityEvidence, + options: ZeroSolveOptions, problem: ZeroProblem, +) -> AcceptanceDecision: + training = decide_training_acceptance(cycles=cycles, fit=fit, geometry_evidence=geometry_evidence, + limits=limits, observability=observability, options=options, problem=problem) + failures = dict(training.failure_reasons) + if not holdout.palm_orientation_validation_passed: + failures["palm_orientation"] = "palm_orientation_holdout_too_large" + if not holdout.improvement_passed: + for name, value in cycles.applied_training.items(): + if (name not in problem.fixed_offsets and value != 0. + and holdout.improvement_confidence_lower.get(name, 0.) <= 0.): + failures[name] = "zero_offset_did_not_improve_with_95pct_confidence" + # Geometry is the root cause; retain its reason over downstream symptoms. + failures.update(geometry_evidence.observation_failures) + errors = holdout.validation_errors + passed = bool(training.passed and holdout.improvement_passed + and holdout.palm_orientation_validation_passed + and errors.size == len(problem.profile.direct_zero_joints) - len(problem.fixed_offsets) + and errors.size > 0 + and float(np.mean(errors)) <= options.maximum_validation_mae_rad + and float(np.percentile(errors, 95.)) <= options.maximum_validation_p95_rad + and (options.maximum_validation_error_rad is None + or float(np.max(errors)) <= options.maximum_validation_error_rad)) + return AcceptanceDecision(finger_roll_common_mode=training.finger_roll_common_mode, + failure_reasons=failures, passed=passed) + + +def applied_output_offsets(profile, applied_training, output_offsets, product_finger_rolls, common_mode): + """The same training-frozen coordinate convention for Tag fit and release.""" + offsets = {**applied_training, **output_offsets} + if profile.parallel_root_pattern: + for name in product_finger_rolls: + offsets[name] = float(offsets[name]) - common_mode + return offsets + + +def assemble_result( + validation_cycle: int, + *, + cycles: CycleEvidence, + decision: AcceptanceDecision, + fit: TrainingFit, + geometry_evidence: GeometryEvidence, + holdout: HoldoutEvidence, + limits: OffsetLimits, + lines: LineEvidence, + observability: ObservabilityEvidence, + problem: ZeroProblem, +): + applied_training = cycles.applied_training + axis_cone_bias_classification_by_joint = geometry_evidence.axis_cone_bias_classification_by_joint + axis_cone_mismatch_by_joint = geometry_evidence.axis_cone_mismatch_by_joint + axis_line_rms = lines.axis_line_rms + base_rotation = fit.base_rotation + base_translation = fit.base_translation + confidence_half_widths = cycles.confidence_half_widths + cycle_values = cycles.cycle_values + failure_reasons = decision.failure_reasons + finger_roll_common_mode = decision.finger_roll_common_mode + improvement_by_joint = holdout.improvement_by_joint + improvement_confidence_lower = holdout.improvement_confidence_lower + observability_condition_number = observability.observability_condition_number + observability_parameter_count = observability.observability_parameter_count + observability_rank = observability.observability_rank + offset_covariance = observability.offset_covariance + original_error_by_joint = holdout.original_error_by_joint + output_offsets = problem.output_offsets + passed = decision.passed + product_finger_rolls = limits.product_finger_rolls + profile = problem.profile + training_cycle_ids = cycles.training_cycle_ids + uncertainties = cycles.uncertainties + validation_error_by_joint = holdout.validation_error_by_joint + validation_errors = holdout.validation_errors + validation_line_error_by_joint = lines.validation_line_error_by_joint + + # Never refit a model that has passed its holdout with the validation + # cycle. The published offsets are exactly the frozen training result + # that produced ``validation_errors`` above. + final_offsets = applied_output_offsets(profile, applied_training, output_offsets, + product_finger_rolls, finger_roll_common_mode) + # Every active joint must be present in the runtime payload/URDF writer, + # but absence of an absolute observation is not evidence for the + # reference finger's assembly offset. Preserve the source-CAD zero for + # those independent motors while continuing to share their dynamic curve. + all_offsets = { + name: 0.0 for name in profile.hand.active_joints + } + all_offsets.update(final_offsets) + for target, source in profile.inherited_static_zero_joints.items(): + all_offsets[target] = final_offsets[source] + return ZeroSolveResult( + direct_offsets_rad=final_offsets, + all_active_offsets_rad=all_offsets, + base_translation_xyz_m=tuple(float(value) for value in base_translation), + base_quaternion_xyzw=tuple(float(value) for value in base_rotation.as_quat()), + validation_errors_rad=tuple(float(value) for value in validation_errors), + validation_error_by_joint_rad=validation_error_by_joint, + validation_line_error_by_joint_m=validation_line_error_by_joint, + axis_line_rms_m=axis_line_rms, + passed=passed, + cycle_offsets_rad={ + name: tuple(float(value) for value in values) + for name, values in cycle_values.items() + }, + offset_uncertainty_rad=uncertainties, + offset_confidence_half_width_rad=confidence_half_widths, + training_cycles=training_cycle_ids, + validation_cycle=int(validation_cycle), + validation_original_error_by_joint_rad=original_error_by_joint, + validation_improvement_by_joint_rad=improvement_by_joint, + validation_improvement_confidence_lower_rad=( + improvement_confidence_lower + ), + observability_rank=observability_rank, + observability_parameter_count=observability_parameter_count, + observability_condition_number=observability_condition_number, + offset_covariance_rad2=offset_covariance, + axis_cone_mismatch_by_joint_rad=axis_cone_mismatch_by_joint, + axis_cone_bias_classification_by_joint=( + axis_cone_bias_classification_by_joint + ), + failure_reasons=failure_reasons, + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/axis_lines.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/axis_lines.py new file mode 100644 index 0000000..6519a14 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/axis_lines.py @@ -0,0 +1,603 @@ +"""Axis lines.""" + +from __future__ import annotations + +from dataclasses import replace +from typing import Any, Mapping, Sequence +import math + +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation +import numpy as np + +from ...geometry.rotation import robust_rotation_summary +from ..trajectory_geometry import _fit_circle_with_axis, _plane_basis +from .geometry_helpers import ( + AXIS_POINT_IMAGE_PLANE_MAXIMUM_OBLIQUITY_RAD, + AXIS_POINT_MINIMUM_ROTATION_RAD, + AXIS_POINT_RESIDUAL_SCALE_M, + _pose_matrix, + _relative_rotation, + _vector, +) +from .rotation_curves import _baseline_reference, _canonical_reference_records, _near_zero_records +from .types import JointAxisMeasurement + + +def with_depth_free_axis_projection( + measurement: JointAxisMeasurement, + camera_center_common_xyz_m: Sequence[float], +) -> JointAxisMeasurement: + """Attach the source-camera interpretation plane of an axis line. + + The plane is defined by the camera centre and the fitted 3-D line, but is + only a projective observation: moving either fitted line point along its + optical ray leaves the plane unchanged. A fixed Tag mount changes the + moving point trajectory, not its recovered physical screw axis. + """ + camera_center = _vector( + camera_center_common_xyz_m, 3, name="axis camera centre" + ) + point = np.asarray(measurement.point_common_xyz_m, dtype=float) + axis = np.asarray(measurement.axis_common_xyz, dtype=float) + axis /= np.linalg.norm(axis) + ray = point - camera_center + ray_norm = float(np.linalg.norm(ray)) + if ray_norm <= 1.0e-6: + raise ValueError("axis point coincides with its source camera") + plane_normal = np.cross(ray / ray_norm, axis) + plane_norm = float(np.linalg.norm(plane_normal)) + if plane_norm <= 1.0e-6: + raise ValueError("axis projection is degenerate in its source camera") + plane_normal /= plane_norm + return replace( + measurement, + axis_point_camera_center_common_xyz_m=tuple( + float(value) for value in camera_center + ), + axis_point_interpretation_plane_normal_common_xyz=tuple( + float(value) for value in plane_normal + ), + ) + + +def cross_view_side_line_source( + measurement: JointAxisMeasurement, +) -> str | None: + """Return the side alias that supplied a fallback axis-line point.""" + sources = tuple( + str(source) + for source in getattr( + measurement, "pose_axis_line_source_joints", () + ) + ) + if ( + getattr(measurement, "axis_point_source", "") + in { + "side_circle_cross_view", + "side_circle_shared_radius_cross_view", + "side_interpretation_plane_cross_view", + } + and len(sources) == 1 + and sources[0].endswith("_side") + ): + return sources[0] + return None + + +def axis_line_uses_depth_free_interpretation_plane( + measurement: JointAxisMeasurement, +) -> bool: + """Return whether only the source-camera bearing is geometrically used.""" + return bool( + measurement.axis_point_source + in { + "side_interpretation_plane_cross_view", + "front_interpretation_plane_cross_view_validated", + } + and measurement.axis_point_camera_center_common_xyz_m is not None + ) + + +def refit_axis_line_group_with_shared_radius( + measurements: Sequence[JointAxisMeasurement], + records: Sequence[Mapping[str, Any]], + *, + zero_command_u8: int, + canonical_zero_direction: str | None, +) -> tuple[JointAxisMeasurement, ...]: + """Refit repeated cross-view axis lines with one physical radius. + + A side-view roll alias observes the same child Tag and the same physical + lever arm in every cycle. Fitting an independent radius to each short, + near-edge-on arc leaves radius and circle centre strongly correlated; + sub-pixel PnP noise can then move the reported axis line by several + millimetres even though every trajectory has a low radial residual. + + Keep a separate centre (and therefore an independent line-repeatability + check) for every cycle, but solve one shared radius from all cycles. This + is a physical constraint rather than a relaxed quality gate: the returned + lines are still checked against the unchanged cycle RMS limit, and each + cycle's radial residual remains an independent hard check. + """ + group = tuple(measurements) + if len(group) < 2: + return group + cycles = [int(measurement.cycle) for measurement in group] + if len(set(cycles)) != len(cycles): + raise ValueError("shared-radius axis group contains duplicate cycles") + + entries: list[dict[str, Any]] = [] + initial_parameters: list[float] = [] + initial_radii: list[float] = [] + for measurement in group: + cycle_records = [ + dict(record) + for record in records + if int(record.get("cycle", -1)) == int(measurement.cycle) + ] + motion_records = [ + record + for record in cycle_records + if str(record.get("kind", "sample")) != "baseline_hold_sample" + ] + if len(motion_records) < 6: + motion_records = cycle_records + if len(motion_records) < 6: + raise ValueError( + f"cycle {measurement.cycle + 1} has too few shared-radius samples" + ) + + reference_records = _canonical_reference_records( + cycle_records, canonical_zero_direction + ) + zero_records = _near_zero_records( + reference_records, int(zero_command_u8) + ) + if not zero_records: + raise ValueError( + f"cycle {measurement.cycle + 1} has no shared-radius zero pose" + ) + parent_poses = np.asarray( + [_pose_matrix(record["parent_pose_common"]) for record in zero_records] + ) + parent_translation = np.median(parent_poses[:, :3, 3], axis=0) + parent_quaternion = robust_rotation_summary( + [ + Rotation.from_matrix(matrix[:3, :3]).as_quat() + for matrix in parent_poses + ] + )[0] + parent_rotation = Rotation.from_quat(parent_quaternion) + common_axis = _vector( + measurement.axis_common_xyz, 3, name="shared-radius common axis" + ) + common_axis /= np.linalg.norm(common_axis) + parent_axis = parent_rotation.inv().apply(common_axis) + parent_axis /= np.linalg.norm(parent_axis) + + points = np.asarray( + [record["relative_translation_xyz_m"] for record in motion_records], + dtype=float, + ) + basis_x, basis_y = _plane_basis(parent_axis) + origin = np.mean(points, axis=0) + local = points - origin + points_xy = np.column_stack((local @ basis_x, local @ basis_y)) + initial = _fit_circle_with_axis(points, parent_axis) + initial_center = _vector( + initial["center_xyz_m"], 3, name="initial shared-radius centre" + ) + initial_parameters.extend( + [ + float((initial_center - origin) @ basis_x), + float((initial_center - origin) @ basis_y), + ] + ) + initial_radii.append(float(initial["radius_m"])) + entries.append( + { + "measurement": measurement, + "points": points, + "points_xy": points_xy, + "origin": origin, + "basis_x": basis_x, + "basis_y": basis_y, + "parent_axis": parent_axis, + "parent_rotation": parent_rotation, + "parent_translation": parent_translation, + } + ) + + median_radius = float(np.median(initial_radii)) + if median_radius <= 1.0e-6 or not math.isfinite(median_radius): + raise ValueError("shared-radius axis group has an invalid initial radius") + initial_value = np.asarray( + [*initial_parameters, median_radius], dtype=float + ) + + def residual(parameters: np.ndarray) -> np.ndarray: + radius = float(parameters[-1]) + return np.concatenate( + [ + np.linalg.norm( + entry["points_xy"] + - parameters[2 * index : 2 * index + 2], + axis=1, + ) + - radius + for index, entry in enumerate(entries) + ] + ) / 0.0005 + + lower = np.full(initial_value.shape, -np.inf, dtype=float) + upper = np.full(initial_value.shape, np.inf, dtype=float) + lower[-1] = max(1.0e-6, 0.5 * median_radius) + upper[-1] = 2.0 * median_radius + solution = least_squares( + residual, + initial_value, + bounds=(lower, upper), + loss="soft_l1", + f_scale=1.0, + max_nfev=3000, + ) + if not solution.success: + raise ValueError( + "shared-radius axis optimization failed: " + solution.message + ) + + shared_radius = float(solution.x[-1]) + if not math.isfinite(shared_radius): + raise ValueError("shared-radius axis optimization is non-finite") + result: list[JointAxisMeasurement] = [] + for index, entry in enumerate(entries): + center_xy = solution.x[2 * index : 2 * index + 2] + center_parent = ( + entry["origin"] + + float(center_xy[0]) * entry["basis_x"] + + float(center_xy[1]) * entry["basis_y"] + ) + # The coordinate along an infinite axis is a gauge. Retain the + # robust centre of this cycle's observed axial coordinates. + axial_offsets = ( + entry["points"] - center_parent + ) @ entry["parent_axis"] + center_parent += float(np.median(axial_offsets)) * entry["parent_axis"] + center_common = ( + entry["parent_rotation"].apply(center_parent) + + entry["parent_translation"] + ) + radial_residual = ( + np.linalg.norm( + entry["points_xy"] - center_xy, + axis=1, + ) + - shared_radius + ) + radial_rms = float(np.sqrt(np.mean(np.square(radial_residual)))) + measurement = entry["measurement"] + result.append( + replace( + measurement, + point_common_xyz_m=tuple( + float(value) for value in center_common + ), + radial_rms_m=max(float(measurement.radial_rms_m), radial_rms), + axis_point_source="side_circle_shared_radius_cross_view", + ) + ) + return tuple(result) + + +def maximum_axis_line_cycle_spread_m( + measurements: Sequence[JointAxisMeasurement], +) -> float: + """Measure repeatability of independently fitted near-parallel lines. + + Axis-line points have an arbitrary coordinate along their own direction. + Compare only the perpendicular displacement, symmetrically against both + fitted directions, so that the result remains meaningful with the small + allowed cycle-to-cycle direction variation. + """ + maximum = 0.0 + for left_index, left in enumerate(measurements): + left_axis = np.asarray(left.axis_common_xyz, dtype=float) + left_axis /= np.linalg.norm(left_axis) + left_point = np.asarray(left.point_common_xyz_m, dtype=float) + for right in measurements[left_index + 1 :]: + right_axis = np.asarray(right.axis_common_xyz, dtype=float) + right_axis /= np.linalg.norm(right_axis) + delta = np.asarray(right.point_common_xyz_m, dtype=float) - left_point + maximum = max( + maximum, + float(np.linalg.norm(np.cross(delta, left_axis))), + float(np.linalg.norm(np.cross(delta, right_axis))), + ) + return maximum + + +def axis_line_cycle_rms_m( + measurements: Sequence[JointAxisMeasurement], +) -> float: + """Return RMS line-position scatter about the four-cycle consensus. + + For parallel lines, the sum of squared pairwise distances divided by + ``n**2`` equals the mean squared distance from their centroid. Averaging + each pair's distance against both near-parallel directions preserves that + identity while avoiding an arbitrary choice of one cycle's direction. + """ + count = len(measurements) + if count < 2: + return 0.0 + squared_pairwise_sum = 0.0 + for left_index, left in enumerate(measurements): + left_axis = np.asarray(left.axis_common_xyz, dtype=float) + left_axis /= np.linalg.norm(left_axis) + left_point = np.asarray(left.point_common_xyz_m, dtype=float) + for right in measurements[left_index + 1 :]: + right_axis = np.asarray(right.axis_common_xyz, dtype=float) + right_axis /= np.linalg.norm(right_axis) + delta = np.asarray(right.point_common_xyz_m, dtype=float) - left_point + left_distance = float(np.linalg.norm(np.cross(delta, left_axis))) + right_distance = float(np.linalg.norm(np.cross(delta, right_axis))) + squared_pairwise_sum += 0.5 * ( + left_distance**2 + right_distance**2 + ) + return float(math.sqrt(squared_pairwise_sum / (count**2))) + + +def _fit_axis_point_from_pose_trajectory( + records: Sequence[Mapping[str, Any]], + *, + zero_command_u8: int, + axis_parent_xyz: Sequence[float], + angle_axis_parent_xyz: Sequence[float], + phase_reference_point_parent_xyz: Sequence[float], + view_normal_common_xyz: Sequence[float] | None, + canonical_zero_direction: str | None = None, + allow_axial_translation: bool = False, + residual_diagnostics: dict[str, float] | None = None, +) -> tuple[np.ndarray, float, str]: + """Fit the closest point on a revolute axis from full relative poses. + + If ``T(q)`` maps the moving Tag into its parent Tag frame, then + ``T(q) @ inv(T(0))`` is a rotation about the physical joint axis and its + translation obeys ``(I - R(q)) p = t(q)``. Solving this equation over the + complete trajectory uses both pose orientation and translation and avoids + treating a monocular Tag-centre depth arc as ground-truth geometry. + """ + samples = [dict(record) for record in records] + reference_samples = _canonical_reference_records( + samples, canonical_zero_direction + ) + zero_records = _near_zero_records(reference_samples, zero_command_u8) + if not zero_records: + raise ValueError( + f"axis-point fit has no record near baseline {zero_command_u8}" + ) + + reference_rotation = Rotation.from_quat( + _baseline_reference(reference_samples, zero_command_u8) + ).as_matrix() + reference_translation = np.median( + np.asarray( + [record["relative_translation_xyz_m"] for record in zero_records], + dtype=float, + ), + axis=0, + ) + axis = _vector(axis_parent_xyz, 3, name="axis-point direction") + axis /= np.linalg.norm(axis) + angle_axis = _vector( + angle_axis_parent_xyz, 3, name="axis-point angle direction" + ) + angle_axis /= np.linalg.norm(angle_axis) + phase_reference_point = _vector( + phase_reference_point_parent_xyz, + 3, + name="axis-point phase reference", + ) + helper = ( + np.asarray([1.0, 0.0, 0.0]) + if abs(float(axis[0])) < 0.8 + else np.asarray([0.0, 1.0, 0.0]) + ) + basis_first = np.cross(axis, helper) + basis_first /= np.linalg.norm(basis_first) + basis = np.column_stack( + (basis_first, np.cross(axis, basis_first)) + ) + + view_normal_common = None + use_image_plane_projection = False + if view_normal_common_xyz is not None: + view_normal_common = _vector( + view_normal_common_xyz, 3, name="view normal" + ) + view_normal_common /= np.linalg.norm(view_normal_common) + reference_parent_quaternion = robust_rotation_summary( + [ + Rotation.from_matrix( + _pose_matrix(record["parent_pose_common"])[:3, :3] + ).as_quat() + for record in zero_records + ] + )[0] + reference_parent_rotation = Rotation.from_quat( + reference_parent_quaternion + ) + reference_view_normal_parent = reference_parent_rotation.inv().apply( + view_normal_common + ) + reference_view_normal_parent /= np.linalg.norm( + reference_view_normal_parent + ) + use_image_plane_projection = abs( + float(axis @ reference_view_normal_parent) + ) >= math.cos(AXIS_POINT_IMAGE_PLANE_MAXIMUM_OBLIQUITY_RAD) + + matrices: list[np.ndarray] = [] + translations: list[np.ndarray] = [] + raw_matrices: list[np.ndarray] = [] + raw_translations: list[np.ndarray] = [] + used_image_plane_projection = False + raw_angles: list[float] = [] + translation_angles: list[float] = [] + reference_radial = reference_translation - phase_reference_point + reference_radial -= axis * float(reference_radial @ axis) + reference_radial_norm = float(np.linalg.norm(reference_radial)) + if reference_radial_norm < 1.0e-6: + raise ValueError("axis-point phase reference radius is degenerate") + reference_radial /= reference_radial_norm + for record in samples: + observed_rotation = Rotation.from_quat( + _relative_rotation(record) + ).as_matrix() + observed_delta_rotation = observed_rotation @ reference_rotation.T + raw_angle = float( + Rotation.from_matrix(observed_delta_rotation).as_rotvec() + @ angle_axis + ) + if abs(raw_angle) < AXIS_POINT_MINIMUM_ROTATION_RAD: + continue + observed_translation = _vector( + record["relative_translation_xyz_m"], + 3, + name="relative translation", + ) + observed_radial = observed_translation - phase_reference_point + observed_radial -= axis * float(observed_radial @ axis) + observed_radial_norm = float(np.linalg.norm(observed_radial)) + if observed_radial_norm <= 1.0e-6: + continue + observed_radial /= observed_radial_norm + raw_angles.append(raw_angle) + translation_angles.append( + math.atan2( + float(axis @ np.cross(reference_radial, observed_radial)), + float( + np.clip(reference_radial @ observed_radial, -1.0, 1.0) + ), + ) + ) + orientation_sign = 1.0 + if raw_angles and float( + np.sum(np.asarray(raw_angles) * np.asarray(translation_angles)) + ) < 0.0: + orientation_sign = -1.0 + + for record in samples: + observed_rotation = Rotation.from_quat( + _relative_rotation(record) + ).as_matrix() + observed_translation = _vector( + record["relative_translation_xyz_m"], + 3, + name="relative translation", + ) + observed_delta_rotation = observed_rotation @ reference_rotation.T + signed_angle = float( + Rotation.from_matrix(observed_delta_rotation).as_rotvec() + @ angle_axis + ) * orientation_sign + if abs(signed_angle) < AXIS_POINT_MINIMUM_ROTATION_RAD: + continue + # Direction and angle have deliberately separate sources. A trusted + # upstream/circle direction may replace a biased planar-PnP axis, while + # the relative-orientation trajectory still provides a repeatable + # scalar travel. Reconstruct the admissible revolute motion before + # solving its axis line instead of feeding a contradictory 3-D + # rotation into the translation equations. + # The rotation-trajectory axis is undirected. Align its scalar sign + # with the selected physical axis using the Tag-centre trajectory; + # this remains robust even when a trusted upstream direction replaces + # a badly biased planar-PnP orientation axis. + delta_rotation = Rotation.from_rotvec( + axis * signed_angle + ).as_matrix() + delta_translation = ( + observed_translation + - delta_rotation @ reference_translation + ) + # A screw-driven revolute joint may carry real translation along its + # axis. That component is in the null space of (I - R), contains no + # information about the perpendicular axis-line point, and must not + # inflate or bias the line fit as if the mechanism were pure rotary. + axis_projection = ( + np.eye(3) - np.outer(axis, axis) + if allow_axial_translation + else np.eye(3) + ) + projection = axis_projection + axis_point_matrix = (np.eye(3) - delta_rotation) @ basis + raw_matrices.append(axis_point_matrix) + raw_translations.append(delta_translation) + if use_image_plane_projection: + assert view_normal_common is not None + parent_rotation = Rotation.from_matrix( + _pose_matrix(record["parent_pose_common"])[:3, :3] + ) + view_normal_parent = parent_rotation.inv().apply( + view_normal_common + ) + view_normal_parent /= np.linalg.norm(view_normal_parent) + image_projection = np.eye(3) - np.outer( + view_normal_parent, view_normal_parent + ) + projection = image_projection @ axis_projection + # A single end-on camera cannot distinguish absolute depth from a + # shift along the revolute axis. Keep the observable image-plane + # equations only; adding a free baseline-depth variable makes the + # axis point rank-deficient and pretends that this gauge is + # observable. Parallel phase chains are later compared in the + # same view, where their common depth gauge cancels. + used_image_plane_projection = True + matrices.append(projection @ axis_point_matrix) + translations.append(projection @ delta_translation) + + if len(matrices) < 6: + raise ValueError("axis-point fit has too few observable pose samples") + matrix = np.vstack(matrices) + translation = np.concatenate(translations) + singular_values = np.linalg.svd(matrix, compute_uv=False) + if ( + singular_values.size < 2 + or singular_values[-1] <= 1.0e-9 + or singular_values[-1] / singular_values[0] < 1.0e-3 + ): + raise ValueError("axis-point pose trajectory is ill-conditioned") + + unknown_count = matrix.shape[1] + solution = least_squares( + lambda value: ( + matrix @ value - translation + ) / AXIS_POINT_RESIDUAL_SCALE_M, + np.zeros(unknown_count, dtype=float), + loss="soft_l1", + f_scale=1.0, + max_nfev=1000, + ) + if not solution.success: + raise ValueError( + "axis-point pose optimization failed: " + solution.message + ) + residual = matrix @ solution.x - translation + rms = float(np.sqrt(np.mean(np.square(residual)))) + if residual_diagnostics is not None: + raw_residual = ( + np.asarray(raw_matrices) @ solution.x - np.asarray(raw_translations) + ) + axial = raw_residual @ axis + transverse = raw_residual - axial[:, None] * axis + residual_diagnostics.update( + raw_rms_m=float(np.sqrt(np.mean(raw_residual ** 2))), + axial_rms_m=float(np.sqrt(np.mean(axial ** 2))), + transverse_rms_m=float(np.sqrt(np.mean(transverse ** 2))), + ) + source = ( + "pose_trajectory_image_plane" + if used_image_plane_projection + else "pose_trajectory_3d" + ) + return basis @ solution.x[:2], rms, source diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/axis_observations.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/axis_observations.py new file mode 100644 index 0000000..4d0fc44 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/axis_observations.py @@ -0,0 +1,571 @@ +"""Axis observations.""" + +from __future__ import annotations + +from typing import Any, Mapping, Sequence +import math + +from scipy.spatial.transform import Rotation +import numpy as np + +from ...geometry.rotation import fit_rotation_axis, robust_rotation_summary +from ..trajectory_geometry import _fit_circle_with_axis, _fit_plane_axis +from .axis_lines import _fit_axis_point_from_pose_trajectory +from .geometry_helpers import ( + PALM_AXIS_INCREMENT_COMMAND_SEPARATION_U8, + PALM_AXIS_INCREMENT_CONSENSUS_PERCENTILE, + PALM_AXIS_INCREMENT_MINIMUM_PAIR_COUNT, + PALM_AXIS_INCREMENT_MINIMUM_ROTATION_RAD, + _pose_matrix, + _relative_rotation, + _vector, +) +from .rotation_curves import ( + _baseline_reference, + _canonical_reference_records, + _near_zero_records, + _spatial_input, +) +from .types import JointAxisMeasurement, PalmOrientationMeasurement + + +def _incremental_common_rotation_axis( + samples_by_bin: Mapping[ + tuple[str, int], Sequence[Mapping[str, Any]] + ], + *, + command_separation_u8: int = ( + PALM_AXIS_INCREMENT_COMMAND_SEPARATION_U8 + ), + minimum_rotation_rad: float = ( + PALM_AXIS_INCREMENT_MINIMUM_ROTATION_RAD + ), + minimum_pair_count: int = PALM_AXIS_INCREMENT_MINIMUM_PAIR_COUNT, + consensus_percentile: float = ( + PALM_AXIS_INCREMENT_CONSENSUS_PERCENTILE + ), +) -> tuple[np.ndarray, int]: + """Fit one physical axis from robust local Tag rotations. + + A single baseline-to-endpoint logarithm is sensitive to smooth planar-PnP + curvature: the fitted axis then changes when the same Tag trajectory is + translated to another part of the image. Local finite rotations are + expressed directly in the common camera frame, and their undirected + weighted consensus estimates the physical revolute axis. The worst + quartile is discarded once more after the initial consensus, which is + enough to reject endpoint branch curvature without learning a + serial-specific yaw value or an image-position correction table. + """ + separation = int(command_separation_u8) + if separation < 4 or separation > 64: + raise ValueError("palm axis command separation must be in [4, 64]") + if not 0.0 < float(minimum_rotation_rad) < math.pi: + raise ValueError("palm axis minimum increment must be in (0, pi)") + if int(minimum_pair_count) < 6: + raise ValueError("palm axis minimum pair count must be at least six") + percentile = float(consensus_percentile) + if not 50.0 <= percentile <= 90.0: + raise ValueError("palm axis consensus percentile must be in [50, 90]") + + binned_common_rotations: dict[tuple[str, int], Rotation] = {} + for key, group in samples_by_bin.items(): + child_quaternions = [] + for record in group: + pose = record.get("child_pose_common") + if not isinstance(pose, Mapping): + continue + quaternion = pose.get("quaternion_xyzw") + if quaternion is not None: + child_quaternions.append(quaternion) + if not child_quaternions: + continue + binned_common_rotations[(str(key[0]), int(key[1]))] = ( + Rotation.from_quat( + robust_rotation_summary(child_quaternions)[0] + ) + ) + + directions: list[np.ndarray] = [] + weights: list[float] = [] + for direction in ("decreasing", "increasing"): + commands = sorted( + command + for candidate_direction, command in binned_common_rotations + if candidate_direction == direction + ) + for start_command in commands: + candidates = [ + command + for command in commands + if separation <= command - start_command <= separation + 2 + ] + if not candidates: + continue + end_command = candidates[0] + start = binned_common_rotations[(direction, start_command)] + end = binned_common_rotations[(direction, end_command)] + local_rotvec = (start.inv() * end).as_rotvec() + common_rotvec = start.apply(local_rotvec) + increment = float(np.linalg.norm(common_rotvec)) + if increment < float(minimum_rotation_rad): + continue + directions.append(common_rotvec / increment) + weights.append(increment) + + if len(directions) < int(minimum_pair_count): + raise ValueError( + "palm axis has too few full-stroke local rotation pairs: " + f"{len(directions)}/{int(minimum_pair_count)}" + ) + vectors = np.asarray(directions, dtype=float) + increments = np.asarray(weights, dtype=float) + + def consensus(selected: np.ndarray) -> np.ndarray: + scatter = np.einsum( + "n,ni,nj->ij", + increments[selected], + vectors[selected], + vectors[selected], + ) + eigenvalues, eigenvectors = np.linalg.eigh(scatter) + if not np.all(np.isfinite(eigenvalues)): + raise ValueError("palm axis local-rotation consensus is invalid") + axis = eigenvectors[:, -1] + return axis / np.linalg.norm(axis) + + selected = np.ones(len(vectors), dtype=bool) + axis = consensus(selected) + # Two deterministic refinement rounds prevent the initial scatter from + # being pulled toward a dense endpoint-bias cluster. + for _ in range(2): + deviations = np.arccos( + np.clip(np.abs(vectors @ axis), -1.0, 1.0) + ) + limit = float(np.percentile(deviations, percentile)) + selected = deviations <= limit + if int(np.count_nonzero(selected)) < int(minimum_pair_count): + raise ValueError("palm axis robust consensus retained too few pairs") + axis = consensus(selected) + return axis, int(np.count_nonzero(selected)) + + +def fit_partial_palm_orientation_measurement( + source_joint: str, + model_joint: str, + records: Sequence[Mapping[str, Any]], + *, + cycle: int, + zero_command_u8: int, + minimum_arc_rad: float = math.radians(15.0), + maximum_rotation_orthogonal_rms_rad: float = math.radians(2.5), + maximum_command_distance_u8: int = 255, +) -> PalmOrientationMeasurement: + """Fit a physical axis within a configured window around encoder zero.""" + cycle_samples = [ + dict(record) + for record in records + if int(record.get("cycle", -1)) == int(cycle) + ] + if len(cycle_samples) < 12: + raise ValueError( + f"{source_joint} cycle {cycle + 1} has too few visible samples" + ) + if not 0.0 < float(minimum_arc_rad) < math.pi: + raise ValueError("palm orientation minimum arc must be in (0, pi)") + if float(maximum_rotation_orthogonal_rms_rad) <= 0.0: + raise ValueError( + "palm orientation rotation residual limit must be positive" + ) + command_distance = int(maximum_command_distance_u8) + if command_distance < 1 or command_distance > 255: + raise ValueError( + "palm orientation command distance must be in [1, 255]" + ) + zero = int(zero_command_u8) + samples = [ + record + for record in cycle_samples + if abs(int(record["command_u8"]) - zero) <= command_distance + ] + if len(samples) < 12: + raise ValueError( + f"{source_joint} cycle {cycle + 1} has too few zero-adjacent " + "visible samples" + ) + reference = Rotation.from_quat( + _baseline_reference(samples, int(zero_command_u8)) + ) + samples_by_bin: dict[tuple[str, int], list[Mapping[str, Any]]] = {} + for record in samples: + key = ( + str(record.get("direction", "")), + int(record["command_u8"]), + ) + samples_by_bin.setdefault(key, []).append(record) + if len(samples_by_bin) < 6: + raise ValueError( + f"{source_joint} cycle {cycle + 1} has too few visible command bins" + ) + binned_rotations = [ + Rotation.from_quat( + robust_rotation_summary( + [_relative_rotation(record) for record in group] + )[0] + ) + for group in samples_by_bin.values() + ] + vectors = [ + (reference.inv() * rotation).as_rotvec() + for rotation in binned_rotations + ] + axis_child = fit_rotation_axis( + vectors, [command for _direction, command in samples_by_bin] + ) + angles = np.asarray( + [float(vector @ axis_child) for vector in vectors], dtype=float + ) + observed_arc = float(np.ptp(angles)) + orthogonal_rms = float( + np.sqrt( + np.mean( + [ + np.linalg.norm( + vector - float(vector @ axis_child) * axis_child + ) + ** 2 + for vector in vectors + ] + ) + ) + ) + if observed_arc < float(minimum_arc_rad): + raise ValueError( + f"{source_joint} cycle {cycle + 1} visible rotation arc " + f"{math.degrees(observed_arc):.3f}deg is below " + f"{math.degrees(minimum_arc_rad):.3f}deg" + ) + if orthogonal_rms > float(maximum_rotation_orthogonal_rms_rad): + raise ValueError( + f"{source_joint} cycle {cycle + 1} zero-adjacent rotation " + f"residual {math.degrees(orthogonal_rms):.3f}deg exceeds " + f"{math.degrees(maximum_rotation_orthogonal_rms_rad):.3f}deg" + ) + zero_records = _near_zero_records(samples, int(zero_command_u8)) + if not zero_records: + raise ValueError( + f"{source_joint} cycle {cycle + 1} has no visible zero pose" + ) + parent_poses = np.asarray( + [_pose_matrix(record["parent_pose_common"]) for record in zero_records] + ) + parent_quaternion = robust_rotation_summary( + [ + Rotation.from_matrix(matrix[:3, :3]).as_quat() + for matrix in parent_poses + ] + )[0] + axis_parent = reference.apply(axis_child) + axis_common = Rotation.from_quat(parent_quaternion).apply(axis_parent) + axis_common /= np.linalg.norm(axis_common) + axis_estimator = "baseline_relative_so3" + incremental_pair_count = 0 + # Product recordings persist the selected moving-Tag pose in the common + # camera frame. Use the complete visible stroke only for a local-motion + # axis consensus; retain the zero-adjacent fit above as the unchanged arc + # and residual quality gate. Legacy/synthetic records without the common + # child pose keep their previous estimator exactly. + if any( + isinstance(record.get("child_pose_common"), Mapping) + for record in cycle_samples + ): + full_stroke_bins: dict[ + tuple[str, int], list[Mapping[str, Any]] + ] = {} + for record in cycle_samples: + key = ( + str(record.get("direction", "")), + int(record["command_u8"]), + ) + full_stroke_bins.setdefault(key, []).append(record) + incremental_axis, incremental_pair_count = ( + _incremental_common_rotation_axis(full_stroke_bins) + ) + if float(incremental_axis @ axis_common) < 0.0: + incremental_axis = -incremental_axis + axis_common = incremental_axis + axis_estimator = "robust_full_stroke_local_so3_v1" + state = np.median( + np.asarray( + [record["state_u8"] for record in zero_records], dtype=float + ), + axis=0, + ) + return PalmOrientationMeasurement( + source_joint=str(source_joint), + model_joint=str(model_joint), + cycle=int(cycle), + axis_common_xyz=tuple(float(value) for value in axis_common), + condition_state_u8=tuple(float(value) for value in state), + observed_arc_rad=observed_arc, + rotation_orthogonal_rms_rad=orthogonal_rms, + axis_estimator=axis_estimator, + incremental_pair_count=incremental_pair_count, + ) + + +def fit_partial_palm_orientation_measurements( + *, + sources: Mapping[str, str], + records_by_joint: Mapping[str, Sequence[Mapping[str, Any]]], + motor_by_source: Mapping[str, int], + baseline_command_u8: Sequence[int], + cycles: Sequence[int], + minimum_sources: int, + minimum_arc_rad: float = math.radians(15.0), + maximum_rotation_orthogonal_rms_rad: float = math.radians(2.5), + maximum_command_distance_u8: int = 255, +) -> tuple[tuple[PalmOrientationMeasurement, ...], Mapping[str, str]]: + """Fit every usable optional source and require configured coverage.""" + source_map = {str(name): str(model) for name, model in sources.items()} + minimum = int(minimum_sources) + if not source_map: + if minimum != 0: + raise ValueError( + "palm orientation minimum is non-zero without sources" + ) + return (), {} + if minimum < 2 or minimum > len(source_map): + raise ValueError( + "palm orientation minimum source count must be between two " + "and the configured source count" + ) + missing_motors = sorted(set(source_map) - set(motor_by_source)) + if missing_motors: + raise ValueError( + "palm orientation sources are missing motor mappings: " + + ",".join(missing_motors) + ) + fitted: list[PalmOrientationMeasurement] = [] + rejected: dict[str, str] = {} + for cycle in (int(value) for value in cycles): + cycle_fitted: list[PalmOrientationMeasurement] = [] + for source_joint, model_joint in source_map.items(): + motor = int(motor_by_source[source_joint]) + try: + measurement = fit_partial_palm_orientation_measurement( + source_joint, + model_joint, + records_by_joint.get(source_joint, ()), + cycle=cycle, + zero_command_u8=int(baseline_command_u8[motor]), + minimum_arc_rad=minimum_arc_rad, + maximum_rotation_orthogonal_rms_rad=( + maximum_rotation_orthogonal_rms_rad + ), + maximum_command_distance_u8=( + maximum_command_distance_u8 + ), + ) + except Exception as error: + rejected[f"{source_joint}:cycle{cycle + 1}"] = str(error) + continue + cycle_fitted.append(measurement) + if len(cycle_fitted) < minimum: + cycle_reasons = { + key: value + for key, value in rejected.items() + if key.endswith(f":cycle{cycle + 1}") + } + raise ValueError( + f"palm orientation cycle {cycle + 1} has " + f"{len(cycle_fitted)}/{minimum} usable sources: " + + "; ".join( + f"{key}={value}" for key, value in cycle_reasons.items() + ) + ) + fitted.extend(cycle_fitted) + return tuple(fitted), rejected + + +def fit_joint_axis_measurement( + joint: str, + records: Sequence[Mapping[str, Any]], + *, + cycle: int, + zero_command_u8: int, + axis_common_constraint: Sequence[float] | None = None, + constrained_circle_joints: frozenset[str] = frozenset(), + view_normal_common_xyz: Sequence[float] | None = None, + canonical_zero_direction: str | None = None, + separate_axial_residual: bool = False, + input_to_joint_direction: int = -1, + condition_command_field: str | None = None, +) -> JointAxisMeasurement: + """Fit one physical screw axis from one complete scan cycle.""" + samples = [ + dict(record) for record in records if int(record["cycle"]) == int(cycle) + ] + if len(samples) < 12: + raise ValueError(f"{joint} cycle {cycle + 1} has too few samples") + points = np.asarray( + [record["relative_translation_xyz_m"] for record in samples], dtype=float + ) + free_circle_axis, free_plane_rms = _fit_plane_axis([points]) + singular_values = np.linalg.svd( + points - np.mean(points, axis=0), compute_uv=False + ) + circle_axis_observability = ( + 0.0 + if singular_values.size < 2 or singular_values[0] <= 1.0e-12 + else float(singular_values[1] / singular_values[0]) + ) + + reference_samples = _canonical_reference_records( + samples, canonical_zero_direction + ) + reference = Rotation.from_quat( + _baseline_reference(reference_samples, zero_command_u8) + ) + rotation_vectors = [ + (reference.inv() * Rotation.from_quat(_relative_rotation(record))).as_rotvec() + for record in samples + ] + commands = [_spatial_input(record) for record in samples] + if "input_value" in samples[0]: + if input_to_joint_direction not in {-1, 1}: + raise ValueError("native spatial input requires a fixed direction") + vectors = np.asarray(rotation_vectors, dtype=float) + _, singular, vh = np.linalg.svd(vectors, full_matrices=False) + if not singular.size or singular[0] <= 1e-6: + raise ValueError("native rotation axis is unobservable") + rotation_axis_child = vh[0] + trend = float((np.asarray(commands) - np.mean(commands)) @ (vectors @ rotation_axis_child)) + if abs(trend) <= 1e-12: + raise ValueError("native rotation direction is unobservable") + if np.sign(trend) != input_to_joint_direction: + rotation_axis_child = -rotation_axis_child + else: + rotation_axis_child = fit_rotation_axis(rotation_vectors, commands) + # reference maps the child Tag frame at baseline into the parent Tag + # frame. The quaternion delta axis is expressed in that child frame, + # while the fitted centre circle is expressed in the parent frame. This + # conversion is what makes arbitrary Tag mounting rotations harmless. + rotation_axis = reference.apply(rotation_axis_child) + if float(rotation_axis @ free_circle_axis) < 0.0: + free_circle_axis = -free_circle_axis + disagreement = math.acos( + float(np.clip(rotation_axis @ free_circle_axis, -1.0, 1.0)) + ) + + zero_records = _near_zero_records(reference_samples, zero_command_u8) + if not zero_records: + raise ValueError( + f"{joint} cycle has no record near baseline {zero_command_u8}" + ) + parent_poses = np.asarray( + [_pose_matrix(record["parent_pose_common"]) for record in zero_records] + ) + parent_translation = np.median(parent_poses[:, :3, 3], axis=0) + parent_quaternion = robust_rotation_summary( + [ + Rotation.from_matrix(matrix[:3, :3]).as_quat() + for matrix in parent_poses + ] + )[0] + parent_rotation = Rotation.from_quat(parent_quaternion) + axis_direction_source = "rotation" + + if axis_common_constraint is not None: + common_axis = _vector( + axis_common_constraint, 3, name="common axis constraint" + ) + common_axis /= np.linalg.norm(common_axis) + fitted_axis = parent_rotation.inv().apply(common_axis) + if float(fitted_axis @ rotation_axis) < 0.0: + fitted_axis = -fitted_axis + circle = _fit_circle_with_axis(points, fitted_axis) + plane_rms = float(circle["plane_rms_m"]) + axis_direction_source = "upstream_constraint" + elif str(joint) in constrained_circle_joints: + # The side/front views are close to end-on for these axes. Monocular + # planar-PnP depth bias can therefore tilt even an apparently smooth, + # low-residual Tag-centre circle. The relative orientation trajectory + # observes the screw-axis direction directly and is invariant to an + # arbitrary fixed Tag mounting rotation; use it to constrain the 3-D + # circle and estimate only the axis line. Never switch the direction + # source based on a rotation-vs-circle threshold: that discontinuity + # makes otherwise identical repeat cycles choose different models. + fitted_axis = rotation_axis + circle = _fit_circle_with_axis(points, fitted_axis) + plane_rms = float(circle["plane_rms_m"]) + else: + # Oblique trajectories with an observable 3-D motion plane retain the + # independent rotation/centre cross-check and fuse both estimates. + free_circle = _fit_circle_with_axis(points, free_circle_axis) + fitted_axis = rotation_axis + free_circle_axis + if float(np.linalg.norm(fitted_axis)) < 1.0e-9: + raise ValueError(f"{joint} rotation and centre axes are opposed") + fitted_axis /= np.linalg.norm(fitted_axis) + circle = free_circle + plane_rms = max( + float(free_plane_rms), float(circle["plane_rms_m"]) + ) + axis_direction_source = "rotation_circle_fusion" + axis_common = parent_rotation.apply(fitted_axis) + residual_diagnostics: dict[str, float] = {} + separate_axial = separate_axial_residual or str(joint).endswith("_side") + point_parent, pose_axis_line_rms_m, axis_point_source = ( + _fit_axis_point_from_pose_trajectory( + samples, + zero_command_u8=zero_command_u8, + axis_parent_xyz=fitted_axis, + angle_axis_parent_xyz=rotation_axis, + phase_reference_point_parent_xyz=circle["center_xyz_m"], + view_normal_common_xyz=view_normal_common_xyz, + canonical_zero_direction=canonical_zero_direction, + allow_axial_translation=separate_axial, + residual_diagnostics=residual_diagnostics, + ) + ) + point_common = parent_rotation.apply(point_parent) + parent_translation + states = [record.get("state_values", record.get("state_u8")) for record in zero_records] + # Command-conditioned geometry never invents an encoder condition. Keep + # unavailable diagnostics explicit while preserving legacy requirements. + if any(value is None for value in states): + if condition_command_field is None: + raise ValueError("axis_condition_feedback_missing") + state = None + else: + state = tuple(float(value) for value in np.median(np.asarray(states, dtype=float), axis=0)) + return JointAxisMeasurement( + joint=str(joint), + cycle=int(cycle), + axis_common_xyz=tuple(float(value) for value in axis_common), + point_common_xyz_m=tuple(float(value) for value in point_common), + condition_state_u8=state, + plane_rms_m=float(plane_rms), + radial_rms_m=float(circle["radial_rms_m"]), + rotation_circle_axis_difference_rad=float(disagreement), + view_normal_common_xyz=( + None + if view_normal_common_xyz is None + else tuple( + float(value) + for value in _vector( + view_normal_common_xyz, 3, name="view normal" + ) + ) + ), + axis_direction_source=axis_direction_source, + circle_axis_observability=float(circle_axis_observability), + axis_point_source=axis_point_source, + pose_axis_line_rms_m=pose_axis_line_rms_m, + pose_axis_line_raw_rms_m=residual_diagnostics["raw_rms_m"], + pose_axis_line_axial_rms_m=residual_diagnostics["axial_rms_m"], + pose_axis_line_transverse_rms_m=residual_diagnostics["transverse_rms_m"], + axis_point_axial_component_separated=separate_axial, + pose_axis_line_source_joints=(str(joint),), + condition_command_u8=(tuple(float(v) for v in np.median( + np.asarray([r[condition_command_field] for r in zero_records], dtype=float), axis=0)) + if condition_command_field else None), + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/base_pose.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/base_pose.py new file mode 100644 index 0000000..4e76bb1 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/base_pose.py @@ -0,0 +1,440 @@ +"""Base localization selected by geometric constraints, shared by all profiles.""" + +from __future__ import annotations + +from typing import Mapping, Sequence +import math + +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation +import numpy as np + +from .geometry_helpers import ZERO_MINIMUM_AXIS_CONE_RAD +from .residuals import ObservationGeometry +from .stages import TrainingProblem +from .types import JointAxisMeasurement + + +def fit_base_pose( + selected: Sequence[JointAxisMeasurement], + pose_offsets: Mapping[str, float] | None = None, + *, + problem: TrainingProblem, + geometry: ObservationGeometry, +) -> tuple[Rotation, np.ndarray]: + profile = problem.profile + zero_offsets = problem.zero_offsets + curves = geometry.curves + predicted_local = geometry.predicted_local + + pose_zero_offsets = zero_offsets if pose_offsets is None else pose_offsets + anchors_by_joint = { + name: [item for item in selected if item.joint == name] + for name in profile.root_anchor_joints + } + if any(not items for items in anchors_by_joint.values()): + raise ValueError("zero solve is missing root axis anchors") + + def undirected_axis_average( + values: Sequence[Sequence[float]], + ) -> np.ndarray: + vectors = np.asarray(values, dtype=float) + reference = vectors[0] / np.linalg.norm(vectors[0]) + signs = np.where(vectors @ reference < 0.0, -1.0, 1.0) + result = np.sum(vectors * signs[:, None], axis=0) + norm = float(np.linalg.norm(result)) + if norm < 1.0e-9: + raise ValueError("root axis average is degenerate") + return result / norm + + root_names = tuple(sorted(profile.root_anchor_joints)) + predicted_axes: dict[str, np.ndarray] = {} + predicted_points: dict[str, np.ndarray] = {} + observed_axes: dict[str, np.ndarray] = {} + observed_points: dict[str, np.ndarray] = {} + for name in root_names: + items = anchors_by_joint[name] + predicted = [predicted_local(item, pose_zero_offsets) for item in items] + predicted_axes[name] = undirected_axis_average( + [axis for axis, _ in predicted] + ) + predicted_points[name] = np.median( + np.asarray([point for _, point in predicted]), axis=0 + ) + observed_axes[name] = undirected_axis_average( + [item.axis_common_xyz for item in items] + ) + observed_points[name] = np.median( + np.asarray( + [item.point_common_xyz_m for item in items], dtype=float + ), + axis=0, + ) + + if ( + profile.parallel_root_pattern + and profile.base_pose_strategy == "full_hand" + ): + # In the product layout none of the four finger-roll zeros is a + # mechanical prior. Using one finger's pitch axis to orient the + # palm would therefore absorb that finger's roll zero into the + # palm pose. The named positions of five parallel root lines do + # observe rotation about their common direction, independent of + # all five root-joint zeros. Fit that transverse line pattern and + # leave the unobservable translation along the common direction + # at zero; all zero-sensitive phase residuals use line-to-line + # differences and are invariant to that gauge. + predicted_common = undirected_axis_average( + [predicted_axes[name] for name in root_names] + ) + observed_common = undirected_axis_average( + [observed_axes[name] for name in root_names] + ) + predicted_center = np.mean( + np.asarray([predicted_points[name] for name in root_names]), + axis=0, + ) + observed_center = np.mean( + np.asarray([observed_points[name] for name in root_names]), + axis=0, + ) + predicted_pattern = { + name: ( + (delta := predicted_points[name] - predicted_center) + - predicted_common * float(delta @ predicted_common) + ) + for name in root_names + } + observed_pattern = { + name: ( + (delta := observed_points[name] - observed_center) + - observed_common * float(delta @ observed_common) + ) + for name in root_names + } + if max( + np.linalg.norm(value) for value in predicted_pattern.values() + ) < 0.003: + raise ValueError("root axis-line pattern is degenerate") + if max( + np.linalg.norm(value) for value in observed_pattern.values() + ) < 0.003: + raise ValueError("observed root axis-line pattern is degenerate") + + def align_axis(source: np.ndarray, target: np.ndarray) -> Rotation: + source = source / np.linalg.norm(source) + target = target / np.linalg.norm(target) + cross = np.cross(source, target) + cross_norm = float(np.linalg.norm(cross)) + dot = float(np.clip(source @ target, -1.0, 1.0)) + if cross_norm > 1.0e-10: + return Rotation.from_rotvec( + cross / cross_norm * math.atan2(cross_norm, dot) + ) + if dot > 0.0: + return Rotation.identity() + basis = np.eye(3)[int(np.argmin(np.abs(source)))] + axis = np.cross(source, basis) + axis /= np.linalg.norm(axis) + return Rotation.from_rotvec(axis * math.pi) + + candidates: list[tuple[float, Rotation, np.ndarray]] = [] + for sign in (1.0, -1.0): + signed_observed_axis = sign * observed_common + axis_rotation = align_axis( + predicted_common, signed_observed_axis + ) + mapped_pattern = { + name: axis_rotation.apply(predicted_pattern[name]) + for name in root_names + } + cosine = sum( + float(mapped_pattern[name] @ observed_pattern[name]) + for name in root_names + ) + sine = sum( + float( + signed_observed_axis + @ np.cross( + mapped_pattern[name], observed_pattern[name] + ) + ) + for name in root_names + ) + phase_rotation = Rotation.from_rotvec( + signed_observed_axis * math.atan2(sine, cosine) + ) + rotation = phase_rotation * axis_rotation + translation_samples = [] + for name in root_names: + delta = observed_points[name] - rotation.apply( + predicted_points[name] + ) + translation_samples.append( + delta + - signed_observed_axis + * float(delta @ signed_observed_axis) + ) + translation = np.median( + np.asarray(translation_samples), axis=0 + ) + + # Root-axis points recovered from planar Tags occasionally + # contain a large but repeatable depth/line-position outlier. + # A plain Procrustes sum lets one such point rotate the palm + # frame and then makes the same bias look like a common zero + # offset on all four finger-roll joints. Refine only the + # rigid palm pose with a millimetre-scale robust loss. At + # least three mutually consistent named root lines therefore + # determine the transverse pattern while an outlier remains + # visible in the line diagnostics below. + transverse_helper = np.eye(3)[ + int(np.argmin(np.abs(signed_observed_axis))) + ] + transverse_first = np.cross( + signed_observed_axis, transverse_helper + ) + transverse_first /= np.linalg.norm(transverse_first) + transverse_second = np.cross( + signed_observed_axis, transverse_first + ) + + def robust_root_pattern_residual( + value: np.ndarray, + ) -> np.ndarray: + candidate_rotation = ( + Rotation.from_rotvec( + signed_observed_axis * float(value[0]) + ) + * rotation + ) + candidate_translation = ( + translation + + transverse_first * float(value[1]) + + transverse_second * float(value[2]) + ) + residuals: list[float] = [] + for name in root_names: + delta = observed_points[name] - ( + candidate_rotation.apply(predicted_points[name]) + + candidate_translation + ) + residuals.extend( + ( + float(delta @ transverse_first) / 0.001, + float(delta @ transverse_second) / 0.001, + ) + ) + return np.asarray(residuals, dtype=float) + + root_pattern_solution = least_squares( + robust_root_pattern_residual, + np.zeros(3, dtype=float), + bounds=( + np.asarray([-math.pi, -0.25, -0.25]), + np.asarray([math.pi, 0.25, 0.25]), + ), + loss="soft_l1", + f_scale=1.0, + max_nfev=1000, + ) + if not root_pattern_solution.success: + raise ValueError("robust root axis-line pattern fit failed") + rotation = ( + Rotation.from_rotvec( + signed_observed_axis + * float(root_pattern_solution.x[0]) + ) + * rotation + ) + translation = ( + translation + + transverse_first * float(root_pattern_solution.x[1]) + + transverse_second * float(root_pattern_solution.x[2]) + ) + axis_errors: list[float] = [] + for item in selected: + predicted_axis, _ = predicted_local(item, pose_zero_offsets) + observed_axis = np.asarray(item.axis_common_xyz, dtype=float) + axis_errors.append( + math.acos( + abs( + float( + np.clip( + rotation.apply(predicted_axis) + @ observed_axis, + -1.0, + 1.0, + ) + ) + ) + ) + ) + line_errors = [] + for name in root_names: + predicted_point = ( + rotation.apply(predicted_points[name]) + translation + ) + delta = observed_points[name] - predicted_point + line_errors.append( + float( + np.linalg.norm( + delta + - signed_observed_axis + * float(delta @ signed_observed_axis) + ) + ) + ) + score = float(np.mean(np.square(axis_errors))) + float( + np.mean(np.square(np.asarray(line_errors) / 0.01)) + ) + candidates.append((score, rotation, translation)) + _, rotation, translation = min( + candidates, key=lambda item: item[0] + ) + non_root_items = [ + item + for item in selected + if item.joint not in profile.root_anchor_joints + ] + if not non_root_items: + raise ValueError( + "non-parallel axes are required for palm axial translation" + ) + + def axial_translation_residual(value: np.ndarray) -> np.ndarray: + candidate_translation = ( + translation + observed_common * float(value[0]) + ) + residuals: list[float] = [] + for item in non_root_items: + predicted_axis, predicted_point = predicted_local( + item, pose_zero_offsets + ) + predicted_axis = rotation.apply(predicted_axis) + predicted_point = ( + rotation.apply(predicted_point) + + candidate_translation + ) + observed_axis = np.asarray( + item.axis_common_xyz, dtype=float + ) + if float(predicted_axis @ observed_axis) < 0.0: + observed_axis = -observed_axis + delta = np.asarray( + item.point_common_xyz_m, dtype=float + ) - predicted_point + perpendicular = delta - observed_axis * float( + delta @ observed_axis + ) + residuals.extend( + float(component) / 0.001 + for component in perpendicular + ) + return np.asarray(residuals, dtype=float) + + axial_solution = least_squares( + axial_translation_residual, + np.asarray([0.0]), + bounds=(np.asarray([-1.0]), np.asarray([1.0])), + loss="soft_l1", + f_scale=1.0, + ) + if not axial_solution.success: + raise ValueError("palm axial translation fit failed") + translation = ( + translation + + observed_common * float(axial_solution.x[0]) + ) + return rotation, translation + + # Legacy layouts have only one observed finger chain. Their + # non-parallel reference-finger pitch axis remains the orientation + # anchor; the product profile above deliberately does not use it. + primary = max( + root_names, + key=lambda name: float( + np.ptp(np.asarray(curves[name].angle_rad)) + ), + ) + orientation_anchor = profile.orientation_anchor_joint + if not orientation_anchor: + raise ValueError("serial zero solve requires an orientation anchor") + orientation_items = [ + item for item in selected if item.joint == orientation_anchor + ] + if not orientation_items: + raise ValueError( + f"zero solve is missing palm orientation anchor " + f"{orientation_anchor}" + ) + predicted_orientation_axis = undirected_axis_average( + [ + predicted_local(item, pose_zero_offsets)[0] + for item in orientation_items + ] + ) + observed_orientation_axis = undirected_axis_average( + [item.axis_common_xyz for item in orientation_items] + ) + + def frame_from_two_axes( + primary_axis: np.ndarray, orientation_axis: np.ndarray + ) -> np.ndarray: + first = primary_axis / np.linalg.norm(primary_axis) + second = orientation_axis - first * float(orientation_axis @ first) + second_norm = float(np.linalg.norm(second)) + if second_norm < math.sin(ZERO_MINIMUM_AXIS_CONE_RAD): + raise ValueError("palm orientation axes are nearly parallel") + second /= second_norm + return np.column_stack((first, second, np.cross(first, second))) + + predicted_frame = frame_from_two_axes( + predicted_axes[primary], + predicted_orientation_axis, + ) + candidates: list[tuple[float, Rotation, np.ndarray]] = [] + for primary_sign in (1.0, -1.0): + for orientation_sign in (1.0, -1.0): + observed_frame = frame_from_two_axes( + primary_sign * observed_axes[primary], + orientation_sign * observed_orientation_axis, + ) + rotation = Rotation.from_matrix( + observed_frame @ predicted_frame.T + ) + translation = np.median( + np.asarray( + [ + observed_points[name] + - rotation.apply(predicted_points[name]) + for name in root_names + ] + ), + axis=0, + ) + + # Resolve both undirected-axis sign branches using every + # distinct measured joint. This selects a palm-frame branch; + # it does not fit link geometry or encoder offsets. + errors_by_joint: dict[str, list[float]] = {} + for item in selected: + predicted_axis, _ = predicted_local(item, pose_zero_offsets) + predicted_axis = rotation.apply(predicted_axis) + observed_axis = np.asarray(item.axis_common_xyz, dtype=float) + alignment = float( + np.clip(predicted_axis @ observed_axis, -1.0, 1.0) + ) + error = math.acos( + alignment + if item.joint in profile.directed_base_axis_joints + else abs(alignment) + ) + errors_by_joint.setdefault(item.joint, []).append(error) + branch_score = sum( + min(float(np.median(values)), math.radians(30.0)) ** 2 + for values in errors_by_joint.values() + ) + candidates.append((branch_score, rotation, translation)) + _, rotation, translation = min(candidates, key=lambda item: item[0]) + return rotation, translation diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/geometry_helpers.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/geometry_helpers.py new file mode 100644 index 0000000..9443510 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/geometry_helpers.py @@ -0,0 +1,217 @@ +"""Geometry helpers.""" + +from __future__ import annotations + +from typing import Any, Mapping, Sequence +import math + +from scipy.spatial.transform import Rotation +import numpy as np + +from ...domain.measurement import JointCurveFit + + +def circle_direction_is_constrained( + joint_name: str, constrained_circle_joints: frozenset[str] +) -> bool: + """Match the constraint used by both canonical and side aliases.""" + name = str(joint_name) + return name in constrained_circle_joints or name.endswith("_side") + + +def select_cross_view_roll_direction_source( + primary_cone_residuals_rad: Sequence[float], + secondary_cone_residuals_rad: Sequence[float], + maximum_cone_mismatch_rad: float, +) -> str: + """Choose one roll-axis view for the complete repeated-sweep group. + + The choice must not be made independently for every cycle. A residual + sitting just either side of the cone gate can otherwise alternate the + selected camera and turn a fixed cross-view bias into a false cycle-axis + spread. The secondary view wins only with a three-quarter consensus and + a median residual inside the unchanged geometry gate; ambiguous groups + retain the primary view. + """ + primary = np.asarray(primary_cone_residuals_rad, dtype=float) + secondary = np.asarray(secondary_cone_residuals_rad, dtype=float) + if ( + primary.ndim != 1 + or secondary.ndim != 1 + or len(primary) != len(secondary) + or len(primary) < 3 + or not np.all(np.isfinite(primary)) + or not np.all(np.isfinite(secondary)) + or float(maximum_cone_mismatch_rad) <= 0.0 + ): + return "primary" + limit = float(maximum_cone_mismatch_rad) + required_consensus = int(math.ceil(0.75 * len(primary))) + primary_passes = int(np.count_nonzero(primary <= limit)) + secondary_passes = int(np.count_nonzero(secondary <= limit)) + if ( + secondary_passes >= required_consensus + and primary_passes < required_consensus + and float(np.median(secondary)) <= limit + and float(np.median(primary)) > limit + ): + return "secondary" + return "primary" + + +ZERO_REFERENCE_MAXIMUM_DISTANCE_U8 = 16 + + +AXIS_POINT_MINIMUM_ROTATION_RAD = math.radians(3.0) + + +AXIS_POINT_IMAGE_PLANE_MAXIMUM_OBLIQUITY_RAD = math.radians(45.0) + + +AXIS_POINT_RESIDUAL_SCALE_M = 0.001 + + +ZERO_MINIMUM_AXIS_CONE_RAD = math.radians(15.0) + + +def _zero_sensitive_axis_error_rad( + predicted_axis: Sequence[float], + observed_axis: Sequence[float], + parent_axis: Sequence[float], +) -> float: + """Return only the axis error that a parent-joint zero can change. + + Rotating a downstream axis about its parent preserves their mutual cone + angle. The component normal to their plane is therefore the observable + encoder-zero error; cone-angle mismatch belongs to fixed geometry/PnP and + must not push a zero offset or fail its holdout validation. + """ + predicted = _vector(predicted_axis, 3, name="predicted axis") + predicted /= np.linalg.norm(predicted) + observed = _vector(observed_axis, 3, name="observed axis") + observed /= np.linalg.norm(observed) + parent = _vector(parent_axis, 3, name="parent axis") + parent /= np.linalg.norm(parent) + if float(predicted @ observed) < 0.0: + observed = -observed + predicted_projected = predicted - parent * float(predicted @ parent) + observed_projected = observed - parent * float(observed @ parent) + predicted_norm = float(np.linalg.norm(predicted_projected)) + observed_norm = float(np.linalg.norm(observed_projected)) + minimum_projection = math.sin(ZERO_MINIMUM_AXIS_CONE_RAD) + if min(predicted_norm, observed_norm) < minimum_projection: + raise ValueError( + "parent and downstream axes have an unobservable cone angle" + ) + predicted_projected /= predicted_norm + observed_projected /= observed_norm + return math.atan2( + float(parent @ np.cross(predicted_projected, observed_projected)), + float( + np.clip(predicted_projected @ observed_projected, -1.0, 1.0) + ), + ) + + +def _axis_cone_mismatch_rad( + predicted_axis: Sequence[float], + observed_axis: Sequence[float], + parent_axis: Sequence[float], +) -> float: + """Return zero-invariant parent/downstream cone-angle disagreement.""" + predicted = _vector(predicted_axis, 3, name="predicted axis") + predicted /= np.linalg.norm(predicted) + observed = _vector(observed_axis, 3, name="observed axis") + observed /= np.linalg.norm(observed) + parent = _vector(parent_axis, 3, name="parent axis") + parent /= np.linalg.norm(parent) + predicted_cone = math.acos( + abs(float(np.clip(parent @ predicted, -1.0, 1.0))) + ) + observed_cone = math.acos( + abs(float(np.clip(parent @ observed, -1.0, 1.0))) + ) + return abs(predicted_cone - observed_cone) + + +def _vector(value: Sequence[float], size: int, *, name: str) -> np.ndarray: + result = np.asarray(value, dtype=float) + if result.shape != (size,) or not np.all(np.isfinite(result)): + raise ValueError(f"{name} must contain {size} finite values") + return result + + +def _pose_matrix(payload: Mapping[str, Any]) -> np.ndarray: + translation = _vector(payload["translation_xyz_m"], 3, name="translation") + quaternion = _vector(payload["quaternion_xyzw"], 4, name="quaternion") + quaternion /= np.linalg.norm(quaternion) + result = np.eye(4) + result[:3, :3] = Rotation.from_quat(quaternion).as_matrix() + result[:3, 3] = translation + return result + + +def _relative_rotation(record: Mapping[str, Any]) -> np.ndarray: + quaternion = _vector( + record["relative_quaternion_xyzw"], 4, name="relative quaternion" + ) + return quaternion / np.linalg.norm(quaternion) + + +PALM_AXIS_INCREMENT_COMMAND_SEPARATION_U8 = 24 + + +PALM_AXIS_INCREMENT_MINIMUM_ROTATION_RAD = math.radians(0.3) + + +PALM_AXIS_INCREMENT_MINIMUM_PAIR_COUNT = 24 + + +PALM_AXIS_INCREMENT_CONSENSUS_PERCENTILE = 75.0 + + +def _angles_from_state( + state_u8: Sequence[float], + *, + curves: Mapping[str, JointCurveFit], + motor_by_joint: Mapping[str, int], + inherited_zero_joints: Mapping[str, str] | None = None, +) -> dict[str, float]: + state = np.asarray(state_u8, dtype=float) + result: dict[str, float] = {} + for joint, motor in motor_by_joint.items(): + source = (inherited_zero_joints or {}).get(joint, joint) + if source not in curves: + continue + curve = curves[source] + value = float(state[int(motor)]) + if not math.isfinite(value): + raise ValueError("nonfinite spatial condition feedback") + knots = curve.circle.get("input_knots") + if knots is not None: + if not knots[0] <= value <= knots[-1]: + raise ValueError(f"spatial condition outside measured native support:{joint}:{value}") + result[joint] = float(np.interp(value, knots, curve.angle_rad)) + result[joint] += float(curve.circle.get("known_cad_baseline_rad", 0.0)) + else: + if not 0 <= value <= 255: + raise ValueError(f"spatial condition outside byte domain:{joint}") + result[joint] = float(curve.angle_rad[int(np.rint(value))]) + return result + + +def robust_circular_location(values: Sequence[float]) -> float: + array = np.asarray(values, dtype=float) + if array.size == 0: + raise ValueError("circular residual set is empty") + centre = math.atan2( + float(np.mean(np.sin(array))), + float(np.mean(np.cos(array))), + ) + centred = np.arctan2(np.sin(array - centre), np.cos(array - centre)) + return float( + math.atan2( + math.sin(centre + float(np.median(centred))), + math.cos(centre + float(np.median(centred))), + ) + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/optimization.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/optimization.py new file mode 100644 index 0000000..55a18a9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/optimization.py @@ -0,0 +1,127 @@ +"""Ordered zero-offset optimization using training observations only.""" + +from __future__ import annotations + +from functools import partial +from typing import Mapping, Sequence +import math + +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation +import numpy as np + +from .base_pose import fit_base_pose +from .residuals import ObservationGeometry +from .stages import OffsetLimits, TrainingProblem +from .types import JointAxisMeasurement + + +def optimise_offsets( + selected: Sequence[JointAxisMeasurement], + base_rotation: Rotation, + base_translation: np.ndarray, + initial: Mapping[str, float] | None = None, + *, + limits: OffsetLimits, + problem: TrainingProblem, + geometry: ObservationGeometry, + fitted_names=None, +) -> dict[str, float]: + diagnostic_offset_limits = limits.diagnostic_offset_limits + fixed_offsets = problem.fixed_offsets + offset_limits = limits.offset_limits + profile = problem.profile + angular_error_samples = geometry.angular_error_samples + + result = {name: 0.0 for name in profile.direct_zero_joints} + if initial is not None: + result.update( + { + name: float(initial[name]) + for name in profile.direct_zero_joints + } + ) + result.update(fixed_offsets) + for name, diagnostic_limit, configured_limit in zip( + profile.direct_zero_joints, + diagnostic_offset_limits, + offset_limits, + ): + if name in fixed_offsets: + continue + if fitted_names is not None and name not in fitted_names: + continue + has_axis_pair = name in profile.same_view_axis_pair_by_offset + limit = float( + configured_limit if has_axis_pair else diagnostic_limit + ) + + def residual(value: np.ndarray) -> np.ndarray: + candidate = dict(result) + candidate[name] = float(value[0]) + samples = angular_error_samples( + candidate, selected, base_rotation, base_translation, only_offsets={name} + )[name] + return np.asarray( + [ + math.atan2(math.sin(item), math.cos(item)) + / math.radians(1.0) + for item in samples + ], + dtype=float, + ) + + starts = [0.0, -0.5 * limit, 0.5 * limit] + if initial is not None: + starts.append(float(initial[name])) + solutions = [ + least_squares( + residual, + np.asarray( + [np.clip(start, -limit + 1.0e-9, limit - 1.0e-9)] + ), + bounds=(np.asarray([-limit]), np.asarray([limit])), + loss="soft_l1", + f_scale=1.0, + max_nfev=1000, + ) + for start in starts + ] + solution = min( + solutions, key=lambda item: float(np.sum(np.square(item.fun))) + ) + if not solution.success: + raise ValueError( + f"URDF zero optimization failed for {name}: " + f"{solution.message}" + ) + result[name] = float(solution.x[0]) + return result + + +def solve_selected( + selected: Sequence[JointAxisMeasurement], + initial: Mapping[str, float] | None = None, + *, + limits: OffsetLimits, + problem: TrainingProblem, + geometry: ObservationGeometry, +) -> tuple[Rotation, np.ndarray, dict[str, float]]: + profile = problem.profile + + fit_pose = partial(fit_base_pose, geometry=geometry, problem=problem) + fit_offsets = partial(optimise_offsets, geometry=geometry, problem=problem, limits=limits) + rotation, translation = fit_pose(selected) + offsets = fit_offsets( + selected, rotation, translation, initial=initial + ) + if profile.base_pose_strategy == "serial_chain": + # The first pose estimate only supplies a branch for the invariant + # same-view yaw solve. Refit after yaw is known so that the + # downstream pitch phase is evaluated in the corrected serial + # thumb frame, then freeze that pose for holdout validation. + rotation, translation = fit_pose(selected, offsets) + offsets = fit_offsets( + selected, rotation, translation, initial=offsets + ) + return rotation, translation, offsets diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/preparation.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/preparation.py new file mode 100644 index 0000000..a86b751 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/preparation.py @@ -0,0 +1,305 @@ +"""Input validation and separation of training and independent validation.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Mapping, Sequence +import math +import json + +import numpy as np + +from ...urdf.kinematics import UrdfKinematicModel +from .stages import OffsetLimits, ZeroProblem, ZeroSolveOptions +from .types import JointAxisMeasurement, PalmOrientationMeasurement, ZeroCalibrationProfile + + +def prepare_zero_problem( + *, + source_urdf: str | Path, + measurements: Sequence[JointAxisMeasurement], + palm_orientation_measurements: Sequence[PalmOrientationMeasurement], + training_cycles: Sequence[int], + validation_cycle: int, + options: ZeroSolveOptions, + hand_type: str | None, + tag_layout: str | None, + fixed_direct_zero_offsets_rad: Mapping[str, float] | None, + static_output_zero_offsets_rad: Mapping[str, float] | None, + zero_profile: ZeroCalibrationProfile | None, +) -> ZeroProblem: + """Validate protected inputs and separate observations before optimization.""" + maximum_offset_rad = options.maximum_offset_rad + finger_maximum_offset_rad = options.finger_maximum_offset_rad + joint_maximum_offset_rad = options.joint_maximum_offset_rad + maximum_cycle_difference_rad = options.maximum_cycle_difference_rad + minimum_applied_offset_rad = options.minimum_applied_offset_rad + significance_sigma = options.significance_sigma + maximum_validation_error_rad = options.maximum_validation_error_rad + maximum_confidence_half_width_rad = options.maximum_confidence_half_width_rad + maximum_axis_cone_mismatch_rad = options.maximum_axis_cone_mismatch_rad + maximum_systematic_axis_cone_bias_rad = options.maximum_systematic_axis_cone_bias_rad + maximum_pose_axis_line_rms_m = options.maximum_pose_axis_line_rms_m + maximum_observability_condition_number = options.maximum_observability_condition_number + if zero_profile is None: + raise ValueError("zero_profile is required; the core has no model defaults") + profile = zero_profile + hand_type = profile.hand.side if hand_type is None else hand_type + tag_layout = profile.hand.layout_id if tag_layout is None else tag_layout + if profile.hand.side != str(hand_type).lower(): + raise ValueError("zero profile hand side does not match hand_type") + if profile.hand.layout_id != str(tag_layout): + raise ValueError("zero profile layout does not match tag_layout") + model = UrdfKinematicModel(source_urdf) + training = [m for m in measurements if m.cycle in set(training_cycles)] + validation = [m for m in measurements if validation_cycle is not None and m.cycle == int(validation_cycle)] + expected = set(profile.axis_joints) + if ( + {m.joint for m in training} != expected + or (validation_cycle is not None and {m.joint for m in validation} != expected) + ): + observed_training = {m.joint for m in training} + observed_validation = {m.joint for m in validation} + coverage = { + "training_missing": sorted(expected-observed_training), + "training_unexpected": sorted(observed_training-expected), + "validation_missing": sorted(expected-observed_validation) if validation_cycle is not None else [], + "validation_unexpected": sorted(observed_validation-expected) if validation_cycle is not None else [], + "training_missing_root_anchors": sorted(set(profile.root_anchor_joints)-observed_training), + "validation_missing_root_anchors": (sorted(set(profile.root_anchor_joints)-observed_validation) + if validation_cycle is not None else []), + } + raise ValueError("axis measurements do not contain all required joints/cycles:" + +json.dumps(coverage, sort_keys=True)) + configured_palm_sources = { + str(name): str(model_joint) + for name, model_joint in ( + profile.hand.palm_orientation_sources or {} + ).items() + } + orientation_measurements = tuple(palm_orientation_measurements) + if configured_palm_sources: + minimum_orientation_sources = int( + profile.hand.minimum_palm_orientation_sources + ) + unknown_orientation_sources = sorted( + { + item.source_joint + for item in orientation_measurements + if item.source_joint not in configured_palm_sources + or configured_palm_sources[item.source_joint] + != item.model_joint + } + ) + if unknown_orientation_sources: + raise ValueError( + "palm orientation measurements do not match the product " + "profile: " + + ",".join(unknown_orientation_sources) + ) + required_orientation_cycles = { + *(int(value) for value in training_cycles), + *((int(validation_cycle),) if validation_cycle is not None else ()), + } + for cycle in required_orientation_cycles: + cycle_sources = { + item.source_joint + for item in orientation_measurements + if int(item.cycle) == cycle + } + if len(cycle_sources) < minimum_orientation_sources: + raise ValueError( + f"palm orientation cycle {cycle + 1} contains " + f"{len(cycle_sources)}/{minimum_orientation_sources} " + "qualified sources" + ) + elif orientation_measurements: + raise ValueError( + "palm orientation measurements were supplied without a profile" + ) + orientation_validation = tuple( + item + for item in orientation_measurements + if validation_cycle is not None and int(item.cycle) == int(validation_cycle) + ) + orientation_by_model_cycle: dict[ + tuple[str, int], PalmOrientationMeasurement + ] = {} + for item in orientation_measurements: + key = (str(item.model_joint), int(item.cycle)) + if key in orientation_by_model_cycle: + raise ValueError( + "palm orientation has multiple sources for " + f"{key[0]} cycle {key[1] + 1}" + ) + orientation_by_model_cycle[key] = item + if not 0.0 < finger_maximum_offset_rad <= maximum_offset_rad: + raise ValueError("finger maximum offset must be positive and no larger than thumb") + joint_limits = { + str(name): float(value) + for name, value in dict(joint_maximum_offset_rad or {}).items() + } + unknown_joint_limits = sorted(set(joint_limits) - set(profile.direct_zero_joints)) + if unknown_joint_limits: + raise ValueError( + "joint maximum offsets contain unknown direct joints: " + + ",".join(unknown_joint_limits) + ) + if any( + not math.isfinite(value) or not 0.0 < value <= math.radians(90.0) + for value in joint_limits.values() + ): + raise ValueError("joint maximum offsets must be finite and in (0, 90deg]") + if maximum_cycle_difference_rad <= 0.0: + raise ValueError("maximum cycle difference must be positive") + if minimum_applied_offset_rad < 0.0 or significance_sigma < 0.0: + raise ValueError("zero significance thresholds must be non-negative") + if maximum_axis_cone_mismatch_rad <= 0.0: + raise ValueError("maximum axis cone mismatch must be positive") + if ( + maximum_systematic_axis_cone_bias_rad is not None + and ( + maximum_systematic_axis_cone_bias_rad + <= maximum_axis_cone_mismatch_rad + or maximum_systematic_axis_cone_bias_rad > math.radians(90.0) + ) + ): + raise ValueError( + "maximum systematic axis cone bias must exceed the precision " + "limit and be at most 90deg" + ) + if maximum_pose_axis_line_rms_m <= 0.0: + raise ValueError("maximum pose axis-line RMS must be positive") + if maximum_observability_condition_number <= 1.0: + raise ValueError( + "maximum observability condition number must be greater than one" + ) + if ( + maximum_validation_error_rad is not None + and maximum_validation_error_rad <= 0.0 + ): + raise ValueError("maximum validation error must be positive") + if ( + maximum_confidence_half_width_rad is not None + and maximum_confidence_half_width_rad <= 0.0 + ): + raise ValueError("maximum confidence half width must be positive") + fixed_offsets = { + str(name): float(value) + for name, value in ( + profile.fixed_direct_zero_offsets_rad + if fixed_direct_zero_offsets_rad is None + else fixed_direct_zero_offsets_rad + ).items() + } + unknown_fixed_offsets = sorted( + set(fixed_offsets) - set(profile.direct_zero_joints) + ) + if unknown_fixed_offsets: + raise ValueError( + "fixed direct zero offsets contain unknown joints: " + + ",".join(unknown_fixed_offsets) + ) + if any( + not math.isfinite(value) or abs(value) > math.radians(90.0) + for value in fixed_offsets.values() + ): + raise ValueError( + "fixed direct zero offsets must be finite and within +/-90deg" + ) + output_offsets = { + str(name): float(value) + for name, value in ( + profile.static_output_zero_offsets_rad + if static_output_zero_offsets_rad is None + else static_output_zero_offsets_rad + ).items() + } + unknown_output_offsets = sorted( + set(output_offsets) - set(profile.direct_zero_joints) + ) + if unknown_output_offsets: + raise ValueError( + "static output zero offsets contain unknown joints: " + + ",".join(unknown_output_offsets) + ) + if any( + not math.isfinite(value) or abs(value) > math.radians(90.0) + for value in output_offsets.values() + ): + raise ValueError( + "static output zero offsets must be finite and within +/-90deg" + ) + zero_offsets = {name: 0.0 for name in profile.direct_zero_joints} + zero_offsets.update(fixed_offsets) + + return ZeroProblem( + profile=profile, + model=model, + training=training, + validation=validation, + configured_palm_sources=configured_palm_sources, + orientation_validation=orientation_validation, + orientation_by_model_cycle=orientation_by_model_cycle, + joint_limits=joint_limits, + fixed_offsets=fixed_offsets, + output_offsets=output_offsets, + zero_offsets=zero_offsets, + ) + + +def prepare_offset_limits( + *, + options: ZeroSolveOptions, + problem: ZeroProblem, +) -> OffsetLimits: + finger_maximum_offset_rad = options.finger_maximum_offset_rad + joint_limits = problem.joint_limits + maximum_offset_rad = options.maximum_offset_rad + profile = problem.profile + + product_finger_rolls = tuple(profile.common_mode_zero_joints) + offset_limits = np.asarray( + [ + joint_limits.get( + name, + ( + finger_maximum_offset_rad + if name in profile.small_offset_joints + else maximum_offset_rad + ), + ) + for name in profile.direct_zero_joints + ], + dtype=float, + ) + # Do not make a configured safety limit the numerical optimizer's bound. + # Otherwise a genuine out-of-range estimate and a modelling failure both + # collapse to exactly +/-20 or +/-3 degrees, which hides the magnitude and + # encourages pointless rescans. Search farther for diagnostics, then keep + # the original configured limits as unchanged pass/fail gates below. + diagnostic_offset_limits = np.minimum( + math.radians(90.0), + np.maximum(3.0 * offset_limits, offset_limits + math.radians(5.0)), + ) + if profile.parallel_root_pattern: + # The absolute rotation of the fitted palm frame about the four + # parallel roll axes is a shared gauge. Each physical finger zero is + # only its deviation from the four-finger median, but the raw scalar + # solves include that common mode. Give those four diagnostic solves + # enough range for the unchanged global common-mode limit plus the + # unchanged per-finger deviation limit; applying the per-finger bound + # before removing the gauge clips every solve to the same value and + # destroys the observable deviations. + for index, name in enumerate(profile.direct_zero_joints): + if name in product_finger_rolls: + diagnostic_offset_limits[index] = min( + math.radians(90.0), + maximum_offset_rad + offset_limits[index], + ) + + return OffsetLimits( + product_finger_rolls=product_finger_rolls, + offset_limits=offset_limits, + diagnostic_offset_limits=diagnostic_offset_limits, + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/residuals.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/residuals.py new file mode 100644 index 0000000..a8edd05 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/residuals.py @@ -0,0 +1,355 @@ +"""CAD observation residuals with explicit, immutable geometry inputs.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from typing import Mapping, Sequence +import math + +from scipy.spatial.transform import Rotation +import numpy as np + +from ...domain.measurement import JointCurveFit +from ...urdf.kinematics import UrdfKinematicModel +from .geometry_helpers import ( + _angles_from_state, + _zero_sensitive_axis_error_rad, + robust_circular_location, +) +from .types import JointAxisMeasurement, PalmOrientationMeasurement, ZeroCalibrationProfile + + +@dataclass(frozen=True) +class ObservationGeometry: + """CAD and frozen observations; no fitted state or acceptance policy.""" + profile: ZeroCalibrationProfile + model: UrdfKinematicModel + curves: Mapping[str, JointCurveFit] + motor_by_joint: Mapping[str, int] + orientation_by_model_cycle: Mapping[tuple[str, int], PalmOrientationMeasurement] + incomplete_training_cycles: frozenset[int] = frozenset() + + def complete_offsets(self, selected): + """Offsets whose same-cycle observation dependencies actually exist.""" + keys = {(item.joint, item.cycle) for item in selected} + available = set() + for name, observer in self.profile.offset_observer_joint.items(): + for joint, cycle in keys: + if joint != observer: + continue + pair = self.profile.same_view_axis_pair_by_offset.get(name) + if pair and all((axis, cycle) in self.orientation_by_model_cycle for axis in pair): + available.add(name) + elif observer in self.profile.axis_parent_joint: + available.add(name) + elif (self.profile.phase_parent_joint.get(observer), cycle) in keys: + available.add(name) + return available + + def for_cycles(self, cycles: Sequence[int]) -> ObservationGeometry: + selected = set(cycles) + return replace(self, orientation_by_model_cycle={ + key: value for key, value in self.orientation_by_model_cycle.items() if key[1] in selected + }) + + def predicted_local( + self, + measurement: JointAxisMeasurement, + offsets: Mapping[str, float], + ) -> tuple[np.ndarray, np.ndarray]: + curves = self.curves + model = self.model + motor_by_joint = self.motor_by_joint + profile = self.profile + angles = _angles_from_state( + ( + measurement.condition_state_u8 + if measurement.condition_command_u8 is None + else measurement.condition_command_u8 + ), + curves=curves, + motor_by_joint=motor_by_joint, + inherited_zero_joints=profile.inherited_zero_joints, + ) + return model.axis_line( + measurement.joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + + def predicted_palm_orientation_local( + self, + measurement: PalmOrientationMeasurement, + offsets: Mapping[str, float], + ) -> np.ndarray: + curves = self.curves + model = self.model + motor_by_joint = self.motor_by_joint + profile = self.profile + angles = _angles_from_state( + measurement.condition_state_u8, + curves=curves, + motor_by_joint=motor_by_joint, + inherited_zero_joints=profile.inherited_zero_joints, + ) + axis, _ = model.axis_line( + measurement.model_joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + return axis / np.linalg.norm(axis) + + def phase_error( + self, + predicted_parent_axis: np.ndarray, + predicted_parent_point: np.ndarray, + predicted_child_point: np.ndarray, + observed_parent_axis: np.ndarray, + observed_parent_point: np.ndarray, + observed_child_point: np.ndarray, + view_normal_common: Sequence[float] | None = None, + ) -> float: + parent_axis = predicted_parent_axis / np.linalg.norm(predicted_parent_axis) + observed_axis = observed_parent_axis / np.linalg.norm(observed_parent_axis) + if float(parent_axis @ observed_axis) < 0.0: + observed_axis = -observed_axis + predicted_delta = predicted_child_point - predicted_parent_point + observed_delta = observed_child_point - observed_parent_point + predicted_radial = predicted_delta - parent_axis * float( + predicted_delta @ parent_axis + ) + observed_radial = observed_delta - observed_axis * float( + observed_delta @ observed_axis + ) + angle_axis = parent_axis + if view_normal_common is not None: + view_normal = np.asarray(view_normal_common, dtype=float) + normal_norm = float(np.linalg.norm(view_normal)) + if normal_norm > 1.0e-9: + view_normal /= normal_norm + # When looking approximately along the rotation axis, image + # x/y contains the complete radial phase while optical depth + # is both unnecessary and much noisier for a 16 mm planar + # Tag. For an edge-on axis the depth component is genuinely + # needed for observability, so retain the full 3-D residual. + if abs(float(parent_axis @ view_normal)) >= math.cos( + math.radians(45.0) + ): + # Use an image-plane phase for an end-on observation. + # Projection alone removes optical depth, but does NOT + # remove an arbitrary along-axis point coordinate when + # the camera is even slightly oblique to the axis. + # A closest point is defined relative to its parent Tag + # origin, not the physical bearing centre. Different Tag + # mounts therefore choose different along-axis gauges. + # Reusing delta here would reintroduce that arbitrary + # coordinate and turn it into a phase at oblique views. + predicted_radial = predicted_radial - view_normal * float( + predicted_radial @ view_normal + ) + observed_radial = observed_radial - view_normal * float( + observed_radial @ view_normal + ) + angle_axis = view_normal + if float(angle_axis @ parent_axis) < 0.0: + angle_axis = -angle_axis + predicted_radius = float(np.linalg.norm(predicted_radial)) + observed_radius = float(np.linalg.norm(observed_radial)) + if min(predicted_radius, observed_radius) < 0.003: + raise ValueError("parallel-axis radial phase is not observable") + predicted_radial /= predicted_radius + observed_radial /= observed_radius + return math.atan2( + float(angle_axis @ np.cross(predicted_radial, observed_radial)), + float(np.clip(predicted_radial @ observed_radial, -1.0, 1.0)), + ) + + def same_view_axis_pair_errors( + self, + offset_joint: str, + selected: Sequence[JointAxisMeasurement], + offsets: Mapping[str, float], + ) -> tuple[float, ...]: + """Return the camera-frame-invariant residual for a serial-axis pair. + + This observation intentionally has two mirror roots. The optimiser + disambiguates them with the original cross-view estimate, but the + pair residual alone determines the final numerical zero. + """ + curves = self.curves + model = self.model + motor_by_joint = self.motor_by_joint + orientation_by_model_cycle = self.orientation_by_model_cycle + profile = self.profile + pair = profile.same_view_axis_pair_by_offset.get(offset_joint) + if pair is None: + return () + anchor_joint, observer_joint = pair + + def angle(left: np.ndarray, right: np.ndarray) -> float: + cosine = float(left @ right) / float( + np.linalg.norm(left) * np.linalg.norm(right) + ) + return math.acos(abs(float(np.clip(cosine, -1.0, 1.0)))) + + errors: list[float] = [] + for cycle in sorted({int(item.cycle) for item in selected}): + anchor = orientation_by_model_cycle.get((anchor_joint, cycle)) + observer = orientation_by_model_cycle.get( + (observer_joint, cycle) + ) + if anchor is None or observer is None: + return () + angles = _angles_from_state( + observer.condition_state_u8, + curves=curves, + motor_by_joint=motor_by_joint, + inherited_zero_joints=profile.inherited_zero_joints, + ) + predicted_anchor, _ = model.axis_line( + anchor_joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + predicted_observer, _ = model.axis_line( + observer_joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + observed_anchor = np.asarray( + anchor.axis_common_xyz, dtype=float + ) + observed_observer = np.asarray( + observer.axis_common_xyz, dtype=float + ) + errors.append( + angle(predicted_anchor, predicted_observer) + - angle(observed_anchor, observed_observer) + ) + return tuple(errors) + + def angular_error_samples( + self, + offsets: Mapping[str, float], + selected: Sequence[JointAxisMeasurement], + base_rotation: Rotation, + base_translation: np.ndarray, + *, only_offsets=None, + ) -> dict[str, tuple[float, ...]]: + curves = self.curves + model = self.model + motor_by_joint = self.motor_by_joint + phase_error = self.phase_error + predicted_local = self.predicted_local + profile = self.profile + same_view_axis_pair_errors = self.same_view_axis_pair_errors + by_key = {(item.joint, item.cycle): item for item in selected} + errors: dict[str, list[float]] = { + name: [] for name in profile.direct_zero_joints + } + for offset_joint, observer_joint in profile.offset_observer_joint.items(): + if only_offsets is not None and offset_joint not in only_offsets: + continue + pair_errors = same_view_axis_pair_errors( + offset_joint, selected, offsets + ) + if pair_errors: + errors[offset_joint].extend(pair_errors) + continue + observer_items = [ + item for item in selected if item.joint == observer_joint + ] + if not observer_items: + raise ValueError(f"zero observer is missing: {observer_joint}") + for item in observer_items: + observer_axis, observer_point = predicted_local(item, offsets) + observer_axis = base_rotation.apply(observer_axis) + observer_point = ( + base_rotation.apply(observer_point) + base_translation + ) + observed_axis = np.asarray(item.axis_common_xyz, dtype=float) + if observer_joint in profile.axis_parent_joint: + parent_joint = profile.axis_parent_joint[observer_joint] + angles = _angles_from_state( + ( + item.condition_state_u8 + if item.condition_command_u8 is None + else item.condition_command_u8 + ), + curves=curves, + motor_by_joint=motor_by_joint, + inherited_zero_joints=profile.inherited_zero_joints, + ) + parent_axis, _ = model.axis_line( + parent_joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + parent_axis = base_rotation.apply(parent_axis) + error = _zero_sensitive_axis_error_rad( + observer_axis, observed_axis, parent_axis + ) + else: + parent_joint = profile.phase_parent_joint[observer_joint] + observed_parent = by_key.get((parent_joint, item.cycle)) + if observed_parent is None: + if item.cycle in self.incomplete_training_cycles: + continue + raise ValueError( + f"phase parent is missing: {parent_joint} cycle {item.cycle}" + ) + angles = _angles_from_state( + ( + item.condition_state_u8 + if item.condition_command_u8 is None + else item.condition_command_u8 + ), + curves=curves, + motor_by_joint=motor_by_joint, + inherited_zero_joints=profile.inherited_zero_joints, + ) + parent_axis, parent_point = model.axis_line( + parent_joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + parent_axis = base_rotation.apply(parent_axis) + parent_point = ( + base_rotation.apply(parent_point) + base_translation + ) + error = phase_error( + parent_axis, + parent_point, + observer_point, + np.asarray(observed_parent.axis_common_xyz, dtype=float), + np.asarray(observed_parent.point_common_xyz_m, dtype=float), + np.asarray(item.point_common_xyz_m, dtype=float), + item.view_normal_common_xyz, + ) + errors[offset_joint].append(float(error)) + return { + name: tuple(values) + for name, values in errors.items() + if values + } + + def angular_errors( + self, + offsets: Mapping[str, float], + selected: Sequence[JointAxisMeasurement], + base_rotation: Rotation, + base_translation: np.ndarray, + ) -> dict[str, float]: + angular_error_samples = self.angular_error_samples + return { + name: robust_circular_location(values) + for name, values in angular_error_samples( + offsets, selected, base_rotation, base_translation + ).items() + } diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/rotation_curves.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/rotation_curves.py new file mode 100644 index 0000000..061d526 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/rotation_curves.py @@ -0,0 +1,423 @@ +"""Rotation curves.""" + +from __future__ import annotations + +from typing import Any, Mapping, Sequence +import math + +from scipy.spatial.transform import Rotation +import numpy as np + +from ...domain.measurement import JointCurveFit +from ...geometry.rotation import fit_rotation_axis, robust_rotation_summary +from ..trajectory_geometry import _fit_joint_curve +from .geometry_helpers import ZERO_REFERENCE_MAXIMUM_DISTANCE_U8, _relative_rotation, _vector + + +def _reference_group_key(record: Mapping[str, Any]) -> tuple[Any, Any]: + return record.get("cycle"), record.get("direction") + + +def _canonical_reference_records( + records: Sequence[Mapping[str, Any]], + canonical_zero_direction: str | None, +) -> list[Mapping[str, Any]]: + """Select the sole physical-zero branch when one is configured.""" + if canonical_zero_direction is None: + return list(records) + if canonical_zero_direction not in {"decreasing", "increasing"}: + raise ValueError("canonical zero direction is invalid") + selected = [ + record + for record in records + if str(record.get("direction")) == canonical_zero_direction + ] + if not selected: + raise ValueError( + f"canonical {canonical_zero_direction} zero branch has no samples" + ) + return selected + + +def _spatial_input(record: Mapping[str, Any]) -> float: + """Native input for geometry; the old byte spelling is read-only compatibility.""" + value = float(record["input_value"] if "input_value" in record else record["command_u8"]) + if not math.isfinite(value): + raise ValueError("nonfinite spatial observation input") + return value + + +def _interpolate_reference_rotation( + records: Sequence[Mapping[str, Any]], + zero_command_u8: int, + maximum_distance_u8: int | None = ZERO_REFERENCE_MAXIMUM_DISTANCE_U8, +) -> Rotation | None: + by_command: dict[float, list[np.ndarray]] = {} + for record in records: + command = _spatial_input(record) + by_command.setdefault(command, []).append(_relative_rotation(record)) + if not by_command: + return None + + rotations = { + command: Rotation.from_quat(robust_rotation_summary(values)[0]) + for command, values in by_command.items() + } + zero = float(zero_command_u8) + if zero in rotations: + return rotations[zero] + + lower = [command for command in rotations if command < zero] + upper = [command for command in rotations if command > zero] + lower_command = max(lower) if lower else None + upper_command = min(upper) if upper else None + if lower_command is not None and upper_command is not None: + lower_distance = zero - lower_command + upper_distance = upper_command - zero + if maximum_distance_u8 is None or max( + lower_distance, upper_distance + ) <= float(maximum_distance_u8): + lower_rotation = rotations[lower_command] + upper_rotation = rotations[upper_command] + fraction = lower_distance / (upper_command - lower_command) + delta = (lower_rotation.inv() * upper_rotation).as_rotvec() + return lower_rotation * Rotation.from_rotvec(delta * fraction) + + nearest_command = min(rotations, key=lambda command: abs(command - zero)) + if maximum_distance_u8 is None or abs( + nearest_command - zero + ) <= float(maximum_distance_u8): + return rotations[nearest_command] + return None + + +def _near_zero_records( + records: Sequence[Mapping[str, Any]], zero_command_u8: int +) -> list[Mapping[str, Any]]: + groups: dict[tuple[Any, Any], list[Mapping[str, Any]]] = {} + for record in records: + groups.setdefault(_reference_group_key(record), []).append(record) + selected: list[Mapping[str, Any]] = [] + zero = float(zero_command_u8) + for group in groups.values(): + distance = min(abs(_spatial_input(record) - zero) for record in group) + if "input_value" not in group[0] and distance > ZERO_REFERENCE_MAXIMUM_DISTANCE_U8: + continue + selected.extend( + record + for record in group + if abs(_spatial_input(record) - zero) == distance + ) + return selected + + +def _baseline_reference( + records: Sequence[Mapping[str, Any]], + zero_command_u8: int, + maximum_distance_u8: int | None = ZERO_REFERENCE_MAXIMUM_DISTANCE_U8, +) -> tuple[float, float, float, float]: + groups: dict[tuple[Any, Any], list[Mapping[str, Any]]] = {} + for record in records: + groups.setdefault(_reference_group_key(record), []).append(record) + values = [ + rotation.as_quat() + for group in groups.values() + if ( + rotation := _interpolate_reference_rotation( + group, + zero_command_u8, + maximum_distance_u8, + ) + ) + is not None + ] + if not values: + distance = ( + "the observed physical stroke" + if maximum_distance_u8 is None + else f"{int(maximum_distance_u8)} commands of zero {zero_command_u8}" + ) + raise ValueError(f"joint records have no samples within {distance}") + return robust_rotation_summary(values)[0] + + +def baseline_hysteresis_by_cycle_rad( + records: Sequence[Mapping[str, Any]], + *, + zero_command_u8: int, + axis_xyz: Sequence[float] | None = None, +) -> tuple[float, ...]: + """Return decreasing/increasing joint-angle disagreement per cycle. + + Full SO(3) disagreement includes planar-PnP tilt noise that is orthogonal + to the fitted revolute axis. When an axis is supplied, report only the + physically meaningful component about that axis; the orthogonal component + remains covered by the independent rotation-model residual gate. + """ + samples = [dict(record) for record in records] + axis: np.ndarray | None = None + if axis_xyz is not None: + axis = _vector(axis_xyz, 3, name="baseline hysteresis axis") + norm = float(np.linalg.norm(axis)) + if norm <= 0.0: + raise ValueError("baseline hysteresis axis must be non-zero") + axis /= norm + result: list[float] = [] + for cycle in sorted({int(record["cycle"]) for record in samples}): + rotations: dict[str, Rotation] = {} + for direction in ("decreasing", "increasing"): + selected = [ + record + for record in samples + if int(record["cycle"]) == cycle + and str(record["direction"]) == direction + ] + reference = _interpolate_reference_rotation( + selected, zero_command_u8 + ) + if reference is None: + raise ValueError( + f"cycle {cycle} {direction} is missing baseline samples" + ) + rotations[direction] = reference + delta = ( + rotations["decreasing"].inv() + * rotations["increasing"] + ) + result.append( + float( + delta.magnitude() + if axis is None + else abs(float(delta.as_rotvec() @ axis)) + ) + ) + if not result: + raise ValueError("baseline hysteresis requires at least one cycle") + return tuple(result) + + +def fit_rotation_joint_curve( + records: Sequence[Mapping[str, Any]], + *, + zero_command_u8: int, + canonical_zero_direction: str | None = None, + require_observed_domain_endpoints: bool = True, + zero_reference_maximum_distance_u8: int | None = ( + ZERO_REFERENCE_MAXIMUM_DISTANCE_U8 + ), +) -> JointCurveFit: + """Fit a direction-aware curve from parent-to-child Tag orientations. + + With ``canonical_zero_direction`` both branches share one physical + reference. Only the canonical branch is zero at ``zero_command_u8``; + the other branch retains its measured backlash/compliance offset. + + Byte-feedback products keep the default requirement that both exact + 0/255 endpoints were observed. Physical-angle products may set + ``require_observed_domain_endpoints=False`` after their acquisition policy + has independently proved feedback travel and coverage; the dense internal + curve then uses bounded edge extrapolation instead of inventing endpoint + feedback samples. + """ + samples = [dict(record) for record in records] + if len(samples) < 12: + raise ValueError("rotation trajectory requires at least 12 samples") + vectors: list[np.ndarray] = [] + commands: list[int] = [] + values_by_record: list[float] = [] + # One installation/reference for the entire training session. Recentring + # each cycle would absorb physical Tag slip into nuisance mounting angles. + reference = Rotation.from_quat(_baseline_reference( + _canonical_reference_records(samples, canonical_zero_direction), + zero_command_u8, zero_reference_maximum_distance_u8, + )) + for record in samples: + observed = Rotation.from_quat(_relative_rotation(record)) + vector = ( + reference.inv() * observed + ).as_rotvec() + vectors.append(vector) + commands.append(int(record["command_u8"])) + axis = fit_rotation_axis(vectors, commands) + values_by_record = [float(vector @ axis) for vector in vectors] + curves, correction, hysteresis = _fit_joint_curve( + samples, + values_by_record, + preserve_direction_offset=True, + require_observed_domain_endpoints=require_observed_domain_endpoints, + ) + canonical_key = "angle_rad" if canonical_zero_direction is None else f"{canonical_zero_direction}_rad" + shared_zero = float(curves[canonical_key][int(zero_command_u8)]) + for key in ("angle_rad", "decreasing_rad", "increasing_rad"): + values = np.asarray(curves[key], dtype=float) - shared_zero + curves[key] = [round(float(value), 8) for value in values] + # Keep the stored measurement reference in exactly the same coordinate + # gauge as the shifted curve; do not apply this shift twice at validation. + reference = reference * Rotation.from_rotvec(axis * shared_zero) + if canonical_zero_direction is not None: + # Before the bridge has observed motion direction it must use the + # same branch that defines the URDF physical zero, never an average + # pose that the mechanism may not be able to occupy. + curves["angle_rad"] = list(curves[canonical_key]) + orthogonal = [ + float(np.linalg.norm(vector - float(vector @ axis) * axis)) + for vector in vectors + ] + return JointCurveFit( + angle_rad=tuple(float(value) for value in curves["angle_rad"]), + decreasing_rad=tuple(float(value) for value in curves["decreasing_rad"]), + increasing_rad=tuple(float(value) for value in curves["increasing_rad"]), + circle={ + "space": "relative_rotation_3d", + "axis_xyz": [float(value) for value in axis], + "zero_command_u8": int(zero_command_u8), + "reference_quaternion_xyzw": [ + float(value) for value in reference.as_quat() + ], + "canonical_zero_direction": canonical_zero_direction, + "reference_policy": "training_frozen_installation_v1", + "training_cycles": sorted({int(record["cycle"]) for record in samples}), + }, + maximum_monotonic_correction_rad=float(correction), + maximum_hysteresis_rad=float(hysteresis), + quality={ + "rotation_orthogonal_rms_rad": float( + np.sqrt(np.mean(np.square(orthogonal))) + ), + "arc_rad": float( + max(curves["angle_rad"]) - min(curves["angle_rad"]) + ), + }, + ) + + +def measure_rotation_joint_observation( + fit: JointCurveFit, quaternion_xyzw: Sequence[float] +) -> float: + """Measure one parent-to-child orientation with a fitted 3-D curve.""" + if fit.circle.get("space") != "relative_rotation_3d": + raise ValueError("joint fit is not a relative-rotation curve") + reference = Rotation.from_quat( + _vector( + fit.circle["reference_quaternion_xyzw"], + 4, + name="reference quaternion", + ) + ) + observed = Rotation.from_quat( + _vector(quaternion_xyzw, 4, name="observed quaternion") + ) + axis = _vector(fit.circle["axis_xyz"], 3, name="rotation axis") + axis /= np.linalg.norm(axis) + return float((reference.inv() * observed).as_rotvec() @ axis) + + +def measure_joint_curve_observation( + fit: JointCurveFit, + *, + quaternion_xyzw: Sequence[float] | None = None, + image_relative_xy_px: Sequence[float] | None = None, +) -> float: + """Measure one observation in the same space as its fitted curve.""" + if fit.circle.get("space") == "relative_rotation_3d": + if quaternion_xyzw is None: + raise ValueError("rotation observation quaternion is missing") + return measure_rotation_joint_observation(fit, quaternion_xyzw) + if fit.circle.get("space") != "image_2d": + raise ValueError("unsupported joint curve observation representation") + if image_relative_xy_px is None: + raise ValueError("image curve observation point is missing") + point = np.asarray(image_relative_xy_px, dtype=float) + centre = np.asarray(fit.circle["center_xy_px"], dtype=float) + reference = np.asarray(fit.circle["reference_xy_px"], dtype=float) + vector = point - centre + if ( + point.shape != (2,) + or not np.all(np.isfinite(point)) + or float(np.linalg.norm(vector)) < 1.0e-9 + ): + raise ValueError("image curve observation point is invalid") + return float(fit.circle["orientation_sign"]) * math.atan2( + float(reference[0] * vector[1] - reference[1] * vector[0]), + float(reference @ vector), + ) + + +def rotation_curve_holdout_errors( + fit: JointCurveFit, + records: Sequence[Mapping[str, Any]], + *, + zero_command_u8: int, + zero_reference_maximum_distance_u8: int | None = ( + ZERO_REFERENCE_MAXIMUM_DISTANCE_U8 + ), +) -> tuple[float, ...]: + """Validate against the frozen training reference, never refit holdout. + + The distance argument is retained for legacy callers but deliberately + cannot select a new reference from validation samples. + """ + samples = [dict(record) for record in records] + if not samples: + raise ValueError("holdout records are empty") + if int(fit.circle["zero_command_u8"]) != int(zero_command_u8): + raise ValueError("holdout cannot change the fitted zero coordinate") + training_cycles = set(fit.circle.get("training_cycles", ())) + if any(int(row["cycle"]) in training_cycles for row in samples): + raise ValueError("training cycles cannot enter independent holdout") + reference = Rotation.from_quat(_vector( + fit.circle["reference_quaternion_xyzw"], 4, name="frozen reference quaternion")) + axis = _vector(fit.circle["axis_xyz"], 3, name="rotation axis") + axis /= np.linalg.norm(axis) + errors: list[float] = [] + for record in samples: + observed = Rotation.from_quat(_relative_rotation(record)) + angle = float((reference.inv() * observed).as_rotvec() @ axis) + command = int(record["command_u8"]) + direction = str(record["direction"]) + if not 0 <= command <= 255 or direction not in {"increasing", "decreasing"}: + raise ValueError("holdout SDK input or direction is invalid") + expected_curve = ( + fit.decreasing_rad + if direction == "decreasing" + else fit.increasing_rad + ) + expected = float(expected_curve[command]) + predicted = reference * Rotation.from_rotvec(axis * expected) + magnitude = float((predicted.inv() * observed).magnitude()) + # Include off-axis installation slip without losing the historical + # signed phase-error diagnostic used by reports. + errors.append(math.copysign(magnitude, angle - expected)) + return tuple(errors) + + +def joint_curve_holdout_errors( + fit: JointCurveFit, + records: Sequence[Mapping[str, Any]], + *, + zero_command_u8: int, +) -> tuple[float, ...]: + """Validate either a rotation or fixed-parent image-circle curve.""" + if fit.circle.get("space") == "relative_rotation_3d": + return rotation_curve_holdout_errors( + fit, records, zero_command_u8=zero_command_u8 + ) + if fit.circle.get("space") != "image_2d": + raise ValueError("unsupported joint curve holdout representation") + if not records: + raise ValueError("holdout records are empty") + errors: list[float] = [] + for record in records: + observed = measure_joint_curve_observation( + fit, + image_relative_xy_px=record["image_relative_xy_px"], + ) + command = int(record["command_u8"]) + direction = str(record["direction"]) + expected_curve = ( + fit.decreasing_rad + if direction == "decreasing" + else fit.increasing_rad + ) + errors.append(observed - float(expected_curve[command])) + return tuple(errors) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/solve.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/solve.py new file mode 100644 index 0000000..4672d0f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/solve.py @@ -0,0 +1,163 @@ +"""Public spatial zero pipeline with frozen training and independent validation.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Mapping, Sequence +import math + +from ...domain.measurement import JointCurveFit +from .acceptance import assemble_result, decide_acceptance, decide_training_acceptance +from .optimization import solve_selected +from .preparation import prepare_offset_limits, prepare_zero_problem +from .residuals import ObservationGeometry +from .stages import TrainingFit, TrainingProblem, ZeroSolveOptions, ObservabilityEvidence, CycleEvidence +from .statistics import estimate_cycle_evidence, estimate_observability +from .types import ( + JointAxisMeasurement, + PalmOrientationMeasurement, + ZeroCalibrationProfile, + ZeroSolveResult, +) +from .validation import check_observation_geometry, validate_axis_lines, validate_holdout + + +@dataclass(frozen=True) +class FrozenZeroTraining: + input_sha256: str + fit: TrainingFit + observability: ObservabilityEvidence + cycles: CycleEvidence + applied_offsets: Mapping[str, float] + + +@dataclass(frozen=True) +class ZeroTrainingResult: + offsets: Mapping[str, float] + confidence_half_widths: Mapping[str, float] + cycle_values: Mapping[str, Sequence[float]] + failures: tuple[str, ...] + frozen: FrozenZeroTraining | None = None + failure_reasons: Mapping[str, str] | None = None + + +def fit_urdf_zero_training(*, measurements, training_cycles, **kwargs): + """Training-only entry: independent validation observations cannot enter.""" + if any(item.cycle not in training_cycles for item in ( + *measurements, *kwargs.get("palm_orientation_measurements", ()))): + raise ValueError("zero_training_received_nontraining_data") + if "validation_cycle" in kwargs: + raise ValueError("zero_training_has_no_validation_cycle") + return solve_urdf_zero_offsets(measurements=measurements, training_cycles=training_cycles, + validation_cycle=None, **kwargs) + + +def solve_urdf_zero_offsets( + *, + source_urdf: str | Path, + measurements: Sequence[JointAxisMeasurement], + palm_orientation_measurements: Sequence[PalmOrientationMeasurement] = (), + curves: Mapping[str, JointCurveFit], + motor_by_joint: Mapping[str, int], + training_cycles: Sequence[int] = (0, 1), + validation_cycle: int | None = 2, + maximum_offset_rad: float = math.radians(20.0), + finger_maximum_offset_rad: float = math.radians(3.0), + joint_maximum_offset_rad: Mapping[str, float] | None = None, + maximum_cycle_difference_rad: float = math.radians(0.75), + minimum_applied_offset_rad: float = math.radians(0.3), + significance_sigma: float = 3.0, + maximum_validation_mae_rad: float = math.radians(1.0), + maximum_validation_p95_rad: float = math.radians(2.0), + maximum_validation_error_rad: float | None = None, + maximum_confidence_half_width_rad: float | None = None, + maximum_axis_cone_mismatch_rad: float = math.radians(5.0), + maximum_systematic_axis_cone_bias_rad: float | None = None, + maximum_pose_axis_line_rms_m: float = 0.001, + maximum_observability_condition_number: float = 10000000000.0, + hand_type: str | None = None, + tag_layout: str | None = None, + fixed_direct_zero_offsets_rad: Mapping[str, float] | None = None, + static_output_zero_offsets_rad: Mapping[str, float] | None = None, + zero_profile: ZeroCalibrationProfile | None = None, + allow_partial_training_cycles: bool = False, + frozen_training: FrozenZeroTraining | None = None, +) -> ZeroSolveResult | ZeroTrainingResult: + """Prepare, fit training only, validate the frozen result, then assemble.""" + options = ZeroSolveOptions( + maximum_offset_rad=maximum_offset_rad, + finger_maximum_offset_rad=finger_maximum_offset_rad, + joint_maximum_offset_rad=joint_maximum_offset_rad, + maximum_cycle_difference_rad=maximum_cycle_difference_rad, + minimum_applied_offset_rad=minimum_applied_offset_rad, + significance_sigma=significance_sigma, + maximum_validation_mae_rad=maximum_validation_mae_rad, + maximum_validation_p95_rad=maximum_validation_p95_rad, + maximum_validation_error_rad=maximum_validation_error_rad, + maximum_confidence_half_width_rad=maximum_confidence_half_width_rad, + maximum_axis_cone_mismatch_rad=maximum_axis_cone_mismatch_rad, + maximum_systematic_axis_cone_bias_rad=maximum_systematic_axis_cone_bias_rad, + maximum_pose_axis_line_rms_m=maximum_pose_axis_line_rms_m, + maximum_observability_condition_number=maximum_observability_condition_number, + ) + problem = prepare_zero_problem( + options=options, + source_urdf=source_urdf, + measurements=measurements, + palm_orientation_measurements=palm_orientation_measurements, + training_cycles=training_cycles, + validation_cycle=validation_cycle, + hand_type=hand_type, + tag_layout=tag_layout, + fixed_direct_zero_offsets_rad=fixed_direct_zero_offsets_rad, + static_output_zero_offsets_rad=static_output_zero_offsets_rad, + zero_profile=zero_profile, + ) + geometry = ObservationGeometry(problem.profile, problem.model, curves, motor_by_joint, problem.orientation_by_model_cycle, + frozenset(training_cycles) if allow_partial_training_cycles else frozenset()) + training_geometry = geometry.for_cycles(training_cycles) + training_problem = TrainingProblem(problem.profile, problem.training, problem.fixed_offsets, problem.zero_offsets) + limits = prepare_offset_limits(problem=problem, options=options) + from ..frozen import encode + from ...domain.capture_plan import evidence_digest + import hashlib + input_sha256 = evidence_digest(encode((tuple(problem.training), tuple(training_cycles), + curves, motor_by_joint, options, problem.profile, + hashlib.sha256(Path(source_urdf).read_bytes()).hexdigest(), + training_geometry.orientation_by_model_cycle, allow_partial_training_cycles))) if ( + validation_cycle is None or frozen_training is not None) else "" + if frozen_training is not None: + if frozen_training.input_sha256 != input_sha256: + raise ValueError("frozen_zero_training_inputs_changed") + fit, observability, cycles = (frozen_training.fit, frozen_training.observability, frozen_training.cycles) + rotation, offsets = fit.base_rotation, fit.training_offsets + else: + rotation, translation, offsets = solve_selected( + problem=training_problem, limits=limits, geometry=training_geometry, selected=problem.training) + fit = TrainingFit(rotation, translation, offsets) + observability = estimate_observability(problem=training_problem, fit=fit, geometry=training_geometry) + cycles = estimate_cycle_evidence(problem=training_problem, limits=limits, fit=fit, options=options, + geometry=training_geometry, measurements=problem.training, training_cycles=training_cycles) + geometry_evidence = check_observation_geometry(problem=problem, options=options, + geometry=geometry, selected=list(measurements), offsets=offsets, rotation=rotation) + if validation_cycle is None: + decision = decide_training_acceptance(problem=problem, limits=limits, fit=fit, options=options, + observability=observability, geometry_evidence=geometry_evidence, cycles=cycles) + from .acceptance import applied_output_offsets + applied = applied_output_offsets(problem.profile, cycles.applied_training, problem.output_offsets, + limits.product_finger_rolls, decision.finger_roll_common_mode) + return ZeroTrainingResult(offsets, cycles.confidence_half_widths, cycles.cycle_values, + tuple(f"{reason}:{name}" for name, reason in sorted(decision.failure_reasons.items())), + FrozenZeroTraining(input_sha256, fit, observability, cycles, applied), dict(decision.failure_reasons)) + holdout = validate_holdout(problem=problem, fit=fit, cycles=cycles, options=options, + geometry=geometry, measurements=measurements) + lines = validate_axis_lines(problem=problem, fit=fit, cycles=cycles, geometry=geometry) + decision = decide_acceptance(problem=problem, limits=limits, fit=fit, options=options, + observability=observability, geometry_evidence=geometry_evidence, cycles=cycles, holdout=holdout) + result = assemble_result(problem=problem, limits=limits, fit=fit, observability=observability, + geometry_evidence=geometry_evidence, cycles=cycles, holdout=holdout, lines=lines, + decision=decision, validation_cycle=validation_cycle) + if frozen_training is not None and dict(result.direct_offsets_rad) != dict(frozen_training.applied_offsets): + raise ValueError('frozen_zero_applied_offsets_changed') + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/stages.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/stages.py new file mode 100644 index 0000000..e9f4cc9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/stages.py @@ -0,0 +1,121 @@ +"""Explicit inputs and evidence passed between spatial solution stages.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Mapping, Sequence + +from scipy.spatial.transform import Rotation +import numpy as np + +from ...urdf.kinematics import UrdfKinematicModel +from .types import JointAxisMeasurement, PalmOrientationMeasurement, ZeroCalibrationProfile + + +@dataclass(frozen=True) +class ZeroProblem: + profile: ZeroCalibrationProfile + model: UrdfKinematicModel + training: Sequence[JointAxisMeasurement] + validation: Sequence[JointAxisMeasurement] + configured_palm_sources: Mapping[str, str] + orientation_validation: Sequence[PalmOrientationMeasurement] + orientation_by_model_cycle: Mapping[tuple[str, int], PalmOrientationMeasurement] + joint_limits: Mapping[str, float] + fixed_offsets: Mapping[str, float] + output_offsets: Mapping[str, float] + zero_offsets: Mapping[str, float] + + +@dataclass(frozen=True) +class TrainingProblem: + """Training-only view: the optimizer cannot access holdout observations.""" + + profile: ZeroCalibrationProfile + training: Sequence[JointAxisMeasurement] + fixed_offsets: Mapping[str, float] + zero_offsets: Mapping[str, float] + + +@dataclass(frozen=True) +class OffsetLimits: + product_finger_rolls: tuple[str, ...] + offset_limits: np.ndarray + diagnostic_offset_limits: np.ndarray + + +@dataclass(frozen=True) +class TrainingFit: + base_rotation: Rotation + base_translation: np.ndarray + training_offsets: Mapping[str, float] + + +@dataclass(frozen=True) +class ObservabilityEvidence: + observability_rank: int + observability_parameter_count: int + observability_condition_number: float + offset_covariance: Mapping[str, float] + + +@dataclass(frozen=True) +class GeometryEvidence: + observation_failures: Mapping[str, str] + axis_cone_mismatch_by_joint: Mapping[str, float] + axis_cone_bias_classification_by_joint: Mapping[str, str] + + +@dataclass(frozen=True) +class CycleEvidence: + cycle_values: Mapping[str, Sequence[float]] + cycle_models: Mapping[int, tuple[Rotation, np.ndarray]] + training_cycle_ids: tuple[int, ...] + uncertainties: Mapping[str, float] + confidence_half_widths: Mapping[str, float] + cycle_consistent: bool + inconsistent_cycles: Sequence[str] + insignificant_large: Sequence[str] + applied_training: Mapping[str, float] + + +@dataclass(frozen=True) +class HoldoutEvidence: + validation_error_by_joint: Mapping[str, float] + original_error_by_joint: Mapping[str, float] + improvement_by_joint: Mapping[str, float] + improvement_confidence_lower: Mapping[str, float] + improvement_passed: bool + palm_orientation_validation_passed: bool + validation_errors: np.ndarray + + +@dataclass(frozen=True) +class LineEvidence: + validation_line_error_by_joint: Mapping[str, float] + axis_line_rms: float + + +@dataclass(frozen=True) +class AcceptanceDecision: + finger_roll_common_mode: float + failure_reasons: Mapping[str, str] + passed: bool + + +@dataclass(frozen=True) +class ZeroSolveOptions: + maximum_offset_rad: float + finger_maximum_offset_rad: float + joint_maximum_offset_rad: Mapping[str, float] | None + maximum_cycle_difference_rad: float + minimum_applied_offset_rad: float + significance_sigma: float + maximum_validation_mae_rad: float + maximum_validation_p95_rad: float + maximum_validation_error_rad: float | None + maximum_confidence_half_width_rad: float | None + maximum_axis_cone_mismatch_rad: float + maximum_systematic_axis_cone_bias_rad: float | None + maximum_pose_axis_line_rms_m: float + maximum_observability_condition_number: float diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/statistics.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/statistics.py new file mode 100644 index 0000000..8841fe0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/statistics.py @@ -0,0 +1,254 @@ +"""Training observability, cycle repeatability and offset confidence.""" + +from __future__ import annotations + +from functools import partial +from typing import Sequence +import math + +from scipy.spatial.transform import Rotation +from scipy.stats import t as student_t +import numpy as np + +from .optimization import optimise_offsets +from .residuals import ObservationGeometry +from .stages import ( + CycleEvidence, + ObservabilityEvidence, + OffsetLimits, + TrainingFit, + TrainingProblem, + ZeroSolveOptions, +) +from .types import JointAxisMeasurement + + +def observability_residual( + parameters: np.ndarray, + *, + problem: TrainingProblem, + geometry: ObservationGeometry, +): + profile = problem.profile + training = problem.training + predicted_local = geometry.predicted_local + + rotation = Rotation.from_rotvec(parameters[:3]) + translation = parameters[3:6] * 0.05 + offsets = { + name: float(value) + for name, value in zip( + profile.direct_zero_joints, parameters[6:] + ) + } + residuals: list[float] = [] + for item in training: + predicted_axis, predicted_point = predicted_local(item, offsets) + predicted_axis = rotation.apply(predicted_axis) + predicted_axis /= np.linalg.norm(predicted_axis) + predicted_point = rotation.apply(predicted_point) + translation + observed_axis = np.asarray(item.axis_common_xyz, dtype=float) + observed_axis /= np.linalg.norm(observed_axis) + if float(predicted_axis @ observed_axis) < 0.0: + observed_axis = -observed_axis + observed_point = np.asarray(item.point_common_xyz_m, dtype=float) + predicted_moment = np.cross(predicted_point, predicted_axis) + observed_moment = np.cross(observed_point, observed_axis) + residuals.extend(float(value) for value in predicted_axis - observed_axis) + residuals.extend( + float(value) / 0.05 + for value in predicted_moment - observed_moment + ) + return np.asarray(residuals, dtype=float) + + +def estimate_observability( + *, + fit: TrainingFit, + problem: TrainingProblem, + geometry: ObservationGeometry, +) -> ObservabilityEvidence: + base_rotation = fit.base_rotation + base_translation = fit.base_translation + profile = problem.profile + training_offsets = fit.training_offsets + + residual = partial(observability_residual, problem=problem, geometry=geometry) + observability_parameters = np.asarray( + [ + *base_rotation.as_rotvec(), + *(base_translation / 0.05), + *( + training_offsets[name] + for name in profile.direct_zero_joints + ), + ], + dtype=float, + ) + observability_base_residual = residual( + observability_parameters + ) + observability_jacobian = np.empty( + ( + observability_base_residual.size, + observability_parameters.size, + ), + dtype=float, + ) + finite_difference_step = 1.0e-6 + for column in range(observability_parameters.size): + positive = observability_parameters.copy() + negative = observability_parameters.copy() + positive[column] += finite_difference_step + negative[column] -= finite_difference_step + observability_jacobian[:, column] = ( + residual(positive) + - residual(negative) + ) / (2.0 * finite_difference_step) + singular_values = np.linalg.svd( + observability_jacobian, compute_uv=False + ) + singular_threshold = ( + 0.0 + if singular_values.size == 0 + else float(singular_values[0]) * 1.0e-7 + ) + observability_rank = int( + np.count_nonzero(singular_values > singular_threshold) + ) + observability_parameter_count = int(observability_parameters.size) + observability_condition_number = ( + float("inf") + if observability_rank < observability_parameter_count + else float(singular_values[0] / singular_values[-1]) + ) + residual_dof = max( + 1, + observability_base_residual.size - observability_parameter_count, + ) + residual_variance = float( + observability_base_residual @ observability_base_residual + ) / residual_dof + covariance = residual_variance * np.linalg.pinv( + observability_jacobian.T @ observability_jacobian, + rcond=1.0e-12, + ) + offset_covariance = { + name: max(0.0, float(covariance[6 + index, 6 + index])) + for index, name in enumerate(profile.direct_zero_joints) + } + + return ObservabilityEvidence( + observability_rank=observability_rank, + observability_parameter_count=observability_parameter_count, + observability_condition_number=observability_condition_number, + offset_covariance=offset_covariance, + ) + + +def estimate_cycle_evidence( + measurements: Sequence[JointAxisMeasurement], + training_cycles: Sequence[int], + *, + limits: OffsetLimits, + fit: TrainingFit, + options: ZeroSolveOptions, + problem: TrainingProblem, + geometry: ObservationGeometry, +) -> CycleEvidence: + base_rotation = fit.base_rotation + base_translation = fit.base_translation + fixed_offsets = problem.fixed_offsets + maximum_confidence_half_width_rad = options.maximum_confidence_half_width_rad + maximum_cycle_difference_rad = options.maximum_cycle_difference_rad + minimum_applied_offset_rad = options.minimum_applied_offset_rad + profile = problem.profile + significance_sigma = options.significance_sigma + training_offsets = fit.training_offsets + + fit_offsets = partial(optimise_offsets, geometry=geometry, problem=problem, limits=limits) + cycle_values: dict[str, list[float]] = { + name: [] for name in profile.direct_zero_joints + } + cycle_models: dict[int, tuple[Rotation, np.ndarray]] = {} + training_cycle_ids = tuple(sorted({int(value) for value in training_cycles})) + for cycle in training_cycle_ids: + selected = [item for item in measurements if item.cycle == cycle] + available = geometry.complete_offsets(selected) + if not available: + continue + # Keep one palm pose while comparing cycles. Refitting a base pose from + # only two nearly parallel root axes per cycle makes harmless root-line + # noise appear as a large encoder-zero change. + cycle_rotation, cycle_translation = base_rotation, base_translation + cycle_offsets = fit_offsets( + selected, + cycle_rotation, + cycle_translation, + initial=training_offsets, + fitted_names=available, + ) + cycle_models[cycle] = (cycle_rotation, cycle_translation) + for name, value in cycle_offsets.items(): + if name in available: + cycle_values[name].append(value) + uncertainties: dict[str, float] = {} + confidence_half_widths: dict[str, float] = {} + cycle_consistent = True + inconsistent_cycles: list[str] = [] + for name, values in cycle_values.items(): + array = np.asarray(values, dtype=float) + spread = float(np.ptp(array)) if array.size else float("inf") + if spread > maximum_cycle_difference_rad: + cycle_consistent = False + inconsistent_cycles.append(name) + uncertainties[name] = ( + 0.0 + if array.size < 2 + else float(np.std(array, ddof=1) / math.sqrt(array.size)) + ) + confidence_half_widths[name] = ( + float("inf") + if array.size < 2 + else float( + student_t.ppf(0.975, df=array.size - 1) + * uncertainties[name] + ) + ) + + insignificant_large: list[str] = [] + applied_training: dict[str, float] = {} + for name, value in training_offsets.items(): + if name in fixed_offsets: + applied_training[name] = fixed_offsets[name] + continue + uncertainty = uncertainties[name] + confidence_half_width = confidence_half_widths[name] + if ( + abs(value) < minimum_applied_offset_rad + or abs(value) + <= max(significance_sigma * uncertainty, confidence_half_width) + ): + applied_training[name] = 0.0 + validated_zero_candidate = bool( + profile.accept_validated_zero_in_confidence_interval + and maximum_confidence_half_width_rad is not None + and abs(value) <= confidence_half_width + and confidence_half_width <= maximum_confidence_half_width_rad + ) + if abs(value) >= minimum_applied_offset_rad and not validated_zero_candidate: + insignificant_large.append(name) + else: + applied_training[name] = value + + return CycleEvidence( + cycle_values=cycle_values, + cycle_models=cycle_models, + training_cycle_ids=training_cycle_ids, + uncertainties=uncertainties, + confidence_half_widths=confidence_half_widths, + cycle_consistent=cycle_consistent, + inconsistent_cycles=inconsistent_cycles, + insignificant_large=insignificant_large, + applied_training=applied_training, + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/types.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/types.py new file mode 100644 index 0000000..0dfd0b2 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/types.py @@ -0,0 +1,171 @@ +"""Types.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Protocol, Sequence + + +class SpatialHandGeometry(Protocol): + side: str + layout_id: str + active_joints: Sequence[str] + reference_finger: str + palm_orientation_sources: Mapping[str, str] + minimum_palm_orientation_sources: int + stable_cross_view_cone_bias: bool + + +@dataclass(frozen=True) +class ZeroCalibrationProfile: + hand: SpatialHandGeometry + direct_zero_joints: tuple[str, ...] + axis_joints: tuple[str, ...] + # Dynamic command-angle curves may be shared by unobserved fingers. This + # mapping is intentionally *not* an authorization to copy an absolute + # encoder/URDF zero between independent motors. + inherited_zero_joints: Mapping[str, str] + # Absolute static-zero inheritance requires an independent mechanical + # guarantee. With the current 11-Tag layout only the reference finger is + # observed, so the conservative mapping is empty and unobserved active + # finger origins retain their source-CAD zero. + inherited_static_zero_joints: Mapping[str, str] + constrained_circle_joints: frozenset[str] + root_anchor_joints: frozenset[str] + axis_parent_joint: Mapping[str, str] + phase_parent_joint: Mapping[str, str] + offset_observer_joint: Mapping[str, str] + # Some serial offsets can be observed from the angle between two axes + # captured by the same camera. The mapping is geometric topology only; + # it never contains a model- or serial-specific zero value. + same_view_axis_pair_by_offset: Mapping[str, tuple[str, str]] + fixed_direct_zero_offsets_rad: Mapping[str, float] + static_output_zero_offsets_rad: Mapping[str, float] + # Product full-hand fitting uses the five root-axis line pattern. The + # thumb kernel instead uses only the serial thumb chain, so its nuisance + # palm pose cannot be influenced by finger observations. + base_pose_strategy: str = "full_hand" + # A serial-chain model may use a separate palm-root joint axis to fix the + # otherwise free rotation about its primary root axis. G20 retains its + # historical defaults; other model profiles can name the physical anchor + # explicitly without introducing model-specific branches in the solver. + orientation_anchor_joint: str | None = None + # A model whose feedback direction is mechanically reviewed may use the + # signed rotation axes to disambiguate the otherwise mirrored palm-frame + # branches. The default remains undirected for legacy G20/L6 profiles. + directed_base_axis_joints: frozenset[str] = frozenset() + # A profile may retain zero when a *bounded training confidence interval* + # contains it. The frozen zero still faces every geometry/cycle/holdout + # check below. Default False preserves existing G20/L6/O6 decisions. + accept_validated_zero_in_confidence_interval: bool = False + parallel_root_pattern: bool = False + common_mode_zero_joints: tuple[str, ...] = () + small_offset_joints: frozenset[str] = frozenset() + independent_observed_motion: bool = False + + @property + def reference_finger(self) -> str: + return self.hand.reference_finger + + +@dataclass(frozen=True) +class JointAxisMeasurement: + joint: str + cycle: int + axis_common_xyz: tuple[float, float, float] + point_common_xyz_m: tuple[float, float, float] + condition_state_u8: tuple[float, ...] | None + plane_rms_m: float + radial_rms_m: float + rotation_circle_axis_difference_rad: float + # Optical-axis direction expressed in the shared calibration frame. It + # lets the phase solver discard the least reliable monocular-PnP depth + # component when the joint axis is viewed approximately end-on. Older + # recordings and synthetic callers may omit it and retain the 3-D path. + view_normal_common_xyz: tuple[float, float, float] | None = None + # Logical commands that produced the condition. Firmware feedback may + # saturate a few u8 short of an endpoint (for example right motor 10 reads + # 250 for command 255); kinematics must use the command-indexed curve while + # retaining condition_state_u8 for diagnostics and safety. + condition_command_u8: tuple[float, ...] | None = None + axis_direction_source: str = "unspecified" + circle_axis_observability: float = 0.0 + axis_point_source: str = "circle_center" + pose_axis_line_rms_m: float = 0.0 + # Unprojected residuals are evidence, not extra phase observations. The + # axial component lies in the null space of (I-R) for a revolute axis. + pose_axis_line_raw_rms_m: float | None = None + pose_axis_line_axial_rms_m: float | None = None + pose_axis_line_transverse_rms_m: float | None = None + axis_point_axial_component_separated: bool = False + # Measurement record(s) that supplied pose_axis_line_rms_m. A combined + # cross-view axis may keep the front direction but take its physical line + # point and line-quality residual from the side alias. Retry logic must + # clear the actual quality source instead of blindly rescanning ``joint``. + pose_axis_line_source_joints: tuple[str, ...] = () + # Camera centre that observed ``point_common_xyz_m``. When populated, + # the zero solver can use only the ray from this centre to the fitted axis + # point. That ray is the depth-free interpretation-plane observation of + # the physical axis; translating a monocular planar-PnP solution along + # its optical ray therefore cannot rotate the recovered palm frame. + axis_point_camera_center_common_xyz_m: ( + tuple[float, float, float] | None + ) = None + # Normal of the source camera's interpretation plane for this axis line. + # Unlike a 3-D PnP line point, the plane is unchanged by optical-depth + # error. Several named parallel root lines jointly recover their common + # physical direction as the null direction of these plane normals. + axis_point_interpretation_plane_normal_common_xyz: ( + tuple[float, float, float] | None + ) = None + + +@dataclass(frozen=True) +class PalmOrientationMeasurement: + """Direction-only joint observation from a partially visible sweep. + + The moving Tag may disappear before the motor reaches its far endpoint. + Only the relative SO(3) trajectory is retained, so fixed Tag translation + and mounting rotation cannot define the palm phase. + """ + + source_joint: str + model_joint: str + cycle: int + axis_common_xyz: tuple[float, float, float] + condition_state_u8: tuple[float, ...] + observed_arc_rad: float + rotation_orthogonal_rms_rad: float + axis_estimator: str = "baseline_relative_so3" + incremental_pair_count: int = 0 + + +@dataclass(frozen=True) +class ZeroSolveResult: + direct_offsets_rad: Mapping[str, float] + all_active_offsets_rad: Mapping[str, float] + base_translation_xyz_m: tuple[float, float, float] + base_quaternion_xyzw: tuple[float, float, float, float] + validation_errors_rad: tuple[float, ...] + validation_error_by_joint_rad: Mapping[str, float] + validation_line_error_by_joint_m: Mapping[str, float] + axis_line_rms_m: float + passed: bool + cycle_offsets_rad: Mapping[str, tuple[float, ...]] + offset_uncertainty_rad: Mapping[str, float] + offset_confidence_half_width_rad: Mapping[str, float] + training_cycles: tuple[int, ...] + validation_cycle: int + validation_original_error_by_joint_rad: Mapping[str, float] + validation_improvement_by_joint_rad: Mapping[str, float] + validation_improvement_confidence_lower_rad: Mapping[str, float] + observability_rank: int + observability_parameter_count: int + observability_condition_number: float + offset_covariance_rad2: Mapping[str, float] + axis_cone_mismatch_by_joint_rad: Mapping[str, float] + axis_cone_bias_classification_by_joint: Mapping[str, str] + failure_reasons: Mapping[str, str] + # Optional diagnostic evidence from an explicitly selected observation + # policy; does not change the generic solver's acceptance decision. + axis_residual_diagnostics: Mapping[str, Mapping[str, Any]] | None = None diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/validation.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/validation.py new file mode 100644 index 0000000..4363cb2 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/spatial_solver/validation.py @@ -0,0 +1,405 @@ +"""Independent holdout and geometric consistency checks of the frozen fit.""" + +from __future__ import annotations + +from typing import Mapping, Sequence +import math + +from scipy.spatial.transform import Rotation +from scipy.stats import t as student_t +import numpy as np + +from .geometry_helpers import _angles_from_state, _axis_cone_mismatch_rad +from .residuals import ObservationGeometry +from .stages import ( + CycleEvidence, + GeometryEvidence, + HoldoutEvidence, + LineEvidence, + TrainingFit, + ZeroProblem, + ZeroSolveOptions, +) +from .types import JointAxisMeasurement + + +def check_observation_geometry( + selected: Sequence[JointAxisMeasurement], + offsets: Mapping[str, float], + rotation: Rotation, + *, + options: ZeroSolveOptions, + problem: ZeroProblem, + geometry: ObservationGeometry, +): + fixed_offsets = problem.fixed_offsets + maximum_axis_cone_mismatch_rad = options.maximum_axis_cone_mismatch_rad + maximum_confidence_half_width_rad = options.maximum_confidence_half_width_rad + maximum_cycle_difference_rad = options.maximum_cycle_difference_rad + maximum_pose_axis_line_rms_m = options.maximum_pose_axis_line_rms_m + maximum_systematic_axis_cone_bias_rad = options.maximum_systematic_axis_cone_bias_rad + model = problem.model + profile = problem.profile + curves = geometry.curves + motor_by_joint = geometry.motor_by_joint + + axis_cone_mismatch_by_joint: dict[str, float] = {} + axis_cone_bias_classification_by_joint: dict[str, str] = {} + """Reject repeatable but geometrically inadmissible zero observers.""" + by_key = {(item.joint, item.cycle): item for item in selected} + failures: dict[str, str] = {} + for offset_joint, observer_joint in profile.offset_observer_joint.items(): + if offset_joint in fixed_offsets: + continue + observer_items = [ + item for item in selected if item.joint == observer_joint + ] + if observer_joint in profile.axis_parent_joint: + parent_joint = profile.axis_parent_joint[observer_joint] + cone_mismatches: list[float] = [] + for item in observer_items: + state = ( + item.condition_state_u8 + if item.condition_command_u8 is None + else item.condition_command_u8 + ) + angles = _angles_from_state( + state, + curves=curves, + motor_by_joint=motor_by_joint, + inherited_zero_joints=( + profile.inherited_zero_joints + ), + ) + predicted_axis, _ = model.axis_line( + observer_joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + parent_axis, _ = model.axis_line( + parent_joint, + zero_offsets=offsets, + joint_angles=angles, + independent_mimic_angles=profile.independent_observed_motion, + ) + cone_mismatches.append( + _axis_cone_mismatch_rad( + rotation.apply(predicted_axis), + item.axis_common_xyz, + rotation.apply(parent_axis), + ) + ) + maximum_cone_mismatch = max(cone_mismatches) + axis_cone_mismatch_by_joint[offset_joint] = ( + maximum_cone_mismatch + ) + if maximum_cone_mismatch > maximum_axis_cone_mismatch_rad: + cone_range = float(np.ptp(cone_mismatches)) + stable_product_bias = bool( + profile.hand.stable_cross_view_cone_bias + and maximum_systematic_axis_cone_bias_rad is not None + and len(cone_mismatches) >= 4 + and maximum_cone_mismatch + <= maximum_systematic_axis_cone_bias_rad + and cone_range <= maximum_cycle_difference_rad + ) + if stable_product_bias: + # A parent zero rotates the downstream direction + # around the parent axis and cannot change their cone + # angle. The zero-sensitive residual above already + # projects both directions onto the parent-normal + # plane, so a repeatable cross-camera/planar-PnP cone + # bias cannot corrupt the written encoder zero. Keep + # it visible in the result while retaining the gross + # gate for a wrong axis, loose Tag, or moved camera. + axis_cone_bias_classification_by_joint[offset_joint] = ( + "stable_cross_view_or_planar_pnp_bias" + ) + else: + failures[offset_joint] = ( + "zero_axis_cone_mismatch_too_large" + ) + else: + parent_joint = profile.phase_parent_joint[observer_joint] + phase_items: list[JointAxisMeasurement] = [] + propagated_angle_uncertainties: list[float] = [] + for item in observer_items: + phase_items.append(item) + parent_item = by_key.get((parent_joint, item.cycle)) + if parent_item is not None: + phase_items.append(parent_item) + parent_axis = np.asarray( + parent_item.axis_common_xyz, dtype=float + ) + parent_axis /= np.linalg.norm(parent_axis) + separation = ( + np.asarray(item.point_common_xyz_m, dtype=float) + - np.asarray( + parent_item.point_common_xyz_m, dtype=float + ) + ) + radial = separation - parent_axis * float( + separation @ parent_axis + ) + effective_distance = float(np.linalg.norm(radial)) + if effective_distance <= 1.0e-6: + propagated_angle_uncertainties.append(float("inf")) + else: + line_uncertainty = math.hypot( + item.pose_axis_line_rms_m, + parent_item.pose_axis_line_rms_m, + ) + propagated_angle_uncertainties.append( + math.atan2( + line_uncertainty, effective_distance + ) + ) + if profile.parallel_root_pattern: + angle_limit = ( + maximum_confidence_half_width_rad + if maximum_confidence_half_width_rad is not None + else math.radians(0.5) + ) + if ( + not propagated_angle_uncertainties + or max(propagated_angle_uncertainties) > angle_limit + ): + failures[offset_joint] = ( + "zero_phase_axis_line_angle_uncertainty_too_large" + ) + elif ( + not profile.parallel_root_pattern + and any( + item.pose_axis_line_rms_m + > maximum_pose_axis_line_rms_m + for item in phase_items + ) + ): + failures[offset_joint] = ( + "zero_phase_axis_line_residual_too_large" + ) + return GeometryEvidence(failures, axis_cone_mismatch_by_joint, axis_cone_bias_classification_by_joint) + + +def validate_holdout( + measurements: Sequence[JointAxisMeasurement], + *, + cycles: CycleEvidence, + fit: TrainingFit, + options: ZeroSolveOptions, + problem: ZeroProblem, + geometry: ObservationGeometry, +) -> HoldoutEvidence: + applied_training = cycles.applied_training + base_rotation = fit.base_rotation + base_translation = fit.base_translation + configured_palm_sources = problem.configured_palm_sources + cycle_models = cycles.cycle_models + fixed_offsets = problem.fixed_offsets + maximum_axis_cone_mismatch_rad = options.maximum_axis_cone_mismatch_rad + maximum_validation_error_rad = options.maximum_validation_error_rad + orientation_validation = problem.orientation_validation + profile = problem.profile + training_cycle_ids = cycles.training_cycle_ids + validation = problem.validation + zero_offsets = problem.zero_offsets + angular_errors = geometry.angular_errors + predicted_palm_orientation_local = geometry.predicted_palm_orientation_local + same_view_axis_pair_errors = geometry.same_view_axis_pair_errors + + candidate_errors = angular_errors( + applied_training, validation, base_rotation, base_translation + ) + original_errors = angular_errors( + zero_offsets, validation, base_rotation, base_translation + ) + validation_error_by_joint: dict[str, float] = {} + original_error_by_joint: dict[str, float] = {} + improvement_by_joint: dict[str, float] = {} + improvement_confidence_lower: dict[str, float] = {} + improvement_passed = True + if profile.same_view_axis_pair_by_offset: + # Validate the same camera/Tag-mount-invariant axis-pair angle used by + # the configured offset. This keeps the side channel out of every + # other joint, including the already stable thumb CMC roll solve. + palm_orientation_validation_errors = tuple( + abs(float(error)) + for offset_joint in profile.same_view_axis_pair_by_offset + for error in same_view_axis_pair_errors( + offset_joint, validation, applied_training + ) + ) + else: + palm_orientation_validation_errors = tuple( + math.acos( + abs( + float( + np.clip( + base_rotation.apply( + predicted_palm_orientation_local( + item, zero_offsets + ) + ) + @ np.asarray(item.axis_common_xyz, dtype=float), + -1.0, + 1.0, + ) + ) + ) + ) + for item in orientation_validation + ) + palm_orientation_validation_limit = ( + maximum_validation_error_rad + if maximum_validation_error_rad is not None + else maximum_axis_cone_mismatch_rad + ) + palm_orientation_validation_passed = bool( + not configured_palm_sources + or ( + palm_orientation_validation_errors + and float(np.median(palm_orientation_validation_errors)) + <= palm_orientation_validation_limit + ) + ) + for offset_joint, observer_joint in profile.offset_observer_joint.items(): + if offset_joint in fixed_offsets: + improvement_by_joint[offset_joint] = 0.0 + improvement_confidence_lower[offset_joint] = 0.0 + continue + candidate = abs(candidate_errors[offset_joint]) + original = abs(original_errors[offset_joint]) + validation_error_by_joint[observer_joint] = candidate + original_error_by_joint[observer_joint] = original + improvement_by_joint[offset_joint] = original - candidate + if applied_training[offset_joint] != 0.0 and not candidate < original: + improvement_passed = False + for offset_joint in profile.direct_zero_joints: + if offset_joint in fixed_offsets: + improvement_confidence_lower[offset_joint] = 0.0 + continue + if applied_training[offset_joint] == 0.0: + improvement_confidence_lower[offset_joint] = 0.0 + continue + cycle_improvements: list[float] = [] + for cycle in training_cycle_ids: + selected = [item for item in measurements if item.cycle == cycle] + cycle_rotation, cycle_translation = cycle_models[cycle] + candidate = abs( + angular_errors( + applied_training, + selected, + cycle_rotation, + cycle_translation, + )[offset_joint] + ) + original = abs( + angular_errors( + zero_offsets, + selected, + cycle_rotation, + cycle_translation, + )[offset_joint] + ) + cycle_improvements.append(original - candidate) + improvement_array = np.asarray(cycle_improvements, dtype=float) + improvement_se = ( + float("inf") + if improvement_array.size < 2 + else float( + np.std(improvement_array, ddof=1) + / math.sqrt(improvement_array.size) + ) + ) + lower = ( + float("-inf") + if not math.isfinite(improvement_se) + else float( + np.mean(improvement_array) + - student_t.ppf( + 0.975, df=improvement_array.size - 1 + ) + * improvement_se + ) + ) + improvement_confidence_lower[offset_joint] = lower + if lower <= 0.0: + improvement_passed = False + + validation_errors = np.asarray( + list(validation_error_by_joint.values()), dtype=float + ) + + return HoldoutEvidence( + validation_error_by_joint=validation_error_by_joint, + original_error_by_joint=original_error_by_joint, + improvement_by_joint=improvement_by_joint, + improvement_confidence_lower=improvement_confidence_lower, + improvement_passed=improvement_passed, + palm_orientation_validation_passed=palm_orientation_validation_passed, + validation_errors=validation_errors, + ) + + +def validate_axis_lines( + *, + cycles: CycleEvidence, + fit: TrainingFit, + problem: ZeroProblem, + geometry: ObservationGeometry, +) -> LineEvidence: + applied_training = cycles.applied_training + base_rotation = fit.base_rotation + base_translation = fit.base_translation + validation = problem.validation + predicted_local = geometry.predicted_local + + validation_line_samples: dict[str, list[float]] = {} + for item in validation: + predicted_axis, predicted_point = predicted_local( + item, applied_training + ) + predicted_axis = base_rotation.apply(predicted_axis) + predicted_axis /= np.linalg.norm(predicted_axis) + predicted_point = ( + base_rotation.apply(predicted_point) + base_translation + ) + observed_axis = np.asarray(item.axis_common_xyz, dtype=float) + observed_axis /= np.linalg.norm(observed_axis) + observed_point = np.asarray(item.point_common_xyz_m, dtype=float) + cross = np.cross(predicted_axis, observed_axis) + cross_norm = float(np.linalg.norm(cross)) + separation = observed_point - predicted_point + line_error = ( + abs(float(separation @ cross)) / cross_norm + if cross_norm > 1.0e-6 + else float( + np.linalg.norm( + separation + - predicted_axis * float(separation @ predicted_axis) + ) + ) + ) + validation_line_samples.setdefault(item.joint, []).append(line_error) + validation_line_error_by_joint = { + name: float(np.sqrt(np.mean(np.square(values)))) + for name, values in validation_line_samples.items() + } + all_validation_line_errors = np.asarray( + [ + value + for values in validation_line_samples.values() + for value in values + ], + dtype=float, + ) + axis_line_rms = ( + float("inf") + if all_validation_line_errors.size == 0 + else float( + np.sqrt(np.mean(np.square(all_validation_line_errors))) + ) + ) + + return LineEvidence(validation_line_error_by_joint=validation_line_error_by_joint, axis_line_rms=axis_line_rms) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/tag_installation.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/tag_installation.py new file mode 100644 index 0000000..403d07a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/tag_installation.py @@ -0,0 +1,179 @@ +"""One training-frozen Tag-to-link installation per physical Tag. + +This is not a zero solver. The CAD zero/base registration must already have +independent observability evidence. No holdout observation participates in +installation fitting, and no installation is fitted again for another task. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Mapping, Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..geometry.rotation import robust_rotation_summary +from ..domain.capture_plan import LEGACY_TRAINING +from ..urdf.kinematics import UrdfKinematicModel + + +def rigid_matrix(value) -> np.ndarray: + result = np.asarray(value, dtype=float) + if result.shape != (4, 4) or not np.all(np.isfinite(result)): + raise ValueError("Tag/base pose must be a finite rigid transform") + r = result[:3, :3] + if not np.allclose(result[3], (0, 0, 0, 1), atol=1e-9) or not np.allclose(r.T @ r, np.eye(3), atol=1e-6) or not np.isclose(np.linalg.det(r), 1, atol=1e-6): + raise ValueError("Tag/base pose must be a rigid transform") + return result + + +def matrix_tuple(value) -> tuple[tuple[float, ...], ...]: + return tuple(tuple(float(v) for v in row) for row in rigid_matrix(value)) + + +def link_pose(model: UrdfKinematicModel, link: str, angles: Mapping[str, float]) -> np.ndarray: + if link == model.root_link: + return np.eye(4) + if link not in model.parent_joint_by_child: + raise ValueError(f"Tag installation references a missing link:{link}") + return model.link_transform(model.parent_joint_by_child[link], + zero_offsets={}, joint_angles=angles, independent_mimic_angles=True) + + +@dataclass(frozen=True) +class TagTrainingPose: + sample_id: str + role: str + cycle: int + common_from_tag: tuple[tuple[float, ...], ...] + # Explicit CAD coordinates, prepared from the fitted measurement result, + # NOT obtained by reading a serializer's just-written JSON/URDF. + cad_angles: Mapping[str, float] + + +@dataclass(frozen=True) +class FrozenTagInstallation: + role: str + link: str + link_from_tag: tuple[tuple[float, ...], ...] + training_sample_ids: tuple[str, ...] + training_rotation_p95_deg: float + training_translation_p95_m: float + training_cycles: tuple[int, ...] = LEGACY_TRAINING + + +class TagInstallationFailure(ValueError): + """All role residuals from one failed rigid-chain validation.""" + + def __init__(self, diagnostics): + self.diagnostics = diagnostics + failed = [name for name, row in diagnostics.items() if not row["passed"]] + super().__init__("tag_installation_not_rigid:" + ";".join( + f"{name}:rotation_p95_deg={diagnostics[name]['rotation_p95_deg']:.6f}:" + f"translation_p95_m={diagnostics[name]['translation_p95_m']:.6f}" for name in failed)) + + +def fit_tag_installations( + *, source_model: UrdfKinematicModel, common_from_base, + link_by_role: Mapping[str, str], observations: Sequence[TagTrainingPose], + minimum_samples: int = 40, + training_cycles_by_role: Mapping[str, Sequence[int]] | None = None, +) -> dict[str, FrozenTagInstallation]: + """Fit mounting transforms once across each role's declared training cycles. + + Repeated records of one image/Tag are deduplicated only when their pose + and joint conditions agree. Conflicting duplicates are invalid evidence. + Training residuals check rigid installation, not a per-frame PnP gate. + """ + base_from_common = np.linalg.inv(rigid_matrix(common_from_base)) + partitions = {role: tuple(training_cycles_by_role[role]) if training_cycles_by_role is not None + else LEGACY_TRAINING for role in link_by_role} + if any(cycles not in (LEGACY_TRAINING, LEGACY_TRAINING[:2]) for cycles in partitions.values()): + raise ValueError("Tag installation requires declared independent training cycles") + grouped: dict[str, dict[str, tuple[int, np.ndarray]]] = {role: {} for role in link_by_role} + for row in observations: + if row.role not in link_by_role: + raise ValueError(f"undeclared Tag installation:{row.role}") + if row.cycle not in partitions[row.role] or not row.sample_id: + raise ValueError("only identified training images may fit Tag installations") + candidate = np.linalg.inv(link_pose(source_model, link_by_role[row.role], row.cad_angles)) @ base_from_common @ rigid_matrix(row.common_from_tag) + previous = grouped[row.role].get(row.sample_id) + if previous is not None and (previous[0] != row.cycle or not np.allclose(previous[1], candidate, atol=1e-8, rtol=0)): + raise ValueError(f"conflicting duplicate Tag image:{row.role}:{row.sample_id}") + grouped[row.role][row.sample_id] = (row.cycle, candidate) + output, diagnostics = {}, {} + for role, unique in sorted(grouped.items()): + if len(unique) < minimum_samples or {value[0] for value in unique.values()} != set(partitions[role]): + raise ValueError(f"Tag installation lacks declared training evidence:{role}") + matrices = np.asarray([value[1] for value in unique.values()]) + rotation = Rotation.from_quat(robust_rotation_summary( + Rotation.from_matrix(matrices[:, :3, :3]).as_quat().tolist())[0]) + translation = np.median(matrices[:, :3, 3], axis=0) + errors = (rotation.inv() * Rotation.from_matrix(matrices[:, :3, :3])).magnitude() + distances = np.linalg.norm(matrices[:, :3, 3] - translation, axis=1) + rotation_p95 = float(np.rad2deg(np.percentile(errors, 95))) + translation_p95 = float(np.percentile(distances, 95)) + diagnostics[role] = {"count": len(unique), "rotation_p95_deg": rotation_p95, + "translation_p95_m": translation_p95, + "passed": rotation_p95 <= 2.0 and translation_p95 <= 0.003} + transform = np.eye(4) + transform[:3, :3], transform[:3, 3] = rotation.as_matrix(), translation + output[role] = FrozenTagInstallation(role, link_by_role[role], matrix_tuple(transform), + tuple(sorted(unique)), rotation_p95, translation_p95, partitions[role]) + if any(not row["passed"] for row in diagnostics.values()): + raise TagInstallationFailure(diagnostics) + return output + + +def register_base_translation( + *, source_model: UrdfKinematicModel, common_from_base, + link_by_role: Mapping[str, str], observations: Sequence[TagTrainingPose], +) -> tuple[tuple[float, ...], ...]: + """Register translation jointly with constant mounts, training only. + + The axis/zero solver owns orientation and observable joint zeros. Its + monocular line-point translation can contain a depth gauge. Full rigid + trajectories remove that gauge through p_tag = p_base + R_base*p_link + + R_base*R_link*p_mount. No extra joint zero or CAD geometry is estimated. + """ + base = rigid_matrix(common_from_base).copy() + roles = tuple(sorted(link_by_role)) + slots = {role: 3 + 3*index for index, role in enumerate(roles)} + count = 3 + 3*len(roles) + matrices, rhs = [], [] + seen = set() + for row in observations: + if row.cycle not in {0, 1, 2} or not row.sample_id or row.role not in slots: + raise ValueError("base registration requires identified training Tag poses") + identity = (row.role, row.sample_id) + if identity in seen: + raise ValueError("duplicate base-registration image") + seen.add(identity) + link = link_pose(source_model, link_by_role[row.role], row.cad_angles) + matrix = np.zeros((3, count)) + matrix[:, :3] = np.eye(3) + index = slots[row.role] + matrix[:, index:index+3] = base[:3, :3] @ link[:3, :3] + matrices.append(matrix) + rhs.append(rigid_matrix(row.common_from_tag)[:3, 3] - base[:3, :3] @ link[:3, 3]) + if not matrices: + raise ValueError("base registration has no training poses") + a, b = np.vstack(matrices), np.concatenate(rhs) + estimate, _, rank, singular = np.linalg.lstsq(a, b, rcond=None) + if rank != count or singular[-1] / singular[0] < 1e-8: + raise ValueError("base translation/mounts are not jointly observable") + # Robust weights act on entire 3-D observations; no axis is selectively + # discarded to hide a bad CAD/mount fit. + for _ in range(8): + residual = (a @ estimate - b).reshape(-1, 3) + distance = np.linalg.norm(residual, axis=1) + scale = max(0.0005, 1.4826*float(np.median(distance))) + weights = np.repeat(np.sqrt(np.minimum(1.0, scale / np.maximum(distance, 1e-12))), 3) + updated = np.linalg.lstsq(a*weights[:, None], b*weights, rcond=None)[0] + if np.linalg.norm(updated - estimate) < 1e-10: + estimate = updated + break + estimate = updated + base[:3, 3] = estimate[:3] + return matrix_tuple(base) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/training_quality.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/training_quality.py new file mode 100644 index 0000000..ec058ea --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/training_quality.py @@ -0,0 +1,174 @@ +"""Bounded training decisions; no holdout input and no hardware interface.""" + +from dataclasses import asdict, replace +import hashlib +from itertools import combinations +import math +from pathlib import Path + +import numpy as np +from scipy.stats import t as student_t + +from ..domain.capture_plan import (CapturePlan, TASKWISE_STAGED, evidence_digest, + select_task_training, training_cycles) +from ..domain.motion_path import record_scan_identity +from ..domain.sampling import command_nodes +from ..urdf.kinematics import UrdfKinematicModel +from ..urdf.acceptance import angular_metrics +from .command_motion import fit_command_training +from .spatial import measure_joint_curve_observation + + +TRAINING_DECISION_VERSION = "training_decision_v1" +# Zero confidence uses the production spatial solver's unchanged limit. +MAXIMUM_CONFIDENCE_HALF_WIDTH_RAD = math.radians(1.) +TRAINING_FIELDS = ("kind", "joint", "view", "task_name", "cycle", "direction", "segment_key", + "attempt", "sample_phase", "image_stamp_ns", "motor_index", "command_u8", "command_rad", + "feedback_u8", "feedback_rad", "steady_index", "steady_target", "relative_quaternion_xyzw", + "relative_translation_xyz_m", "parent_pose_common", "child_pose_common", "view_normal_common_xyz", + "camera_center_common_xyz_m", "state_u8", "state_rad", "command_vector_u8", "command_vector_rad") + + +def training_snapshot(profile, records, task_key, cycles): + """Latest attempts only. Validation rows are excluded before all statistics.""" + chosen = select_task_training(profile, task_key, cycles) + allowed = {task.key: training_cycles(chosen, task) for task in chosen.motion.tasks} + latest = {} + for row in records: + if row.get("task_name") in allowed and row.get("cycle") in allowed[row["task_name"]]: + key = record_scan_identity(row) + latest[key] = max(latest.get(key, 0), int(row.get("attempt", 1))) + rows = [] + for row in records: + if (row.get("kind") != "joint_sample" or row.get("task_name") not in allowed + or row.get("cycle") not in allowed[row["task_name"]] + or row.get("sample_phase", "sweep") not in {"sweep", "steady"} + or int(row.get("attempt", 1)) != latest[record_scan_identity(row)]): + continue + rows.append({key: row[key] for key in TRAINING_FIELDS if key in row}) + return tuple(rows) + + +def _by_joint(rows, phase): + result = {} + for row in rows: + if row.get("sample_phase", "sweep") == phase: + result.setdefault(row["joint"], []).append({**row, + "sample_id": f"{row['view']}:{row['image_stamp_ns']}"}) + return result + + +def _curve_repeatability(profile, task, motion, steady, cycles): + failures, metrics = [], {} + for name in task.joints: + curve = motion.coordinate_curves[name] + values, by_direction = [], {} + for direction in ("increasing", "decreasing"): + directional_values = [] + for node in command_nodes(profile, task): + repeated = [] + for cycle in cycles: + rows = [row for row in steady[name] if row["cycle"] == cycle + and row["direction"] == direction + and math.isclose(float(row["steady_target"]), node, abs_tol=1e-9)] + repeated.append(float(np.median([measure_joint_curve_observation(curve, + quaternion_xyzw=row["relative_quaternion_xyzw"]) for row in rows]))) + values.append(repeated) + directional_values.append(repeated) + array = np.asarray(directional_values) + errors = np.concatenate([array[:, a]-array[:, b] for a, b in combinations(range(len(cycles)), 2)]) + by_direction[direction] = angular_metrics(errors) + array = np.asarray(values) + spread = float(np.max(np.ptp(array, axis=1))) + width = float(np.max(student_t.ppf(.975, len(cycles)-1) + * np.std(array, axis=1, ddof=1) / math.sqrt(len(cycles)))) + metrics[name] = {"maximum_cycle_difference_rad": spread, + "maximum_angle_confidence_half_width_rad": width, + "independent_cycle_count": len(cycles), + "repeatability_by_direction": {key: asdict(value) for key, value in by_direction.items()}} + # Curve consistency is an angular error gate, not a zero-offset CI. + # Applying the 1-degree zero CI limit at every command knot would + # introduce a stricter, unrelated rejection of otherwise sound data. + if not all(value.passed for value in by_direction.values()): + failures.append(f"training_repeatability:{name}") + return failures, metrics + + +def assess_training(profile, task_key, cycles, rows, references, source_urdf): + """Assess one immutable task snapshot without reading validation data. + + Adaptive collection keeps the older conservative behavior: missing + full-hand geometry requests a third round. Taskwise staged collection uses + local two-round repeatability to decide immediately; its full-hand spatial + fit remains a separate mandatory gate after every training task is frozen. + """ + cycles = tuple(cycles) + chosen = select_task_training(profile, task_key, cycles) + task = next(t for t in profile.motion.tasks if t.key == task_key) + taskwise = profile.quality.training_policy == TASKWISE_STAGED + if taskwise: + # A task decision is deliberately local and therefore remains stable + # when later fingers are acquired. Full-hand zero geometry is checked + # by the final training-only fit before any artifact can be published. + rows = tuple(row for row in rows if row.get("task_name") == task_key) + if any(row["cycle"] not in training_cycles(chosen, row["task_name"]) for row in rows): + raise ValueError("training_assessment_received_nontraining_data") + sweep, steady = _by_joint(rows, "sweep"), _by_joint(rows, "steady") + reference_inputs = {name: {"baseline_command": ref.baseline_command, + "quaternion": ref.quaternion(profile.measurement.measurements[name].view).tolist()} + for name, ref in references.items() if name in sweep} + source_hash = hashlib.sha256(Path(source_urdf).read_bytes()).hexdigest() if source_urdf is not None else "" + source = {"rows": rows, "references": reference_inputs, "source_urdf": source_hash} + failures, metrics = [], {} + fitted_model = None + geometry = {"status": "deferred", "reason": "spatial_dependencies_not_complete"} + try: + if source_urdf is None: + raise ValueError("training_source_urdf_missing") + model = UrdfKinematicModel(source_urdf) + local = fit_command_training(chosen, model, + {name: sweep[name] for name in task.joints}, {name: steady[name] for name in task.joints}, + {name: references[name] for name in task.joints}) + fitted_model = {"curves": {name: asdict(curve) for name, curve in local.coordinate_curves.items()}, + "mappings": {name: asdict(mapping) for name, mapping in local.mappings.items()}} + failures, metrics = _curve_repeatability(chosen, task, local, steady, cycles) + required = set() if taskwise else set(profile.zero.axis_joints) + ready = bool(required) and required <= sweep.keys() & steady.keys() & references.keys() + if ready: + from .session import compile_spatial_profile, build_axis_observations + from .spatial_solver.solve import fit_urdf_zero_training + motion = fit_command_training(chosen, model, {name: sweep[name] for name in required}, + {name: steady[name] for name in required}, {name: references[name] for name in required}) + zero_profile = compile_spatial_profile(chosen) + axes = build_axis_observations(chosen, model, steady, motion, zero_profile, include_holdout=False) + baselines = {**{name: value.cad_angle_rad for name, value in profile.zero.known_baseline_geometry.items()}, + **{name: 0. for name in profile.zero.cad_zero_assumptions}} + curves = {name: replace(curve, circle={**curve.circle, "known_cad_baseline_rad": baselines[name]}) + if name in baselines and name not in zero_profile.direct_zero_joints else curve + for name, curve in motion.coordinate_curves.items()} + from .motion_fit import channel_for_joint + zero = fit_urdf_zero_training(source_urdf=source_urdf, measurements=axes, + training_cycles=tuple(sorted({a.cycle for a in axes})), curves=curves, + motor_by_joint={name: channel_for_joint(profile, name) for name in curves}, + zero_profile=zero_profile, maximum_offset_rad=math.radians(20), + finger_maximum_offset_rad=math.radians(20), + maximum_confidence_half_width_rad=MAXIMUM_CONFIDENCE_HALF_WIDTH_RAD, + maximum_pose_axis_line_rms_m=.0015, allow_partial_training_cycles=True) + geometry = {"status": "checked", "zero_offsets_rad": dict(zero.offsets), + "zero_confidence_half_width_rad": {name: width if math.isfinite(width) else None + for name, width in zero.confidence_half_widths.items()}, + "independent_cycles_by_joint": {name: len(values) for name, values in zero.cycle_values.items()}} + failures.extend(zero.failures) + except (ValueError, KeyError, np.linalg.LinAlgError) as error: + failures.append(str(error)) + decision = ("add_training" if len(cycles) == 2 and (failures + or (geometry["status"] == "deferred" and not taskwise)) + else "fail" if failures else "freeze") + record = {"kind": "training_decision", "version": TRAINING_DECISION_VERSION, + "task_name": task_key, "assessed_cycles": list(cycles), "decision": decision, + "failures": failures, "metrics": metrics, "geometry": geometry, + "frozen_training_sha256": (evidence_digest({"local_model": fitted_model, "geometry": geometry}) + if decision == "freeze" else None), + "source_sha256": evidence_digest(source), "source_count": len(rows), + "input_plan_sha256": CapturePlan.from_profile(profile).sha256} + return {**record, "decision_sha256": evidence_digest(record)} diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/fitting/trajectory_geometry.py b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/trajectory_geometry.py new file mode 100644 index 0000000..a02bbca --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/fitting/trajectory_geometry.py @@ -0,0 +1,356 @@ +"""Shared point-trajectory and legacy byte-domain numerical primitives.""" +from __future__ import annotations +import math +from typing import Any, Mapping, Sequence +import numpy as np +from scipy.optimize import least_squares +from ..domain.task import DIRECTION_DECREASING, DIRECTION_INCREASING, DIRECTIONS +from .curve import isotonic_nonincreasing + +def _vector3(value: Sequence[float], *, name: str) -> np.ndarray: + vector = np.asarray(value, dtype=float) + if vector.shape != (3,) or not np.all(np.isfinite(vector)): + raise ValueError(f"{name} must contain three finite values") + return vector + + +def _plane_basis(axis: Sequence[float]) -> tuple[np.ndarray, np.ndarray]: + normal = _vector3(axis, name="axis") + normal /= np.linalg.norm(normal) + candidates = np.eye(3) + seed = candidates[int(np.argmin(np.abs(candidates @ normal)))] + first = np.cross(normal, seed) + first /= np.linalg.norm(first) + second = np.cross(normal, first) + second /= np.linalg.norm(second) + return first, second + + +def _fit_plane_axis(point_sets: Sequence[np.ndarray]) -> tuple[np.ndarray, float]: + centred: list[np.ndarray] = [] + for points in point_sets: + array = np.asarray(points, dtype=float) + if array.ndim != 2 or array.shape[1] != 3 or len(array) < 3: + raise ValueError("each trajectory must contain at least three 3-D points") + # The arithmetic centroid of points in a plane remains in that plane + # and transforms correctly under a camera rotation. A component-wise + # median generally does neither. + centred.append(array - np.mean(array, axis=0)) + matrix = np.concatenate(centred, axis=0) + _, _, vh = np.linalg.svd(matrix, full_matrices=False) + axis = vh[-1] + axis /= np.linalg.norm(axis) + residuals = matrix @ axis + plane_rms = float(np.sqrt(np.mean(np.square(residuals)))) + return axis, plane_rms + + +def _fit_circle_with_axis( + points_xyz: Sequence[Sequence[float]], + axis_xyz: Sequence[float], +) -> dict[str, Any]: + points = np.asarray(points_xyz, dtype=float) + if ( + points.ndim != 2 + or points.shape[1] != 3 + or len(points) < 6 + or not np.all(np.isfinite(points)) + ): + raise ValueError("a circle requires at least six finite 3-D points") + axis = _vector3(axis_xyz, name="circle axis") + axis /= np.linalg.norm(axis) + basis_x, basis_y = _plane_basis(axis) + origin = np.mean(points, axis=0) + local = points - origin + xy = np.column_stack((local @ basis_x, local @ basis_y)) + + design = np.column_stack((2.0 * xy[:, 0], 2.0 * xy[:, 1], np.ones(len(xy)))) + target = np.sum(np.square(xy), axis=1) + initial_x, initial_y, constant = np.linalg.lstsq( + design, target, rcond=None + )[0] + initial_radius = math.sqrt( + max( + float(constant + initial_x * initial_x + initial_y * initial_y), + np.finfo(float).eps, + ) + ) + + def residual(parameters: np.ndarray) -> np.ndarray: + centre = parameters[:2] + radius = float(parameters[2]) + return np.linalg.norm(xy - centre, axis=1) - radius + + fitted = least_squares( + residual, + np.asarray([initial_x, initial_y, initial_radius], dtype=float), + loss="soft_l1", + f_scale=0.0005, + max_nfev=2000, + ) + centre_xy = fitted.x[:2] + radius = abs(float(fitted.x[2])) + radial_residuals = residual( + np.asarray([centre_xy[0], centre_xy[1], radius], dtype=float) + ) + centre_xyz = origin + centre_xy[0] * basis_x + centre_xy[1] * basis_y + plane_offsets = (points - centre_xyz) @ axis + centre_xyz += float(np.median(plane_offsets)) * axis + plane_residuals = (points - centre_xyz) @ axis + return { + "axis_xyz": [float(value) for value in axis], + "center_xyz_m": [float(value) for value in centre_xyz], + "radius_m": radius, + "radial_rms_m": float( + np.sqrt(np.mean(np.square(radial_residuals))) + ), + "plane_rms_m": float( + np.sqrt(np.mean(np.square(plane_residuals))) + ), + } + + +def _project_radial( + point_xyz: Sequence[float], + circle: Mapping[str, Any], +) -> np.ndarray: + point = _vector3(point_xyz, name="trajectory point") + centre = _vector3(circle["center_xyz_m"], name="circle centre") + axis = _vector3(circle["axis_xyz"], name="circle axis") + axis /= np.linalg.norm(axis) + radial = point - centre + radial -= float(radial @ axis) * axis + if float(np.linalg.norm(radial)) < 1.0e-9: + raise ValueError("trajectory point lies on the fitted rotation axis") + return radial + + +def _signed_angle( + reference_radial_xyz: Sequence[float], + observed_radial_xyz: Sequence[float], + axis_xyz: Sequence[float], +) -> float: + reference = _vector3(reference_radial_xyz, name="reference radial") + observed = _vector3(observed_radial_xyz, name="observed radial") + axis = _vector3(axis_xyz, name="angle axis") + axis /= np.linalg.norm(axis) + reference -= float(reference @ axis) * axis + observed -= float(observed @ axis) * axis + reference /= np.linalg.norm(reference) + observed /= np.linalg.norm(observed) + return math.atan2( + float(axis @ np.cross(reference, observed)), + float(np.clip(reference @ observed, -1.0, 1.0)), + ) + + +def _reference_radial( + records: Sequence[Mapping[str, Any]], + points: Sequence[np.ndarray], + circle: Mapping[str, Any], +) -> np.ndarray: + references = [ + _project_radial(point, circle) + for record, point in zip(records, points) + if int(record.get("command_u8", -1)) == 255 + ] + if not references: + raise ValueError("trajectory is missing command-255 reference points") + radial = np.median(np.asarray(references, dtype=float), axis=0) + axis = _vector3(circle["axis_xyz"], name="circle axis") + axis /= np.linalg.norm(axis) + radial -= float(radial @ axis) * axis + if float(np.linalg.norm(radial)) < 1.0e-9: + raise ValueError("command-255 reference is degenerate") + return radial + + +def _angle_for_circle( + point_xyz: Sequence[float], + circle: Mapping[str, Any], +) -> float: + return _signed_angle( + circle["reference_radial_xyz_m"], + _project_radial(point_xyz, circle), + circle["axis_xyz"], + ) + + +def _low_command_median( + records: Sequence[Mapping[str, Any]], + values: Sequence[float], +) -> float: + selected = [ + float(value) + for record, value in zip(records, values) + if int(record.get("command_u8", 255)) <= 16 + ] + if not selected: + selected = [ + float(value) + for _, value in sorted( + zip(records, values), + key=lambda item: int(item[0].get("command_u8", 255)), + )[: max(3, len(records) // 20)] + ] + return float(np.median(selected)) + + +def _orient_circle_positive( + circle: dict[str, Any], + records: Sequence[Mapping[str, Any]], + points: Sequence[np.ndarray], +) -> dict[str, Any]: + reference = _reference_radial(records, points, circle) + circle["reference_radial_xyz_m"] = [ + float(value) for value in reference + ] + values = [_angle_for_circle(point, circle) for point in points] + if _low_command_median(records, values) < 0.0: + axis = -_vector3(circle["axis_xyz"], name="circle axis") + circle["axis_xyz"] = [float(value) for value in axis] + values = [_angle_for_circle(point, circle) for point in points] + circle["observed_arc_rad"] = float(max(values) - min(values)) + return circle + + +def _fit_joint_curve( + records: Sequence[Mapping[str, Any]], + values: Sequence[float], + *, + endpoint_reference: Mapping[str, Sequence[float]] | None = None, + preserve_direction_offset: bool = False, + require_observed_domain_endpoints: bool = True, +) -> tuple[dict[str, Any], float, float]: + by_direction: dict[str, list[list[float]]] = { + direction: [[] for _ in range(256)] for direction in DIRECTIONS + } + for record, value in zip(records, values): + direction = str(record["direction"]) + command = int(record["command_u8"]) + by_direction[direction][command].append(float(value)) + + fitted: dict[str, list[float]] = {} + maximum_correction = 0.0 + for direction in DIRECTIONS: + commands = np.asarray( + [ + command + for command, samples in enumerate(by_direction[direction]) + if samples + ], + dtype=int, + ) + if commands.size < 3: + raise ValueError( + f"{direction} centre trajectory requires at least 3 commands" + ) + if require_observed_domain_endpoints and ( + int(commands[0]) != 0 or int(commands[-1]) != 255 + ): + raise ValueError( + f"{direction} centre trajectory requires commands 0 and 255" + ) + raw = np.asarray( + [ + float(np.median(by_direction[direction][command])) + for command in commands + ], + dtype=float, + ) + if not preserve_direction_offset: + raw -= raw[-1] + projected_samples = isotonic_nonincreasing(raw) + if not preserve_direction_offset: + projected_samples -= projected_samples[-1] + maximum_correction = max( + maximum_correction, + float(np.max(np.abs(projected_samples - raw))), + ) + curve = np.interp( + np.arange(256, dtype=float), + commands.astype(float), + projected_samples, + ) + if not preserve_direction_offset: + curve -= curve[255] + if endpoint_reference is not None: + curve = _regularize_coupled_zero_tail( + curve, + endpoint_reference[f"{direction}_rad"], + ) + fitted[direction] = [ + round(float(value), 8) for value in curve + ] + + decreasing = np.asarray(fitted[DIRECTION_DECREASING], dtype=float) + increasing = np.asarray(fitted[DIRECTION_INCREASING], dtype=float) + hysteresis = float(np.max(np.abs(decreasing - increasing))) + combined = 0.5 * (decreasing + increasing) + if not preserve_direction_offset: + combined -= combined[255] + return ( + { + "angle_rad": [round(float(value), 8) for value in combined], + "decreasing_rad": fitted[DIRECTION_DECREASING], + "increasing_rad": fitted[DIRECTION_INCREASING], + }, + maximum_correction, + hysteresis, + ) + + +def _regularize_coupled_zero_tail( + values: Sequence[float], + reference_values: Sequence[float], + *, + maximum_tail_commands: int = 16, + zero_tolerance_rad: float = 1.0e-10, +) -> np.ndarray: + """Replace a short noise-created zero tail using a coupled joint shape. + + The passive IP and active MCP share motor 15. Close to command 255 the + IP centre trajectory is small enough that measurement noise can become + negative. Isotonic projection correctly prevents a negative angle, but + otherwise turns all remaining commands into an artificial zero plateau. + Continue the last resolved IP/MCP ratio over a short tail instead. This + changes neither the resolved part of the curve nor the exact 255 zero. + """ + curve = np.asarray(values, dtype=float).copy() + reference = np.asarray(reference_values, dtype=float) + if curve.shape != (256,) or reference.shape != (256,): + raise ValueError("endpoint curves must each contain 256 values") + if not np.all(np.isfinite(curve)) or not np.all(np.isfinite(reference)): + raise ValueError("endpoint curves must be finite") + maximum_tail = int(maximum_tail_commands) + tolerance = float(zero_tolerance_rad) + if maximum_tail < 2 or tolerance < 0.0: + raise ValueError("invalid endpoint regularization settings") + + anchor = 254 + while anchor >= 0 and abs(float(curve[anchor])) <= tolerance: + anchor -= 1 + tail_commands = 255 - anchor + if ( + anchor < 0 + or tail_commands < 2 + or tail_commands > maximum_tail + or curve[anchor] <= tolerance + or reference[anchor] <= tolerance + or abs(float(curve[255])) > tolerance + or abs(float(reference[255])) > tolerance + ): + curve[255] = 0.0 + return curve + + ratio = float(curve[anchor] / reference[anchor]) + continuation = np.maximum( + 0.0, + ratio * reference[anchor + 1 :], + ) + continuation = np.minimum.accumulate(continuation) + continuation = np.minimum(continuation, float(curve[anchor])) + continuation[-1] = 0.0 + curve[anchor + 1 :] = continuation + return curve + diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/__init__.py new file mode 100644 index 0000000..2bc55d4 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/__init__.py @@ -0,0 +1,41 @@ +"""Pure geometry used by online and offline calibration.""" + +from .extrinsics import ( + CameraCalibrationIdentity, + CameraExtrinsics, + camera_info_fingerprint, + load_camera_extrinsics, + matrix_payload, + transform_matrix, + validate_camera_extrinsics_payload, +) +from .rotation import ( + delta_rotation_vector, + fit_rotation_axis, + image_plane_tag_quaternion_xyzw, + normalize_quaternion_xyzw, + relative_quaternion_xyzw, + robust_rotation_summary, + rotation_inlier_fraction, + rotation_rms_rad, + rotation_spread_rad, +) + +__all__ = [ + "CameraCalibrationIdentity", + "CameraExtrinsics", + "camera_info_fingerprint", + "delta_rotation_vector", + "fit_rotation_axis", + "image_plane_tag_quaternion_xyzw", + "load_camera_extrinsics", + "matrix_payload", + "normalize_quaternion_xyzw", + "relative_quaternion_xyzw", + "robust_rotation_summary", + "rotation_inlier_fraction", + "rotation_rms_rad", + "rotation_spread_rad", + "transform_matrix", + "validate_camera_extrinsics_payload", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/camera.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/camera.py new file mode 100644 index 0000000..ea84795 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/camera.py @@ -0,0 +1,18 @@ +"""Projection contract for detections on image_proc's rectified images.""" +import numpy as np + + +def rectified_camera_matrix(projection): + """CameraInfo.P, not raw K, is the intrinsic matrix of image_rect. + + Never silently fall back to K: that fits a different pixel coordinate + system and can produce smooth but biased tag poses. + """ + values = np.asarray(projection, dtype=float) + if values.size != 12: + raise ValueError('rectified detections require a 3x4 CameraInfo.P') + matrix = values.reshape(3, 4)[:, :3].copy() + if (not np.all(np.isfinite(matrix)) or matrix[0, 0] <= 0 + or matrix[1, 1] <= 0 or not np.allclose(matrix[2], [0, 0, 1])): + raise ValueError('invalid rectified CameraInfo.P') + return matrix diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/candidate_selection.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/candidate_selection.py new file mode 100644 index 0000000..7eb690f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/candidate_selection.py @@ -0,0 +1,277 @@ +"""Articulated Tag candidate resolution using training data only. + +Re-selects actual corner-derived IPPE solutions; does not manufacture rigid +poses, substitute SDK angles, or relax the spatial solver's acceptance gates. +""" +from itertools import product +import math +from collections.abc import Mapping + +import numpy as np +from scipy.spatial.transform import Rotation as R + +from .pnp import solve_square_tag_ippe +from .tag_pose.ippe import fixed_pose_reprojection_error +from .tag_pose.branch_confirmation import BranchConfirmation +from .tag_pose.parameters import DEFAULT_POSE_TRACKING_PARAMETERS, FROZEN_BRANCH_POLICY_VERSIONS +from .tag_pose.types import SquareTagPose +from .tag_pose.image_reference import IMAGE_REFERENCE_SOURCE, reference_from_evidence +from .image_motion_replay import IMAGE_POSE_SOURCE, has_image_model, replay_image_models, validate_image_sample + +POLICY = 'training_frozen_articulated_candidates_v1' +MATRIX_SOURCE = 'CameraInfo.P[:3,:3]' + + +def _rotation(pose): + return R.from_quat(pose['quaternion_xyzw']) + + +def _relative(parent, child): + rp = _rotation(parent) + return ((rp.inv()*_rotation(child)).as_quat(), + rp.inv().apply(np.asarray(child['translation_xyz_m'])-parent['translation_xyz_m'])) + + +def _trajectory_score(parent, child): + pairs = [_relative(a, b) for a, b in zip(parent, child)] + rotations = R.from_quat([q for q, _ in pairs]) + points = np.asarray([p for _, p in pairs]) + vectors = (rotations*rotations[0].inv()).as_rotvec() + axis = np.linalg.svd(vectors, full_matrices=False)[2][0] + projected = R.from_rotvec((vectors@axis)[:, None]*axis) + off_axis = float(np.sqrt(np.mean((projected.inv()*rotations*rotations[0].inv()).magnitude()**2))) + # Free six-parameter fixed-pivot fit, no CAD zero or mounting-angle prior. + a = np.concatenate((np.tile(np.eye(3), (len(points), 1, 1)), rotations.as_matrix()), axis=2).reshape(-1, 6) + predicted = (a@np.linalg.lstsq(a, points.ravel(), rcond=None)[0]).reshape(-1, 3) + rms = float(np.sqrt(np.mean(np.sum((points-predicted)**2, axis=1)))) + return {'pivot_rms_m': rms, 'off_axis_rms_rad': off_axis, + 'score': rms/.0015 + off_axis/math.radians(1)} + + +def _recorded_pose(payload): + if not isinstance(payload, Mapping): + raise ValueError('frozen_branch_evidence_missing:selected_pose') + quaternion = tuple(payload.get('quaternion_xyzw', ())) + translation = tuple(payload.get('translation_xyz_m', ())) + if (len(quaternion) != 4 or len(translation) != 3 + or not np.all(np.isfinite(quaternion + translation)) + or not np.isclose(np.linalg.norm(quaternion), 1, atol=1e-5)): + raise ValueError('frozen_branch_evidence_invalid:selected_pose') + return SquareTagPose(quaternion, translation, 0.) + + +def _check_frozen_paths(rows, evidence, selected_paths, role_pairs, fixed_roles): + """A geometry preference cannot replace any already-frozen image branch. + + Revisions identify a role within its capture, not a physical installation + across sessions. JointResume verifies the latter before importing rows. + Compare each path pose with that image's original confirmed pose instead + of assuming numerically equal revisions authorize cross-session reuse. + """ + equivalence = BranchConfirmation(DEFAULT_POSE_TRACKING_PARAMETERS) + for row in rows: + stamp, view = int(row['image_stamp_ns']), row.get('view') + frame = evidence[stamp] + identity = f"joint={row['joint']}:view={view}:image={stamp}:cycle={row['cycle']}" + if (not view or frame.get('view') != view or any( + frame.get(key) != row.get(key) for key in ('cycle', 'direction', 'attempt'))): + raise ValueError(f'frozen_branch_frame_identity_changed:{identity}') + observed = row.get('pnp_observation_evidence', {}) + if not isinstance(observed, Mapping): + raise ValueError(f'frozen_branch_evidence_missing:{identity}') + for field, role in zip(('parent', 'child'), role_pairs[row['joint']]): + item = observed.get(field, {}) + if not isinstance(item, Mapping) or item.get('tag_role') != role: + raise ValueError(f'frozen_branch_evidence_missing:{identity}:role={role}') + source = item.get('pose_source') + fixed_source = source in {'cached_fixed_reference', 'verified_fixed_reference', IMAGE_REFERENCE_SOURCE} + if (fixed_source + != bool(frame['roles'][role].get('locked_reference'))): + raise ValueError(f'frozen_branch_pose_source_changed:{identity}:role={role}') + if fixed_source and role not in fixed_roles: + raise ValueError(f'frozen_branch_fixed_role_invalid:{identity}:role={role}') + if source == 'cached_fixed_reference' and role in fixed_roles: + revision = item.get('reference_branch_revision') + else: + diagnostics = item.get('candidate_diagnostics', {}) + if (source not in {'current_image', 'verified_fixed_reference', IMAGE_POSE_SOURCE, IMAGE_REFERENCE_SOURCE} or not isinstance(diagnostics, Mapping) + or diagnostics.get('observation_stamp_ns') != stamp + or diagnostics.get('branch_status') != 'tracking' + or diagnostics.get('branch_frozen') is not True): + raise ValueError(f'frozen_branch_evidence_unconfirmed:{identity}:role={role}') + revision = diagnostics.get('branch_revision') + if source == 'verified_fixed_reference' and ( + diagnostics.get('fixed_reference_verified') is not True + or item.get('reference_branch_revision') != revision): + raise ValueError(f'frozen_branch_fixed_reference_unverified:{identity}:role={role}') + if isinstance(revision, bool) or not isinstance(revision, int) or revision < 1: + raise ValueError(f'frozen_branch_revision_invalid:{identity}:role={role}') + original = _recorded_pose(item.get('selected_pose')) + if source == 'verified_fixed_reference': + _check_fixed_projection(original, item, frame, role, identity) + if source == IMAGE_REFERENCE_SOURCE: + data = frame['roles'][role] + reference = reference_from_evidence(item, stamp_ns=stamp, camera_matrix=frame['camera_matrix']) + recorded_ref = reference_from_evidence(data, stamp_ns=stamp, camera_matrix=frame['camera_matrix']) + if reference != recorded_ref or not np.array_equal(item.get('corners_xy'), data.get('corners_xy')): + raise ValueError(f'frozen_branch_image_reference_changed:{identity}:role={role}') + recorded = _recorded_pose(frame['roles'][role].get('selected')) + if not equivalence.equivalent(original, recorded): + raise ValueError(f'frozen_branch_recorded_pose_changed:{identity}:role={role}') + proposed = _recorded_pose(selected_paths[stamp][role]) + if not equivalence.equivalent(original, proposed): + angle, translation = equivalence.distance(original, proposed) + raise ValueError(f'frozen_branch_reselection_forbidden:{identity}:role={role}:' + f'rotation_deg={math.degrees(angle):.6f}:translation_mm={translation*1000:.6f}') + + +def _check_fixed_projection(pose, item, frame, role, identity): + """A fixed-pose marker cannot bypass current-image geometric evidence.""" + data = frame['roles'][role] + try: + if not np.array_equal(np.asarray(item['corners_xy']), np.asarray(data['corners_xy'])): + raise ValueError('corners changed') + error = fixed_pose_reprojection_error(pose, data['corners_xy'], + tag_size_m=data.get('tag_size_m', frame['tag_size_m']), camera_matrix=frame['camera_matrix']) + limit = float(data.get('maximum_reprojection_error_px', 1.5)) + if not math.isfinite(limit) or limit <= 0 or not math.isfinite(error) or error > limit: + raise ValueError('fixed pose no longer explains this image') + except (KeyError, TypeError, ValueError) as exc: + raise ValueError(f'frozen_branch_fixed_projection_invalid:{identity}:role={role}') from exc + + +def resolve_chain_observations(records, *, task_key, role_pairs, + projection_override=None, solve_pose=solve_square_tag_ippe, fixed_roles=(), + require_frozen_branches=False, training_cycles=(0, 1, 2), holdout_cycle=3): + """Return copied observations and auditable candidate-selection evidence. + + Older captures did not save P. They remain on the legacy path; K is never + guessed to be P. An explicit override is for isolated offline diagnosis + and must be reported as such, not advertised as a verified whole session. + A current capture automatically preserves its frozen branches; production + callers enforce this even when a journal's policy header was removed. + """ + rows = [dict(r) for r in records] + preserve_frozen = require_frozen_branches or any( + row.get('kind') == 'session_start' + and row.get('pose_tracking_policy_version') in FROZEN_BRANCH_POLICY_VERSIONS for row in rows) + roles = tuple(dict.fromkeys(role for pair in role_pairs.values() for role in pair)) + if not role_pairs or len(roles) > 8 or any(len(pair) != 2 or pair[0] == pair[1] for pair in role_pairs.values()): + raise ValueError('candidate selection requires a bounded articulated observation graph') + joint_rows = [r for r in rows if r.get('joint') in role_pairs + and r.get('task_name') == task_key and r.get('sample_phase') != 'joint_zero'] + evidence = {int(r['image_stamp_ns']): r for r in rows + if ('roles' in r or str(r.get('kind', '')).endswith('pnp_candidate_frame')) + and r.get('task_name') == task_key} + report = {'policy': POLICY, 'training_cycles': list(training_cycles), 'holdout_cycle': holdout_cycle, + 'projection_override_used': projection_override is not None, + 'is_accuracy_certificate': False} + if not evidence: + if preserve_frozen: + raise ValueError(f'frozen_branch_evidence_missing:task={task_key}:candidate_frames') + return rows, {**report, 'status': 'legacy_no_corners'} + if projection_override is None and any( + r.get('camera_matrix_source') != MATRIX_SOURCE for r in evidence.values()): + return rows, {**report, 'status': 'legacy_projection_unverified', + 'reason': 'Recorded matrix may be raw K; no silent K-to-P substitution.'} + # Use only the same accepted attempt as the downstream fitter. + latest = {} + for r in joint_rows: + key = (int(r['cycle']), r['direction']) + latest[key] = max(latest.get(key, 0), int(r.get('attempt', 1))) + chosen_rows = [r for r in joint_rows if int(r.get('attempt', 1)) == latest[(int(r['cycle']), r['direction'])]] + stamps = sorted({int(r['image_stamp_ns']) for r in chosen_rows}) + if not stamps or any(s not in evidence for s in stamps): + raise ValueError('corner replay lacks evidence for accepted observations') + if any(int(evidence[s]['cycle']) not in (*training_cycles, holdout_cycle) for s in stamps): + raise ValueError('corner replay observation outside capture plan') + training = np.asarray([int(evidence[s]['cycle']) in training_cycles for s in stamps]) + if sum(training) < 40 or not any(int(evidence[s]['cycle']) == holdout_cycle for s in stamps): + raise ValueError('corner replay requires training and independent holdout') + if np.flatnonzero(training)[-1] > np.flatnonzero(~training)[0]: + raise ValueError('holdout must follow the complete training trajectory') + if any(has_image_model(item) for stamp in stamps for item in evidence[stamp]['roles'].values()): + if projection_override is not None: + raise ValueError('frozen image model cannot use a different camera projection') + lookup, verified = {}, {} + for stamp in stamps: + verified[stamp] = replay_image_models(evidence[stamp]) + if not verified[stamp]: + raise ValueError('image_motion_provenance_mixed_pose_policies') + lookup[stamp] = {role: evidence[stamp]['roles'][role]['selected'] for role in roles} + for row in chosen_rows: + stamp = int(row['image_stamp_ns']) + validate_image_sample(row, evidence[stamp], verified[stamp]) + _check_frozen_paths(chosen_rows, evidence, lookup, role_pairs, fixed_roles) + return rows, {**report, 'policy': 'frozen_image_motion_replay_v1', 'status': 'resolved', + 'frozen_branches_preserved': True, 'geometry_refitted': False, + 'training_frames': int(sum(training)), 'holdout_frames': int(sum(~training)), + 'changed_joint_rows': 0} + paths = {role: [[], []] for role in roles} + for stamp in stamps: + frame = evidence[stamp] + matrix = np.asarray(frame['camera_matrix'] if projection_override is None else projection_override) + for role in roles: + data = frame['roles'][role] + if data.get('locked_reference'): + if role not in fixed_roles or not data.get('selected'): + raise ValueError('cached fixed reference has no frozen pose') + cs = [dict(data['selected'], + reprojection_error_px=float(data['selected'].get('reprojection_error_px', 0.0)))] + else: + poses = solve_pose(data['corners_xy'], tag_size_m=data.get('tag_size_m', frame['tag_size_m']), camera_matrix=matrix) + limit = float(data.get('maximum_reprojection_error_px', 1.5)) + poses = [p for p in poses if p.reprojection_error_px <= limit] + if not poses: + raise ValueError(f'corner replay has no eligible pose:{stamp}:{role}') + cs = [dict(quaternion_xyzw=list(p.quaternion_xyzw), translation_xyz_m=list(p.translation_xyz_m), + reprojection_error_px=p.reprojection_error_px) for p in poses[:2]] + if len(cs) == 1: + cs.append(cs[0]) + if paths[role][0]: + previous = [_rotation(paths[role][i][-1]) for i in range(2)] + def cost(order): + return sum((previous[i].inv()*_rotation(cs[order[i]])).magnitude() for i in range(2)) + order = min(((0, 1), (1, 0)), key=cost) + cs = [cs[i] for i in order] + for i, pose in enumerate(cs): + paths[role][i].append(pose) + scores = [] + for branches in product(range(2), repeat=len(roles)): + train = {role: [p for p, keep in zip(paths[role][branch], training) if keep] + for role, branch in zip(roles, branches)} + metrics = [_trajectory_score(train[parent], train[child]) for parent, child in role_pairs.values()] + image_penalty = float(np.mean([p['reprojection_error_px'] for ps in train.values() for p in ps])) + scores.append({'branches': list(branches), 'score': sum(m['score'] for m in metrics)+.5*image_penalty, + 'training_pairs': metrics, 'mean_reprojection_px': image_penalty}) + selected = min(scores, key=lambda s: s['score']) + lookup = {stamp: {role: paths[role][branch][i] for role, branch in zip(roles, selected['branches'])} + for i, stamp in enumerate(stamps)} + if preserve_frozen: + _check_frozen_paths(chosen_rows, evidence, lookup, role_pairs, fixed_roles) + report['frozen_branches_preserved'] = True + changed = 0 + for row in chosen_rows: + stamp = int(row['image_stamp_ns']) + parent_role, child_role = role_pairs[row['joint']] + parent, child = lookup[stamp][parent_role], lookup[stamp][child_role] + # Preserve the actual camera->common transform, not an assumed identity. + old_camera_parent = evidence[stamp]['roles'][parent_role]['selected'] + if old_camera_parent is None: + raise ValueError('Accepted joint row has no original selected parent pose') + rc = _rotation(row['parent_pose_common'])*_rotation(old_camera_parent).inv() + tc = np.asarray(row['parent_pose_common']['translation_xyz_m'])-rc.apply(old_camera_parent['translation_xyz_m']) + quaternion, translation = _relative(parent, child) + changed += int((_rotation({'quaternion_xyzw': row['relative_quaternion_xyzw']}).inv()*R.from_quat(quaternion)).magnitude() > 1e-7) + row['relative_quaternion_xyzw'] = quaternion.tolist() + row['relative_translation_xyz_m'] = translation.tolist() + for field, pose in (('parent_pose_common', parent), ('child_pose_common', child)): + row[field] = {'quaternion_xyzw': (rc*_rotation(pose)).as_quat().tolist(), + 'translation_xyz_m': (rc.apply(pose['translation_xyz_m'])+tc).tolist()} + row['pnp_reprojection_error_px'] = max(parent['reprojection_error_px'], child['reprojection_error_px']) + row['pose_selection_policy'] = POLICY + if projection_override is not None: + row['projection_reprocessing_scope'] = 'partial_external_projection' + return rows, {**report, 'status': 'resolved', 'selected_branches': selected['branches'], + 'hypotheses': scores, 'training_frames': int(sum(training)), + 'holdout_frames': int(sum(~training)), 'changed_joint_rows': changed} diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/extrinsics.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/extrinsics.py new file mode 100644 index 0000000..6825976 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/extrinsics.py @@ -0,0 +1,212 @@ +"""Camera-extrinsic data model shared by calibration and runtime nodes.""" + +from __future__ import annotations + +import hashlib +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np +import yaml +from scipy.spatial.transform import Rotation + + +def camera_info_fingerprint( + *, + width: int, + height: int, + camera_matrix: Sequence[Sequence[float]] | Sequence[float], + distortion: Sequence[float] = (), + rectification: Sequence[float] = (), + projection: Sequence[float] = (), +) -> str: + """Return a stable fingerprint for rectified image geometry.""" + matrix = np.asarray(camera_matrix, dtype=float).reshape(3, 3) + payload = { + "width": int(width), + "height": int(height), + "camera_matrix": [round(float(value), 12) for value in matrix.flat], + "distortion": [round(float(value), 12) for value in distortion], + "rectification": [round(float(value), 12) for value in rectification], + "projection": [round(float(value), 12) for value in projection], + } + encoded = json.dumps( + payload, sort_keys=True, separators=(",", ":") + ).encode("utf-8") + return hashlib.sha256(encoded).hexdigest() + + +def transform_matrix( + translation_xyz_m: Sequence[float], + quaternion_xyzw: Sequence[float], +) -> np.ndarray: + translation = np.asarray(translation_xyz_m, dtype=float) + quaternion = np.asarray(quaternion_xyzw, dtype=float) + if translation.shape != (3,) or not np.all(np.isfinite(translation)): + raise ValueError("translation_xyz_m must contain three finite values") + if quaternion.shape != (4,) or not np.all(np.isfinite(quaternion)): + raise ValueError("quaternion_xyzw must contain four finite values") + norm = float(np.linalg.norm(quaternion)) + if norm < 1.0e-12: + raise ValueError("quaternion_xyzw has zero norm") + result = np.eye(4, dtype=float) + result[:3, :3] = Rotation.from_quat(quaternion / norm).as_matrix() + result[:3, 3] = translation + return result + + +def matrix_payload(matrix: Sequence[Sequence[float]]) -> dict[str, list[float]]: + value = np.asarray(matrix, dtype=float) + if value.shape != (4, 4) or not np.all(np.isfinite(value)): + raise ValueError("transform must be a finite 4x4 matrix") + return { + "translation_xyz_m": [float(item) for item in value[:3, 3]], + "quaternion_xyzw": [ + float(item) for item in Rotation.from_matrix(value[:3, :3]).as_quat() + ], + } + + +@dataclass(frozen=True) +class CameraCalibrationIdentity: + serial_number: str + width: int + height: int + intrinsics_sha256: str + + +@dataclass(frozen=True) +class CameraExtrinsics: + """Transforms every declared camera into one Profile-selected reference.""" + + cameras: Mapping[str, CameraCalibrationIdentity] + reference_view: str + reference_from_view: Mapping[str, np.ndarray] + quality: Mapping[str, float] + + def transform(self, view: str) -> np.ndarray: + if view not in self.reference_from_view: + raise KeyError(f"extrinsics do not contain view {view}") + return np.asarray(self.reference_from_view[view], dtype=float).copy() + + +def validate_camera_extrinsics_payload( + payload: Mapping[str, Any], + *, + required_views: Sequence[str], + reference_view: str, + quality_limits: Mapping[str, float] | None = None, + minimum_capture_counts: Mapping[str, int] | None = None, +) -> None: + if int(payload.get("schema_version", -1)) != 1: + raise ValueError("camera extrinsics schema_version must be 1") + reference = str(reference_view) + if payload.get("reference_view") != reference: + raise ValueError( + "camera extrinsics reference_view differs from the Profile" + ) + cameras = payload.get("cameras") + transforms = payload.get(f"{reference}_from_view") + quality = payload.get("quality") + views = tuple(str(view) for view in required_views) + if not views or len(set(views)) != len(views): + raise ValueError("required extrinsic views must be non-empty and unique") + if reference not in views: + raise ValueError("extrinsic reference view is not required") + if not isinstance(cameras, Mapping) or set(cameras) != set(views): + raise ValueError("camera extrinsics differ from the Profile views") + if not isinstance(transforms, Mapping) or set(transforms) != set(views): + raise ValueError("camera transforms differ from the Profile views") + if not isinstance(quality, Mapping) or not bool(quality.get("passed")): + raise ValueError("camera extrinsics quality is not passed") + for key, limit in dict(quality_limits or {}).items(): + value = float(quality.get(key, float("inf"))) + if not np.isfinite(value) or value > limit: + raise ValueError( + f"camera extrinsics {key}={value} exceeds {limit}" + ) + for key, minimum in dict(minimum_capture_counts or {}).items(): + if int(quality.get(key, 0)) < int(minimum): + raise ValueError( + f"camera extrinsics {key} must be at least {minimum}" + ) + for view in views: + identity = cameras[view] + if not isinstance(identity, Mapping): + raise ValueError(f"{view} camera identity must be an object") + if not str(identity.get("serial_number", "")): + raise ValueError(f"{view} camera serial_number is missing") + if int(identity.get("width", 0)) <= 0 or int(identity.get("height", 0)) <= 0: + raise ValueError(f"{view} camera image dimensions are invalid") + fingerprint = str(identity.get("intrinsics_sha256", "")) + if len(fingerprint) != 64: + raise ValueError(f"{view} camera intrinsics fingerprint is invalid") + transform = transforms[view] + if not isinstance(transform, Mapping): + raise ValueError(f"{view} transform must be an object") + matrix = transform_matrix( + transform.get("translation_xyz_m", ()), + transform.get("quaternion_xyzw", ()), + ) + if view == reference and not np.allclose( + matrix, np.eye(4), atol=1.0e-9 + ): + raise ValueError("reference-view transform must be identity") + serials = [str(cameras[view]["serial_number"]) for view in views] + if len(set(serials)) != len(views): + raise ValueError("camera extrinsics serial numbers must be unique") + + +def load_camera_extrinsics( + path: str | Path, + *, + required_views: Sequence[str], + reference_view: str, + quality_limits: Mapping[str, float] | None = None, + minimum_capture_counts: Mapping[str, int] | None = None, +) -> CameraExtrinsics: + source = Path(path).expanduser().resolve() + if not source.is_file(): + raise ValueError(f"camera extrinsics file does not exist: {source}") + with source.open("r", encoding="utf-8") as stream: + payload = yaml.safe_load(stream) + if not isinstance(payload, Mapping): + raise ValueError("camera extrinsics file must contain an object") + validate_camera_extrinsics_payload( + payload, + required_views=required_views, + reference_view=reference_view, + quality_limits=quality_limits, + minimum_capture_counts=minimum_capture_counts, + ) + views = tuple(str(view) for view in required_views) + transform_key = f"{reference_view}_from_view" + cameras = { + view: CameraCalibrationIdentity( + serial_number=str(payload["cameras"][view]["serial_number"]), + width=int(payload["cameras"][view]["width"]), + height=int(payload["cameras"][view]["height"]), + intrinsics_sha256=str( + payload["cameras"][view]["intrinsics_sha256"] + ), + ) + for view in views + } + transforms = { + view: transform_matrix( + payload[transform_key][view]["translation_xyz_m"], + payload[transform_key][view]["quaternion_xyzw"], + ) + for view in views + } + return CameraExtrinsics( + cameras=cameras, + reference_view=str(reference_view), + reference_from_view=transforms, + quality={ + str(key): float(value) if isinstance(value, (int, float)) else value + for key, value in payload["quality"].items() + }, + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/frozen_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/frozen_evidence.py new file mode 100644 index 0000000..6ae9c11 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/frozen_evidence.py @@ -0,0 +1,105 @@ +"""Share immutable, content-bound image models without copying them per frame. + +The JSON representation and its hash are unchanged. Per-image diagnostics stay +independent mutable dictionaries; only the already-frozen model is shared. +""" +from functools import cached_property, lru_cache +import hashlib +import json + + +class FrozenEvidence(dict): + @cached_property + def canonical_json(self): + return json.dumps(self, sort_keys=True, separators=(',', ':'), allow_nan=False) + + @cached_property + def sha256(self): + return hashlib.sha256(self.canonical_json.encode()).hexdigest() + + def _immutable(self, *args, **kwargs): + raise TypeError('frozen evidence cannot be changed') + + __setitem__ = __delitem__ = clear = pop = popitem = setdefault = update = __ior__ = _immutable + + def __deepcopy__(self, memo): + return self + + def __reduce__(self): + return (freeze_evidence, (dict(self),)) + + +def freeze_evidence(value): + if isinstance(value, dict): + return FrozenEvidence((key, freeze_evidence(item)) for key, item in value.items()) + if isinstance(value, (list, tuple)): + return tuple(freeze_evidence(item) for item in value) + return value + + +def canonical_evidence(value): + """Cache serialization only for recursively immutable evidence.""" + if isinstance(value, FrozenEvidence): + return value.canonical_json + return json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False) + + +def evidence_sha256(value): + if isinstance(value, FrozenEvidence): + return value.sha256 + return hashlib.sha256(canonical_evidence(value).encode()).hexdigest() + + +@lru_cache(maxsize=64) +def image_model_evidence(model): + """The model dataclasses contain immutable tuples and are value-hashable.""" + from .tag_pose.image_motion_model import image_model_payload + return freeze_evidence(image_model_payload(model)) + + +class EvidenceDecoder: + """Intern verified models while streaming old and new JSONL records.""" + def __init__(self, *, verify_hashes=True): + self.models = {} + self.references = {} + self.verify_hashes = verify_hashes + + def _intern(self, payload, identity, cache, error): + if not self.verify_hashes: + # Passed-task resume defers replay to finalization. Sharing must + # still preserve the exact content, even for conflicting digests. + previous = cache.get(identity) + if previous is not None and payload == previous[0]: + return previous[1] + frozen = freeze_evidence(payload) + if previous is None: + cache[identity] = (payload, frozen) + return frozen + digest = hashlib.sha256(json.dumps(payload, sort_keys=True, + separators=(',', ':'), allow_nan=False).encode()).hexdigest() + if identity != digest: + raise ValueError(error) + if identity not in cache: + cache[identity] = freeze_evidence(payload) + return cache[identity] + + def object_hook(self, row): + payload = row.get('frozen_image_model') + if payload is not None: + row['frozen_image_model'] = self._intern(payload, row.get('image_model_sha256'), + self.models, 'image_motion_provenance_model_hash_invalid') + reference = row.get('reference_frame') + if reference is not None: + row['reference_frame'] = self._intern(reference, row.get('reference_frame_sha256'), + self.references, 'image_reference_identity_changed') + return row + + def loads(self, line): + # Most evidence rows contain observations only. Avoid recursively + # invoking the model interning hook for every nested pose/candidate + # dictionary when neither interned object can be present. + frozen_key = b'"frozen_image_model"' if isinstance(line, bytes) else '"frozen_image_model"' + reference_key = b'"reference_frame"' if isinstance(line, bytes) else '"reference_frame"' + if frozen_key not in line and reference_key not in line: + return json.loads(line) + return json.loads(line, object_hook=self.object_hook) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/image_motion_replay.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/image_motion_replay.py new file mode 100644 index 0000000..a95d10e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/image_motion_replay.py @@ -0,0 +1,186 @@ +"""Read back image-constrained poses against their frozen model and raw corners. + +This never trains geometry or chooses a new trajectory. The image solver may +estimate only this image's joint angles, including on the independent holdout. +Raw IPPE candidates remain separate from the selected constrained poses. +""" + +from collections.abc import Mapping +from functools import lru_cache +import json + +import numpy as np +from scipy.spatial.transform import Rotation + +from .frozen_evidence import canonical_evidence, evidence_sha256 +from .tag_pose.motion_evidence import MotionEvidenceFrame, RoleCandidates +from .tag_pose.motion_image_types import ImageMotionFrame, ImageRoleObservation +from .tag_pose.types import SquareTagPose +from .tag_pose.image_reference import IMAGE_REFERENCE_SOURCE, reference_from_evidence + + +IMAGE_POSE_SOURCE = "image_constrained_current_image" + + +def image_model_sha256(payload): + return evidence_sha256(payload) + + +@lru_cache(maxsize=64) +def _read_image_model(encoded): + from .tag_pose.production_image_motion import image_motion_model_from_dict + + return image_motion_model_from_dict(json.loads(encoded)) + + +def frozen_image_model(item): + """Read a named, content-bound model; a marker alone grants no permission.""" + payload, identity = item.get("frozen_image_model"), item.get("image_model_sha256") + if not isinstance(payload, Mapping) or image_model_sha256(payload) != identity: + raise ValueError("image_motion_provenance_model_hash_invalid") + return _read_image_model(canonical_evidence(payload)) + + +def has_image_model(item): + return (item.get("pose_source") == IMAGE_POSE_SOURCE + or "frozen_image_model" in item or "image_model_sha256" in item) + + +def _pose(payload): + try: + q, t = tuple(payload["quaternion_xyzw"]), tuple(payload["translation_xyz_m"]) + error = float(payload["reprojection_error_px"]) + if (len(q) != 4 or len(t) != 3 or not np.all(np.isfinite((*q, *t, error))) + or not np.isclose(np.linalg.norm(q), 1., atol=1e-5) or error < 0): + raise ValueError("invalid pose") + return SquareTagPose(q, t, error) + except (KeyError, TypeError, ValueError) as exc: + raise ValueError("image_motion_provenance_pose_invalid") from exc + + +def _same_pose(actual, expected): + return (float((Rotation.from_quat(actual.quaternion_xyzw).inv() + * Rotation.from_quat(expected.quaternion_xyzw)).magnitude()) <= 1e-6 + and np.linalg.norm(np.subtract(actual.translation_xyz_m, expected.translation_xyz_m)) <= 1e-8 + and abs(actual.reprojection_error_px - expected.reprojection_error_px) <= 1e-6) + + +def replay_image_models(frame): + """Recompute every constrained role from the original frame, without fitting.""" + from .tag_pose.production_image_motion import select_image_motion_frame + + if (frame.get("camera_matrix_source") != "CameraInfo.P[:3,:3]" + or frame.get("input_is_rectified") is not True): + raise ValueError("image_motion_provenance_projection_unverified") + models, selected = {}, {} + for role, item in frame["roles"].items(): + if not has_image_model(item): + continue + if item.get("pose_source") != IMAGE_POSE_SOURCE: + raise ValueError("image_motion_provenance_pose_source_changed") + identity = item.get("image_model_sha256") + model = frozen_image_model(item) + models[identity] = model + if role not in {geometry.relation.child_role for geometry in model.geometry}: + raise ValueError("image_motion_provenance_role_not_in_model") + for identity, model in models.items(): + if (max(model.source_stamps_ns) >= frame["image_stamp_ns"] + or not np.array_equal(np.asarray(frame["camera_matrix"]), model.camera_matrix)): + raise ValueError("image_motion_provenance_model_not_frozen_before_image") + children = {geometry.relation.child_role for geometry in model.geometry} + references = {ref.role: ref for ref in model.reference_frames} + roles, observations = [], [] + for role, size in model.tag_sizes: + item = frame["roles"].get(role) + if item is None or float(item.get("tag_size_m", -1)) != size: + raise ValueError("image_motion_provenance_role_or_size_changed") + if role in children: + if (item.get("pose_source") != IMAGE_POSE_SOURCE + or item.get("image_model_sha256") != identity): + raise ValueError("image_motion_provenance_chain_model_changed") + candidates = tuple(_pose(pose) for pose in item.get("reprojection_valid_candidates", ())) + if not candidates: + raise ValueError("image_motion_provenance_raw_candidates_missing") + else: + # A root may itself be an earlier frozen moving parent. Its + # current selected pose is used, never its previous image. + diagnostics = item.get("candidate_diagnostics", {}) + if (item.get("pose_source") not in {"verified_fixed_reference", IMAGE_POSE_SOURCE, IMAGE_REFERENCE_SOURCE} + or diagnostics.get("branch_frozen") is not True + or diagnostics.get("branch_status") != "tracking" + or diagnostics.get("observation_stamp_ns") != frame["image_stamp_ns"]): + raise ValueError("image_motion_provenance_root_not_frozen_in_current_image") + if role in references or item.get("pose_source") == IMAGE_REFERENCE_SOURCE: + reference = reference_from_evidence(item, stamp_ns=frame["image_stamp_ns"], + camera_matrix=frame["camera_matrix"]) + if reference != references.get(role): + raise ValueError("image_motion_provenance_reference_binding_changed") + candidates = (_pose(item["selected"]),) + points = item.get("corners_xy") + if points is not None: + array = np.asarray(points, dtype=float) + if array.shape != (4, 2) or not np.all(np.isfinite(array)): + raise ValueError("image_motion_provenance_corners_invalid") + observations.append(ImageRoleObservation(role, size, tuple(map(tuple, array)))) + elif role in children: + raise ValueError("image_motion_provenance_corners_missing") + roles.append(RoleCandidates(role, candidates, role not in children)) + result = select_image_motion_frame(model, ImageMotionFrame( + MotionEvidenceFrame(frame["image_stamp_ns"], tuple(roles)), + tuple(map(tuple, frame["camera_matrix"])), tuple(observations), model.reference_frames)) + if not result.resolved: + raise ValueError(f"image_motion_provenance_frame_unresolved:{result.reason}") + by_role = {item.role: item.pose for item in result.selections} + for role in children: + if role not in by_role or not _same_pose(_pose(frame["roles"][role]["selected"]), by_role[role]): + raise ValueError(f"image_motion_provenance_selected_pose_changed:{role}") + selected[role] = by_role[role] + return selected + + +def validate_image_sample(row, frame, replayed): + """Bind sample pose, corners, model identity and relative geometry to a frame.""" + if (row.get("view") != frame.get("view") or row.get("image_stamp_ns") != frame.get("image_stamp_ns") + or any(row.get(key) != frame.get(key) for key in ("task_name", "cycle", "direction", "attempt"))): + raise ValueError("image_motion_provenance_sample_identity_changed") + evidence = row.get("pnp_observation_evidence", {}) + if set(evidence) != {"parent", "child"}: + raise ValueError("image_motion_provenance_sample_roles_missing") + for item in evidence.values(): + role = item.get("tag_role") + data = frame["roles"].get(role) + if data is None: + raise ValueError("image_motion_provenance_sample_role_changed") + if not _same_pose(_pose(item["selected_pose"]), _pose(data["selected"])): + raise ValueError("image_motion_provenance_sample_pose_changed") + if has_image_model(item): + if (item.get("pose_source") != IMAGE_POSE_SOURCE or role not in replayed + or item.get("image_model_sha256") != data.get("image_model_sha256") + or image_model_sha256(item["frozen_image_model"]) != data.get("image_model_sha256") + or not np.array_equal(item.get("corners_xy"), data.get("corners_xy"))): + raise ValueError("image_motion_provenance_sample_model_or_corners_changed") + elif has_image_model(data): + raise ValueError("image_motion_provenance_sample_solver_marker_removed") + if IMAGE_REFERENCE_SOURCE in (item.get("pose_source"), data.get("pose_source")): + sample_ref = reference_from_evidence(item, stamp_ns=row["image_stamp_ns"], + camera_matrix=frame["camera_matrix"]) + frame_ref = reference_from_evidence(data, stamp_ns=frame["image_stamp_ns"], + camera_matrix=frame["camera_matrix"]) + if sample_ref != frame_ref or not np.array_equal(item.get("corners_xy"), data.get("corners_xy")): + raise ValueError("image_motion_provenance_sample_reference_changed") + parent = _pose(evidence["parent"]["selected_pose"]) + child = _pose(evidence["child"]["selected_pose"]) + rp, rc = Rotation.from_quat(parent.quaternion_xyzw), Rotation.from_quat(child.quaternion_xyzw) + relative = Rotation.from_quat(row["relative_quaternion_xyzw"]) + translation = rp.inv().apply(np.subtract(child.translation_xyz_m, parent.translation_xyz_m)) + if ((relative.inv()*rp.inv()*rc).magnitude() > 1e-7 + or not np.allclose(translation, row["relative_translation_xyz_m"], atol=1e-8, rtol=0)): + raise ValueError("image_motion_provenance_relative_pose_changed") + common_parent, common_child = row["parent_pose_common"], row["child_pose_common"] + rp = Rotation.from_quat(common_parent["quaternion_xyzw"]) + rc = Rotation.from_quat(common_child["quaternion_xyzw"]) + common_translation = rp.inv().apply(np.subtract(common_child["translation_xyz_m"], + common_parent["translation_xyz_m"])) + if ((relative.inv()*rp.inv()*rc).magnitude() > 1e-7 + or not np.allclose(translation, common_translation, atol=1e-8, rtol=0)): + raise ValueError("image_motion_provenance_common_pose_changed") diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/pnp.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/pnp.py new file mode 100644 index 0000000..33c4270 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/pnp.py @@ -0,0 +1,19 @@ +"""Stable PnP API; implementations are separated by pose-estimation responsibility.""" + +from .tag_pose.types import SquareTagPose as SquareTagPose +from .tag_pose.relative import _relative_pose as _relative_pose +from .tag_pose.relative import _normal_alignment_rad as _normal_alignment_rad +from .tag_pose.trajectory import select_rigid_group_trajectory as select_rigid_group_trajectory +from .tag_pose.rigid_group import select_static_rigid_group_initialization as select_static_rigid_group_initialization +from .tag_pose.ippe import _as_camera_matrix as _as_camera_matrix +from .tag_pose.ippe import square_object_points as square_object_points +from .tag_pose.ippe import solve_square_tag_ippe as solve_square_tag_ippe +from .tag_pose.ippe import rotation_distance_rad as rotation_distance_rad +from .tag_pose.tracking import _validate_reprojection_thresholds as _validate_reprojection_thresholds +from .tag_pose.tracking import select_continuous_pose as select_continuous_pose +from .tag_pose.tracking import SquareTagPoseTracker as SquareTagPoseTracker +from .tag_pose.rigid_group import SquareTagGroupPoseTracker as SquareTagGroupPoseTracker +from .tag_pose.parameters import PoseTrackingParameters as PoseTrackingParameters +from .tag_pose.parameters import DEFAULT_POSE_TRACKING_PARAMETERS as DEFAULT_POSE_TRACKING_PARAMETERS +from .tag_pose.parameters import DEFAULT_REPROJECTION_TIE_PX as DEFAULT_REPROJECTION_TIE_PX +from .tag_pose.parameters import POSE_TRACKING_POLICY_VERSION as POSE_TRACKING_POLICY_VERSION diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/rotation.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/rotation.py new file mode 100644 index 0000000..4fd14a8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/rotation.py @@ -0,0 +1,179 @@ +"""Pure quaternion summaries and rotation-axis fitting.""" + +from __future__ import annotations + +import math +from typing import Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + + +def normalize_quaternion_xyzw(values: Sequence[float]) -> np.ndarray: + quaternion = np.asarray(values, dtype=float) + if quaternion.shape != (4,) or not np.all(np.isfinite(quaternion)): + raise ValueError("quaternion must contain four finite xyzw values") + norm = float(np.linalg.norm(quaternion)) + if norm < 1e-12: + raise ValueError("quaternion norm is zero") + return quaternion / norm + + +def relative_quaternion_xyzw( + parent_camera_quaternion: Sequence[float], + child_camera_quaternion: Sequence[float], +) -> tuple[float, float, float, float]: + """Compute parent-to-child orientation from two camera-to-Tag rotations.""" + parent = Rotation.from_quat( + normalize_quaternion_xyzw(parent_camera_quaternion) + ) + child = Rotation.from_quat( + normalize_quaternion_xyzw(child_camera_quaternion) + ) + quaternion = (parent.inv() * child).as_quat() + return tuple(float(value) for value in quaternion) + + +def image_plane_tag_quaternion_xyzw( + corners_xy: Sequence[Sequence[float]], +) -> tuple[float, float, float, float]: + """Estimate Tag orientation about the optical axis from ordered corners.""" + corners = np.asarray(corners_xy, dtype=float) + if corners.shape != (4, 2) or not np.all(np.isfinite(corners)): + raise ValueError("corners_xy must contain four finite xy points") + x_axis = (corners[1] - corners[0]) + (corners[2] - corners[3]) + if float(np.linalg.norm(x_axis)) < 1e-9: + raise ValueError("tag x-axis is degenerate") + angle = -math.atan2(float(x_axis[1]), float(x_axis[0])) + quaternion = Rotation.from_rotvec([0.0, 0.0, angle]).as_quat() + return tuple(float(value) for value in quaternion) + + +def robust_rotation_summary( + quaternions_xyzw: Sequence[Sequence[float]], +) -> tuple[tuple[float, float, float, float], float]: + """Return a robust orientation and maximum angular residual in radians.""" + if not quaternions_xyzw: + raise ValueError("at least one quaternion is required") + rotations = Rotation.from_quat( + np.asarray( + [normalize_quaternion_xyzw(value) for value in quaternions_xyzw], + dtype=float, + ) + ) + reference = rotations[0] + delta_vectors = (reference.inv() * rotations).as_rotvec() + median_delta = np.median(delta_vectors, axis=0) + robust = reference * Rotation.from_rotvec(median_delta) + residuals = (robust.inv() * rotations).magnitude() + maximum = float(np.max(residuals)) if residuals.size else 0.0 + return tuple(float(value) for value in robust.as_quat()), maximum + + +def rotation_spread_rad( + quaternions_xyzw: Sequence[Sequence[float]], +) -> float: + """Return the maximum geodesic residual around a robust orientation.""" + _, spread = robust_rotation_summary(quaternions_xyzw) + return spread + + +def rotation_rms_rad( + quaternions_xyzw: Sequence[Sequence[float]], + *, + outlier_threshold_rad: float | None = None, +) -> float: + """Return RMS geodesic noise around a robust orientation.""" + robust, _ = robust_rotation_summary(quaternions_xyzw) + reference = Rotation.from_quat(robust) + rotations = Rotation.from_quat( + np.asarray( + [normalize_quaternion_xyzw(value) for value in quaternions_xyzw], + dtype=float, + ) + ) + residuals = (reference.inv() * rotations).magnitude() + if outlier_threshold_rad is not None: + threshold = float(outlier_threshold_rad) + if threshold <= 0.0: + raise ValueError("outlier_threshold_rad must be positive") + residuals = residuals[residuals <= threshold] + if residuals.size == 0: + return float("inf") + return float(np.sqrt(np.mean(np.square(residuals)))) + + +def rotation_inlier_fraction( + quaternions_xyzw: Sequence[Sequence[float]], + *, + outlier_threshold_rad: float, +) -> float: + """Return the fraction close to the robust orientation.""" + threshold = float(outlier_threshold_rad) + if threshold <= 0.0: + raise ValueError("outlier_threshold_rad must be positive") + robust, _ = robust_rotation_summary(quaternions_xyzw) + reference = Rotation.from_quat(robust) + rotations = Rotation.from_quat( + np.asarray( + [normalize_quaternion_xyzw(value) for value in quaternions_xyzw], + dtype=float, + ) + ) + residuals = (reference.inv() * rotations).magnitude() + return float(np.mean(residuals <= threshold)) + + +def delta_rotation_vector( + reference_xyzw: Sequence[float], + observed_xyzw: Sequence[float], +) -> np.ndarray: + reference = Rotation.from_quat(normalize_quaternion_xyzw(reference_xyzw)) + observed = Rotation.from_quat(normalize_quaternion_xyzw(observed_xyzw)) + return (reference.inv() * observed).as_rotvec() + + +def fit_rotation_axis( + vectors: Sequence[Sequence[float]], + commands: Sequence[int], +) -> np.ndarray: + """Fit and orient the single rotational axis used by one command sweep.""" + matrix = np.asarray(vectors, dtype=float) + command_values = np.asarray(commands, dtype=int) + if matrix.ndim != 2 or matrix.shape[1] != 3: + raise ValueError("vectors must have shape (N, 3)") + if command_values.shape != (matrix.shape[0],): + raise ValueError("commands must match vectors") + useful = np.linalg.norm(matrix, axis=1) > 1e-6 + if int(np.count_nonzero(useful)) < 3: + raise ValueError("insufficient non-zero rotations to fit an axis") + _, _, vh = np.linalg.svd(matrix[useful], full_matrices=False) + axis = vh[0] + projections = matrix @ axis + low = projections[command_values <= 16] + high = projections[command_values >= 239] + # Physical-angle adapters normalize their measured feedback into the + # legacy 0..255 fitting coordinate. Tracking lag and mechanical travel + # mean those records need not reach the historical <=16 endpoint even + # when the observed physical stroke is complete. SVD axis sign is + # arbitrary, so fall back to the ends of the *observed* command domain + # instead of allowing that arbitrary sign to reverse an otherwise valid + # trajectory. Byte-feedback products that observe the canonical end + # bands retain their existing behaviour. + if not low.size or not high.size: + observed = command_values[useful] + lower = int(np.min(observed)) + upper = int(np.max(observed)) + span = upper - lower + if span <= 0: + raise ValueError("commands do not span a rotation trajectory") + band = max(1, int(math.ceil(0.1 * span))) + low = projections[ + useful & (command_values <= lower + band) + ] + high = projections[ + useful & (command_values >= upper - band) + ] + if low.size and high.size and float(np.median(low)) < float(np.median(high)): + axis = -axis + return axis / np.linalg.norm(axis) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_border.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_border.py new file mode 100644 index 0000000..a197fc5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_border.py @@ -0,0 +1,44 @@ +"""Independent pixel support for a decoded square's four outer edges. + +A partially covered AprilTag can still decode without a bit error, while its +quad follows the occluder. Such a quad is not evidence of reference motion. +This check uses the current detected quad, never the locked reference: a fully +visible translated/rotated marker remains eligible for the movement guard. +""" + +import cv2 +import numpy as np + + +def inspect_tag_border(gray, corners): + points = np.asarray(corners, dtype=np.float32) + if (gray.ndim != 2 or points.shape != (4, 2) or not np.all(np.isfinite(points))): + return {"passed": False, "reason": "border_image_or_quad_invalid"} + edge = float(np.min(np.linalg.norm(points-np.roll(points, 1, axis=0), axis=1))) + if edge < 12: + return {"passed": False, "reason": "border_image_underresolved"} + # Sample opposite sides of the printed black/white boundary, including + # near-corner portions. A wider band would miss curved occluder edges. + inset = max(.025, 1.25/edge) + u = np.linspace(.05, .95, 25, dtype=np.float32) + def bands(offset): + return np.asarray([np.c_[u, np.full(25, offset)], + np.c_[np.full(25, 1-offset), u], np.c_[u, np.full(25, 1-offset)], + np.c_[np.full(25, offset), u]], dtype=np.float32) + transform = cv2.getPerspectiveTransform(np.float32([[0, 0], [1, 0], [1, 1], [0, 1]]), points) + def sample(normalized): + xy = cv2.perspectiveTransform(normalized.reshape(-1, 1, 2), transform).reshape(4, 25, 2) + if (np.min(xy) < 1 or np.max(xy[:, :, 0]) > gray.shape[1]-2 + or np.max(xy[:, :, 1]) > gray.shape[0]-2): + return None + return cv2.remap(gray, xy[:, :, 0], xy[:, :, 1], cv2.INTER_LINEAR).astype(float) + inside, outside = sample(bands(inset)), sample(bands(-inset)) + if inside is None or outside is None: + return {"passed": False, "reason": "border_image_out_of_bounds"} + black, white = float(np.percentile(inside, 25)), float(np.percentile(outside, 75)) + threshold = (black+white)/2 + support = np.mean((inside < threshold) & (outside > threshold), axis=1) + passed = white-black >= 30 and bool(np.all(support >= .9)) + return {"passed": passed, "reason": "" if passed else "tag_border_incomplete", + "policy": "current_quad_border_v1", "edge_support": support.tolist(), + "contrast_gray": white-black, "minimum_edge_support": .9, "minimum_contrast_gray": 30} diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/__init__.py new file mode 100644 index 0000000..b85ebd0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/__init__.py @@ -0,0 +1 @@ +"""Shared pose estimation primitives; public API is core.geometry.pnp.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/branch_confirmation.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/branch_confirmation.py new file mode 100644 index 0000000..0e44e93 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/branch_confirmation.py @@ -0,0 +1,299 @@ +"""Image-evidence confirmation and frozen-reference branch consistency. + +Confirmation is repeatable image evidence, not a claim of physical truth. +After a reference is frozen, conflicting evidence must invalidate capture; +it cannot authorize a different planar solution for the same reference. +""" + +from dataclasses import dataclass +import math +from typing import Sequence + +import numpy as np + +from .ippe import rotation_distance_rad +from .fixed_reference import FixedTagReference +from .parameters import BRANCH_TRANSLATION_EQUIVALENCE_M, PoseTrackingParameters +from .types import SquareTagPose + + +@dataclass +class PendingBranch: + pose: SquareTagPose + started_ns: int + count: int = 1 + + +@dataclass +class BranchState: + observed_ns: int = 0 + pose: SquareTagPose | None = None + revision: int = 0 + pending: PendingBranch | None = None + frozen: bool = False + recovery_required: bool = False + conflict: bool = False + status: str = "initializing" + reason: str = "pose_branch_unconfirmed" + motion_evidence_id: str | None = None + + +class BranchConfirmation: + """Mutable metadata, accessed only under the owning tracker's short lock.""" + + def __init__(self, parameters: PoseTrackingParameters): + self.parameters = parameters + count = parameters.branch_confirmation_frames + if isinstance(count, bool) or not isinstance(count, int) or count < 2: + raise ValueError("branch_confirmation_frames must be an integer >= 2") + for name in ("branch_confirmation_minimum_seconds", "branch_equivalence_rad"): + value = getattr(parameters, name) + if not math.isfinite(value) or value <= 0: + raise ValueError(f"{name} must be finite and positive") + if parameters.branch_equivalence_rad > math.radians(1.0): + raise ValueError("branch_equivalence_rad must not exceed 1 degree") + self.states: dict[str, BranchState] = {} + self.corrections: dict[str, int] = {} + + def reset(self): + self.states.clear() + self.corrections.clear() + + def distance(self, first: SquareTagPose, second: SquareTagPose) -> tuple[float, float]: + return ( + rotation_distance_rad(first.quaternion_xyzw, second.quaternion_xyzw), + float(np.linalg.norm(np.asarray(first.translation_xyz_m) - second.translation_xyz_m)), + ) + + def continuous(self, first: SquareTagPose, second: SquareTagPose) -> bool: + angle, translation = self.distance(first, second) + return (angle <= self.parameters.maximum_pose_jump_rad + and translation <= self.parameters.maximum_translation_jump_m) + + def equivalent(self, first: SquareTagPose, second: SquareTagPose) -> bool: + angle, translation = self.distance(first, second) + # A 4 cm image acceptance limit is not equivalence of two solutions. + return (angle <= self.parameters.branch_equivalence_rad + and translation <= BRANCH_TRANSLATION_EQUIVALENCE_M) + + def nearest(self, reference: SquareTagPose, candidates: Sequence[SquareTagPose]) -> SquareTagPose: + def cost(candidate): + angle, translation = self.distance(reference, candidate) + return (angle / self.parameters.maximum_pose_jump_rad + + translation / self.parameters.maximum_translation_jump_m) + return min(candidates, key=cost) + + @staticmethod + def reject(state: BranchState, reason: str, status: str) -> tuple[None, str]: + state.status, state.reason = status, reason + return None, reason + + @staticmethod + def accept(state: BranchState, selected: SquareTagPose) -> tuple[SquareTagPose, str]: + state.pose = selected + state.pending = None + state.status, state.reason = "tracking", "" + return selected, "" + + def confirmed(self, state: BranchState, selected: SquareTagPose, stamp: int, + candidates: Sequence[SquareTagPose]) -> bool: + pending = state.pending + if (pending is None or not self.continuous(pending.pose, selected) + or not self.equivalent(self.nearest(pending.pose, candidates), selected)): + state.pending = PendingBranch(selected, stamp) + return False + pending.pose = selected + pending.count += 1 + return (pending.count >= self.parameters.branch_confirmation_frames + and stamp - pending.started_ns >= round( + self.parameters.branch_confirmation_minimum_seconds * 1e9)) + + def _observe(self, role: str, stamp: int) -> tuple[BranchState | None, bool]: + state = self.states.setdefault(role, BranchState()) + if stamp <= state.observed_ns: + return None, False + gap = state.observed_ns > 0 and stamp - state.observed_ns > round( + self.parameters.reset_after_seconds * 1e9) + state.observed_ns = stamp # Rejections are observations, not a lost Tag. + return state, gap + + def update_fixed(self, role: str, reference: FixedTagReference, + checked_pose: SquareTagPose | None, stamp: int) -> tuple[SquareTagPose | None, str]: + """Validate stationarity in the image; never track a new base pose. + + The fixed pose was confirmed and frozen before this call. IPPE image + ranking alone cannot contradict the explicit stationary constraint. + A failed image invalidates observations using this reference, not the + frozen pose itself. Actual reference movement is monitored separately; + prolonged missing data is handled by the task's normal quality gates. + """ + state, gap = self._observe(role, stamp) + if state is None: + return None, "pose_observation_not_new" + if (type(reference.branch_revision) is not int or not state.frozen + or state.revision != reference.branch_revision): + return self.reject(state, "pose_branch_reference_invalid", "unavailable") + if state.conflict: + return self.reject(state, "pose_branch_conflict", "frozen_conflict") + if gap: + state.pending = None + state.recovery_required = True + if checked_pose is None: + state.pending = None + state.recovery_required = True + return self.reject(state, "fixed_reference_pose_unverified", "fixed_reference_unavailable") + if state.recovery_required: + if state.status != "recovering": + state.pending = None + if not self.confirmed(state, reference.pose, stamp, (reference.pose,)): + return self.reject(state, "pose_branch_unconfirmed", "recovering") + state.recovery_required = False + return self.accept(state, checked_pose) + + def observe_motion(self, role: str, candidates: Sequence[SquareTagPose], + stamp: int) -> tuple[None, str]: + """Register a frame whose branch will be selected jointly, outside locks. + + Recording candidates is not confirmation. In particular, repeated image + winners cannot change a motion-authorized identity while the geometric + selector is evaluating this frame. + """ + state, gap = self._observe(role, stamp) + if state is None: + return None, "pose_observation_not_new" + if state.conflict: + return self.reject(state, "pose_branch_conflict", "frozen_conflict") + if gap: + state.pending = None + if state.frozen or state.motion_evidence_id is not None: + state.recovery_required = True + else: + state.pose = None + if not candidates: + state.pending = None + return self.reject(state, "no_pose_within_reprojection_or_tilt_limit", "unavailable") + # Preserve recovery confirmation between frames; merely receiving a + # frame must not clear PendingBranch before the joint selection commits. + state.reason = "pose_motion_evidence_required" + if not state.recovery_required: + state.status = "motion_pending" + return None, state.reason + + def select_motion(self, state: BranchState, selected: SquareTagPose, + evidence_id: str, *, establish: bool) -> tuple[SquareTagPose | None, str]: + """Apply an externally verified geometric selection to one metadata copy. + + The tracker checks image membership and atomically commits all copies. + This method never fits a model or changes an existing evidence identity. + """ + if state.conflict: + return self.reject(state, "pose_branch_conflict", "frozen_conflict") + if state.motion_evidence_id is None: + if state.frozen or not establish: + return self.reject(state, "pose_motion_evidence_required", "motion_unconfirmed") + state.motion_evidence_id = evidence_id + state.revision += 1 + state.recovery_required = False + return self.accept(state, selected) + if evidence_id != state.motion_evidence_id: + return self.reject(state, "pose_motion_evidence_changed", "motion_unconfirmed") + if state.pose is None: + return self.reject(state, "pose_branch_reference_invalid", "unavailable") + if state.recovery_required: + if not self.equivalent(state.pose, selected): + state.pending = None + return self.reject(state, "pose_branch_recovery_required", "recovery_required") + if not self.confirmed(state, selected, state.observed_ns, (selected,)): + return self.reject(state, "pose_branch_unconfirmed", "recovering") + state.recovery_required = False + elif not self.continuous(state.pose, selected): + state.pending = None + return self.reject(state, "pose_motion_branch_discontinuous", "motion_unconfirmed") + return self.accept(state, selected) + + def update(self, role: str, candidates: Sequence[SquareTagPose], stamp: int, + tie: float) -> tuple[SquareTagPose | None, str]: + state, gap = self._observe(role, stamp) + if state is None: + return None, "pose_observation_not_new" + if state.conflict: + return self.reject(state, "pose_branch_conflict", "frozen_conflict") + if gap: + state.pending = None + if state.frozen: + state.recovery_required = True + else: + state.pose = None + if not candidates: + state.pending = None + return self.reject(state, "no_pose_within_reprojection_or_tilt_limit", "unavailable") + candidates = sorted(candidates, key=lambda c: c.reprojection_error_px) + best = candidates[0] + distinct = [c for c in candidates[1:] if not self.equivalent(best, c)] + decisive = not distinct or all(c.reprojection_error_px > best.reprojection_error_px + tie for c in distinct) + if state.recovery_required: + # Without a temporal path, only a return to the last known pose + # supplies a conservative reference for independent tracking. + near = self.nearest(state.pose, candidates) + if (not self.equivalent(state.pose, near) + or best.reprojection_error_px + tie < near.reprojection_error_px): + state.pending = None + return self.reject(state, "pose_branch_recovery_required", "recovery_required") + if not self.confirmed(state, near, stamp, candidates): + return self.reject(state, "pose_branch_unconfirmed", "recovering") + state.recovery_required = False + return self.accept(state, near) + if state.pose is None: + if not decisive: + state.pending = None + return self.reject(state, "pose_branch_unconfirmed", "initializing") + if not self.confirmed(state, best, stamp, candidates): + return self.reject(state, "pose_branch_unconfirmed", "initializing") + state.revision += 1 + return self.accept(state, best) + + incumbent = self.nearest(state.pose, candidates) + continuous = self.continuous(state.pose, incumbent) + advantage = best.reprojection_error_px + tie < incumbent.reprojection_error_px + if continuous and (not advantage or self.equivalent(incumbent, best)): + return self.accept(state, incumbent) + + # Propagate the incumbent's identity while evidence is rejected. This + # does not emit a sample, and cannot age into a five-second reset. + if continuous: + state.pose = incumbent + if state.frozen and continuous: + # Both image-valid branches still exist and the incumbent has a + # continuous path. A different image-error winner is ambiguity, + # not evidence that the reference moved. Quarantine the image; + # retain this path so later observations can recover without a + # reset, branch switch, or new joint zero. + state.pending = None + return self.reject(state, "pose_branch_ambiguous", "frozen_ambiguous") + if not decisive: + state.pending = None + return self.reject(state, "pose_jump", "unconfirmed") + if not self.confirmed(state, best, stamp, candidates): + return self.reject(state, "pose_branch_unconfirmed", "conflict_pending" if state.frozen else "correcting") + if state.frozen: + state.conflict = True + return self.reject(state, "pose_branch_conflict", "frozen_conflict") + state.revision += 1 + self.corrections[role] = self.corrections.get(role, 0) + 1 + self.accept(state, best) + # A corrected tracker can establish NEW references, but the transition + # itself must never be interpreted as a measured joint displacement. + return self.reject(state, "pose_branch_corrected", "corrected") + + def diagnostics(self, role: str) -> dict[str, int | str | bool]: + state = self.states[role] + return { + "observation_stamp_ns": state.observed_ns, + "branch_revision": state.revision, + "branch_status": state.status, + "branch_reason": state.reason, + "branch_confirmation_count": 0 if state.pending is None else state.pending.count, + "branch_frozen": state.frozen, + "motion_evidence_verified": state.motion_evidence_id is not None, + "motion_evidence_id": state.motion_evidence_id or "", + } diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/cad_hinge.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/cad_hinge.py new file mode 100644 index 0000000..3d85c4a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/cad_hinge.py @@ -0,0 +1,140 @@ +"""Image hinges constrained by geometry retained in the output URDF. + +Only adjacent parallel axes are represented here. Their signed parallelism +and perpendicular separation are invariant under joint-zero corrections. +Camera poses, Tag installations and image angles remain measured quantities. +""" + +from dataclasses import dataclass +import math + +import numpy as np +from scipy.spatial.transform import Rotation + +from .motion_image_solver import ImageHingeBundle +from .source_hinge import SourceHinge + + +@dataclass(frozen=True) +class ParallelAxisGeometry: + parent_joint: str + child_joint: str + axis_sign: int + distance_m: float + + def __post_init__(self): + if (not self.parent_joint or not self.child_joint or self.parent_joint == self.child_joint + or self.axis_sign not in {-1, 1} + or not math.isfinite(self.distance_m) or self.distance_m <= 1e-6): + raise ValueError("invalid_parallel_axis_geometry") + + +class CadImageHingeBundle(ImageHingeBundle): + """Eliminate three variables per constrained hinge, without penalty weights. + + The child axis is the parent axis expressed in the parent Tag frame. Its + pivot is on the known-radius circle about the parent axis; one phase is + estimated. This keeps the model's axial-pivot gauge fixed and leaves no + redundant optimizer columns. The usual full Jacobian includes image-angle + uncertainty and dependencies on the parent's installation parameters. + """ + + def __init__(self, frames, relations, poses, *, constraints, source_urdf_sha256, source_hinges=()): + super().__init__(frames, relations, poses) + self.constraints = tuple(constraints) + self.source_urdf_sha256 = source_urdf_sha256 + self.source_hinges = tuple(source_hinges) + sources = {item.geometry.relation.joint: item for item in self.source_hinges} + if len(sources) != len(self.source_hinges): + raise ValueError("source_hinge_duplicate") + indices = {relation.joint: i for i, relation in enumerate(relations)} + if set(sources) & set(indices) or not set(sources) <= {c.parent_joint for c in self.constraints}: + raise ValueError("source_hinge_unused_or_overlapping") + self._constraints = {} + for constraint in self.constraints: + parent = indices.get(constraint.parent_joint, sources.get(constraint.parent_joint)) + child = indices.get(constraint.child_joint) + parent_relation = (parent.geometry.relation if isinstance(parent, SourceHinge) + else None if parent is None else relations[parent]) + if (parent is None or child is None or isinstance(parent, int) and parent >= child + or relations[child].parent_role != parent_relation.child_role + or child in self._constraints): + raise ValueError("parallel_axis_constraint_outside_observed_chain") + self._constraints[child] = (parent, constraint) + self._full_initial = self.initial.copy() + removed = {10*i + local for i in self._constraints for local in (0, 1, 6)} + self._kept = np.asarray([i for i in range(len(self.initial)) if i not in removed]) + self._columns = {original: column for column, original in enumerate(self._kept)} + for index, (parent, _) in sorted(self._constraints.items()): + parameters = self._full_initial[self._kept] + _, _, _, parent_mount = self._parent_values(parameters, parent) + _, _, old_pivot, _ = super().geometry_values(self._full_initial, index) + tangent = self.axis_basis(parameters, index) + vector = parent_mount + old_pivot + self._full_initial[10*index + 5] = math.atan2(tangent[:, 1] @ vector, tangent[:, 0] @ vector) + self.scale[10*index + 5] = 1. + self.initial = self._full_initial[self._kept] + self.scale = self.scale[self._kept] + + @property + def static_parameter_count(self): + return 10 * self.joints - 3 * len(self._constraints) + + def geometry_parameter_indices(self, index): + return tuple(self._columns[original] for original in range(10*index, 10*(index+1)) + if original in self._columns) + + def geometry_dependency_indices(self, index): + result = self.geometry_parameter_indices(index) + if index in self._constraints and isinstance(self._constraints[index][0], int): + result += self.geometry_dependency_indices(self._constraints[index][0]) + return result + + def _parent_values(self, parameters, parent): + if isinstance(parent, int): + return self.geometry_values(parameters, parent) + g = parent.geometry + return (np.asarray(g.axis_parent_xyz), Rotation.from_quat(g.reference_quaternion_xyzw), + np.asarray(g.pivot_parent_xyz_m), np.asarray(g.mount_child_xyz_m)) + + def inherited_uncertainty(self, index): + if index not in self._constraints: + return 0., 0. + parent, constraint = self._constraints[index] + if isinstance(parent, int): + axis, point = self.inherited_uncertainty(parent) + return axis, point + constraint.distance_m * axis + axis = parent.child_axis_uncertainty_rad + # Triangle bound includes the lever arm affected by inherited tilt. + return axis, parent.child_point_uncertainty_m + constraint.distance_m * axis + + def _expand(self, parameters): + full = self._full_initial.copy() + full[self._kept] = parameters + return full + + def axis_basis(self, parameters, index): + if index not in self._constraints: + values = self._expand(parameters)[10*index:10*index+2] + return Rotation.from_rotvec(self.bases[index] @ values).as_matrix() @ self.bases[index] + parent, constraint = self._constraints[index] + axis, reference, _, _ = self._parent_values(parameters, parent) + from .motion_image_solver import _basis + parent_basis = self.axis_basis(parameters, parent) if isinstance(parent, int) else _basis(axis) + basis = reference.inv().as_matrix() @ parent_basis + basis[:, 1] *= constraint.axis_sign + return basis + + def geometry_values(self, parameters, index): + full = self._expand(parameters) + if index not in self._constraints: + return super().geometry_values(full, index) + parent, constraint = self._constraints[index] + parent_axis, parent_reference, _, parent_mount = self._parent_values(parameters, parent) + axis = constraint.axis_sign * parent_reference.inv().apply(parent_axis) + values = full[10*index:10*(index+1)] + reference = Rotation.from_rotvec(values[2:5]) * self.references[index] + phase = values[5] + pivot = constraint.distance_m * (self.axis_basis(parameters, index) @ [math.cos(phase), math.sin(phase)]) + pivot -= parent_mount - axis * (axis @ parent_mount) + return axis, reference, pivot, values[7:10] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/cad_image_model.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/cad_image_model.py new file mode 100644 index 0000000..53d5402 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/cad_image_model.py @@ -0,0 +1,69 @@ +"""A frozen image model with explicit, source-bound URDF constraints.""" + +from dataclasses import dataclass +from typing import ClassVar + +import numpy as np +from scipy.spatial.transform import Rotation + +from .cad_hinge import ParallelAxisGeometry +from .image_motion_model import ImageMotionModel +from .source_hinge import SourceHinge + +CAD_IMAGE_MOTION_MODEL_POLICY = "image_hinge_v2_source_parallel_geometry" +TRANSFERRED_IMAGE_MOTION_MODEL_POLICY = "image_hinge_v3_transferred_parallel_geometry" + + +@dataclass(frozen=True) +class CadImageMotionModel(ImageMotionModel): + POLICY: ClassVar[str] = CAD_IMAGE_MOTION_MODEL_POLICY + policy: str = CAD_IMAGE_MOTION_MODEL_POLICY + constraints: tuple[ParallelAxisGeometry, ...] = () + source_urdf_sha256: str = "" + + def __post_init__(self): + super().__post_init__() + if (not isinstance(self.constraints, tuple) or not self.constraints + or len(self.source_urdf_sha256) != 64 + or any(c not in "0123456789abcdef" for c in self.source_urdf_sha256)): + raise ValueError("image_model_source_geometry_missing") + geometry = {item.relation.joint: item for item in self.geometry} + measured = set(geometry) + sources = getattr(self, "source_hinges", ()) + if len({item.geometry.relation.joint for item in sources}) != len(sources): + raise ValueError("image_model_source_hinge_duplicate") + if any(item.geometry.relation.joint in geometry for item in sources): + raise ValueError("image_model_source_hinge_overlaps_current") + geometry.update((item.geometry.relation.joint, item.geometry) for item in sources) + children = set() + for constraint in self.constraints: + if not isinstance(constraint, ParallelAxisGeometry): + raise ValueError("image_model_source_geometry_invalid") + parent, child = geometry.get(constraint.parent_joint), geometry.get(constraint.child_joint) + if (parent is None or child is None or parent.relation.child_role != child.relation.parent_role + or constraint.child_joint in children or constraint.child_joint not in measured): + raise ValueError("image_model_source_geometry_graph_changed") + children.add(constraint.child_joint) + axis = Rotation.from_quat(parent.reference_quaternion_xyzw).inv().apply(parent.axis_parent_xyz) + if not np.allclose(child.axis_parent_xyz, constraint.axis_sign * axis, atol=1e-8, rtol=0): + raise ValueError("image_model_source_axis_changed") + vector = np.asarray(parent.mount_child_xyz_m) + child.pivot_parent_xyz_m + distance = np.linalg.norm(vector - axis * (axis @ vector)) + if not np.isclose(distance, constraint.distance_m, atol=1e-8, rtol=0): + raise ValueError("image_model_source_axis_distance_changed") + + +@dataclass(frozen=True) +class TransferredImageMotionModel(CadImageMotionModel): + POLICY: ClassVar[str] = TRANSFERRED_IMAGE_MOTION_MODEL_POLICY + policy: str = TRANSFERRED_IMAGE_MOTION_MODEL_POLICY + source_hinges: tuple[SourceHinge, ...] = () + + def __post_init__(self): + if not isinstance(self.source_hinges, tuple) or not self.source_hinges or any( + not isinstance(item, SourceHinge) for item in self.source_hinges): + raise ValueError("image_model_source_hinge_missing") + super().__post_init__() + parents = {c.parent_joint for c in self.constraints} + if any(item.geometry.relation.joint not in parents for item in self.source_hinges): + raise ValueError("image_model_source_hinge_unused") diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/chain_candidate_audit.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/chain_candidate_audit.py new file mode 100644 index 0000000..44f47ec --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/chain_candidate_audit.py @@ -0,0 +1,60 @@ +"""Group duplicate optimizer solutions before testing physical alternatives. + +This is a non-authorizing diagnostic. All seeds remain in the audit. Grouping +uses training geometry only and complete-link numerical equivalence, not pixel +scores, holdout errors, or relaxed calibration precision limits. +""" +import numpy as np +from scipy.spatial.transform import Rotation + + +def equivalent_training_signatures(first, second): + # Numerical optimizer tolerance, far below the 1 degree / 1 mm source + # budget. These values do not certify either model's physical accuracy. + angle_tolerance = np.radians(.002) + position_tolerance = 2e-6 + left = np.asarray(first['geometry'], dtype=float) + right = np.asarray(second['geometry'], dtype=float) + if (left.shape != (3, 6) or right.shape != left.shape + or not np.all(np.isfinite(left)) or not np.all(np.isfinite(right))): + raise ValueError('chain_training_signature_geometry_invalid') + for a, b in zip(left, right): + if not np.isclose(np.linalg.norm(a[:3]), 1.) or not np.isclose(np.linalg.norm(b[:3]), 1.): + raise ValueError('chain_training_signature_axis_invalid') + angle = np.arctan2(np.linalg.norm(np.cross(a[:3], b[:3])), abs(a[:3]@b[:3])) + if angle > angle_tolerance or np.linalg.norm(a[3:]-b[3:]) > position_tolerance: + return False + for key, shape in (('installation', (4, 4)), ('stage_poses', (3, 4, 4))): + a, b = np.asarray(first[key], dtype=float), np.asarray(second[key], dtype=float) + if a.shape != shape or b.shape != shape or not np.all(np.isfinite(a)) or not np.all(np.isfinite(b)): + raise ValueError('chain_training_signature_pose_invalid') + for x, y in zip(a.reshape(-1, 4, 4), b.reshape(-1, 4, 4)): + for pose in (x, y): + if (not np.allclose(pose[3], [0, 0, 0, 1]) + or not np.allclose(pose[:3, :3].T@pose[:3, :3], np.eye(3), atol=1e-8) + or not np.isclose(np.linalg.det(pose[:3, :3]), 1.)): + raise ValueError('chain_training_signature_rotation_invalid') + if (Rotation.from_matrix(x[:3, :3].T@y[:3, :3]).magnitude() > angle_tolerance + or np.linalg.norm(x[:3, 3]-y[:3, 3]) > position_tolerance): + return False + return True + + +def training_solution_families(candidates): + """Deterministic, complete-link groups; failed/missing signatures stay vetoes.""" + families = [] + for index, candidate in enumerate(candidates): + signature = candidate.get('training_signature') if candidate.get('converged') else None + if signature is not None: + for family in families: + if all(candidates[other].get('training_signature') is not None + and candidates[other].get('converged') + and equivalent_training_signatures(signature, candidates[other]['training_signature']) + for other in family): + family.append(index) + break + else: + families.append([index]) + else: + families.append([index]) + return tuple(tuple(family) for family in families) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/finger_chain_diagnostic.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/finger_chain_diagnostic.py new file mode 100644 index 0000000..5eb23d0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/finger_chain_diagnostic.py @@ -0,0 +1,8 @@ +"""Compatibility imports for retained diagnostic replays; no release authority.""" +from .finger_chain_images import ( + FingerChainImages, chain_candidate_seeds, continuous_phase_angles, + compare_chain_output_angles, +) + +__all__ = ["FingerChainImages", "chain_candidate_seeds", "continuous_phase_angles", + "compare_chain_output_angles"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/finger_chain_images.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/finger_chain_images.py new file mode 100644 index 0000000..18285bc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/finger_chain_images.py @@ -0,0 +1,358 @@ +"""Shared raw-image finger graph and bounded numerical solver. + +The geometry, covariance and projection operations carry no release authority. +Production callers must separately prove physical zeros, candidate uncertainty, +independent validation and the protected original-URDF contract. +""" +from itertools import product + +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation + +from .ippe import solve_square_tag_ippe, square_object_points +from .motion_evidence import _axis +from .motion_image_solver import _basis +from .relative import _relative_pose + + +class FingerChainImages: + """Shared tag4-frame geometry; each declared parallel edge removes 3 DOFs.""" + + def __init__(self, rows, phases, roles, *, pip_dip_distance_m=None, mcp_pip_distance_m=None, + independent_stage_references=False, estimate_tag_scale=False): + self.rows = tuple(rows) + self.roles = tuple(roles) + self.phases = np.asarray(phases, dtype=int) + self.count = len(rows) + self.distances = {phase: distance for phase, distance in + ((1, mcp_pip_distance_m), (2, pip_dip_distance_m)) if distance is not None} + if any(not np.isfinite(distance) or distance <= 1e-6 for distance in self.distances.values()): + raise ValueError('finger_chain_invalid_parallel_geometry') + self.pip_dip_distance_m = pip_dip_distance_m + self.offsets, scale = [], [1.]*3+[.03]*3+[1.]*3+[.03]*3 + for phase in range(3): + self.offsets.append(len(scale)) + scale.extend([1.] if phase in self.distances else [1., 1., .03, .03]) + if self.phases.shape != (self.count,) or set(self.phases) != {0, 1, 2}: + raise ValueError('finger_chain_three_phases_required') + self.pose_offsets = {0: 0, 1: 0, 2: 0} + anchors = set() + if independent_stage_references: + # Each source stage has one observed reference pose, NOT arbitrary + # per-image drift. Its first training angle defines a gauge only; + # it is not an encoder/URDF zero measurement. + for phase in (0, 1): + self.pose_offsets[phase] = len(scale) + scale.extend([1.]*3+[.03]*3) + anchors.add(int(np.flatnonzero(self.phases == phase)[0])) + self.tag_scale_column = None + if estimate_tag_scale: + if len(self.distances) != 2: + raise ValueError('finger_chain_scale_requires_two_structural_lengths') + self.tag_scale_column = len(scale) + scale.append(.03) + self.static_width = len(scale) + self.angle_columns = {} + for i in range(self.count): + if i not in anchors: + self.angle_columns[i] = len(scale) + scale.append(1.) + self.scale = np.asarray(scale) + self.matrix = np.asarray(rows[0]['camera_matrix']) + sizes = [rows[0]['tags'][role]['tag_size_m'] for role in roles] + self.pixels = np.asarray([[r['tags'][role]['corners_xy'] for role in roles] for r in rows]) + if (len(roles) != 2 or self.pixels.shape != (self.count, 2, 4, 2) + or not np.all(np.isfinite(self.pixels)) + or any(not np.array_equal(r['camera_matrix'], self.matrix) for r in rows) + or any(r['tags'][role]['tag_size_m'] != size + for r in rows for role, size in zip(roles, sizes))): + raise ValueError('finger_chain_image_contract_changed') + self.objects = np.asarray([square_object_points(size) for size in sizes]) + self.candidates = tuple(tuple(tuple(p for p in solve_square_tag_ippe( + self.pixels[i, j], tag_size_m=sizes[j], camera_matrix=self.matrix) + if p.reprojection_error_px <= 1.5) for j in range(2)) for i in range(self.count)) + if any(not candidates for pair in self.candidates for candidates in pair): + raise ValueError('finger_chain_raw_candidates_missing') + + def initialize(self, branches): + # All six phase/tag IPPE combinations are independently seeded (64). + poses = [tuple(pair[j][min(branches[2*phase+j], len(pair[j])-1)] for j in range(2)) + for phase, pair in zip(self.phases, self.candidates)] + zero_index = int(np.flatnonzero(self.phases == 2)[0]) + from .rigid_tag_pair import _pose_vector + initial = np.zeros(len(self.scale)) + initial[:6] = _pose_vector(poses[zero_index][0]) + held_pairs = [_relative_pose(*pair) for phase, pair in zip(self.phases, poses) if phase < 2] + reference = Rotation.from_quat([rotation.as_quat() for rotation, _ in held_pairs]).mean() + origin = np.mean([point for _, point in held_pairs], axis=0) + initial[6:12] = np.r_[reference.as_rotvec(), origin] + self.axes, self.bases = [], [] + self.signs = {} + for phase in range(3): + indices = np.flatnonzero(self.phases == phase) + pose_offset = self.pose_offsets[phase] + if pose_offset: + initial[pose_offset:pose_offset+6] = _pose_vector(poses[indices[0]][0]) + parent = Rotation.from_rotvec(initial[pose_offset:pose_offset+3]) + if phase == 2: + relative = [_relative_pose(*poses[i]) for i in indices] + rotations = Rotation.from_quat([r.as_quat() for r, _ in relative]) + points = np.asarray([t for _, t in relative]) + zero_rotation, zero_point = reference, origin + center = np.zeros(3) + else: + vectors = np.asarray([_pose_vector(poses[i][0]) for i in indices]) + rotations, points = Rotation.from_rotvec(vectors[:, :3]), vectors[:, 3:] + zero_rotation, zero_point = parent, initial[pose_offset+3:pose_offset+6] + center = zero_point + axis, _ = _axis(rotations) + basis = _basis(axis) + angles = (rotations*zero_rotation.inv()).as_rotvec()@axis + for i, angle in zip(indices, angles): + if i in self.angle_columns: + initial[self.angle_columns[i]] = angle + matrices = Rotation.from_rotvec(angles[:, None]*axis).as_matrix() + blocks = np.einsum('nij,jk->nik', np.eye(3)-matrices, basis) + targets = points-center-np.einsum('nij,j->ni', matrices, zero_point-center) + point = basis@np.linalg.lstsq( + blocks.reshape(-1, 2), targets.ravel(), rcond=None)[0] + if phase < 2: + axis, point = parent.inv().apply(axis), parent.inv().apply(point) + self.axes.append(axis) + self.bases.append(_basis(axis)) + offset = self.offsets[phase] + if phase in self.distances: + previous_axis, previous_point, tangent = self._geometry_frame(initial, phase-1) + self.signs[phase] = 1 if previous_axis@axis >= 0 else -1 + vector = point-previous_point + initial[offset] = np.arctan2(vector@tangent[:, 1], vector@tangent[:, 0]) + else: + initial[offset+2:offset+4] = self.bases[phase].T@point + return initial + + def geometry(self, shared, phase): + axis, pivot, _ = self._geometry_frame(shared, phase) + return axis, pivot + + def _geometry_frame(self, shared, phase): + offset = self.offsets[phase] + if phase in self.distances: + axis, center, tangent = self._geometry_frame(shared, phase-1) + pivot = center+self.distances[phase]*(tangent@[ + np.cos(shared[offset]), np.sin(shared[offset])]) + axis = self.signs[phase]*axis + return axis, pivot-axis*(axis@pivot), tangent + change = Rotation.from_rotvec(self.bases[phase]@shared[offset:offset+2]) + axis = change.apply(self.axes[phase]) + tangent = change.as_matrix()@self.bases[phase] + return axis, tangent@shared[offset+2:offset+4], tangent + + def project(self, shared, angles, phases): + size_scale = 1. if self.tag_scale_column is None else np.exp(shared[self.tag_scale_column]) + child_local = Rotation.from_rotvec(shared[6:9]).apply(self.objects[1]*size_scale)+shared[9:12] + zero_points = np.concatenate((self.objects[0]*size_scale, child_local)) + points = np.broadcast_to(zero_points, (len(angles), 8, 3)).copy() + camera = np.empty_like(points) + for phase in range(3): + mask = phases == phase + if not np.any(mask): + continue + axis, pivot = self.geometry(shared, phase) + motion = Rotation.from_rotvec(angles[mask, None]*axis).as_matrix() + if phase < 2: + points[mask] = np.einsum('nij,kj->nki', motion, zero_points-pivot)+pivot + else: + children = np.einsum('nij,kj->nki', motion, child_local-pivot)+pivot + points[mask, 4:] = children + pose_offset = self.pose_offsets[phase] + parent = Rotation.from_rotvec(shared[pose_offset:pose_offset+3]) + camera[mask] = points[mask]@parent.as_matrix().T+shared[pose_offset+3:pose_offset+6] + if np.any(camera[:, :, 2] <= 1e-6): + return np.full((len(angles), 8, 2), 1e6) + projected = camera@self.matrix.T + return projected[:, :, :2]/projected[:, :, 2:] + + def residual(self, parameters): + angles = np.zeros(self.count) + for i, column in self.angle_columns.items(): + angles[i] = parameters[column] + return (self.project(parameters[:self.static_width], angles, self.phases) + -self.pixels.reshape(-1, 8, 2)).ravel() + + def fit(self, branches): + initial = self.initialize(branches) + columns = getattr(self, 'optimization_columns', np.arange(len(initial))) + def unpack(values): + parameters = initial.copy() + parameters[columns] = values + return parameters + jacobian = getattr(self, 'solver_jacobian', getattr(self, 'jacobian', '2-point')) + options = dict(getattr(self, 'solver_options', {})) + if 'bounds' in options: + options['bounds'] = tuple(np.broadcast_to(bound, initial.shape)[columns] + for bound in options['bounds']) + # Small shared graph: exact solver avoids LSMR conditioning ambiguity. + result = least_squares(lambda values: self.residual(unpack(values)), initial[columns], + x_scale=self.scale[columns], + jac=(lambda values: jacobian(unpack(values))[:, columns]) if callable(jacobian) else jacobian, + **options, + max_nfev=getattr(self, 'maximum_joint_evaluations', 200), + ftol=getattr(self, 'solver_ftol', 1e-9), xtol=1e-9, gtol=1e-7) + result.x = unpack(result.x) + if len(columns) != len(initial): + # Consumers use the stable semantic layout, not optimizer indices. + result.jac = jacobian(result.x) + result.initialization_evaluations = getattr(self, '_initialization_costs', {}).get(tuple(branches), 0) + return result + + def physical_geometry(self, shared): + """Axes and closest-to-tag4-origin pivot points in common tag4 frame.""" + values = [] + for phase in range(3): + axis, pivot = self.geometry(shared, phase) + pivot = pivot-axis*np.dot(axis, pivot) + values.append(np.r_[axis, pivot]) + return np.asarray(values) + + def covariance(self, fit): + jac = np.asarray(fit.jac)*self.scale[None, :] + width = self.static_width + information = np.zeros((width, width)) + for i in range(self.count): + shared = jac[16*i:16*i+16, :width] + projected = shared + if i in self.angle_columns: + angle = jac[16*i:16*i+16, self.angle_columns[i]] + norm = np.linalg.norm(angle) + if norm < 1e-10: + raise ValueError('finger_chain_angle_unobservable') + unit = angle/norm + projected = shared-np.outer(unit, unit@shared) + information += projected.T@projected + eigen = np.linalg.eigvalsh(information) + if eigen[0] <= eigen[-1]*np.finfo(float).eps*width: + raise ValueError('finger_chain_geometry_rank_deficient') + variance = max(.03**2, float(fit.fun@fit.fun/(len(fit.fun)-len(fit.x)))) + return np.linalg.inv(information)*variance*self.scale[:width, None]*self.scale[None, :width] + + def bounds(self, fit): + covariance = self.covariance(fit) + width = self.static_width + derivative = np.zeros((18, width)) + for column in range(width): + step = 1e-5*self.scale[column] + upper, lower = fit.x[:width].copy(), fit.x[:width].copy() + upper[column] += step + lower[column] -= step + derivative[:, column] = (self.physical_geometry(upper) + -self.physical_geometry(lower)).ravel()/(2*step) + propagated = derivative@covariance@derivative.T + return np.asarray([[3*np.sqrt(max(0., np.linalg.eigvalsh( + propagated[i:i+3, i:i+3])[-1])) for i in (6*phase, 6*phase+3)] + for phase in range(3)]) + + def validate(self, fit, other): + # Only angle is fitted; zero poses, installations and all axes stay frozen. + self._check_validation_geometry(other) + residuals, angles = [], [] + for phase, pixels in zip(other.phases, other.pixels): + alternatives = [] + for seed in (-np.pi/2, 0., np.pi/2): + result = least_squares(lambda x: (self.project(fit.x[:self.static_width], x, + np.array([phase]))[0]-pixels.reshape(8, 2)).ravel(), [seed], + max_nfev=80, ftol=1e-9, xtol=1e-9, gtol=1e-7) + if not result.success or not np.all(np.isfinite(result.fun)): + raise ValueError('finger_chain_validation_not_evaluable') + alternatives.append(result) + best = min(alternatives, key=lambda r: r.cost) + residuals.append(best.fun) + angles.append(float(best.x[0])) + return np.asarray(residuals), continuous_phase_angles(angles, other.phases) + + def _check_validation_geometry(self, other): + if (self.roles != other.roles or not np.array_equal(self.matrix, other.matrix) + or not np.array_equal(self.objects, other.objects)): + raise ValueError('finger_chain_validation_geometry_changed') + + def validation_angle_covariance(self, fit, other, angles): + """Propagate frozen training geometry into independent image angles. + + The validation pixels never update the shared parameters. The first + term is conditional image noise; the second includes correlated + installation, stage-reference and axis uncertainty from training. + This is a local, model-conditional covariance, NOT branch certainty. + """ + self._check_validation_geometry(other) + if {r['image_stamp_ns'] for r in self.rows} & { + r['image_stamp_ns'] for r in other.rows}: + raise ValueError('finger_chain_angle_covariance_requires_independent_images') + angles = np.asarray(angles, dtype=float) + if angles.shape != (other.count,) or not np.all(np.isfinite(angles)): + raise ValueError('finger_chain_validation_angles_invalid') + shared = fit.x[:self.static_width] + step = 1e-5 + angle_jacobian = ((self.project(shared, angles+step, other.phases) + -self.project(shared, angles-step, other.phases))/(2*step)).reshape(other.count, 16) + information = np.sum(angle_jacobian**2, axis=1) + if np.any(information <= 1e-10) or not np.all(np.isfinite(information)): + raise ValueError('finger_chain_validation_angle_unobservable') + sensitivity = np.empty((other.count, self.static_width)) + for column in range(self.static_width): + delta = step*self.scale[column] + upper, lower = shared.copy(), shared.copy() + upper[column] += delta + lower[column] -= delta + derivative = ((self.project(upper, angles, other.phases) + -self.project(lower, angles, other.phases))/(2*delta)).reshape(other.count, 16) + sensitivity[:, column] = -np.sum(angle_jacobian*derivative, axis=1)/information + variance = max(.03**2, float(fit.fun@fit.fun/(len(fit.fun)-len(fit.x)))) + return (np.diag(variance/information) + +sensitivity@self.covariance(fit)@sensitivity.T) + + +def continuous_phase_angles(angles, phases): + """Remove equivalent 2π optimizer wraps before angular-stratum comparisons.""" + angles, phases = np.asarray(angles), np.asarray(phases) + result = np.arctan2(np.sin(angles), np.cos(angles)) + for phase in np.unique(phases): + mask = phases == phase + result[mask] = np.unwrap(result[mask]) + return result + + +def chain_candidate_seeds(): + """Full Cartesian phase/tag IPPE seed enumeration, not global optimality proof.""" + return product(range(2), repeat=6) + + +def compare_chain_output_angles(reference_geometry, reference_angles, + alternative_geometry, alternative_angles, phases): + """Compare same-image angles, removing ONLY axis sign and integral turns. + + Do not subtract an arbitrary zero offset: a different calibrated zero is + a real output difference. Inputs must already share a physical tag frame. + This diagnostic neither selects nor excludes any image-model candidate. + """ + first, second = np.asarray(reference_geometry), np.asarray(alternative_geometry) + phases = np.asarray(phases) + if (first.shape != (3, 6) or second.shape != (3, 6) + or not np.all(np.isfinite(first)) or not np.all(np.isfinite(second)) + or phases.ndim != 1 or set(phases) != {0, 1, 2} + or not np.allclose(np.linalg.norm(first[:, :3], axis=1), 1.) + or not np.allclose(np.linalg.norm(second[:, :3], axis=1), 1.)): + raise ValueError('finger_chain_output_comparison_invalid') + angles = [np.asarray(values, dtype=float) for values in (reference_angles, alternative_angles)] + if any(values.shape != phases.shape or not np.all(np.isfinite(values)) for values in angles): + raise ValueError('finger_chain_output_comparison_invalid') + left, right = [continuous_phase_angles(values, phases) for values in angles] + differences = np.empty_like(left) + for phase in range(3): + mask = phases == phase + dot = first[phase, :3]@second[phase, :3] + if abs(dot) < 1e-8: + raise ValueError('finger_chain_axis_sign_unresolved') + signed = right[mask]*(1 if dot > 0 else -1) + turns = np.round(np.mean(signed-left[mask])/(2*np.pi)) + differences[mask] = signed-left[mask]-2*np.pi*turns + return differences diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/fixed_reference.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/fixed_reference.py new file mode 100644 index 0000000..4ecc8f0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/fixed_reference.py @@ -0,0 +1,11 @@ +"""An immutable camera-local pose for a declared stationary reference Tag.""" + +from dataclasses import dataclass + +from .types import SquareTagPose + + +@dataclass(frozen=True) +class FixedTagReference: + pose: SquareTagPose + branch_revision: int diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/frozen_chain_validation.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/frozen_chain_validation.py new file mode 100644 index 0000000..bcf1f7e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/frozen_chain_validation.py @@ -0,0 +1,148 @@ +"""Frozen command-to-image checks for a jointly fitted finger. + +No inverse-angle fit, PnP selection or parameter update is performed here. +This is one acceptance component, not authority to publish a calibration: +physical zero provenance and the candidate/uncertainty union remain separate. +""" +from copy import deepcopy +from dataclasses import dataclass + +import numpy as np + +from ...domain.result import JointMapping + + +def _image_identity(row): + view, stamp = row.get('view'), row.get('image_stamp_ns') + if (not isinstance(view, str) or not view or type(stamp) is not int or stamp <= 0): + raise ValueError('frozen_chain_image_identity_invalid') + return view, stamp + + +@dataclass(frozen=True) +class FrozenChainImageErrors: + image_ids: tuple + predicted_angles_rad: tuple[float, ...] + # Radial RMS over four corners, independently for each of the two tags. + tag_rms_px: tuple[tuple[float, float], ...] + + +class FrozenChainCommands: + """Snapshot a fitted chain and existing directional SDK mappings. + + reference_angles translate each mapping's physical coordinate into the + fitted image model's numerical gauge. They must be bound to measured + training references by the caller, never estimated from validation images. + dependency_images must include mapping, zero and candidate-selection data, + in addition to the geometric training images already carried by bundle. + """ + + def __init__(self, bundle, shared, mappings, reference_angles, task_keys, *, + dependency_images, training_cycles=(0, 1), holdout_cycle=3): + mappings, task_keys = tuple(mappings), tuple(task_keys) + reference_angles = np.asarray(reference_angles, dtype=float) + shared = np.asarray(shared, dtype=float) + if (len(mappings) != 3 or len(task_keys) != 3 or len(set(task_keys)) != 3 + or any(not isinstance(key, str) or not key for key in task_keys) + or any(not isinstance(mapping, JointMapping) or mapping.input_domain != 'command_u8' + for mapping in mappings) + or len({mapping.motor_index for mapping in mappings}) != 3 + or len({mapping.joint for mapping in mappings}) != 3 + or reference_angles.shape != (3,) or not np.all(np.isfinite(reference_angles)) + or shared.shape != (bundle.static_width,) or not np.all(np.isfinite(shared))): + raise ValueError('frozen_chain_contract_invalid') + if (not training_cycles or len(set(training_cycles)) != len(training_cycles) + or any(type(cycle) is not int or cycle < 0 for cycle in training_cycles) + or type(holdout_cycle) is not int or holdout_cycle <= max(training_cycles)): + raise ValueError('frozen_chain_cycle_partition_invalid') + self._bundle = deepcopy(bundle) + self._shared = shared.copy() + self._mappings = deepcopy(mappings) + self._references = reference_angles.copy() + self._tasks = task_keys + self._holdout = holdout_cycle + self._used = {_image_identity(row) for row in dependency_images} + self._held = {} + self._views = {} + for row, phase in zip(bundle.rows, bundle.phases): + if (type(row.get('cycle')) is not int or row['cycle'] not in training_cycles + or row.get('task_name') != task_keys[phase]): + raise ValueError('frozen_chain_training_partition_invalid') + self._used.add(_image_identity(row)) + if phase in self._views and self._views[phase] != row['view']: + raise ValueError('frozen_chain_training_view_changed') + self._views[phase] = row['view'] + command = self._command_vector(row) + channel = mappings[phase].motor_index + if channel >= len(command): + raise ValueError('frozen_chain_channel_invalid') + held = command.copy() + held[channel] = 0. + if phase in self._held and not np.array_equal(self._held[phase], held): + raise ValueError('frozen_chain_training_held_commands_changed') + self._held[phase] = held + + @staticmethod + def _command_vector(row): + command = np.asarray(row.get('command_vector'), dtype=float) + if (command.ndim != 1 or not len(command) or not np.all(np.isfinite(command)) + or np.any(command < 0) or np.any(command > 255) + or not np.all(command == np.rint(command))): + raise ValueError('frozen_chain_wire_command_invalid') + return command.copy() + + def evaluate(self, rows): + """Evaluate independent steady images; every pixel remains a residual. + + Requires both directions of all three phases. The full declared knot + coverage and sample counts must additionally pass the production + command-sampling contract; this method never substitutes for it. + """ + rows = tuple(rows) + identities = tuple(_image_identity(row) for row in rows) + if not rows or len(set(identities)) != len(rows) or self._used.intersection(identities): + raise ValueError('frozen_chain_holdout_images_not_independent') + angles, phases, observed, directions = [], [], [], set() + for row in rows: + if (type(row.get('cycle')) is not int or row['cycle'] != self._holdout + or row.get('sample_phase') != 'steady'): + raise ValueError('frozen_chain_requires_independent_steady_cycle') + if row.get('task_name') not in self._tasks or row.get('direction') not in ('increasing', 'decreasing'): + raise ValueError('frozen_chain_holdout_task_or_direction_invalid') + phase = self._tasks.index(row['task_name']) + if row['view'] != self._views[phase]: + raise ValueError('frozen_chain_view_changed') + mapping = self._mappings[phase] + command = self._command_vector(row) + if command.shape != self._held[phase].shape: + raise ValueError('frozen_chain_command_shape_changed') + value = command[mapping.motor_index] + target = row.get('steady_target') + if (isinstance(target, bool) or not isinstance(target, (float, int)) + or not np.isfinite(target) or value != target): + raise ValueError('frozen_chain_steady_target_changed') + command[mapping.motor_index] = 0. + if not np.array_equal(command, self._held[phase]): + raise ValueError('frozen_chain_holdout_held_commands_changed') + if not np.array_equal(row.get('camera_matrix'), self._bundle.matrix): + raise ValueError('frozen_chain_camera_changed') + pixels = [] + for role in self._bundle.roles: + tag = row.get('tags', {}).get(role, {}) + if tag.get('tag_size_m') != self._bundle.rows[0]['tags'][role]['tag_size_m']: + raise ValueError('frozen_chain_tag_geometry_changed') + corners = np.asarray(tag.get('corners_xy'), dtype=float) + if corners.shape != (4, 2) or not np.all(np.isfinite(corners)): + raise ValueError('frozen_chain_holdout_pixels_invalid') + pixels.extend(corners) + angles.append(mapping.evaluate(float(value), row['direction'])+self._references[phase]) + phases.append(phase) + observed.append(pixels) + directions.add((phase, row['direction'])) + if directions != {(phase, direction) for phase in range(3) + for direction in ('increasing', 'decreasing')}: + raise ValueError('frozen_chain_holdout_directions_missing') + predicted = self._bundle.project(self._shared, np.asarray(angles), np.asarray(phases)) + error = (predicted-np.asarray(observed)).reshape(-1, 2, 4, 2) + rms = np.sqrt(np.mean(np.sum(error**2, axis=3), axis=2)) + return FrozenChainImageErrors(identities, tuple(angles), tuple(map(tuple, rms))) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/hinge_uncertainty.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/hinge_uncertainty.py new file mode 100644 index 0000000..6918b33 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/hinge_uncertainty.py @@ -0,0 +1,102 @@ +"""Local image-fit uncertainty in both parent and physical child-Tag frames.""" + +import numpy as np + + +def unconstrained_hinge_linearization(bundle, fit, angles): + """Restore full identifiable geometry at identical pixels, without refitting.""" + from scipy.optimize import least_squares + from scipy.spatial.transform import Rotation + from .motion_image_solver import ImageHingeBundle, _basis + + free = ImageHingeBundle(bundle.frames, bundle.relations, bundle.poses) + parameters = [] + for index in range(bundle.joints): + axis, reference, pivot, mount = bundle.geometry_values(fit.x, index) + free.axes[index], free.bases[index] = axis, _basis(axis) + free.references[index] = Rotation.from_rotvec(axis*angles[0, index])*reference + parameters.extend((0., 0., 0., 0., 0., *(free.bases[index].T @ pivot), *mount)) + parameters = np.r_[parameters, (angles[1:]-angles[0]).ravel()] + linearization = least_squares(free.residual, parameters, jac="3-point", + x_scale=free.scale, max_nfev=1) + return free, linearization + + +def image_fit_covariance(bundle, fit): + """Full joint covariance, including every nuisance image angle.""" + jacobian = fit.jac.toarray() if hasattr(fit.jac, "toarray") else np.asarray(fit.jac) + scaled = jacobian * bundle.scale[None, :] + _, singular, vh = np.linalg.svd(scaled, full_matrices=False) + if singular[-1] <= singular[0] * np.finfo(float).eps * max(scaled.shape): + raise ValueError("image_motion_geometry_rank_deficient") + variance = max(.03 ** 2, float(np.sum(fit.fun ** 2) / max(1, len(fit.fun) - len(fit.x)))) + covariance = ((vh.T / singular ** 2) @ vh * variance) * bundle.scale[:, None] * bundle.scale[None, :] + return covariance + + +def preparation_pose_uncertainty(bundle, fit): + """Conservative pose bounds for an independent, single-hinge witness. + + Keep the full geometry/angle covariance. Repeated endpoint images do not + earn a sqrt(N) reduction; report the worst bound over training images. + """ + from scipy.spatial.transform import Rotation + from .motion_image_solver import ImageHingeBundle + if type(bundle) is not ImageHingeBundle or bundle.joints != 1: + raise ValueError("preparation_witness_uncertainty_graph_unsupported") + covariance = image_fit_covariance(bundle, fit) + angles = np.r_[0., fit.x[10:]] + def poses(parameters): + axis, reference, pivot, mount = bundle.geometry_values(parameters, 0) + rotations = Rotation.from_rotvec(np.r_[0., parameters[10:]][:, None]*axis)*reference + return rotations, pivot+rotations.apply(mount) + rotations, _ = poses(fit.x) + derivative = np.zeros((len(angles), 6, len(fit.x))) + for column in range(len(fit.x)): + step = 1e-5*bundle.scale[column] + upper, lower = fit.x.copy(), fit.x.copy() + upper[column] += step + lower[column] -= step + ru, tu = poses(upper) + rl, tl = poses(lower) + derivative[:, :3, column] = ((ru*rotations.inv()).as_rotvec() + -(rl*rotations.inv()).as_rotvec())/(2*step) + derivative[:, 3:, column] = (tu-tl)/(2*step) + propagated = derivative @ covariance @ np.swapaxes(derivative, 1, 2) + return tuple(float(3*np.sqrt(max(0., np.max(np.linalg.eigvalsh( + propagated[:, i:i+3, i:i+3]))))) for i in (0, 3)) + + +def hinge_uncertainty(bundle, fit): + if hasattr(bundle, "uncertainty_problem"): + bundle, fit = bundle.uncertainty_problem(fit) + covariance = image_fit_covariance(bundle, fit) + axes, pivots, child_bounds = [], [], [] + + def coordinates(parameters, index): + axis, reference, pivot, mount = bundle.geometry_values(parameters, index) + child_axis = reference.inv().apply(axis) + # Closest point on the axis in the Tag frame; independent of axial + # pivot gauge, joint angle, and the upstream holding posture. + child_point = -mount + child_axis * (child_axis @ mount) + return np.r_[axis, pivot, child_axis, child_point] + + for index, relation in enumerate(bundle.relations): + derivative = np.zeros((12, len(fit.x))) + for column in bundle.geometry_dependency_indices(index): + step = 1e-5 * bundle.scale[column] + upper, lower = fit.x.copy(), fit.x.copy() + upper[column] += step + lower[column] -= step + derivative[:, column] = (coordinates(upper, index) - coordinates(lower, index)) / (2 * step) + propagated = derivative @ covariance @ derivative.T + bounds = [float(3 * np.sqrt(max(0., np.linalg.eigvalsh(propagated[i:i+3, i:i+3])[-1]))) + for i in (0, 3, 6, 9)] + # A transferred parent is measured, not exact CAD. Keep conservative + # inherited bounds explicit instead of reporting zero axis uncertainty + # merely because that axis was removed from the child optimization. + inherited = bundle.inherited_uncertainty(index) if hasattr(bundle, "inherited_uncertainty") else (0., 0.) + axes.append((relation.joint, bounds[0] + inherited[0])) + pivots.append((relation.joint, bounds[1] + inherited[1])) + child_bounds.append((relation.joint, bounds[2] + inherited[0], bounds[3] + inherited[1])) + return tuple(axes), tuple(pivots), tuple(child_bounds) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_bundle_optimizer.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_bundle_optimizer.py new file mode 100644 index 0000000..066bb20 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_bundle_optimizer.py @@ -0,0 +1,70 @@ +"""Bounded training-only recovery for articulated image bundle fits. + +Sparse LSMR steps are fast, but may stagnate near an active bound. Only a +finite, budget-exhausted fit gets one warm start using the exact dense trust +region solver. Neither holdout images nor another candidate select that retry. +""" + +from dataclasses import dataclass + +import numpy as np +from scipy.optimize import least_squares + +IMAGE_BUNDLE_SOLVER_POLICY = "sparse_then_bounded_exact_v1" +# Covers all six relations / 72 training frames of the production defaults, +# including the simultaneous four-finger yaw task, without unbounded storage. +MAXIMUM_DENSE_PARAMETERS = 512 +MAXIMUM_DENSE_JACOBIAN_ENTRIES = 2_000_000 + + +@dataclass(frozen=True) +class ImageSolverAttempt: + backend: str + budget: int + evaluations: int + status: int + cost: float | None + optimality: float | None + + +def _attempt(backend, budget, fit): + def finite(value): + return float(value) if np.isfinite(value) else None + return ImageSolverAttempt(backend, budget, int(fit.nfev), int(fit.status), + finite(fit.cost), finite(fit.optimality)) + + +def _finite_fit(fit): + return (np.all(np.isfinite(fit.x)) and np.all(np.isfinite(fit.fun)) + and np.isfinite(fit.cost) and np.isfinite(fit.optimality)) + + +def solve_image_bundle(residual, initial, *, sparsity, scale, limits, bounds=(-np.inf, np.inf)): + """At most two solves, with unchanged residuals, bounds and tolerances. + +Already-converged historical fits retain the original numerical path. Large +graphs remain bounded in memory and fail closed if the sparse solve fails. +Worker cancellation/timeout still owns the outer wall-clock limit. +""" + options = dict(bounds=bounds, x_scale=scale, ftol=1e-9, xtol=1e-9, gtol=1e-7) + fit = least_squares(residual, initial, jac_sparsity=sparsity, + max_nfev=limits.maximum_solver_evaluations, + tr_options={"atol": 1e-10, "btol": 1e-10}, **options) + attempts = [_attempt("sparse_lsmr", limits.maximum_solver_evaluations, fit)] + # Offline diagnostic limits predate production recovery and retain their + # explicit single-solve budget. + budget = getattr(limits, "maximum_solver_recovery_evaluations", 0) + if (fit.status == 0 and budget > 0 and _finite_fit(fit) + and len(fit.x) <= MAXIMUM_DENSE_PARAMETERS + and len(fit.x)*len(fit.fun) <= MAXIMUM_DENSE_JACOBIAN_ENTRIES): + try: + recovered = least_squares(residual, fit.x.copy(), tr_solver="exact", + max_nfev=budget, **options) + attempts.append(_attempt("dense_exact", budget, recovered)) + # A failed or worse retry cannot manufacture convergence. + if _finite_fit(recovered) and recovered.cost <= fit.cost: + fit = recovered + except (ValueError, FloatingPointError, np.linalg.LinAlgError): + attempts.append(ImageSolverAttempt("dense_exact", budget, 0, -1, None, None)) + fit.image_solver_attempts = tuple(attempts) + return fit diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_model_selection.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_model_selection.py new file mode 100644 index 0000000..fb2a29b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_model_selection.py @@ -0,0 +1,90 @@ +"""Training-only model choice and held-out, motion-stratified comparisons. + +All comparisons use squared image loss, matching the geometry optimizer. +Holm step-down controls the nominal familywise level for the complete set of +comparisons. These are conditional image tests, not a calibration certificate. +""" +import math + +import numpy as np +from scipy.stats import ttest_1samp, wilcoxon + +from .motion_evidence import MotionEvidenceParameters, _equivalent + +IMAGE_MODEL_SELECTION_POLICY = "training_squared_loss_holm_v1" + + +def training_candidate_index(hypotheses): + """Never replace a training-selected model because of validation scores.""" + eligible = [i for i, hypothesis in enumerate(hypotheses) if hypothesis.training_accepted] + if not eligible: + return None + return min(eligible, key=lambda i: float(np.mean( + [quality.rms_px ** 2 for quality in hypotheses[i].training_quality]))) + + +def equivalent_frame_selections(first, second): + if not first.resolved or not second.resolved: + return False + left = {selection.role: selection.pose for selection in first.selections} + right = {selection.role: selection.pose for selection in second.selections} + return bool(left and len(left) == len(first.selections) and len(right) == len(second.selections) + and left.keys() == right.keys() + and all(_equivalent(pose, right[role]) for role, pose in left.items())) + + +def compare_image_losses(best, alternative, angles, tolerance): + """Compare paired squared errors with the existing pixel-resolution margin. + + One observation per angular stratum prevents repeated images inflating + evidence. Medians and both mean/rank tests prevent an isolated large error + from deciding a branch. The candidate is selected on training images only. + """ + angles = np.asarray(angles, dtype=float) + best, alternative = np.asarray(best, dtype=float), np.asarray(alternative, dtype=float) + if (angles.ndim != 2 or not angles.shape[1] or best.ndim != 1 + or len(best) != len(angles) or alternative.shape != best.shape or not len(best) + or not np.all(np.isfinite(angles)) or not np.all(np.isfinite(best)) + or not np.all(np.isfinite(alternative)) or np.any(best < 0) or np.any(alternative < 0) + or not math.isfinite(tolerance) or tolerance < 0): + return 1. + moving = int(np.argmax(np.ptp(angles, axis=0))) + values = angles[:, moving] + span = float(np.ptp(values)) + parameters = MotionEvidenceParameters() + count = min(24, int(np.floor(span / parameters.angular_bin_rad))) + if count < parameters.minimum_motion_bins: + return 1. + indices = np.minimum(count - 1, np.floor((values - min(values)) / span * count).astype(int)) + losses = alternative ** 2 - (best + tolerance) ** 2 + differences = np.asarray([float(np.median(losses[indices == index])) + for index in range(count) if np.any(indices == index)]) + if (len(differences) < parameters.minimum_motion_bins + or not np.all(np.isfinite(differences)) or np.mean(differences) <= 0): + return 1. + if np.ptp(differences) < 1e-12: + return 2. ** -len(differences) if differences[0] > 0 else 1. + mean_probability = float(ttest_1samp(differences, 0., alternative="greater").pvalue) + rank_probability = float(wilcoxon(differences, alternative="greater", zero_method="wilcox").pvalue) + if not math.isfinite(mean_probability) or not math.isfinite(rank_probability): + return 1. + return max(mean_probability, rank_probability) + + +def holm_adjusted_probabilities(comparisons): + """Order-independent Holm probabilities, returned in input identity order. + + A geometric equivalence check may supply zero. It is still included in the + family; no candidate is omitted merely because of its initialization label. + Nonfinite or invalid probabilities fail closed. + """ + comparisons = tuple(comparisons) + if len({index for index, _ in comparisons}) != len(comparisons): + raise ValueError("duplicate_image_model_comparison") + values = [(index, probability if math.isfinite(probability) and 0 <= probability <= 1 else 1.) + for index, probability in comparisons] + adjusted, previous = {}, 0. + for rank, (index, probability) in enumerate(sorted(values, key=lambda item: item[1])): + previous = max(previous, min(1., probability * (len(values) - rank))) + adjusted[index] = previous + return tuple((index, adjusted[index]) for index, _ in comparisons) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_commit.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_commit.py new file mode 100644 index 0000000..1ff71f8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_commit.py @@ -0,0 +1,166 @@ +"""Bind one image solve to versioned tracker inputs, then commit it once. + +The numerical solve runs without tracker locks. Immutable tracker-owned pixels +and frozen root snapshots prevent callers substituting observations; a weak +identity registry prevents copied or manually assembled decisions being used as +commit authority. All tracker locks are acquired only for metadata checks. +""" +from __future__ import annotations + +from contextlib import ExitStack +from collections.abc import Mapping, Sequence +from ..frozen_evidence import image_model_evidence + +from dataclasses import dataclass +import hashlib +import json +from threading import RLock +from weakref import WeakValueDictionary +from typing import TYPE_CHECKING + +from .image_motion_model import ImageMotionModel +from .image_reference import ImageReferenceSnapshot +from .image_motion_projection import select_image_motion_frame +from .image_projection_worker import ImageProjectionWorker +from .motion_image_types import ImageMotionFrame, ImageRoleQuality + +if TYPE_CHECKING: + from .tracking import MotionFrameCommit, MotionPoseSelection, MotionTrackerSnapshot + + +@dataclass(frozen=True) +class VerifiedImageMotionDecision: + accepted: bool + reason: str + selections: tuple[MotionPoseSelection, ...] = () + root_snapshots: tuple[MotionTrackerSnapshot | ImageReferenceSnapshot, ...] = () + model: ImageMotionModel | None = None + model_sha256: str = "" + quality: tuple[ImageRoleQuality, ...] = () + + +_verified = WeakValueDictionary() +_registry_lock = RLock() + + +def _root_current(snapshot): + if isinstance(snapshot, ImageReferenceSnapshot): + return snapshot.tracker.snapshot_current(snapshot) + tracker, role = snapshot.tracker, snapshot.role + state = tracker._branches.states.get(role) + diagnostics = tracker.last_candidate_diagnostics_by_role.get(role, {}) + evidence_verified = (diagnostics.get("motion_selection_committed") is True and snapshot.evidence_id is not None + if snapshot.motion_managed else diagnostics.get("fixed_reference_verified") is True) + return (tracker._epoch == snapshot.epoch and state is not None + and state.observed_ns == snapshot.stamp_ns and state.revision == snapshot.revision + and state.frozen and snapshot.frozen and state.status == "tracking" + and state.pose == snapshot.previous_pose and evidence_verified + and not state.conflict and not state.recovery_required + and tracker._image_observations_by_role.get(role) is snapshot.image_observation) + + +def _inputs_match(snapshots, roots, model, frame): + items = {r.role: r for r in frame.evidence.roles} + observations = {o.role: o for o in frame.observations} + if len(items) != len(frame.evidence.roles) or len(observations) != len(frame.observations): + return False + for snapshot in (*snapshots, *roots): + image = snapshot.image_observation + item, observation = items.get(snapshot.role), observations.get(snapshot.role) + if (image is None or item is None or observation is None + or snapshot.stamp_ns != frame.evidence.stamp_ns or image.stamp_ns != snapshot.stamp_ns + or image.camera_matrix != model.camera_matrix or image.camera_matrix != frame.camera_matrix + or image.tag_size_m != observation.tag_size_m or image.corners_xy != observation.corners_xy): + return False + if snapshot in roots: + if not item.frozen or item.candidates != (snapshot.previous_pose,): + return False + elif item.frozen or item.candidates != snapshot.candidates: + return False + return True + + +def verify_image_motion_frame(snapshots: Sequence[MotionTrackerSnapshot], model: ImageMotionModel, + frame: ImageMotionFrame, evidence_ids: Mapping[str, str], *, + root_snapshots: Sequence[MotionTrackerSnapshot | ImageReferenceSnapshot] = (), + projection_worker=None) -> VerifiedImageMotionDecision: + """Calculate a decision once; never accept caller-proposed output poses.""" + from .tracking import MotionPoseSelection, SquareTagPoseTracker + if projection_worker is not None and type(projection_worker) is not ImageProjectionWorker: + return VerifiedImageMotionDecision(False, "pose_image_motion_worker_invalid") + snapshots, roots = tuple(snapshots), tuple(root_snapshots) + if not isinstance(model, ImageMotionModel) or not snapshots: + return VerifiedImageMotionDecision(False, "pose_image_motion_inputs_invalid") + child_roles = {g.relation.child_role for g in model.geometry} + root_roles = set(dict(model.tag_sizes)) - child_roles + if (set(evidence_ids) != child_roles or {s.role for s in snapshots} != child_roles + or len(snapshots) != len(child_roles) + or any(not isinstance(value, str) or not value for value in evidence_ids.values())): + return VerifiedImageMotionDecision(False, "pose_image_motion_roles_invalid") + if not roots: + collected = [] + for role in sorted(root_roles): + found = [snapshot for tracker in {s.tracker for s in snapshots} + if (snapshot := tracker.motion_snapshot(role, frame.evidence.stamp_ns)) is not None] + if len(found) != 1: + return VerifiedImageMotionDecision(False, "pose_image_motion_root_missing") + collected.append(found[0]) + roots = tuple(collected) + if {s.role for s in roots} != root_roles or len(roots) != len(root_roles): + return VerifiedImageMotionDecision(False, "pose_image_motion_root_missing") + declared = {ref.role: ref for ref in model.reference_frames} + actual = {s.role: s.reference for s in roots if isinstance(s, ImageReferenceSnapshot)} + if actual != declared: + return VerifiedImageMotionDecision(False, "pose_image_motion_reference_binding_changed") + if not _inputs_match(snapshots, roots, model, frame): + return VerifiedImageMotionDecision(False, "pose_image_motion_observation_mismatch") + with ExitStack() as stack: + for tracker in sorted({s.tracker for s in (*snapshots, *roots)}, key=id): + stack.enter_context(tracker._lock) + if not all(SquareTagPoseTracker._motion_snapshot_is_current(s) for s in snapshots) or not all( + _root_current(s) for s in roots): + return VerifiedImageMotionDecision(False, "pose_observation_superseded") + # This is the only expensive operation. Commit below never repeats it. + result = (select_image_motion_frame(model, frame) if projection_worker is None + else ImageProjectionWorker.solve(projection_worker, model, frame)) + if not result.resolved: + return VerifiedImageMotionDecision(False, result.reason, quality=result.quality) + poses = {item.role: item.pose for item in result.selections} + identity = hashlib.sha256(json.dumps(image_model_evidence(model), sort_keys=True, separators=(",", ":"), + allow_nan=False).encode()).hexdigest() + selections = tuple(MotionPoseSelection(s, poses[s.role], evidence_ids[s.role]) for s in snapshots) + decision = VerifiedImageMotionDecision(True, "", selections, roots, model, identity, result.quality) + with _registry_lock: + _verified[id(decision)] = decision + return decision + + +def commit_image_motion_frame(decision: VerifiedImageMotionDecision, *, + establish: bool = False) -> MotionFrameCommit: + """Consume a verifier-created decision and atomically update all children.""" + from .tracking import MotionFrameCommit, SquareTagPoseTracker + if not isinstance(decision, VerifiedImageMotionDecision): + return MotionFrameCommit(False, "pose_image_motion_decision_invalid") + if not decision.accepted: + return MotionFrameCommit(False, decision.reason) + with _registry_lock: + if _verified.pop(id(decision), None) is not decision: + return MotionFrameCommit(False, "pose_image_motion_decision_invalid") + snapshots = tuple(item.snapshot for item in decision.selections) + with ExitStack() as stack: + for tracker in sorted({s.tracker for s in (*snapshots, *decision.root_snapshots)}, key=id): + stack.enter_context(tracker._lock) + if not all(SquareTagPoseTracker._motion_snapshot_is_current(s) for s in snapshots) or not all( + _root_current(s) for s in decision.root_snapshots): + return MotionFrameCommit(False, "pose_observation_superseded") + for snapshot in snapshots: + tracker, role = snapshot.tracker, snapshot.role + if tracker._image_observations_by_role.get(role) is not snapshot.image_observation: + return MotionFrameCommit(False, "pose_image_motion_observation_mismatch") + previous = tracker._image_model_sha256_by_role.get(role) + if previous is not None and previous != decision.model_sha256: + return MotionFrameCommit(False, "pose_image_motion_model_changed") + if previous is None and snapshot.evidence_id is not None: + return MotionFrameCommit(False, "pose_motion_solver_changed") + return SquareTagPoseTracker._commit_motion_selections_locked(decision.selections, + establish=establish, image_decision=decision) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_model.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_model.py new file mode 100644 index 0000000..321d9c9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_model.py @@ -0,0 +1,185 @@ +"""Frozen image-derived hinge models and their auditable authorization evidence.""" +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import ClassVar, Mapping, TYPE_CHECKING + +import numpy as np + +from .motion_evidence import MotionRelation, MotionRoleSelection +from .motion_image_types import ImageHingeGeometry, ImageRoleQuality +from .parameters import DEFAULT_POSE_TRACKING_PARAMETERS +from .image_reference import StationaryImageReference, image_reference_from_dict +from .pose_bridge import PoseBridgeCheck +from .image_bundle_optimizer import ImageSolverAttempt + +IMAGE_MOTION_MODEL_POLICY = "image_hinge_v1_pre_zero_frozen" + +if TYPE_CHECKING: + from .measured_transfer import TransferGeometryCheck + + +@dataclass(frozen=True) +class ImageMotionModel: + POLICY: ClassVar[str] = IMAGE_MOTION_MODEL_POLICY + geometry: tuple[ImageHingeGeometry, ...] + camera_matrix: tuple[tuple[float, float, float], ...] + tag_sizes: tuple[tuple[str, float], ...] + source_stamps_ns: tuple[int, ...] + training_stamps_ns: tuple[int, ...] + validation_stamps_ns: tuple[int, ...] + branches: tuple[tuple[str, int], ...] + maximum_reprojection_error_px: float = 1.5 + reprojection_tie_px: float = .03 + policy: str = IMAGE_MOTION_MODEL_POLICY + reference_frames: tuple[StationaryImageReference, ...] = () + + @property + def relations(self): + return tuple(g.relation for g in self.geometry) + + def __post_init__(self): + from .motion_image_diagnostics import _ordered_relations + if self.policy != self.POLICY: + raise ValueError("image_motion_model_policy_mismatch") + sequences = (self.geometry, self.camera_matrix, self.tag_sizes, self.source_stamps_ns, + self.training_stamps_ns, self.validation_stamps_ns, self.branches) + if any(not isinstance(value, tuple) for value in sequences) or any( + not isinstance(value, tuple) for values in (self.camera_matrix, self.tag_sizes, self.branches) + for value in values): + raise ValueError("image_motion_model_requires_immutable_sequences") + relations = self.relations + if tuple(_ordered_relations(relations)) != relations: + raise ValueError("image_motion_model_graph_not_ordered") + p = DEFAULT_POSE_TRACKING_PARAMETERS + if (self.maximum_reprojection_error_px != p.maximum_reprojection_error_px + or self.reprojection_tie_px != p.reprojection_tie_px): + raise ValueError("image_motion_model_quality_policy_changed") + matrix = np.asarray(self.camera_matrix) + if (matrix.shape != (3, 3) or not np.all(np.isfinite(matrix)) + or matrix[0, 0] <= 0 or matrix[1, 1] <= 0 + or not np.array_equal(matrix[2], [0, 0, 1])): + raise ValueError("image_motion_model_camera_invalid") + roles = {r for g in self.geometry for r in (g.relation.parent_role, g.relation.child_role)} + roots = roles - {g.relation.child_role for g in self.geometry} + if (not isinstance(self.reference_frames, tuple) + or any(not isinstance(ref, StationaryImageReference) for ref in self.reference_frames) + or len({ref.role for ref in self.reference_frames}) != len(self.reference_frames) + or any(ref.role not in roots or ref.camera_matrix != self.camera_matrix + or dict(self.tag_sizes).get(ref.role) != ref.tag_size_m + or not self.source_stamps_ns + or ref.source_images[-1].stamp_ns >= min(self.source_stamps_ns) + for ref in self.reference_frames)): + raise ValueError("image_motion_reference_frames_invalid") + if (len(dict(self.tag_sizes)) != len(self.tag_sizes) or set(dict(self.tag_sizes)) != roles + or any(not math.isfinite(s) or s <= 0 for _, s in self.tag_sizes)): + raise ValueError("image_motion_model_tag_sizes_invalid") + if len(dict(self.branches)) != len(self.branches) or set(dict(self.branches)) != roles or any( + type(v) is not int or v not in (0, 1) for _, v in self.branches): + raise ValueError("image_motion_model_branches_invalid") + for stamps in (self.source_stamps_ns, self.training_stamps_ns, self.validation_stamps_ns): + if not stamps or any(type(v) is not int or v <= 0 for v in stamps) or any( + b <= a for a, b in zip(stamps, stamps[1:])): + raise ValueError("image_motion_model_sources_invalid") + source, train, validation = map(set, (self.source_stamps_ns, self.training_stamps_ns, + self.validation_stamps_ns)) + if not train.isdisjoint(validation) or not train | validation <= source: + raise ValueError("image_motion_model_source_overlap") + for geometry in self.geometry: + vectors = (geometry.axis_parent_xyz, geometry.reference_quaternion_xyzw, + geometry.pivot_parent_xyz_m, geometry.mount_child_xyz_m) + if any(not isinstance(v, tuple) or len(v) != n for v, n in zip(vectors, (3, 4, 3, 3))) or not all( + math.isfinite(x) for v in vectors for x in v): + raise ValueError("image_motion_model_geometry_invalid") + if not np.isclose(np.linalg.norm(vectors[0]), 1., atol=1e-7) or not np.isclose( + np.linalg.norm(vectors[1]), 1., atol=1e-7): + raise ValueError("image_motion_model_rotation_invalid") + + +@dataclass(frozen=True) +class ImageMotionFrameSelection: + resolved: bool + reason: str + selections: tuple[MotionRoleSelection, ...] = () + quality: tuple[ImageRoleQuality, ...] = () + angles_rad: tuple[tuple[str, float], ...] = () + + +@dataclass(frozen=True) +class ImageMotionHypothesis: + branches: tuple[tuple[str, int], ...] + converged: bool + reason: str + training_quality: tuple[ImageRoleQuality, ...] = () + validation_quality: tuple[ImageRoleQuality, ...] = () + motion_span_rad: tuple[tuple[str, float], ...] = () + axis_uncertainty_95_rad: tuple[tuple[str, float], ...] = () + pivot_uncertainty_95_m: tuple[tuple[str, float], ...] = () + comparison_p_values: tuple[tuple[int, float], ...] = () + training_solver_status: int | None = None + training_solver_evaluations: int = 0 + training_accepted: bool = False + comparison_adjusted_p_values: tuple[tuple[int, float], ...] = () + child_frame_uncertainty: tuple[tuple[str, float, float], ...] = () + source_geometry_checks: tuple[TransferGeometryCheck, ...] = () + pose_bridge_checks: tuple[PoseBridgeCheck, ...] = () + transition_branches: tuple[tuple[str, int], ...] = () + preparation_pose_uncertainty: tuple[float, ...] = () + training_solver_attempts: tuple[ImageSolverAttempt, ...] = () + + +@dataclass(frozen=True) +class ImageMotionResolution: + resolved: bool + reason: str + model: ImageMotionModel | None = None + hypotheses: tuple[ImageMotionHypothesis, ...] = () + selections: tuple[MotionRoleSelection, ...] = () + observer_pose_bridges: tuple[dict, ...] = () + observer_rejections: tuple[str, ...] = () + preparation_transitions: tuple[dict, ...] = () + selected_hypothesis: int | None = None + preparation_transition_rejections: tuple[str, ...] = () + preparation_witnesses: tuple[dict, ...] = () + + +def image_motion_model_from_dict(raw: Mapping) -> ImageMotionModel: + """Read an immutable model; hashes/provenance are enforced by the caller.""" + geometry = tuple(ImageHingeGeometry(MotionRelation(**item["relation"]), + tuple(item["axis_parent_xyz"]), tuple(item["reference_quaternion_xyzw"]), + tuple(item["pivot_parent_xyz_m"]), tuple(item["mount_child_xyz_m"])) for item in raw["geometry"]) + model_type, extra = ImageMotionModel, {} + extra["reference_frames"] = tuple(image_reference_from_dict(item) + for item in raw.get("reference_frames", ())) + from .cad_image_model import (CAD_IMAGE_MOTION_MODEL_POLICY, CadImageMotionModel, + TRANSFERRED_IMAGE_MOTION_MODEL_POLICY, TransferredImageMotionModel) + from .measured_transfer import MEASURED_TRANSFER_POLICY, MeasuredTransferImageMotionModel + if raw["policy"] in {CAD_IMAGE_MOTION_MODEL_POLICY, TRANSFERRED_IMAGE_MOTION_MODEL_POLICY, MEASURED_TRANSFER_POLICY}: + from .cad_hinge import ParallelAxisGeometry + model_type = CadImageMotionModel + extra.update(constraints=tuple(ParallelAxisGeometry(**value) for value in raw["constraints"]), + source_urdf_sha256=raw["source_urdf_sha256"]) + if raw["policy"] in {TRANSFERRED_IMAGE_MOTION_MODEL_POLICY, MEASURED_TRANSFER_POLICY}: + from .source_hinge import source_hinge_from_dict + model_type = TransferredImageMotionModel + extra["source_hinges"] = tuple(source_hinge_from_dict(value) for value in raw["source_hinges"]) + if raw["policy"] == MEASURED_TRANSFER_POLICY: + model_type = MeasuredTransferImageMotionModel + extra["current_geometry_uncertainty"] = tuple(tuple(v) for v in raw["current_geometry_uncertainty"]) + return model_type(geometry=geometry, camera_matrix=tuple(tuple(v) for v in raw["camera_matrix"]), + tag_sizes=tuple((str(r), float(s)) for r, s in raw["tag_sizes"]), + source_stamps_ns=tuple(raw["source_stamps_ns"]), training_stamps_ns=tuple(raw["training_stamps_ns"]), + validation_stamps_ns=tuple(raw["validation_stamps_ns"]), + branches=tuple((str(r), i) for r, i in raw["branches"]), + maximum_reprojection_error_px=raw["maximum_reprojection_error_px"], + reprojection_tie_px=raw["reprojection_tie_px"], policy=raw["policy"], **extra) + + +def image_model_payload(model): + """Preserve historical model hashes when no coordinate reference exists.""" + from dataclasses import asdict + payload = asdict(model) + if payload.get("reference_frames") == (): + payload.pop("reference_frames") + return payload diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_projection.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_projection.py new file mode 100644 index 0000000..8a6cbbc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_motion_projection.py @@ -0,0 +1,165 @@ +"""Current-image angle estimates with immutable, pre-zero hinge geometry.""" +from itertools import product + +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation + +from .image_motion_model import ImageMotionFrameSelection +from .ippe import square_object_points +from .motion_evidence import MotionEvidenceParameters, MotionRoleSelection, _eligible, _equivalent +from .motion_image_diagnostics import _quality +from .relative import _relative_pose +from .types import SquareTagPose + + +def project_image_model(model, angles, roots): + transforms = {role: (Rotation.from_quat(pose.quaternion_xyzw), + np.array(pose.translation_xyz_m)) for role, pose in roots.items()} + pixels = [] + positive = True + matrix, sizes = np.array(model.camera_matrix), dict(model.tag_sizes) + for geometry, angle in zip(model.geometry, angles): + relative = Rotation.from_rotvec(np.array(geometry.axis_parent_xyz) * angle) * Rotation.from_quat( + geometry.reference_quaternion_xyzw) + parent_rotation, parent_translation = transforms[geometry.relation.parent_role] + rotation = parent_rotation * relative + translation = parent_translation + parent_rotation.apply(np.array(geometry.pivot_parent_xyz_m) + + relative.apply(geometry.mount_child_xyz_m)) + role = geometry.relation.child_role + transforms[role] = (rotation, translation) + points = rotation.apply(square_object_points(sizes[role])) + translation + positive = positive and bool(np.all(points[:, 2] > 1e-6)) + homogeneous = points @ matrix.T + pixels.append(homogeneous[:, :2] / np.maximum(homogeneous[:, 2:], 1e-6)) + return np.asarray(pixels), transforms, positive + + +def _frame_inputs(model, frame): + if tuple(tuple(v) for v in frame.camera_matrix) != model.camera_matrix: + raise ValueError("image_motion_camera_changed") + observations = {o.role: o for o in frame.observations} + if frame.reference_frames != model.reference_frames: + raise ValueError("image_motion_reference_frames_changed") + references = {ref.role: ref for ref in model.reference_frames} + candidates = {r.role: r for r in frame.evidence.roles} + roles, sizes = tuple(dict(model.tag_sizes)), dict(model.tag_sizes) + if (len(observations) != len(frame.observations) or len(candidates) != len(frame.evidence.roles) + or not set(roles) <= observations.keys() or not set(roles) <= candidates.keys()): + raise ValueError("image_motion_frame_roles_missing") + for role in roles: + observation = observations[role] + if observation.tag_size_m != sizes[role] or np.shape(observation.corners_xy) != (4, 2) or not np.all( + np.isfinite(observation.corners_xy)): + raise ValueError("image_motion_frame_corners_invalid") + children = tuple(g.relation.child_role for g in model.geometry) + roots = set(roles) - set(children) + poses = {} + for role in roles: + selected = tuple(p for p in candidates[role].candidates if _eligible(p)) + if not selected or (role in roots and (not candidates[role].frozen or len(selected) != 1)): + raise ValueError("image_motion_current_root_or_candidates_unavailable") + poses[role] = selected + frozen = {role: poses[role][0] for role in roots} + # A frozen root is still verified against this image, never silently moved. + for role, pose in frozen.items(): + if role in references: + reference = references[role] + if pose != reference.pose: + raise ValueError("image_motion_reference_pose_changed") + reference.check_image(role, sizes[role], frame.camera_matrix, + observations[role].corners_xy, frame.evidence.stamp_ns) + continue + xyz = Rotation.from_quat(pose.quaternion_xyzw).apply(square_object_points(sizes[role])) + xyz += pose.translation_xyz_m + if np.any(xyz[:, 2] <= 1e-6): + raise ValueError("image_motion_root_behind_camera") + image = xyz @ np.array(model.camera_matrix).T + delta = image[:, :2] / image[:, 2:] - observations[role].corners_xy + if np.sqrt(np.mean(np.sum(delta ** 2, axis=1))) > model.maximum_reprojection_error_px: + raise ValueError("image_motion_current_root_reprojection_failed") + return poses, frozen, np.asarray([observations[r].corners_xy for r in children]), children + + +def image_motion_prediction_errors(model, frame, angles_rad, *, dependency_stamps_ns=()): + """Measure a frozen command prediction without fitting an observed angle. + + The caller converts its frozen mapping into the model's training gauge + and supplies all additional mapping/zero/selection image dependencies. + Return nominal residuals, not an acceptance flag. The measurement-only + 1.5 px limit must not be imposed on combined mapping/measurement error; + final acceptance separately checks measured pixels and physical motion. + This grants neither physical zero nor publication authority. + Current root checks are identical to the original image-angle estimator. + """ + used = set(model.source_stamps_ns) | set(dependency_stamps_ns) + if frame.evidence.stamp_ns in used: + raise ValueError("image_motion_prediction_training_overlap") + angles = np.asarray(angles_rad, dtype=float) + if angles.shape != (len(model.geometry),) or not np.all(np.isfinite(angles)): + raise ValueError("image_motion_prediction_angles_invalid") + _, roots, observed, children = _frame_inputs(model, frame) + pixels, _, positive = project_image_model(model, angles, roots) + if not positive or not np.all(np.isfinite(pixels)): + raise ValueError("image_motion_prediction_projection_invalid") + return _quality((pixels-observed).ravel(), children) + + +def select_image_motion_frame(model, frame): + """Fit only current geometric angles, retaining all candidate initializations. + + No model parameter, baseline or previous pose is changed. Distinct solutions + within the public 0.03 pixel tolerance are rejected rather than ranked. + """ + try: + poses, roots, observed, children = _frame_inputs(model, frame) + roles = tuple(poses) + if np.prod([len(poses[r]) for r in roles]) > 256: + raise ValueError("image_motion_frame_hypothesis_limit") + fits = [] + for values in product(*(poses[role] for role in roles)): + selected = dict(zip(roles, values)) + initial = [] + for geometry in model.geometry: + rotation, _ = _relative_pose(selected[geometry.relation.parent_role], + selected[geometry.relation.child_role]) + initial.append(float((rotation * Rotation.from_quat( + geometry.reference_quaternion_xyzw).inv()).as_rotvec() @ geometry.axis_parent_xyz)) + def residual(angles): + pixels, _, _ = project_image_model(model, angles, roots) + return (pixels - observed).ravel() + fit = least_squares(residual, initial, max_nfev=40, ftol=1e-9, xtol=1e-9, gtol=1e-7) + _, transforms, positive = project_image_model(model, fit.x, roots) + if not fit.success or not positive or not np.all(np.isfinite(fit.fun)): + raise ValueError("image_motion_frame_optimizer_unresolved") + quality = _quality(fit.fun, children) + output = dict(roots) + for role, checked in zip(children, quality): + rotation, translation = transforms[role] + output[role] = SquareTagPose(tuple(rotation.as_quat()), tuple(translation), checked.rms_px) + score = float(np.sqrt(np.mean(np.square(fit.fun.reshape(-1, 2)).sum(axis=1)))) + fits.append((score, output, quality, fit.x, fit.jac, fit.fun)) + if not fits: + raise ValueError("image_motion_frame_reprojection_or_tilt_failed") + fits.sort(key=lambda item: item[0]) + best = fits[0] + for other in fits[1:]: + if other[0] <= best[0] + model.reprojection_tie_px and not all( + _equivalent(best[1][r], other[1][r]) for r in roles): + raise ValueError("image_motion_frame_angles_ambiguous") + jacobian = np.asarray(best[4]) + _, singular, vh = np.linalg.svd(jacobian, full_matrices=False) + if singular[-1] <= singular[0] * np.finfo(float).eps * max(jacobian.shape): + raise ValueError("image_motion_frame_angles_unobservable") + variance = max(model.reprojection_tie_px ** 2, + float(np.sum(best[5] ** 2) / max(1, len(best[5]) - len(best[3])))) + covariance = (vh.T / singular ** 2) @ vh * variance + if np.any(3 * np.sqrt(np.maximum(0., np.diag(covariance))) > + MotionEvidenceParameters().maximum_frame_off_axis_rad): + raise ValueError("image_motion_frame_angles_uncertain") + accepted = all(_eligible(p) for p in best[1].values()) + return ImageMotionFrameSelection(accepted, "" if accepted else "image_motion_frame_reprojection_or_tilt_failed", + tuple(MotionRoleSelection(r, best[1][r]) for r in roles), best[2], + tuple((g.relation.joint, float(a)) for g, a in zip(model.geometry, best[3]))) + except (ValueError, TypeError, KeyError, FloatingPointError, np.linalg.LinAlgError) as error: + return ImageMotionFrameSelection(False, str(error)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_projection_worker.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_projection_worker.py new file mode 100644 index 0000000..2938fdd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_projection_worker.py @@ -0,0 +1,38 @@ +"""Bounded process execution of the unchanged, pure current-image solver.""" + +from concurrent.futures import ProcessPoolExecutor, TimeoutError +from concurrent.futures.process import BrokenProcessPool +import multiprocessing +import threading + +from .image_motion_model import ImageMotionFrameSelection +from .image_motion_projection import select_image_motion_frame + + +class ImageProjectionWorker: + def __init__(self, workers=3): + self._pool = ProcessPoolExecutor(max_workers=workers, + mp_context=multiprocessing.get_context("spawn")) + self._slots = threading.BoundedSemaphore(workers) + self._closed = False + + def solve(self, model, frame): + if self._closed or not self._slots.acquire(blocking=False): + return ImageMotionFrameSelection(False, "image_motion_frame_worker_busy") + try: + future = self._pool.submit(select_image_motion_frame, model, frame) + except (RuntimeError, BrokenProcessPool): + self._slots.release() + return ImageMotionFrameSelection(False, "image_motion_frame_worker_unavailable") + future.add_done_callback(lambda _: self._slots.release()) + try: + return future.result(timeout=2.) + except TimeoutError: + future.cancel() + return ImageMotionFrameSelection(False, "image_motion_frame_worker_timeout") + except BrokenProcessPool: + return ImageMotionFrameSelection(False, "image_motion_frame_worker_unavailable") + + def close(self): + self._closed = True + self._pool.shutdown(wait=False, cancel_futures=True) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_reference.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_reference.py new file mode 100644 index 0000000..d1cba5b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_reference.py @@ -0,0 +1,180 @@ +"""Image stationarity and a coordinate convention, without a Tag normal. + +A fixed planar marker need not have an observable normal to witness that the +camera/fixture is stationary. The coordinate frame below has camera-aligned +axes. Its origin is near the marker solely to condition the hinge fit; it is +not an estimate of the marker's physical orientation. Moving Tags still need +the ordinary independent image/geometry authorization. +""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from functools import cached_property, lru_cache +import hashlib +import json + +import numpy as np + +from ..frozen_evidence import canonical_evidence +from .ippe import solve_square_tag_ippe +from .parameters import DEFAULT_POSE_TRACKING_PARAMETERS +from .types import SquareTagPose + + +IMAGE_REFERENCE_SOURCE = "stationary_image_reference" +IMAGE_REFERENCE_POLICY = "camera_aligned_image_reference_v1" + + +def _canonical(value): + return canonical_evidence(value) + + +@dataclass(frozen=True) +class ReferenceImage: + stamp_ns: int + corners_xy: tuple[tuple[float, float], ...] + + def __post_init__(self): + if (type(self.stamp_ns) is not int or self.stamp_ns <= 0 + or not isinstance(self.corners_xy, tuple) + or any(not isinstance(point, tuple) for point in self.corners_xy) + or np.asarray(self.corners_xy).shape != (4, 2) + or not np.all(np.isfinite(self.corners_xy))): + raise ValueError("image_reference_source_image_invalid") + + +@dataclass(frozen=True) +class ImageReferenceSnapshot: + tracker: object + role: str + epoch: int + stamp_ns: int + reference: StationaryImageReference + image_observation: object + + @property + def previous_pose(self): + return self.reference.pose + + +@dataclass(frozen=True) +class StationaryImageReference: + role: str + tag_size_m: float + camera_matrix: tuple[tuple[float, float, float], ...] + source_images: tuple[ReferenceImage, ...] + origin_xyz_m: tuple[float, float, float] + policy: str = IMAGE_REFERENCE_POLICY + + def __post_init__(self): + matrix = np.asarray(self.camera_matrix) + if (self.policy != IMAGE_REFERENCE_POLICY or not isinstance(self.role, str) or not self.role + or not isinstance(self.camera_matrix, tuple) or matrix.shape != (3, 3) + or any(not isinstance(row, tuple) for row in self.camera_matrix) + or not np.all(np.isfinite(matrix)) or matrix[0, 0] <= 0 or matrix[1, 1] <= 0 + or not np.array_equal(matrix[2], [0, 0, 1]) + or not np.isfinite(self.tag_size_m) or self.tag_size_m <= 0): + raise ValueError("image_reference_camera_or_role_invalid") + if (not isinstance(self.source_images, tuple) or len(self.source_images) < 10 + or any(not isinstance(row, ReferenceImage) for row in self.source_images)): + raise ValueError("image_reference_source_images_invalid") + stamps = [row.stamp_ns for row in self.source_images] + points = np.asarray([row.corners_xy for row in self.source_images]) + if (any(type(s) is not int or s <= 0 for s in stamps) or stamps != sorted(set(stamps)) + or points.shape != (len(stamps), 4, 2) or not np.all(np.isfinite(points))): + raise ValueError("image_reference_source_images_invalid") + origin = np.asarray(self.origin_xyz_m) + if (not isinstance(self.origin_xyz_m, tuple) or origin.shape != (3,) + or not np.all(np.isfinite(origin)) or origin[2] <= 0): + raise ValueError("image_reference_coordinate_origin_invalid") + drift = np.sqrt(np.mean(np.sum((points - np.median(points, axis=0)) ** 2, axis=2), axis=1)) + if np.max(drift) > DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px: + raise ValueError("image_reference_source_not_stationary") + + @cached_property + def _median_corners(self): + return tuple(map(tuple, np.median([row.corners_xy for row in self.source_images], axis=0))) + + @property + def corners_xy(self): + return np.asarray(self._median_corners) + + @property + def pose(self): + # The quaternion is a declared coordinate basis, not a measured Tag + # normal. Zero here is the exact coordinate convention's error. + return SquareTagPose((0., 0., 0., 1.), self.origin_xyz_m, 0.) + + @cached_property + def identity(self): + return hashlib.sha256(_canonical(asdict(self)).encode()).hexdigest() + + def check_image(self, role, size, matrix, corners, stamp_ns): + if (role != self.role or size != self.tag_size_m + or not np.array_equal(matrix, self.camera_matrix) + or stamp_ns < self.source_images[-1].stamp_ns): + raise ValueError("image_reference_binding_changed") + points = np.asarray(corners) + if points.shape != (4, 2) or not np.all(np.isfinite(points)): + raise ValueError("image_reference_current_corners_missing") + error = float(np.sqrt(np.mean(np.sum((points - self.corners_xy) ** 2, axis=1)))) + if error > DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px: + raise ValueError("image_reference_current_image_moved") + return error + + +def coordinate_origin(images, size, matrix): + """Use both candidate centres symmetrically; never select a normal.""" + centres = [] + for row in images: + candidates = [p for p in solve_square_tag_ippe(row.corners_xy, + tag_size_m=size, camera_matrix=matrix) + if p.reprojection_error_px <= DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px] + if not candidates: + raise ValueError("image_reference_source_projection_invalid") + centres.append(np.mean([p.translation_xyz_m for p in candidates], axis=0)) + return tuple(float(v) for v in np.median(centres, axis=0)) + + +@lru_cache(maxsize=128) +def _read_reference(encoded): + raw = json.loads(encoded) + result = StationaryImageReference(raw["role"], float(raw["tag_size_m"]), + tuple(map(tuple, raw["camera_matrix"])), tuple(ReferenceImage(row["stamp_ns"], + tuple(map(tuple, row["corners_xy"]))) for row in raw["source_images"]), + tuple(raw["origin_xyz_m"]), raw["policy"]) + expected = coordinate_origin(result.source_images, result.tag_size_m, result.camera_matrix) + if not np.allclose(result.origin_xyz_m, expected, atol=1e-10, rtol=0): + raise ValueError("image_reference_coordinate_origin_changed") + return result + + +def image_reference_from_dict(raw): + return _read_reference(_canonical(raw)) + + +def reference_from_evidence(item, *, stamp_ns, camera_matrix=None): + """Read the declared coordinate frame and verify its current image.""" + if item.get("pose_source") != IMAGE_REFERENCE_SOURCE: + raise ValueError("image_reference_pose_source_changed") + ref = image_reference_from_dict(item["reference_frame"]) + if item.get("reference_frame_sha256") != ref.identity: + raise ValueError("image_reference_identity_changed") + diagnostics = item.get("candidate_diagnostics", {}) + if (diagnostics.get("observation_stamp_ns") != stamp_ns + or diagnostics.get("reference_frame_is_tag_pose") is not False + or diagnostics.get("branch_status") != "tracking" + or diagnostics.get("branch_frozen") is not True + or diagnostics.get("branch_revision") != 1 + or item.get("reference_branch_revision") != 1): + raise ValueError("image_reference_observation_unverified") + ref.check_image(item.get("tag_role"), item.get("tag_size_m"), + ref.camera_matrix if camera_matrix is None else camera_matrix, + item.get("corners_xy"), stamp_ns) + pose = item.get("selected_pose", item.get("selected")) + if (not isinstance(pose, dict) or tuple(pose.get("quaternion_xyzw", ())) != ref.pose.quaternion_xyzw + or tuple(pose.get("translation_xyz_m", ())) != ref.origin_xyz_m + or pose.get("reprojection_error_px") != 0.): + raise ValueError("image_reference_coordinate_pose_changed") + return ref diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_solve_diagnosis.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_solve_diagnosis.py new file mode 100644 index 0000000..6b9239b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/image_solve_diagnosis.py @@ -0,0 +1,82 @@ +"""Explain saved image-motion candidates without selecting or fitting a pose. + +This is a read-only view of the already recorded candidate evidence. It never +turns a local low residual into a confirmed branch or changes release gates. +""" + +from __future__ import annotations + +from collections import Counter +from typing import Mapping + + +DIAGNOSIS_VERSION = "image_solve_diagnosis_v1" + + +def _quality(rows): + return [{ + "role": str(row.get("role", "")), + "frames": int(row.get("frames", 0)), + "rms_px": row.get("rms_px"), + "maximum_frame_rms_px": row.get("maximum_frame_rms_px"), + } for row in rows] + + +def _hypothesis(index, row): + return { + "index": index, + "branches": [list(item) for item in row.get("branches", ())], + "training_accepted": bool(row.get("training_accepted", False)), + "converged": bool(row.get("converged", False)), + "reason": str(row.get("reason", "")), + "solver_status": row.get("training_solver_status"), + "solver_evaluations": int(row.get("training_solver_evaluations", 0)), + "training_quality": _quality(row.get("training_quality", ())), + "validation_quality": _quality(row.get("validation_quality", ())), + "comparison_adjusted_p_values": [list(item) for item in row.get("comparison_adjusted_p_values", ())], + } + + +def diagnose_image_solve_record(record: Mapping) -> dict: + """Summarize one persisted preparation result; no image data is re-used. + + Only source fields are copied. A missing candidate remains unknown rather + than being treated as rejected, and a successful fit is not a URDF pass. + """ + if record.get("kind") != "motion_branch_initialization": + raise ValueError("image_solve_diagnosis_requires_initialization_record") + reason = str(record.get("reason", "")) + rows = tuple(record.get("hypotheses", ())) + candidates = [_hypothesis(index, row) for index, row in enumerate(rows)] + reasons = Counter(candidate["reason"] or "candidate_accepted" for candidate in candidates) + if record.get("status") == "resolved": + category = "resolved" + elif "image_motion_families_not_distinguishable" in reason: + category = "multiple_plausible_poses" + elif "image_motion_alternative_not_evaluable" in reason or "image_motion_alternative_angles_unresolved" in reason: + category = "alternative_not_evaluated" + elif "image_motion_solver_budget_exhausted" in reason or "image_motion_solver_timeout" in reason: + category = "solver_incomplete" + elif "image_motion_no_observable_image_model" in reason: + category = "no_acceptable_model" + elif "joint_zero_unavailable" in reason or not candidates: + category = "insufficient_or_missing_evidence" + else: + category = "other_unresolved" + return { + "version": DIAGNOSIS_VERSION, + "task_name": record.get("task_name"), + "view": record.get("view"), + "zero_joints": list(record.get("zero_joints", ())), + "status": record.get("status"), + "reason": reason, + "category": category, + "source_image_count": len(record.get("source_image_stamps", ())), + "source_hash_count": len(record.get("source_frame_hashes", {})), + "preparation_observation_rejections": dict(record.get("preparation_observation_rejections", {})), + "candidate_count": len(candidates), + "accepted_training_candidate_count": sum(row["training_accepted"] for row in candidates), + "candidate_reasons": dict(sorted(reasons.items())), + "candidates": candidates, + "accuracy_validated": False, + } diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/ippe.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/ippe.py new file mode 100644 index 0000000..2c2a302 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/ippe.py @@ -0,0 +1,164 @@ +"""Ippe for shared square Tag pose estimation.""" + +from __future__ import annotations + +from typing import Sequence +import math + +from scipy.spatial.transform import Rotation +import cv2 +import numpy as np + +from .types import SquareTagPose + + +def _as_camera_matrix(camera_matrix: Sequence[Sequence[float]]) -> np.ndarray: + matrix = np.asarray(camera_matrix, dtype=np.float64) + if matrix.shape != (3, 3): + raise ValueError("camera_matrix must have shape (3, 3)") + if not np.all(np.isfinite(matrix)): + raise ValueError("camera_matrix must be finite") + if matrix[0, 0] <= 0.0 or matrix[1, 1] <= 0.0: + raise ValueError("camera focal lengths must be positive") + return matrix + + +def square_object_points(tag_size_m: float) -> np.ndarray: + """Return IPPE-square points matching apriltag_msgs corner order. + + ``apriltag_ros`` reports bottom-left, bottom-right, top-right, top-left. + OpenCV's ``SOLVEPNP_IPPE_SQUARE`` requires the same physical corners in + the order below. + """ + size = float(tag_size_m) + if not math.isfinite(size) or size <= 0.0: + raise ValueError("tag_size_m must be finite and positive") + half = size / 2.0 + return np.asarray( + [ + [-half, half, 0.0], + [half, half, 0.0], + [half, -half, 0.0], + [-half, -half, 0.0], + ], + dtype=np.float64, + ) + + +def solve_square_tag_ippe( + corners_xy: Sequence[Sequence[float]], + *, + tag_size_m: float, + camera_matrix: Sequence[Sequence[float]], +) -> list[SquareTagPose]: + """Return every finite, positive-depth IPPE pose for one square tag.""" + image_points = np.asarray(corners_xy, dtype=np.float64) + if image_points.shape != (4, 2): + raise ValueError("corners_xy must have shape (4, 2)") + if not np.all(np.isfinite(image_points)): + raise ValueError("corners_xy must be finite") + intrinsic = _as_camera_matrix(camera_matrix) + object_points = square_object_points(tag_size_m) + distortion = np.zeros((4, 1), dtype=np.float64) + + solved, rotation_vectors, translations, _ = cv2.solvePnPGeneric( + object_points, + image_points, + intrinsic, + distortion, + flags=cv2.SOLVEPNP_IPPE_SQUARE, + ) + if not solved: + return [] + + candidates: list[SquareTagPose] = [] + for rotation_vector, translation in zip(rotation_vectors, translations): + rotation_matrix, _ = cv2.Rodrigues(rotation_vector) + translation_vector = np.asarray(translation, dtype=float).reshape(3) + camera_points = ( + rotation_matrix @ object_points.T + + translation_vector.reshape(3, 1) + ).T + if np.min(camera_points[:, 2]) <= 0.0: + continue + projected, _ = cv2.projectPoints( + object_points, + rotation_vector, + translation_vector, + intrinsic, + distortion, + ) + residual = projected.reshape(4, 2) - image_points + reprojection_error = float( + np.sqrt(np.mean(np.sum(residual * residual, axis=1))) + ) + quaternion = Rotation.from_matrix(rotation_matrix).as_quat() + if not ( + np.all(np.isfinite(quaternion)) + and np.all(np.isfinite(translation_vector)) + and math.isfinite(reprojection_error) + ): + continue + candidates.append( + SquareTagPose( + quaternion_xyzw=tuple(float(value) for value in quaternion), + translation_xyz_m=tuple( + float(value) for value in translation_vector + ), + reprojection_error_px=reprojection_error, + ) + ) + return candidates + + +def fixed_pose_reprojection_error( + pose: SquareTagPose, + corners_xy: Sequence[Sequence[float]], + *, + tag_size_m: float, + camera_matrix: Sequence[Sequence[float]], +) -> float: + """Check a frozen pose against rectified corners without solving a new pose.""" + corners = np.asarray(corners_xy, dtype=np.float64) + if corners.shape != (4, 2) or not np.all(np.isfinite(corners)): + raise ValueError("corners_xy must contain four finite image points") + intrinsic = _as_camera_matrix(camera_matrix) + points = square_object_points(tag_size_m) + rotation = Rotation.from_quat(pose.quaternion_xyzw) + translation = np.asarray(pose.translation_xyz_m, dtype=np.float64) + camera_points = rotation.apply(points) + translation + if not np.all(np.isfinite(camera_points)) or np.min(camera_points[:, 2]) <= 0: + raise ValueError("fixed pose must have finite, positive-depth corners") + projected, _ = cv2.projectPoints(points, rotation.as_rotvec(), translation, + intrinsic, np.zeros(4, dtype=np.float64)) + residual = projected.reshape(4, 2) - corners + error = float(np.sqrt(np.mean(np.sum(residual * residual, axis=1)))) + if not math.isfinite(error): + raise ValueError("fixed pose reprojection error must be finite") + return error + + +def rotation_distance_rad( + first_xyzw: Sequence[float], + second_xyzw: Sequence[float], +) -> float: + first = np.asarray(first_xyzw, dtype=float) + second = np.asarray(second_xyzw, dtype=float) + if first.shape != (4,) or second.shape != (4,): + raise ValueError("quaternions must contain four values") + first_norm = float(np.linalg.norm(first)) + second_norm = float(np.linalg.norm(second)) + if ( + not np.all(np.isfinite(first)) + or not np.all(np.isfinite(second)) + or first_norm <= 0.0 + or second_norm <= 0.0 + ): + raise ValueError("quaternions must be finite and non-zero") + # q and -q represent the same rotation. The absolute dot-product gives + # the geodesic SO(3) distance without constructing two scipy Rotation + # objects for every branch comparison in the live tracker. + cosine_half_angle = abs( + float(np.dot(first / first_norm, second / second_norm)) + ) + return 2.0 * math.acos(float(np.clip(cosine_half_angle, 0.0, 1.0))) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/joint_pair_diagnostic.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/joint_pair_diagnostic.py new file mode 100644 index 0000000..6a8a61f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/joint_pair_diagnostic.py @@ -0,0 +1,329 @@ +"""Bounded, non-authorizing joint fit of held-pair and flexion images. + +Both stages share one installation and hinge. Every camera/parent pose is a +nuisance variable constrained by BOTH tags' raw corners, never a frozen PnP +measurement. This diagnostic deliberately cannot construct a publishable model. +""" +from itertools import product + +import numpy as np +from scipy.optimize import least_squares +from scipy.sparse import lil_matrix +from scipy.spatial.transform import Rotation + +from .ippe import solve_square_tag_ippe, square_object_points +from .motion_evidence import _axis +from .motion_image_solver import _basis +from .relative import _relative_pose +from .rigid_tag_pair import _pose_vector + + +def _split(count, maximum=36): + groups = [np.arange(start, count, 2) for start in (0, 1)] + return tuple(group[np.linspace(0, len(group)-1, min(maximum, len(group))).round().astype(int)] + for group in groups) + + +class JointPairImages: + """Ten physical parameters, plus per-image parent poses and flexion angles.""" + + def __init__(self, rows, flexion, parent_role, child_role): + self.rows, self.flexion = tuple(rows), np.asarray(flexion, dtype=bool) + self.count = len(rows) + if self.flexion.shape != (self.count,): + raise ValueError('joint_pair_phase_shape_invalid') + roles = (parent_role, child_role) + self.roles = roles + self.matrices = np.asarray([r['camera_matrix'] for r in rows]) + self.pixels = np.asarray([[r['tags'][role]['corners_xy'] for role in roles] for r in rows]) + sizes = tuple(rows[0]['tags'][role]['tag_size_m'] for role in roles) + if (self.pixels.shape != (self.count, 2, 4, 2) or self.matrices.shape != (self.count, 3, 3) + or not np.all(np.isfinite(self.pixels)) or not np.all(np.isfinite(self.matrices)) + or any(r['tags'][role]['tag_size_m'] != size for r in rows for role, size in zip(roles,sizes)) + or not np.all(self.matrices == self.matrices[0])): + raise ValueError('joint_pair_image_contract_changed') + self.objects = np.array([square_object_points(size) for size in sizes]) + self.candidates = tuple(tuple(tuple(p for p in solve_square_tag_ippe( + self.pixels[i, j], tag_size_m=sizes[j], camera_matrix=self.matrices[i]) + if p.reprojection_error_px <= 1.5) for j in range(2)) for i in range(self.count)) + if any(not candidates for pair in self.candidates for candidates in pair): + raise ValueError('joint_pair_raw_candidates_missing') + self.offsets, offset = [], 10 + for moving in self.flexion: + self.offsets.append(offset) + offset += 7 if moving else 6 + self.width = offset + self.scale = np.r_[[1.]*3+[.03]*3+[1.]*2+[.03]*2, + np.concatenate([np.r_[[1.]*3+[.03]*3, [1.] if moving else []] for moving in self.flexion])] + + def initialize(self, branches): + # Independent seeds for source parent/child and flexion parent/child. + poses = [tuple(pair[j][min(branches[(2 if moving else 0)+j],len(pair[j])-1)] + for j in range(2)) for pair,moving in zip(self.candidates,self.flexion)] + first = next(i for i,moving in enumerate(self.flexion) if not moving) + reference, origin = _relative_pose(*poses[first]) + rotations = Rotation.from_quat([_relative_pose(*pair)[0].as_quat() + for pair,moving in zip(poses,self.flexion) if moving]) + self.axis, _ = _axis(rotations) + self.basis = _basis(self.axis) + initial = np.zeros(self.width) + initial[:6] = np.r_[reference.as_rotvec(),origin] + for i, (pair,moving,offset) in enumerate(zip(poses,self.flexion,self.offsets)): + initial[offset:offset+6] = _pose_vector(pair[0]) + if moving: + relative,_ = _relative_pose(*pair) + initial[offset+6] = (relative*reference.inv()).as_rotvec()@self.axis + # Linear position fit initializes the closest-point pivot gauge. + blocks, targets = [], [] + for pair,moving,offset in zip(poses,self.flexion,self.offsets): + if not moving: + continue + _,point = _relative_pose(*pair) + rotation = Rotation.from_rotvec(self.axis*initial[offset+6]).as_matrix() + blocks.append((np.eye(3)-rotation)@self.basis) + targets.append(point-rotation@origin) + initial[8:10] = np.linalg.lstsq(np.vstack(blocks),np.concatenate(targets),rcond=None)[0] + return initial + + def geometry(self, parameters): + change = Rotation.from_rotvec(self.basis@parameters[6:8]) + return change.apply(self.axis), change.apply(self.basis@parameters[8:10]) + + def image_residual(self, shared, local, index): + axis,pivot = self.geometry(shared) + motion = Rotation.from_rotvec(axis*(local[6] if self.flexion[index] else 0.)) + reference = Rotation.from_rotvec(shared[:3]) + child = motion.apply(reference.apply(self.objects[1])+shared[3:6]-pivot)+pivot + points = np.concatenate((self.objects[0],child)) + camera = Rotation.from_rotvec(local[:3]).apply(points)+local[3:6] + if np.any(camera[:,2] <= 1e-6): + return np.full(16,1e6) + projected = camera@self.matrices[index].T + return (projected[:,:2]/projected[:,2:]-self.pixels[index].reshape(8,2)).ravel() + + def residual(self, parameters): + axis,pivot = self.geometry(parameters) + local = np.asarray([parameters[offset:offset+6] for offset in self.offsets]) + angles = np.asarray([parameters[offset+6] if moving else 0. + for offset,moving in zip(self.offsets,self.flexion)]) + motion = Rotation.from_rotvec(angles[:,None]*axis).as_matrix() + held_child = Rotation.from_rotvec(parameters[:3]).apply(self.objects[1])+parameters[3:6]-pivot + children = np.einsum('nij,kj->nki',motion,held_child)+pivot + points = np.concatenate((np.broadcast_to(self.objects[0],children.shape),children),axis=1) + parent = Rotation.from_rotvec(local[:,:3]).as_matrix() + camera = np.einsum('nij,nkj->nki',parent,points)+local[:,None,3:] + if np.any(camera[:,:,2] <= 1e-6): + return np.full(16*self.count,1e6) + projected = np.einsum('nij,nkj->nki',self.matrices,camera) + return (projected[:,:,:2]/projected[:,:,2:]-self.pixels.reshape(self.count,8,2)).ravel() + + def fit(self, branches): + initial = self.initialize(branches) + sparsity = lil_matrix((16*self.count,self.width),dtype=int) + for i,(moving,offset) in enumerate(zip(self.flexion,self.offsets)): + sparsity[16*i+8:16*i+16,:10] = 1 + sparsity[16*i:16*i+16,offset:offset+(7 if moving else 6)] = 1 + from .image_bundle_optimizer import solve_image_bundle + from .production_image_motion import ImageMotionParameters + return solve_image_bundle(self.residual,initial,sparsity=sparsity.tocsr(), + scale=self.scale,limits=ImageMotionParameters()) + + def covariance(self, fit): + """Schur-marginalize all parent poses and angles, not just the angles.""" + jac = fit.jac.toarray() if hasattr(fit.jac,'toarray') else np.asarray(fit.jac) + information = np.zeros((10,10)) + for i,(moving,offset) in enumerate(zip(self.flexion,self.offsets)): + block = jac[16*i:16*i+16]*self.scale[None,:] + nuisance = block[:,offset:offset+(7 if moving else 6)] + singular = np.linalg.svd(nuisance,compute_uv=False) + if singular[-1] <= singular[0]*np.finfo(float).eps*max(nuisance.shape): + raise ValueError('joint_pair_parent_rank_deficient') + basis,_ = np.linalg.qr(nuisance,mode='reduced') + shared = block[:,:10] + projected = shared-basis@(basis.T@shared) + information += projected.T@projected + eigen = np.linalg.eigvalsh(information) + if eigen[0] <= eigen[-1]*np.finfo(float).eps*10: + raise ValueError('joint_pair_geometry_rank_deficient') + variance = max(.03**2,float(fit.fun@fit.fun/max(1,len(fit.fun)-len(fit.x)))) + return np.linalg.inv(information)*variance*self.scale[:10,None]*self.scale[None,:10] + + def bounds(self, fit): + covariance = self.covariance(fit) + derivative = np.zeros((6,10)) + for column in range(10): + step = 1e-5*self.scale[column] + upper,lower = fit.x[:10].copy(),fit.x[:10].copy() + upper[column] += step + lower[column] -= step + derivative[:,column] = (np.concatenate(self.geometry(upper))-np.concatenate(self.geometry(lower)))/(2*step) + propagated = derivative@covariance@derivative.T + return tuple(float(3*np.sqrt(max(0.,np.linalg.eigvalsh(propagated[i:i+3,i:i+3])[-1]))) for i in (0,3)) + + def validation_angle_covariance(self, fit, other, local_states): + """Propagate shared installation AND per-image parent-pose uncertainty. + + This is conditional on one retained candidate, not branch authorization. + Independent pixels never update the shared geometry. Off-diagonal terms + must survive so a relative angle is not treated as two independent poses. + """ + source_ids = {r['image_stamp_ns'] for r in self.rows} + current_ids = {r['image_stamp_ns'] for r in other.rows} + if (source_ids & current_ids or len(source_ids) != self.count + or len(current_ids) != other.count): + raise ValueError('joint_pair_angle_covariance_requires_independent_images') + if (len(local_states) != other.count or self.roles != other.roles + or not np.array_equal(self.objects, other.objects) + or not np.array_equal(self.matrices[0], other.matrices[0])): + raise ValueError('joint_pair_validation_contract_changed') + other.axis, other.basis = self.axis, self.basis + shared = fit.x[:10] + sensitivity = np.zeros((other.count, 10)) + noise = np.zeros(other.count) + variance = max(.03**2, float(fit.fun@fit.fun/max(1, len(fit.fun)-len(fit.x)))) + for i, (moving, state) in enumerate(zip(other.flexion, local_states)): + state = np.asarray(state, dtype=float) + width = 7 if moving else 6 + if state.shape != (width,) or not np.all(np.isfinite(state)): + raise ValueError('joint_pair_validation_state_invalid') + if not moving: + continue + scale = np.r_[[1.]*3, [.03]*3, 1.] + local_jac = np.empty((16, width)) + shared_jac = np.empty((16, 10)) + for column in range(width): + delta = 1e-5*scale[column] + upper, lower = state.copy(), state.copy() + upper[column] += delta; lower[column] -= delta + local_jac[:, column] = (other.image_residual(shared, upper, i) + -other.image_residual(shared, lower, i))/(2*delta) + for column in range(10): + delta = 1e-5*self.scale[column] + upper, lower = shared.copy(), shared.copy() + upper[column] += delta; lower[column] -= delta + shared_jac[:, column] = (other.image_residual(upper, state, i) + -other.image_residual(lower, state, i))/(2*delta) + u, singular, vh = np.linalg.svd(local_jac*scale, full_matrices=False) + if singular[-1] <= singular[0]*np.finfo(float).eps*max(local_jac.shape): + raise ValueError('joint_pair_validation_angle_unobservable') + inverse = scale[:, None]*((vh.T/singular)@u.T) + sensitivity[i] = -(inverse@shared_jac)[-1] + noise[i] = variance*(inverse[-1]@inverse[-1]) + return np.diag(noise)+sensitivity@self.covariance(fit)@sensitivity.T + + def validate(self, fit, other, *, return_states=False, return_local_states=False): + # The ten shared physical variables stay frozen on held-out images. + other.axis,other.basis = self.axis,self.basis + residuals,states,locals_ = [],[],[] + for i,(pair,moving) in enumerate(zip(other.candidates,other.flexion)): + alternatives = [] + for parent,child in product(*pair): + seed = _pose_vector(parent) + if moving: + relative,_ = _relative_pose(parent,child) + seed = np.r_[seed,(relative*Rotation.from_rotvec(fit.x[:3]).inv()).as_rotvec()@self.geometry(fit.x)[0]] + result = least_squares(lambda local:other.image_residual(fit.x[:10],local,i),seed, + x_scale=np.r_[[1.]*3+[.03]*3,[1.] if moving else []],max_nfev=100, + ftol=1e-9,xtol=1e-9,gtol=1e-9) + if not result.success or not np.all(np.isfinite(result.fun)): + raise ValueError('joint_pair_validation_not_evaluable') + alternatives.append(result) + best = min(alternatives,key=lambda result:result.cost) + residuals.append(best.fun) + states.append(np.r_[best.x[:3],best.x[6] if moving else 0.]) + locals_.append(best.x.copy()) + if return_local_states: + return np.asarray(residuals), np.asarray(states), tuple(locals_) + return (np.asarray(residuals),np.asarray(states)) if return_states else np.asarray(residuals) + + +def diagnose_joint_pair(source_rows, flexion_rows, parent_role, child_role, *, on_candidate=None): + """Return every candidate; no winner selection or motion authorization.""" + if min(len(source_rows),len(flexion_rows)) < 24: + raise ValueError('joint_pair_independent_images_missing') + groups = [tuple(r['image_stamp_ns'] for r in rows) for rows in (source_rows,flexion_rows)] + if any(stamps != tuple(sorted(set(stamps))) for stamps in groups) or max(groups[0]) >= min(groups[1]): + raise ValueError('joint_pair_source_order_invalid') + splits = [_split(len(rows)) for rows in (source_rows,flexion_rows)] + selections = [[rows[i] for rows,split in zip((source_rows,flexion_rows),splits) for i in split[part]] for part in (0,1)] + phases = [[False]*len(splits[0][part])+[True]*len(splits[1][part]) for part in (0,1)] + training = JointPairImages(selections[0],phases[0],parent_role,child_role) + validation = JointPairImages(selections[1],phases[1],parent_role,child_role) + candidates = [] + for branches in product(range(2),repeat=4): + item = dict(branches=branches,converged=False) + try: + fit = training.fit(branches) + from dataclasses import asdict + attempts = getattr(fit,'image_solver_attempts',()) + item.update(evaluations=sum(a.evaluations for a in attempts) if attempts else int(fit.nfev), + training_cost=float(fit.cost),solver_attempts=[asdict(a) for a in attempts]) + if not fit.success or not np.all(np.isfinite(fit.fun)): + raise ValueError('joint_pair_solver_not_converged') + axis,pivot = training.bounds(fit) + residuals,states,local_states = training.validate(fit,validation,return_local_states=True) + errors = np.sqrt(np.mean(np.sum(residuals.reshape(-1,2,4,2)**2,axis=3),axis=2)) + item.update(converged=True,local_axis_bound_deg=float(np.degrees(axis)),local_pivot_bound_m=pivot, + validation_max_parent_px=float(errors[:,0].max()),validation_max_child_px=float(errors[:,1].max()), + validation_errors_by_role_px=errors.tolist(),validation_motion_coordinates=states.tolist(), + axis_parent_xyz=tuple(training.geometry(fit.x)[0]),pivot_parent_xyz_m=tuple(training.geometry(fit.x)[1]), + installation_quaternion_xyzw=tuple(Rotation.from_rotvec(fit.x[:3]).as_quat()), + installation_translation_xyz_m=tuple(fit.x[3:6])) + # An unavailable uncertainty estimate is a veto for future output + # certification, never grounds to erase a competing image model. + try: + covariance = training.validation_angle_covariance(fit, validation, local_states) + item.update(angle_uncertainty_available=True, + conditional_angle_covariance_rad2=covariance.tolist(), + conditional_angle_bounds_rad=(3*np.sqrt(np.maximum(0., np.diag(covariance)))).tolist()) + except (ValueError, np.linalg.LinAlgError) as error: + item.update(angle_uncertainty_available=False, angle_uncertainty_reason=str(error)) + except (ValueError,np.linalg.LinAlgError) as error: + item['reason'] = str(error) + candidates.append(item) + if on_candidate is not None: + on_candidate(item) + return dict(policy='joint_pair_hinge_diagnostic_v1',publication_allowed=False, + training_stamps=[r['image_stamp_ns'] for r in selections[0]], + validation_stamps=[r['image_stamp_ns'] for r in selections[1]],candidates=candidates, + comparisons=_diagnostic_comparisons(candidates,phases[1])) + + +def _diagnostic_comparisons(candidates, phases): + """Report source/flexion discrimination separately, not an authorization.""" + from .image_model_selection import compare_image_losses, holm_adjusted_probabilities + available = [i for i,candidate in enumerate(candidates) if candidate.get('converged')] + if not available: + return dict(training_candidate=None,phase_tests=[]) + winner = min(available,key=lambda i:candidates[i]['training_cost']) + best = candidates[winner] + errors = np.asarray(best['validation_errors_by_role_px']) + motion = np.asarray(best['validation_motion_coordinates']) + phases = np.asarray(phases,dtype=bool) + comparisons,identities = [],[] + for i,alternative in enumerate(candidates): + if i == winner: + continue + equivalent = False + if alternative.get('converged'): + turn = (Rotation.from_quat(best['installation_quaternion_xyzw']).inv() + *Rotation.from_quat(alternative['installation_quaternion_xyzw'])).magnitude() + axis_angle = np.arccos(np.clip(abs(np.dot(best['axis_parent_xyz'],alternative['axis_parent_xyz'])),0.,1.)) + equivalent = (max(turn,axis_angle) <= np.deg2rad(.1) + and np.linalg.norm(np.asarray(best['installation_translation_xyz_m']) + -alternative['installation_translation_xyz_m']) <= .0001 + and np.linalg.norm(np.asarray(best['pivot_parent_xyz_m'])-alternative['pivot_parent_xyz_m']) <= .0001) + for moving in (False,True): + mask = phases == moving + probability = 1. + if equivalent: + probability = 0. + elif alternative.get('converged'): + other = np.asarray(alternative['validation_errors_by_role_px']) + probability = compare_image_losses(np.sqrt(np.mean(errors[mask]**2,axis=1)), + np.sqrt(np.mean(other[mask]**2,axis=1)),motion[mask],.03) + identities.append((i,'flexion' if moving else 'source')) + comparisons.append((len(comparisons),probability)) + adjusted = holm_adjusted_probabilities(comparisons) + return dict(training_candidate=winner,phase_tests=[dict(candidate=identities[i][0], + phase=identities[i][1],adjusted_p_value=p) for i,p in adjusted]) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/kinematic_chain_diagnostic.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/kinematic_chain_diagnostic.py new file mode 100644 index 0000000..8009c37 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/kinematic_chain_diagnostic.py @@ -0,0 +1,4 @@ +"""Compatibility import for retained diagnostic replays; no release authority.""" +from .kinematic_chain_images import KinematicFingerChainImages + +__all__ = ["KinematicFingerChainImages"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/kinematic_chain_images.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/kinematic_chain_images.py new file mode 100644 index 0000000..b783c65 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/kinematic_chain_images.py @@ -0,0 +1,134 @@ +"""Non-authorizing chain fit with physically linked stage reference poses. + +Held MCP/PIP positions may differ between visits. Represent that difference by +rotations around the same fitted hinges, not independent six-DOF camera poses. +The first angle in each proximal stage fixes only a numerical gauge, never an +encoder or URDF zero. No held-position prior or relaxed acceptance is added. +""" + +import numpy as np +from scipy.spatial.transform import Rotation + +from .finger_chain_images import FingerChainImages + + +class KinematicFingerChainImages(FingerChainImages): + def __init__(self, rows, phases, roles, *, pip_dip_distance_m=None, + mcp_pip_distance_m=None): + super().__init__(rows, phases, roles, pip_dip_distance_m=pip_dip_distance_m, + mcp_pip_distance_m=mcp_pip_distance_m) + self.stage_columns = {phase: self.static_width+2*phase for phase in (0, 1)} + static_scale = np.r_[self.scale[:self.static_width], np.ones(4)] + self.static_width = len(static_scale) + anchors = {int(np.flatnonzero(self.phases == phase)[0]) for phase in (0, 1)} + self.angle_columns = {index: self.static_width+column + for column, index in enumerate(i for i in range(self.count) if i not in anchors)} + self.scale = np.r_[static_scale, np.ones(len(self.angle_columns))] + + def initialize(self, branches): + initial = super().initialize(branches) + for phase in (0, 1): + indices = np.flatnonzero(self.phases == phase) + # The base initializer measures angles from the canonical DIP + # parent frame. Recenter them at the first stage image and retain + # that offset explicitly in the kinematic reference parameters. + pair = self.candidates[indices[0]] + pose = pair[0][min(branches[2*phase], len(pair[0])-1)] + parent = Rotation.from_rotvec(initial[:3]) + axis, _ = self.geometry(initial, phase) + offset = (Rotation.from_quat(pose.quaternion_xyzw)*parent.inv()).as_rotvec()@parent.apply(axis) + initial[self.stage_columns[phase]+phase] = offset + for index in indices: + if index in self.angle_columns: + initial[self.angle_columns[index]] -= offset + return initial + + def _turn(self, points, angles, shared, phase): + axis, pivot = self.geometry(shared, phase) + matrices = Rotation.from_rotvec(np.asarray(angles)[:, None]*axis).as_matrix() + return np.einsum('nij,nkj->nki', matrices, points-pivot)+pivot + + def training_signature(self, shared): + """Physical state for numerical-solution grouping; no holdout inputs.""" + camera_rotation = Rotation.from_rotvec(shared[:3]).as_matrix() + poses = [] + for phase in range(3): + points = np.vstack((np.zeros(3), np.eye(3)))[None, :, :] + if phase < 2: + column = self.stage_columns[phase] + points = self._turn(self._turn(points, [shared[column+1]], shared, 1), + [shared[column]], shared, 0) + points = points[0]@camera_rotation.T+shared[3:6] + pose = np.eye(4) + pose[:3, :3] = (points[1:]-points[0]).T + pose[:3, 3] = points[0] + poses.append(pose.tolist()) + mount = np.eye(4) + mount[:3, :3] = Rotation.from_rotvec(shared[6:9]).as_matrix() + mount[:3, 3] = shared[9:12] + return dict(geometry=self.physical_geometry(shared).tolist(), + installation=mount.tolist(), stage_poses=poses) + + def camera_geometry(self, shared): + """Canonical camera-frame axes and nearby points on their lines. + + Keep points near the joints, not closest to the camera origin: the + latter amplifies small axis tilts by the camera-to-hand distance. + This canonical frame is not an independently verified physical zero. + """ + geometry = self.physical_geometry(shared) + rotation = Rotation.from_rotvec(shared[:3]) + return np.column_stack((rotation.apply(geometry[:, :3]), + rotation.apply(geometry[:, 3:])+shared[3:6])) + + def camera_geometry_covariance(self, shared, covariance): + """Propagate the full shared covariance, including pose correlations. + + Conditional on one candidate, camera intrinsics and imposed geometry; + does not include ambiguity between candidates or extrinsic errors. + """ + width = self.static_width + shared = np.asarray(shared, dtype=float)[:width] + covariance = np.asarray(covariance, dtype=float) + if (shared.shape != (width,) or covariance.shape != (width, width) + or not np.all(np.isfinite(shared)) + or not np.all(np.isfinite(covariance))): + raise ValueError('invalid_shared_geometry_covariance') + derivative = np.zeros((18, width)) + for column in range(width): + step = 1e-5*self.scale[column] + upper, lower = shared.copy(), shared.copy() + upper[column] += step + lower[column] -= step + derivative[:, column] = (self.camera_geometry(upper) + -self.camera_geometry(lower)).ravel()/(2*step) + return derivative@covariance@derivative.T + + def project(self, shared, angles, phases): + child = Rotation.from_rotvec(shared[6:9]).apply(self.objects[1])+shared[9:12] + points = np.broadcast_to(np.concatenate((self.objects[0], child)), + (len(angles), 8, 3)).copy() + for phase in range(3): + mask = phases == phase + count = int(np.count_nonzero(mask)) + if not count: + continue + if phase == 2: + points[mask, 4:] = self._turn(points[mask, 4:], angles[mask], shared, 2) + else: + column = self.stage_columns[phase] + mcp = np.full(count, shared[column]) + pip = np.full(count, shared[column+1]) + if phase == 0: + mcp += angles[mask] + else: + pip += angles[mask] + # Distal-to-proximal composition; both Tags move rigidly in + # these stages because the DIP command is held unchanged. + points[mask] = self._turn(self._turn(points[mask], pip, shared, 1), + mcp, shared, 0) + camera = points@Rotation.from_rotvec(shared[:3]).as_matrix().T+shared[3:6] + if np.any(camera[:, :, 2] <= 1e-6): + return np.full((len(angles), 8, 2), 1e6) + projected = camera@self.matrix.T + return projected[:, :, :2]/projected[:, :, 2:] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/measured_transfer.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/measured_transfer.py new file mode 100644 index 0000000..06d4e79 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/measured_transfer.py @@ -0,0 +1,118 @@ +"""Use measured parent geometry as uncertain evidence, never as exact CAD. + +New hinges are fitted to their own training images within the source-bound +geometry uncertainty. The same domain is checked on model readback. These +bounds are not a proof against systematic camera/Tag bias. +""" + +from dataclasses import dataclass, fields +import math +from typing import ClassVar + +import numpy as np +from scipy.spatial.transform import Rotation + +from .image_motion_model import ImageMotionModel +from .motion_evidence import MotionEvidenceParameters +from .source_hinge import SourceHinge +from .cad_hinge import ParallelAxisGeometry + +MEASURED_TRANSFER_POLICY = "image_hinge_v4_uncertain_source_geometry" + + +@dataclass(frozen=True) +class TransferGeometryCheck: + joint: str + axis_difference_rad: float + axis_allowance_rad: float + distance_difference_m: float + distance_allowance_m: float + + @property + def consistent(self): + return (self.axis_difference_rad <= self.axis_allowance_rad+1e-10 + and self.distance_difference_m <= self.distance_allowance_m+1e-10) + + +def transfer_geometry_checks(geometry, constraints, sources, bounds): + """Require publishable precision, including during model readback.""" + checks, inherited, precision_accepted = assess_transfer_geometry(geometry, constraints, sources, bounds) + if not precision_accepted: + raise ValueError("image_motion_geometry_uncertain") + return checks, inherited + + +def assess_transfer_geometry(geometry, constraints, sources, bounds): + """Match independent fixed-source hinges using their measured error bounds. + + Candidate evaluation is separate from authorization: insufficient precision + prevents freezing a model, but does not erase a converged image explanation + that must still challenge the winner on independent images. Invalid source + identities or topology remain errors, not evaluable competing models. + """ + if (not constraints or not sources or any(not isinstance(c, ParallelAxisGeometry) for c in constraints) + or any(not isinstance(s, SourceHinge) for s in sources)): + raise ValueError("measured_transfer_sources_invalid") + parents = {s.geometry.relation.joint: s for s in sources} + children = {g.relation.joint: g for g in geometry} + uncertainty = {name: (axis, point) for name, axis, point in bounds} + if (len(parents) != len(sources) or set(parents) & set(children) + or set(parents) != {c.parent_joint for c in constraints} + or set(children) != {c.child_joint for c in constraints} + or len(children) != len(constraints) or len(uncertainty) != len(bounds) + or set(uncertainty) != set(children)): + raise ValueError("measured_transfer_graph_unsupported") + checks, inherited, precision_accepted = [], {}, True + limits = MotionEvidenceParameters() + for c in constraints: + source, child = parents[c.parent_joint], children[c.child_joint] + g = source.geometry + if g.relation.child_role != child.relation.parent_role: + raise ValueError("measured_transfer_roles_changed") + axis_bound, point_bound = uncertainty[c.child_joint] + inherited_axis = source.child_axis_uncertainty_rad + inherited_point = source.child_point_uncertainty_m + c.distance_m*inherited_axis + if (any(not math.isfinite(v) or v <= 0 for v in (axis_bound, point_bound)) + or axis_bound+inherited_axis > limits.maximum_split_axis_difference_rad + or point_bound+inherited_point > limits.maximum_frame_pivot_error_m): + precision_accepted = False + axis = c.axis_sign*Rotation.from_quat(g.reference_quaternion_xyzw).inv().apply(g.axis_parent_xyz) + measured_axis = np.asarray(child.axis_parent_xyz) + angle = math.atan2(np.linalg.norm(np.cross(axis, measured_axis)), axis @ measured_axis) + vector = np.asarray(g.mount_child_xyz_m) + child.pivot_parent_xyz_m + # Check the exact domain used by the bounded solver, in the fitted + # axis frame. New image uncertainty cannot enlarge the source prior. + distance = np.linalg.norm(vector-measured_axis*(measured_axis @ vector)) + checks.append(TransferGeometryCheck(c.child_joint, angle, inherited_axis, + abs(float(distance)-c.distance_m), inherited_point)) + inherited[c.child_joint] = (inherited_axis, inherited_point) + return tuple(checks), inherited, precision_accepted + + +@dataclass(frozen=True) +class MeasuredTransferImageMotionModel(ImageMotionModel): + POLICY: ClassVar[str] = MEASURED_TRANSFER_POLICY + policy: str = MEASURED_TRANSFER_POLICY + constraints: tuple[ParallelAxisGeometry, ...] = () + source_urdf_sha256: str = "" + source_hinges: tuple[SourceHinge, ...] = () + current_geometry_uncertainty: tuple[tuple[str, float, float], ...] = () + + def __post_init__(self): + super().__post_init__() + if (len(self.source_urdf_sha256) != 64 + or any(c not in "0123456789abcdef" for c in self.source_urdf_sha256) + or any(not isinstance(v, tuple) for v in (self.constraints, self.source_hinges, + self.current_geometry_uncertainty))): + raise ValueError("image_model_source_geometry_missing") + checks, _ = transfer_geometry_checks(self.geometry, self.constraints, + self.source_hinges, self.current_geometry_uncertainty) + if not all(c.consistent for c in checks): + raise ValueError("image_motion_source_geometry_conflict") + + +def bind_measured_transfer(model, constraints, sources, source_hash, bounds): + values = {f.name: getattr(model, f.name) for f in fields(ImageMotionModel) if f.name != "policy"} + return MeasuredTransferImageMotionModel(**values, constraints=tuple(constraints), + source_hinges=tuple(sources), source_urdf_sha256=source_hash, + current_geometry_uncertainty=tuple(bounds)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/measured_transfer_solver.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/measured_transfer_solver.py new file mode 100644 index 0000000..b6d90af --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/measured_transfer_solver.py @@ -0,0 +1,80 @@ +"""Image fitting with bounded deviations from an independently measured hinge.""" + +import math +import numpy as np +from scipy.sparse import lil_matrix +from scipy.spatial.transform import Rotation + +from .motion_image_solver import ImageHingeBundle, _basis +from .hinge_uncertainty import unconstrained_hinge_linearization +from .measured_transfer import transfer_geometry_checks +from .motion_image_types import ImageHingeGeometry +from .image_bundle_optimizer import solve_image_bundle + + +class MeasuredTransferImageHingeBundle(ImageHingeBundle): + def __init__(self, frames, relations, poses, *, constraints, sources): + super().__init__(frames, relations, poses) + # Validate topology and source precision before removing any freedoms. + initial_geometry = tuple(ImageHingeBundle.geometry_values(self, self.initial, i) for i in range(self.joints)) + geometry = tuple(ImageHingeGeometry(r, tuple(a), tuple(q.as_quat()), tuple(p), tuple(m)) + for r, (a, q, p, m) in zip(relations, initial_geometry)) + transfer_geometry_checks(geometry, constraints, sources, + tuple((r.joint, 1e-12, 1e-12) for r in relations)) + parents = {s.geometry.relation.joint: s for s in sources} + by_child = {c.child_joint: c for c in constraints} + self.source_axes, self.source_mounts, self.distances, self.tangents = [], [], [], [] + self.lower = np.full(len(self.initial), -np.inf) + self.upper = np.full(len(self.initial), np.inf) + for i, relation in enumerate(relations): + c = by_child[relation.joint] + source = parents[c.parent_joint] + g = source.geometry + axis = c.axis_sign*Rotation.from_quat(g.reference_quaternion_xyzw).inv().apply(g.axis_parent_xyz) + tangent = _basis(axis) + old_axis, _, pivot, _ = initial_geometry[i] + radial = old_axis-axis*(axis @ old_axis) + tilt = math.atan2(np.linalg.norm(radial), axis @ old_axis) + azimuth = math.atan2(tangent[:, 1] @ radial, tangent[:, 0] @ radial) + vector = pivot+np.asarray(g.mount_child_xyz_m) + phase = math.atan2(tangent[:, 1] @ vector, tangent[:, 0] @ vector) + radius_bound = source.child_point_uncertainty_m+c.distance_m*source.child_axis_uncertainty_rad + self.initial[i*10:i*10+2] = (np.clip(tilt, 1e-9, source.child_axis_uncertainty_rad*.99), azimuth) + self.initial[i*10+5:i*10+7] = phase, 0. + self.scale[i*10+5] = 1. + self.lower[i*10], self.upper[i*10] = 0., source.child_axis_uncertainty_rad + self.lower[i*10+6], self.upper[i*10+6] = -radius_bound, radius_bound + self.source_axes.append(axis) + self.source_mounts.append(np.asarray(g.mount_child_xyz_m)) + self.distances.append(c.distance_m) + self.tangents.append(tangent) + + def geometry_values(self, parameters, index): + v = parameters[index*10:(index+1)*10] + original = self.source_axes[index] + tangent = self.tangents[index] + tilt_direction = tangent @ [math.cos(v[1]), math.sin(v[1])] + change = Rotation.from_rotvec(np.cross(original, tilt_direction)*v[0]) + axis = change.apply(original) + reference = Rotation.from_rotvec(v[2:5])*self.references[index] + basis = change.apply(tangent.T).T + pivot = (self.distances[index]+v[6])*(basis @ [math.cos(v[5]), math.sin(v[5])]) + mount = self.source_mounts[index] + pivot -= mount-axis*(axis @ mount) + return axis, reference, pivot, v[7:10] + + def solve(self, limits): + width = 8*self.joints + sparsity = lil_matrix((self.count*width, len(self.initial)), dtype=int) + for frame in range(self.count): + for joint in range(self.joints): + rows = slice(frame*width+joint*8, frame*width+(joint+1)*8) + sparsity[rows, self.geometry_parameter_indices(joint)] = 1 + if frame: + sparsity[rows, self.static_parameter_count+(frame-1)*self.joints+joint] = 1 + return solve_image_bundle(self.residual, self.initial, bounds=(self.lower, self.upper), + sparsity=sparsity.tocsr(), scale=self.scale, limits=limits) + + def uncertainty_problem(self, fit): + angles = np.vstack((np.zeros(self.joints), fit.x[self.static_parameter_count:].reshape(-1, self.joints))) + return unconstrained_hinge_linearization(self, fit, angles) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_evidence.py new file mode 100644 index 0000000..d749121 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_evidence.py @@ -0,0 +1,443 @@ +"""Pre-freeze planar-branch evidence from a single articulated motion. + +The measurements are actual image candidates, never SDK-derived angles. A +hinge has one rotation axis and one fixed pivot in its parent Tag coordinates: +``R = exp(theta * axis) R_ref`` and ``t = pivot + R * mount``. These are the +same fixed-axis/fixed-pivot relations used by candidate_selection's trajectory +score. Unlike that diagnostic ranking, this module requires a unique hypothesis +to pass absolute quality and observability checks before authorizing a branch. + +The 1.5 mm / 1 degree RMS scales come from that existing trajectory score. +Motion span, cross-validation and conditioning gates are additional evidence +requirements, not changes to final calibration accuracy limits. Calibration +holdout and previously frozen references must never enter this fit API. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from itertools import permutations, product +import math +from typing import Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + +from .parameters import DEFAULT_POSE_TRACKING_PARAMETERS +from .relative import _relative_pose +from .types import SquareTagPose + + +@dataclass(frozen=True) +class MotionRelation: + joint: str + parent_role: str + child_role: str + + +@dataclass(frozen=True) +class RoleCandidates: + """Actual candidates; ``frozen`` means already selected by prior evidence. + + A previously frozen moving parent must be selected in this image using its + existing constraint before a new relation is trained. Its last image's pose + is not a substitute. Raw current-frame roots passed to select_motion_frame + remain a candidate set; the tracker's separate frozen flag is not this flag. + """ + role: str + candidates: tuple[SquareTagPose, ...] + frozen: bool = False + + +@dataclass(frozen=True) +class MotionEvidenceFrame: + stamp_ns: int + roles: tuple[RoleCandidates, ...] + + +@dataclass(frozen=True) +class MotionRoleSelection: + role: str + pose: SquareTagPose + + +@dataclass(frozen=True) +class MotionEvidenceParameters: + minimum_motion_rad: float = math.radians(15.0) + angular_bin_rad: float = math.radians(1.0) + minimum_motion_bins: int = 12 + minimum_translation_span_m: float = 0.003 + maximum_pivot_condition: float = 100.0 + maximum_pivot_rms_m: float = 0.0015 + maximum_pivot_p95_m: float = 0.003 + maximum_off_axis_rms_rad: float = math.radians(1.0) + maximum_off_axis_p95_rad: float = math.radians(2.0) + maximum_split_axis_difference_rad: float = math.radians(3.0) + maximum_frame_off_axis_rad: float = math.radians(3.0) + maximum_frame_pivot_error_m: float = 0.003 + + def __post_init__(self): + for name, value in vars(self).items(): + if not math.isfinite(value) or value <= 0: + raise ValueError(f"{name} must be finite and positive") + if type(self.minimum_motion_bins) is not int or self.minimum_motion_bins < 12: + raise ValueError("minimum_motion_bins must be an integer >= 12") + + +@dataclass(frozen=True) +class MotionConstraintResidual: + off_axis_rad: float + pivot_error_m: float + accepted: bool + + +@dataclass(frozen=True) +class FrozenMotionConstraint: + relation: MotionRelation + reference_quaternion_xyzw: tuple[float, float, float, float] + axis_parent_xyz: tuple[float, float, float] + pivot_parent_xyz_m: tuple[float, float, float] + mount_child_xyz_m: tuple[float, float, float] + source_stamps_ns: tuple[int, ...] + maximum_off_axis_rad: float + maximum_pivot_error_m: float + + def evaluate(self, parent: SquareTagPose, child: SquareTagPose) -> MotionConstraintResidual: + rotation, translation = _relative_pose(parent, child) + off_axis, pivot = _residuals(self, Rotation.from_quat([rotation.as_quat()]), + np.asarray([translation])) + a, p = float(off_axis[0]), float(pivot[0]) + return MotionConstraintResidual(a, p, bool( + _eligible(parent) and _eligible(child) + and a <= self.maximum_off_axis_rad and p <= self.maximum_pivot_error_m)) + + +@dataclass(frozen=True) +class MotionRelationQuality: + joint: str + reason: str + motion_rad: float = 0.0 + motion_bins: int = 0 + translation_span_m: float = 0.0 + pivot_condition: float = 0.0 + pivot_rms_m: float = 0.0 + pivot_p95_m: float = 0.0 + off_axis_rms_rad: float = 0.0 + off_axis_p95_rad: float = 0.0 + split_axis_difference_rad: float = 0.0 + + +@dataclass(frozen=True) +class MotionHypothesis: + branches: tuple[tuple[str, int], ...] + relations: tuple[MotionRelationQuality, ...] + accepted: bool + + +@dataclass(frozen=True) +class MotionBranchResolution: + resolved: bool + reason: str + selections: tuple[MotionRoleSelection, ...] = () + constraints: tuple[FrozenMotionConstraint, ...] = () + hypotheses: tuple[MotionHypothesis, ...] = () + + +@dataclass(frozen=True) +class MotionFrameSelection: + resolved: bool + reason: str + selections: tuple[MotionRoleSelection, ...] = () + + +def _eligible(pose: SquareTagPose) -> bool: + values = (*pose.quaternion_xyzw, *pose.translation_xyz_m, pose.reprojection_error_px) + if (len(pose.quaternion_xyzw) != 4 or len(pose.translation_xyz_m) != 3 + or not np.all(np.isfinite(values)) + or not np.isclose(np.linalg.norm(pose.quaternion_xyzw), 1.0, atol=1e-5) + or pose.translation_xyz_m[2] <= 0 + or not 0 <= pose.reprojection_error_px <= DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px): + return False + normal = Rotation.from_quat(pose.quaternion_xyzw).apply([0, 0, 1]) + tilt = math.acos(float(np.clip(abs(normal[2]), 0, 1))) + return tilt <= DEFAULT_POSE_TRACKING_PARAMETERS.maximum_tag_tilt_rad + + +def _distance(first: SquareTagPose, second: SquareTagPose) -> tuple[float, float]: + return (float((Rotation.from_quat(first.quaternion_xyzw).inv() + * Rotation.from_quat(second.quaternion_xyzw)).magnitude()), + float(np.linalg.norm(np.subtract(first.translation_xyz_m, second.translation_xyz_m)))) + + +def _equivalent(first: SquareTagPose, second: SquareTagPose) -> bool: + angle, distance = _distance(first, second) + return angle <= math.radians(1.0) and distance <= 0.001 + + +def _validate_relations(relations: Sequence[MotionRelation]) -> tuple[str, ...]: + if not relations or len({r.joint for r in relations}) != len(relations): + raise ValueError("motion relations need non-empty unique joints") + roles = tuple(dict.fromkeys(role for r in relations for role in (r.parent_role, r.child_role))) + if len(roles) > 8 or any(not r.joint or not r.parent_role or not r.child_role + or r.parent_role == r.child_role for r in relations): + raise ValueError("motion relations need a bounded articulated graph") + return roles + + +def _candidate_map(items: Sequence[RoleCandidates], roles: Sequence[str]): + result = {item.role: item for item in items} + if len(result) != len(items) or any(role not in result for role in roles): + return None + for role in roles: + item = result[role] + if not 1 <= len(item.candidates) <= 2 or (item.frozen and len(item.candidates) != 1): + return None + valid = tuple(candidate for candidate in item.candidates if _eligible(candidate)) + if not valid: + return None + result[role] = RoleCandidates(role, valid, item.frozen) + return result + + +def motion_frame_rejection(frame: MotionEvidenceFrame, relations: Sequence[MotionRelation], + *, require_frozen_roots: bool = False, +) -> str: + """Admission uses the solver's existing candidate gates, never fit scores. + + Reject a whole incomplete image, preserving every eligible alternative in + accepted images. The raw rejected image remains part of the capture journal. + """ + roles = _validate_relations(relations) + candidates = _candidate_map(frame.roles, roles) + if candidates is None: + return "motion_candidates_missing_or_invalid" + roots = set(roles) - {relation.child_role for relation in relations} + if require_frozen_roots and any(not candidates[role].frozen for role in roots): + return "root_pose_not_frozen" + return "" + + +def connect_candidate_families(items, *, strict=True): + """Associate candidate identities, never their per-image reprojection ranks. + + Missing alternatives remain missing. Non-strict association is only a + numerical initializer; it must never authorize a branch or certify motion. + """ + # Anchor where both eligible roots are available. If an alternative + # temporarily fails the image-quality gate it stays missing; never copy + # the surviving root into both families to invent evidence. + anchor = max(range(len(items)), key=lambda i: len(items[i].candidates)) + count = len(items[anchor].candidates) + families = [[None] * len(items) for _ in range(count)] + for index, candidate in enumerate(items[anchor].candidates): + families[index][anchor] = candidate + for sequence in (range(anchor + 1, len(items)), range(anchor - 1, -1, -1)): + previous = list(items[anchor].candidates) + for frame_index in sequence: + current = items[frame_index].candidates + def cost(order): + return sum(_distance(previous[family], candidate)[0] + for family, candidate in zip(order, current)) + orders = sorted(permutations(range(count), len(current)), key=cost) + if (strict and len(orders) == 2 and abs(cost(orders[0]) - cost(orders[1])) < 1e-9 + and not _equivalent(previous[0], previous[1])): + return None, "motion_candidate_assignment_ambiguous" + for family, candidate in zip(orders[0], current): + angle, translation = _distance(previous[family], candidate) + p = DEFAULT_POSE_TRACKING_PARAMETERS + if strict and (angle > p.maximum_pose_jump_rad or translation > p.maximum_translation_jump_m): + return None, "motion_candidate_family_discontinuous" + families[family][frame_index] = candidate + previous[family] = candidate + return families, "" + + +def _connect_paths(frames: Sequence[MotionEvidenceFrame], roles: Sequence[str]): + """Preserve both continuous families without treating continuity as truth.""" + candidates = [_candidate_map(frame.roles, roles) for frame in frames] + if any(item is None for item in candidates): + return None, "motion_candidates_missing_or_invalid" + paths = {} + for role in roles: + items = [frame[role] for frame in candidates] + if any(item.frozen != items[0].frozen for item in items): + return None, "motion_candidate_family_interrupted" + families, reason = connect_candidate_families(items) + if reason: + return None, reason + paths[role] = families + # Near-coincident IPPE roots represent one physical hypothesis, not two. + for role, families in paths.items(): + if len(families) == 2 and all(a is not None and b is not None and _equivalent(a, b) + for a, b in zip(*families)): + paths[role] = families[:1] + return paths, "" + + +def _axis(rotations: Rotation) -> tuple[np.ndarray, np.ndarray]: + vectors = (rotations * rotations[0].inv()).as_rotvec() + axis = np.linalg.svd(vectors, full_matrices=False)[2][0] + if np.dot(axis, vectors[-1]) < 0: + axis = -axis + return axis, vectors @ axis + + +def _fit_constraint(relation, rotations, points, stamps, parameters): + axis, angles = _axis(rotations) + projected = Rotation.from_rotvec(angles[:, None] * axis) * rotations[0] + # One axial pivot gauge is unobservable for any revolute joint. Projecting + # onto the measured rotation axis gives rank five instead of fitting that + # gauge to tiny orientation noise with an arbitrary sixth parameter. + design = np.concatenate((np.tile(np.eye(3), (len(points), 1, 1)), + projected.as_matrix()), axis=2).reshape(-1, 6) + u, singular, vh = np.linalg.svd(design, full_matrices=False) + condition = float(singular[0] / max(singular[4], np.finfo(float).tiny)) + solution = vh[:5].T @ ((u[:, :5].T @ points.ravel()) / singular[:5]) + model = FrozenMotionConstraint(relation, tuple(rotations[0].as_quat()), tuple(axis), + tuple(solution[:3]), tuple(solution[3:]), tuple(stamps), + parameters.maximum_frame_off_axis_rad, parameters.maximum_frame_pivot_error_m) + return model, condition + + +def _residuals(model: FrozenMotionConstraint, rotations: Rotation, points: np.ndarray): + delta = rotations * Rotation.from_quat(model.reference_quaternion_xyzw).inv() + axis = np.asarray(model.axis_parent_xyz) + projected = Rotation.from_rotvec((delta.as_rotvec() @ axis)[:, None] * axis) + angular = (projected.inv() * delta).magnitude() + predicted = np.asarray(model.pivot_parent_xyz_m) + rotations.apply(model.mount_child_xyz_m) + return angular, np.linalg.norm(points - predicted, axis=1) + + +def _metrics(angular, pivot): + return (float(np.sqrt(np.mean(pivot**2))), float(np.percentile(pivot, 95)), + float(np.sqrt(np.mean(angular**2))), float(np.percentile(angular, 95))) + + +def _passes(values, parameters): + return all(value <= limit for value, limit in zip(values, ( + parameters.maximum_pivot_rms_m, parameters.maximum_pivot_p95_m, + parameters.maximum_off_axis_rms_rad, parameters.maximum_off_axis_p95_rad))) + + +def _relation_evidence(relation, parent, child, stamps, parameters): + supported = [index for index, (p, c) in enumerate(zip(parent, child)) if p is not None and c is not None] + if len(supported) < parameters.minimum_motion_bins: + return None, MotionRelationQuality(joint=relation.joint, reason="insufficient_candidate_support") + pairs = [_relative_pose(parent[index], child[index]) for index in supported] + stamps = tuple(stamps[index] for index in supported) + rotations = Rotation.from_quat([rotation.as_quat() for rotation, _ in pairs]) + points = np.asarray([point for _, point in pairs]) + _, angles = _axis(rotations) + motion = float(np.ptp(angles)) + # Use one actual image per angular bin; stationary endpoints and high frame + # rates cannot inflate the evidence count or overwhelm the moving arc. + bins: dict[int, list[int]] = {} + for index, angle in enumerate(angles): + key = int(np.floor((angle - float(np.min(angles))) / parameters.angular_bin_rad + 1e-9)) + bins.setdefault(key, []).append(index) + indices = sorted(values[len(values) // 2] for values in bins.values()) + span = float(np.linalg.norm(np.ptp(points[indices], axis=0))) + common = dict(joint=relation.joint, motion_rad=motion, motion_bins=len(indices), translation_span_m=span) + if motion < parameters.minimum_motion_rad or len(indices) < parameters.minimum_motion_bins: + return None, MotionRelationQuality(reason="insufficient_rotation_evidence", **common) + if motion >= math.radians(170): + return None, MotionRelationQuality(reason="rotation_log_wrap_unsupported", **common) + if span < parameters.minimum_translation_span_m: + return None, MotionRelationQuality(reason="insufficient_pivot_translation", **common) + rotations, points = rotations[indices], points[indices] + selected_stamps = tuple(stamps[index] for index in indices) + model, condition = _fit_constraint(relation, rotations, points, selected_stamps, parameters) + values = _metrics(*_residuals(model, rotations, points)) + quality = dict(common, pivot_condition=condition, pivot_rms_m=values[0], pivot_p95_m=values[1], + off_axis_rms_rad=values[2], off_axis_p95_rad=values[3]) + if condition > parameters.maximum_pivot_condition: + return None, MotionRelationQuality(reason="ill_conditioned_pivot", **quality) + if not _passes(values, parameters): + return None, MotionRelationQuality(reason="motion_geometry_residual", **quality) + # Check interleaved bins and separate early/late intervals in both + # directions. Dense or temporally correlated samples cannot independently + # confirm each other just by being adjacent. This is pre-freeze evidence + # only; no fourth calibration round is consumed here. + count = len(indices) + splits = ((np.arange(0, count, 2), np.arange(1, count, 2)), + (np.arange(count // 2), np.arange(count // 2, count))) + maximum_difference = 0.0 + for first, second in splits: + models = [] + for train, validate in ((first, second), (second, first)): + split, split_condition = _fit_constraint(relation, rotations[train], points[train], + tuple(selected_stamps[i] for i in train), parameters) + models.append(split) + if (split_condition > parameters.maximum_pivot_condition + or not _passes(_metrics(*_residuals(split, rotations[validate], points[validate])), parameters)): + return None, MotionRelationQuality(reason="motion_split_validation_failed", **quality) + difference = math.acos(float(np.clip(abs(np.dot(models[0].axis_parent_xyz, + models[1].axis_parent_xyz)), 0, 1))) + maximum_difference = max(maximum_difference, difference) + quality["split_axis_difference_rad"] = maximum_difference + if maximum_difference > parameters.maximum_split_axis_difference_rad: + return None, MotionRelationQuality(reason="motion_split_axis_inconsistent", **quality) + return model, MotionRelationQuality(reason="", **quality) + + +def resolve_motion_branches( + frames: Sequence[MotionEvidenceFrame], relations: Sequence[MotionRelation], *, + parameters: MotionEvidenceParameters = MotionEvidenceParameters(), +) -> MotionBranchResolution: + """Resolve only a unique geometrically admissible pre-freeze hypothesis. + + The caller authorizes this input as the current session's declared zero + approach, before any affected joint is frozen. A previously frozen role is + represented by its sole already-verified candidate, never both IPPE roots. + """ + roles = _validate_relations(relations) + if len(frames) < parameters.minimum_motion_bins: + return MotionBranchResolution(False, "motion_evidence_insufficient_frames") + stamps = tuple(frame.stamp_ns for frame in frames) + if any(type(stamp) is not int or stamp < 0 for stamp in stamps) or any( + a >= b for a, b in zip(stamps, stamps[1:])): + return MotionBranchResolution(False, "motion_evidence_image_identity_invalid") + paths, reason = _connect_paths(frames, roles) + if paths is None: + return MotionBranchResolution(False, reason) + hypotheses, accepted = [], [] + for branches in product(*(range(len(paths[role])) for role in roles)): + selected = {role: paths[role][branch] for role, branch in zip(roles, branches)} + models, qualities = [], [] + for relation in relations: + model, quality = _relation_evidence(relation, selected[relation.parent_role], + selected[relation.child_role], stamps, parameters) + qualities.append(quality) + if model is not None: + models.append(model) + valid = len(models) == len(relations) and all(selected[role][-1] is not None for role in roles) + hypotheses.append(MotionHypothesis(tuple(zip(roles, branches)), tuple(qualities), valid)) + if valid: + accepted.append((selected, tuple(models))) + if len(accepted) != 1: + reason = "motion_geometry_ambiguous" if accepted else "motion_geometry_unresolved" + return MotionBranchResolution(False, reason, hypotheses=tuple(hypotheses)) + selected, models = accepted[0] + return MotionBranchResolution(True, "", tuple(MotionRoleSelection(role, selected[role][-1]) + for role in roles), models, tuple(hypotheses)) + + +def select_motion_frame( + constraints: Sequence[FrozenMotionConstraint], current_candidates: Sequence[RoleCandidates], +) -> MotionFrameSelection: + """Apply immutable evidence to this frame; never refit or synthesize poses.""" + roles = _validate_relations(tuple(model.relation for model in constraints)) + items = _candidate_map(current_candidates, roles) + if items is None: + return MotionFrameSelection(False, "motion_candidates_missing_or_invalid") + accepted = [] + for combination in product(*(items[role].candidates for role in roles)): + poses = dict(zip(roles, combination)) + if not all(model.evaluate(poses[model.relation.parent_role], poses[model.relation.child_role]).accepted + for model in constraints): + continue + if not any(all(_equivalent(poses[role], previous[role]) for role in roles) for previous in accepted): + accepted.append(poses) + if len(accepted) != 1: + return MotionFrameSelection(False, "motion_geometry_ambiguous" if accepted else "motion_geometry_inconsistent") + return MotionFrameSelection(True, "", tuple(MotionRoleSelection(role, accepted[0][role]) for role in roles)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_diagnostics.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_diagnostics.py new file mode 100644 index 0000000..228a91e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_diagnostics.py @@ -0,0 +1,234 @@ +"""Image-domain articulated motion diagnosis, never branch authorization. + +Each candidate family keeps its own fit. Frozen geometry is evaluated on held +out images by solving image angles only. No SDK values, calibration zero or +fourth-round fitting data enter this API. Callers must retain source provenance +and run this bounded but expensive analysis outside runtime state locks. +""" +from __future__ import annotations + +from itertools import product +from typing import Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + +from .motion_evidence import ( + MotionEvidenceParameters, MotionRelation, _axis, _connect_paths, _fit_constraint, _residuals, +) +from .motion_image_solver import ImageHingeBundle +from .motion_image_types import ( + ImageAxisRepeatability, ImageHypothesisDiagnostic, ImageIntervalDiagnostic, + ImageMotionFrame, ImageRoleObservation, ImageRoleQuality, MotionImageDiagnosticParameters, + MotionImageDiagnosticReport, PnpHingeDiagnostic, +) +from .relative import _relative_pose + +__all__ = ["ImageMotionFrame", "ImageRoleObservation", "MotionImageDiagnosticParameters", + "MotionImageDiagnosticReport", "analyze_motion_images"] + + +def _ordered_relations(relations): + if not relations or len({r.joint for r in relations}) != len(relations): + raise ValueError("relations_missing_or_duplicate_joint") + children = {r.child_role for r in relations} + if len(children) != len(relations) or any(r.parent_role == r.child_role for r in relations): + raise ValueError("multiple_parent_or_self_relation") + known = {r.parent_role for r in relations} - children + pending, ordered = list(relations), [] + while pending: + available = [r for r in pending if r.parent_role in known] + if not available: + raise ValueError("cyclic_motion_graph") + for relation in available: + ordered.append(relation) + known.add(relation.child_role) + pending.remove(relation) + return tuple(ordered) + + +def _validate_frames(frames, relations, limits): + if len(frames) < limits.minimum_frames: + raise ValueError("insufficient_image_frames") + if len(frames) > 512: + raise ValueError("source_frame_limit_exceeded") + stamps = [f.evidence.stamp_ns for f in frames] + if any(type(stamp) is not int or stamp <= 0 for stamp in stamps) or any( + newer <= older for older, newer in zip(stamps, stamps[1:])): + raise ValueError("image_identity_invalid") + roles = tuple(dict.fromkeys(role for r in relations for role in (r.parent_role, r.child_role))) + roots = set(roles) - {r.child_role for r in relations} + sizes = {} + first_matrix = np.asarray(frames[0].camera_matrix) + for frame in frames: + matrix = np.asarray(frame.camera_matrix) + if (matrix.shape != (3, 3) or not np.all(np.isfinite(matrix)) + or matrix[0, 0] <= 0 or matrix[1, 1] <= 0 + or not np.array_equal(matrix[2], [0, 0, 1])): + raise ValueError("camera_matrix_invalid") + if not np.array_equal(matrix, first_matrix): + raise ValueError("camera_model_changed") + observations = {o.role: o for o in frame.observations} + candidates = {r.role: r for r in frame.evidence.roles} + references = {r.role: r for r in frame.reference_frames} + if (frame.reference_frames != frames[0].reference_frames + or len(references) != len(frame.reference_frames) + or not references.keys() <= roots): + raise ValueError("image_motion_reference_frames_changed") + for role, reference in references.items(): + observation = observations.get(role) + if observation is None or role not in candidates or candidates[role].candidates != (reference.pose,): + raise ValueError("image_motion_reference_pose_changed") + reference.check_image(role, observation.tag_size_m, matrix, + observation.corners_xy, frame.evidence.stamp_ns) + if len(observations) != len(frame.observations) or any(role not in observations for role in roles): + raise ValueError("image_observation_missing_or_duplicate") + if any(role not in candidates or not candidates[role].frozen for role in roots): + raise ValueError("root_pose_not_frozen") + for role in roles: + observation = observations[role] + corners = np.asarray(observation.corners_xy) + size = observation.tag_size_m + if (corners.shape != (4, 2) or not np.all(np.isfinite(corners)) + or not np.isfinite(size) or size <= 0): + raise ValueError("tag_geometry_invalid") + if role in sizes and size != sizes[role]: + raise ValueError("tag_size_changed") + sizes[role] = size + paths, reason = _connect_paths([f.evidence for f in frames], roles) + if paths is None: + raise ValueError(reason) + return paths, roles + + +def _sample(indices, maximum): + if len(indices) <= maximum: + return list(indices) + return [indices[i] for i in np.linspace(0, len(indices) - 1, maximum, dtype=int)] + + +def _quality(residuals, roles): + norms = np.linalg.norm(np.asarray(residuals).reshape(-1, len(roles), 4, 2), axis=-1) + result = [] + for index, role in enumerate(roles): + rms = np.sqrt(np.mean(norms[:, index] ** 2, axis=1)) + result.append(ImageRoleQuality(role, len(rms), float(np.sqrt(np.mean(rms ** 2))), + float(np.percentile(rms, 95)), float(np.max(rms)))) + return tuple(result) + + +def _subset(poses, indices): + return {role: tuple(items[i] for i in indices) for role, items in poses.items()} + + +def _interval(name, frames, relations, poses, train, validation, limits): + train = _sample(train, limits.maximum_training_frames) + validation = _sample(validation, limits.maximum_validation_frames) + stamps = tuple(frames[i].evidence.stamp_ns for i in train) + heldout = tuple(frames[i].evidence.stamp_ns for i in validation) + if len(train) < limits.minimum_frames or not heldout: + return ImageIntervalDiagnostic(name, False, "insufficient_interval_frames", 0, stamps, heldout) + try: + bundle = ImageHingeBundle(tuple(frames[i] for i in train), relations, _subset(poses, train)) + fit = bundle.solve(limits) + residuals, valid = bundle.validate(fit.x, tuple(frames[i] for i in validation), + _subset(poses, validation), limits) + training = _quality(fit.fun, bundle.child_roles) + checked = _quality(residuals, bundle.child_roles) + converged = bool(fit.success and valid and np.all(np.isfinite(fit.fun)) + and np.all(np.isfinite(residuals))) + return ImageIntervalDiagnostic(name, converged, "" if converged else "optimizer_or_projection_unresolved", + int(fit.nfev), stamps, heldout, training, checked, bundle.geometry(fit.x), + tuple(bundle.motion_spans)) + except (ValueError, FloatingPointError, np.linalg.LinAlgError) as error: + return ImageIntervalDiagnostic(name, False, str(error), 0, stamps, heldout) + + +def _pnp_diagnostics(frames, relations, poses): + result = [] + for relation in relations: + parents, children = poses[relation.parent_role], poses[relation.child_role] + pairs = [_relative_pose(p, c) for p, c in zip(parents, children)] + rotations = Rotation.from_quat([r.as_quat() for r, _ in pairs]) + points = np.asarray([t for _, t in pairs]) + _, angles = _axis(rotations) + span = float(np.ptp(angles)) + if span < MotionEvidenceParameters().minimum_motion_rad: + raise ValueError("insufficient_rotation_evidence") + if span >= np.deg2rad(170): + raise ValueError("rotation_log_wrap_unsupported") + model, condition = _fit_constraint(relation, rotations, points, + tuple(f.evidence.stamp_ns for f in frames), MotionEvidenceParameters()) + if not np.isfinite(condition) or condition > MotionEvidenceParameters().maximum_pivot_condition: + raise ValueError("ill_conditioned_pivot") + angular, errors = _residuals(model, rotations, points) + difference = points - np.asarray(model.pivot_parent_xyz_m) - rotations.apply(model.mount_child_xyz_m) + camera_difference = Rotation.from_quat([p.quaternion_xyzw for p in parents]).apply(difference) + total_squared = float(np.sum(camera_difference ** 2)) + depth_fraction = float(np.sum(camera_difference[:, 2] ** 2) / total_squared) if total_squared > 1e-24 else 0.0 + result.append(PnpHingeDiagnostic(relation.joint, span, + float(np.sqrt(np.mean(errors ** 2))), float(np.percentile(errors, 95)), + depth_fraction, float(np.sqrt(np.mean(angular ** 2))))) + return tuple(result) + + +def _hypothesis(frames, relations, poses, branches, limits): + supported = [i for i in range(len(frames)) if all(items[i] is not None for items in poses.values())] + frames, poses = tuple(frames[i] for i in supported), _subset(poses, supported) + try: + pnp = _pnp_diagnostics(frames, relations, poses) if len(frames) >= limits.minimum_frames else () + if not pnp: + return ImageHypothesisDiagnostic(branches, "insufficient_candidate_support") + except (ValueError, FloatingPointError, np.linalg.LinAlgError) as error: + return ImageHypothesisDiagnostic(branches, str(error)) + full = list(range(len(frames))) + train = _sample(full[::2], limits.maximum_training_frames) + heldout = [i for i in full if i not in set(train)] + midpoint = len(frames) // 2 + intervals = ( + _interval("interleaved", frames, relations, poses, train, heldout, limits), + _interval("early_to_late", frames, relations, poses, full[:midpoint], full[midpoint:], limits), + _interval("late_to_early", frames, relations, poses, full[midpoint:], full[:midpoint], limits), + ) + repeatability = [] + early, late = intervals[1:] + if early.converged and late.converged: + for first, second in zip(early.geometry, late.geometry): + dot = abs(float(np.dot(first.axis_parent_xyz, second.axis_parent_xyz))) + repeatability.append(ImageAxisRepeatability(first.relation.joint, + float(np.arccos(np.clip(dot, -1, 1))), + float(np.linalg.norm(np.subtract(first.pivot_parent_xyz_m, second.pivot_parent_xyz_m))))) + reason = "" if all(interval.converged for interval in intervals) else "incomplete_interval_analysis" + return ImageHypothesisDiagnostic(branches, reason, pnp, intervals, tuple(repeatability)) + + +def analyze_motion_images(frames: Sequence[ImageMotionFrame], relations: Sequence[MotionRelation], *, + parameters: MotionImageDiagnosticParameters | None = None) -> MotionImageDiagnosticReport: + """Return diagnostic evidence only; never select a winning branch or pose. + + Maximum work is bounded by source frames, graph size, candidate families, + sampled image counts and optimizer evaluation limits. Roots must already be + frozen; calibration holdout images must never be passed as training frames. + """ + limits = parameters or MotionImageDiagnosticParameters() + frames, relations = tuple(frames), tuple(relations) + stamps = tuple(frame.evidence.stamp_ns for frame in frames) + try: + if len(relations) > limits.maximum_relations: + raise ValueError("motion_graph_complexity_limit") + relations = _ordered_relations(relations) + paths, roles = _validate_frames(frames, relations, limits) + family_count = int(np.prod([len(paths[role]) for role in roles])) + if family_count > limits.maximum_hypotheses: + raise ValueError("candidate_hypothesis_limit") + except (ValueError, TypeError) as error: + return MotionImageDiagnosticReport("not_available", str(error), stamps) + hypotheses = [] + for indices in product(*(range(len(paths[role])) for role in roles)): + branches = tuple(zip(roles, indices)) + poses = {role: paths[role][index] for role, index in branches} + hypotheses.append(_hypothesis(frames, relations, poses, branches, limits)) + complete = all(not h.reason for h in hypotheses) + status = "available" if complete else "partial" if any(h.intervals for h in hypotheses) else "not_available" + return MotionImageDiagnosticReport(status, "" if complete else "some_hypotheses_not_evaluable", + stamps, tuple(hypotheses)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_solver.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_solver.py new file mode 100644 index 0000000..b1fa77b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_solver.py @@ -0,0 +1,169 @@ +"""Bounded articulated image fit for preparation and offline diagnostics.""" +from __future__ import annotations + +import numpy as np +from scipy.optimize import least_squares +from scipy.sparse import lil_matrix +from scipy.spatial.transform import Rotation + +from .ippe import square_object_points +from .motion_evidence import MotionEvidenceParameters, _axis, _fit_constraint +from .relative import _relative_pose +from .motion_image_types import ImageHingeGeometry +from .image_bundle_optimizer import solve_image_bundle + + +def _basis(axis): + other = np.array([1., 0, 0]) if abs(axis[0]) < .9 else np.array([0., 1, 0]) + first = np.cross(axis, other) + first /= np.linalg.norm(first) + return np.stack((first, np.cross(axis, first)), axis=1) + + +class ImageHingeBundle: + """Shared hinge geometry and per-frame geometric angles; no SDK inputs. + + Relations are topologically sorted. Roots are actual, already frozen poses + for each image, so a previously frozen moving parent is supported too. + Every child has one parent. Each hinge removes the unobservable axial pivot + gauge explicitly. Validation may change angles only, never shared geometry. + """ + + def __init__(self, frames, relations, poses): + self.frames, self.relations, self.poses = frames, relations, poses + self.count, self.joints = len(frames), len(relations) + self.child_roles = tuple(r.child_role for r in relations) + self.root_roles = tuple(dict.fromkeys(r.parent_role for r in relations + if r.parent_role not in self.child_roles)) + self.axes, self.bases, self.references, angles, initial = [], [], [], [], [] + self.motion_spans = [] + for relation in relations: + pairs = [_relative_pose(parent, child) for parent, child in + zip(poses[relation.parent_role], poses[relation.child_role])] + rotations = Rotation.from_quat([r.as_quat() for r, _ in pairs]) + points = np.asarray([t for _, t in pairs]) + axis, theta = _axis(rotations) + # The full arc has passed the diagnostic minimum-span check. A + # half interval is only a counterfactual fit: retain its measured + # span in the report rather than treating it as new authorization. + span = float(np.ptp(theta)) + if span < 1e-6: + raise ValueError("insufficient_interval_rotation") + self.motion_spans.append((relation.joint, span)) + model, condition = _fit_constraint(relation, rotations, points, + tuple(f.evidence.stamp_ns for f in frames), MotionEvidenceParameters()) + if not np.isfinite(condition) or condition > MotionEvidenceParameters().maximum_pivot_condition: + raise ValueError("ill_conditioned_interval_pivot") + pivot, mount = np.array(model.pivot_parent_xyz_m), np.array(model.mount_child_xyz_m) + axial = float(pivot @ axis) + pivot -= axial * axis + mount += rotations[0].inv().apply(axis) * axial + basis = _basis(axis) + self.axes.append(axis) + self.bases.append(basis) + self.references.append(rotations[0]) + angles.append(theta) + initial.extend((0., 0., 0., 0., 0., *(basis.T @ pivot), *mount)) + self.initial = np.r_[initial, np.asarray(angles).T[1:].ravel()] + self.scale = np.r_[np.tile([1, 1, 1, 1, 1, .05, .05, .05, .05, .05], self.joints), + np.ones(self.joints * (self.count - 1))] + self.root_transforms, self.matrices, self.observed, self.objects = self._image_inputs(frames, poses) + + @property + def static_parameter_count(self): + return 10 * self.joints + + def geometry_parameter_indices(self, index): + return tuple(range(index * 10, (index + 1) * 10)) + + def geometry_dependency_indices(self, index): + return self.geometry_parameter_indices(index) + + def _image_inputs(self, frames, poses): + roots = {role: (Rotation.from_quat([p.quaternion_xyzw for p in poses[role]]), + np.asarray([p.translation_xyz_m for p in poses[role]])) for role in self.root_roles} + observations = [{o.role: o for o in frame.observations} for frame in frames] + observed = np.asarray([[o[role].corners_xy for role in self.child_roles] for o in observations]) + objects = {role: square_object_points(observations[0][role].tag_size_m) for role in self.child_roles} + return roots, np.asarray([f.camera_matrix for f in frames]), observed, objects + + def geometry_values(self, parameters, index): + values = parameters[index * 10:(index + 1) * 10] + change = Rotation.from_rotvec(self.bases[index] @ values[:2]) + axis = change.apply(self.axes[index]) + reference = Rotation.from_rotvec(values[2:5]) * self.references[index] + # Transport the initial tangent basis with the axis. Rebuilding + # _basis(axis) switches its helper at |axis.x|=.9, which changes the + # meaning of the same pivot coordinates discontinuously during a fit. + pivot = change.apply(self.bases[index] @ values[5:7]) + return axis, reference, pivot, values[7:10] + + def geometry(self, parameters): + result = [] + for index, relation in enumerate(self.relations): + axis, reference, pivot, mount = self.geometry_values(parameters, index) + result.append(ImageHingeGeometry(relation, tuple(axis), tuple(reference.as_quat()), + tuple(pivot), tuple(mount))) + return tuple(result) + + def project(self, parameters, angles, roots, matrices, objects): + transforms = dict(roots) + projected, valid = [], True + for index, relation in enumerate(self.relations): + axis, reference, pivot, mount = self.geometry_values(parameters, index) + relative = Rotation.from_rotvec(angles[:, index, None] * axis) * reference + parent_rotation, parent_translation = transforms[relation.parent_role] + translation = parent_translation + parent_rotation.apply(pivot + relative.apply(mount)) + rotation = parent_rotation * relative + transforms[relation.child_role] = (rotation, translation) + camera_points = np.einsum('nij,kj->nki', rotation.as_matrix(), objects[relation.child_role]) + camera_points += translation[:, None, :] + valid = valid and bool(np.all(camera_points[:, :, 2] > 1e-6)) + pixels = np.einsum('nij,nkj->nki', matrices, camera_points) + depth = np.maximum(pixels[:, :, 2:], 1e-6) + projected.append(pixels[:, :, :2] / depth) + return np.stack(projected, axis=1), valid + + def residual(self, parameters): + angles = np.vstack((np.zeros(self.joints), parameters[self.static_parameter_count:].reshape(-1, self.joints))) + pixels, _ = self.project(parameters, angles, self.root_transforms, self.matrices, self.objects) + return (pixels - self.observed).ravel() + + def solve(self, parameters): + # A child's image depends on its ancestors' parameters and angles only. + ancestry = {} + for index, relation in enumerate(self.relations): + ancestry[relation.child_role] = (*ancestry.get(relation.parent_role, ()), index) + width = 8 * self.joints + sparsity = lil_matrix((self.count * width, len(self.initial)), dtype=int) + for frame in range(self.count): + for child, role in enumerate(self.child_roles): + rows = slice(frame * width + child * 8, frame * width + (child + 1) * 8) + for ancestor in ancestry[role]: + sparsity[rows, self.geometry_parameter_indices(ancestor)] = 1 + if frame: + sparsity[rows, self.static_parameter_count + (frame - 1) * self.joints + ancestor] = 1 + return solve_image_bundle(self.residual, self.initial, sparsity=sparsity.tocsr(), + scale=self.scale, limits=parameters) + + def validate(self, parameters, frames, poses, limits): + roots, matrices, observed, objects = self._image_inputs(frames, poses) + residuals, converged = [], True + for frame in range(len(frames)): + guess = [] + for index, relation in enumerate(self.relations): + rotation, _ = _relative_pose(poses[relation.parent_role][frame], poses[relation.child_role][frame]) + axis, reference, _, _ = self.geometry_values(parameters, index) + guess.append(float((rotation * reference.inv()).as_rotvec() @ axis)) + frame_roots = {role: (r[frame:frame + 1], t[frame:frame + 1]) for role, (r, t) in roots.items()} + def residual(angles): + pixels, _ = self.project(parameters, angles.reshape(1, self.joints), frame_roots, + matrices[frame:frame + 1], objects) + return (pixels[0] - observed[frame]).ravel() + fit = least_squares(residual, guess, max_nfev=limits.maximum_frame_evaluations, + ftol=1e-9, xtol=1e-9, gtol=1e-7) + _, positive_depth = self.project(parameters, fit.x.reshape(1, self.joints), frame_roots, + matrices[frame:frame + 1], objects) + converged = converged and bool(fit.success and positive_depth) + residuals.append(fit.fun.reshape(self.joints, 4, 2)) + return np.asarray(residuals), converged diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_types.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_types.py new file mode 100644 index 0000000..b4c2dca --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/motion_image_types.py @@ -0,0 +1,123 @@ +"""Immutable inputs and reports for image-domain motion diagnostics. + +These types carry no branch authorization, zero reference or calibration map. +Image residuals and metric PnP residuals deliberately have different fields. +""" +from __future__ import annotations + +from dataclasses import dataclass, field + +from .motion_evidence import MotionEvidenceFrame, MotionRelation +from .image_reference import StationaryImageReference + + +@dataclass(frozen=True) +class ImageRoleObservation: + role: str + tag_size_m: float + corners_xy: tuple[tuple[float, float], ...] + + +@dataclass(frozen=True) +class ImageMotionFrame: + evidence: MotionEvidenceFrame + camera_matrix: tuple[tuple[float, float, float], ...] + observations: tuple[ImageRoleObservation, ...] + reference_frames: tuple[StationaryImageReference, ...] = () + + +@dataclass(frozen=True) +class MotionImageDiagnosticParameters: + maximum_training_frames: int = 36 + maximum_validation_frames: int = 72 + maximum_solver_evaluations: int = 80 + maximum_frame_evaluations: int = 25 + maximum_relations: int = 3 + maximum_hypotheses: int = 8 + minimum_frames: int = 12 + + def __post_init__(self): + for name, value in vars(self).items(): + if type(value) is not int or value <= 0: + raise ValueError(f"{name} must be a positive integer") + if self.minimum_frames < 12 or self.maximum_training_frames < self.minimum_frames: + raise ValueError("image diagnostics require at least 12 training frames") + if (self.maximum_training_frames > 72 or self.maximum_validation_frames > 144 + or self.maximum_solver_evaluations > 150 or self.maximum_frame_evaluations > 50 + or self.maximum_relations > 3 or self.maximum_hypotheses > 8): + raise ValueError("image diagnostic computation limit exceeded") + + +@dataclass(frozen=True) +class ImageRoleQuality: + role: str + frames: int + rms_px: float + frame_rms_p95_px: float + maximum_frame_rms_px: float + + +@dataclass(frozen=True) +class ImageHingeGeometry: + relation: MotionRelation + axis_parent_xyz: tuple[float, float, float] + reference_quaternion_xyzw: tuple[float, float, float, float] + pivot_parent_xyz_m: tuple[float, float, float] + mount_child_xyz_m: tuple[float, float, float] + + +@dataclass(frozen=True) +class ImageIntervalDiagnostic: + name: str + converged: bool + reason: str + solver_evaluations: int + training_stamps_ns: tuple[int, ...] + validation_stamps_ns: tuple[int, ...] + training_quality: tuple[ImageRoleQuality, ...] = () + validation_quality: tuple[ImageRoleQuality, ...] = () + geometry: tuple[ImageHingeGeometry, ...] = () + training_motion_span_rad_by_joint: tuple[tuple[str, float], ...] = () + + +@dataclass(frozen=True) +class PnpHingeDiagnostic: + joint: str + motion_span_rad: float + translation_rms_m: float + translation_p95_m: float + camera_depth_squared_error_fraction: float + off_axis_rms_rad: float + + +@dataclass(frozen=True) +class ImageAxisRepeatability: + joint: str + early_late_axis_difference_rad: float + early_late_pivot_difference_m: float + + +@dataclass(frozen=True) +class ImageHypothesisDiagnostic: + branches: tuple[tuple[str, int], ...] + reason: str + pnp_geometry: tuple[PnpHingeDiagnostic, ...] = () + intervals: tuple[ImageIntervalDiagnostic, ...] = () + repeatability: tuple[ImageAxisRepeatability, ...] = () + + +@dataclass(frozen=True) +class MotionImageDiagnosticReport: + status: str + reason: str + source_stamps_ns: tuple[int, ...] + hypotheses: tuple[ImageHypothesisDiagnostic, ...] = () + scope: str = field(default="diagnostic_not_branch_authorization", init=False) + branch_authorization_allowed: bool = field(default=False, init=False) + calibration_accuracy_verified: bool = field(default=False, init=False) + interpretation: str = ( + "Pixel residuals test image consistency; PnP metric residuals test noisy pose estimates. " + "Neither lowest pixel score nor this diagnostic replaces the existing branch, " + "baseline, interval-repeatability or independent calibration holdout gates. " + "The first training angle is a solver gauge, not a joint zero reference." + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/observer_pose.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/observer_pose.py new file mode 100644 index 0000000..07ce29e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/observer_pose.py @@ -0,0 +1,160 @@ +"""A held descendant's rigid pose from independent upstream camera angles. + +Every IPPE seed sees the same chronological train/holdout split. Alternatives +must be equivalent or separated by the existing independent image-loss test. +A held-out failure vetoes the training winner; it never selects another one. +""" + +from dataclasses import dataclass +import math + +import numpy as np +from scipy.optimize import least_squares +from scipy.spatial.transform import Rotation + +from .ippe import square_object_points +from .relative import _relative_pose + + +OBSERVER_POSE_LIMITS = (math.radians(1), .001) + + +def require_observer_precision_budget(inherited): + """A parent alone must not exhaust the observer's final precision budget.""" + if (len(inherited) != 2 or any(not math.isfinite(v) or v < 0 for v in inherited)): + raise ValueError('observer_parent_uncertainty_invalid') + if any(value >= limit for value, limit in zip(inherited, OBSERVER_POSE_LIMITS)): + raise ValueError('observer_parent_precision_budget_exhausted') + + +@dataclass(frozen=True) +class ObserverPose: + quaternion_xyzw: tuple + translation_xyz_m: tuple + rotation_uncertainty_rad: float + translation_uncertainty_m: float + training_stamps: tuple + validation_stamps: tuple + comparison_adjusted_p_values: tuple = () + + +def _projection(matrix, points): + pixels = points @ matrix.T + return pixels[:, :2]/pixels[:, 2:] + + +def _jacobian(function, steps): + zero = np.zeros(len(steps)) + result = [] + for index, step in enumerate(steps): + perturbation = zero.copy() + perturbation[index] = step + result.append((function(perturbation)-function(-perturbation)).ravel()/(2*step)) + return np.column_stack(result) + + +def _relative_covariance(fit, indices, parents, parent_corners, parent_size, child_points, matrices, variance): + """Propagate same-image parent-pixel uncertainty through the relative fit. + + Parent geometry is never changed. Image noise contributes per frame; + inherited geometry uncertainty is added separately without averaging it. + """ + information = np.zeros((6, 6)) + steps = np.r_[np.full(3, 1e-5), np.full(3, 1e-6)] + relative = Rotation.from_rotvec(fit.x[:3]) + local_child = relative.apply(child_points)+fit.x[3:] + for position, index in enumerate(indices): + parent, matrix = parents[index], matrices[index] + rotation = Rotation.from_quat(parent.quaternion_xyzw) + translation = np.asarray(parent.translation_xyz_m) + def project_parent(delta, points): + return _projection(matrix, rotation.apply(Rotation.from_rotvec(delta[:3]).apply(points)) + + translation+delta[3:]) + points = square_object_points(parent_size) + jacobian = _jacobian(lambda delta: project_parent(delta, points), steps) + _, singular, vh = np.linalg.svd(jacobian, full_matrices=False) + if singular[-1] <= singular[0]*np.finfo(float).eps*max(jacobian.shape): + raise ValueError('observer_parent_pose_rank_deficient') + error = project_parent(np.zeros(6), points)-parent_corners[index] + parent_variance = max(.03**2, float(np.sum(error**2)/2)) + parent_covariance = (vh.T/singular**2)@vh*parent_variance + inherited = _jacobian(lambda delta: project_parent(delta, local_child), steps) + pixel_covariance = np.eye(8)*variance + inherited@parent_covariance@inherited.T + relative_jacobian = fit.jac[position*8:(position+1)*8] + information += relative_jacobian.T@np.linalg.solve(pixel_covariance, relative_jacobian) + eigenvalues = np.linalg.eigvalsh(information) + if eigenvalues[0] <= eigenvalues[-1]*np.finfo(float).eps*6: + raise ValueError('observer_relative_pose_rank_deficient') + return np.linalg.inv(information) + + +def fit_observer_pose(parents, candidates, corners, matrices, size, stamps, *, inherited=(0., 0.), + parent_corners=None, parent_size=None): + require_observer_precision_budget(inherited) + count = len(stamps) + if count < 24 or tuple(stamps) != tuple(sorted(set(stamps))) or any(not c for c in candidates): + raise ValueError("observer_independent_images_missing") + training, validation = np.arange(0, count, 2), np.arange(1, count, 2) + # Bound work without selecting images by a fit's residual. + training = training[np.linspace(0, len(training)-1, min(72, len(training))).round().astype(int)] + validation = validation[np.linspace(0, len(validation)-1, min(72, len(validation))).round().astype(int)] + rotations = Rotation.from_quat([p.quaternion_xyzw for p in parents]) + for indices in (training, validation): + if max((rotations[indices[0]].inv()*rotations[indices]).magnitude()) < math.radians(5): + raise ValueError("observer_viewpoint_span_insufficient") + rotation_matrices = rotations.as_matrix() + translations = np.asarray([p.translation_xyz_m for p in parents]) + matrices, pixels = np.asarray(matrices), np.asarray(corners) + points = square_object_points(size) + + def residual(x, indices): + local = Rotation.from_rotvec(x[:3]).apply(points)+x[3:] + camera = np.einsum('nij,kj->nki', rotation_matrices[indices], local)+translations[indices, None, :] + if np.any(camera[..., 2] <= 0): + return np.full(len(indices)*8, 1e6) + projected = np.einsum('nij,nkj->nki', matrices[indices], camera) + return (projected[..., :2]/projected[..., 2:]-pixels[indices]).ravel() + + fits = [] + for pose in candidates[training[0]]: + rotation, point = _relative_pose(parents[training[0]], pose) + fit = least_squares(residual, np.r_[rotation.as_rotvec(), point], args=(training,), + x_scale=np.r_[np.ones(3), np.full(3, .03)], max_nfev=150, jac='3-point') + if not fit.success or not np.all(np.isfinite(fit.fun)): + raise ValueError("observer_candidate_not_evaluable") + fits.append(fit) + winner = min(fits, key=lambda f: float(f.fun @ f.fun)) + for indices in (training, validation): + errors = residual(winner.x, indices).reshape(-1, 4, 2) + if np.max(np.sqrt(np.mean(np.sum(errors**2, axis=2), axis=1))) > 1.5: + raise ValueError("observer_image_validation_failed") + from .image_model_selection import compare_image_losses, holm_adjusted_probabilities + def errors(fit, indices): + return np.sqrt(np.mean(np.sum(residual(fit.x, indices).reshape(-1, 4, 2)**2, axis=2), axis=1)) + comparisons = [] + angles = (rotations[0].inv()*rotations[validation]).as_rotvec() + for index, fit in enumerate(fits): + if fit is winner: + continue + difference = (Rotation.from_rotvec(winner.x[:3]).inv()*Rotation.from_rotvec(fit.x[:3])).magnitude() + equivalent = difference <= math.radians(.1) and np.linalg.norm(winner.x[3:]-fit.x[3:]) <= .0001 + probability = (0. if equivalent or np.max(errors(fit, training)) > 1.5 else + compare_image_losses(errors(winner, validation), errors(fit, validation), angles, .03)) + comparisons.append((index, probability)) + adjusted = holm_adjusted_probabilities(comparisons) + if any(probability > .01 for _, probability in adjusted): + raise ValueError('observer_candidates_unresolved') + _, singular, vh = np.linalg.svd(winner.jac, full_matrices=False) + if singular[-1] <= singular[0]*np.finfo(float).eps*max(winner.jac.shape): + raise ValueError("observer_pose_rank_deficient") + variance = max(.03**2, float(winner.fun@winner.fun/max(1, len(winner.fun)-6))) + covariance = (vh.T/singular**2)@vh*variance + if parent_corners is not None: + covariance = _relative_covariance(winner, training, parents, np.asarray(parent_corners), parent_size, + points, matrices, variance) + bounds = [float(3*np.sqrt(max(0., np.linalg.eigvalsh(covariance[i:i+3, i:i+3])[-1]))) + + inherited[i//3] for i in (0, 3)] + if not all(math.isfinite(v) for v in bounds) or any(v > limit for v, limit in zip(bounds, OBSERVER_POSE_LIMITS)): + raise ValueError("observer_pose_uncertain") + return ObserverPose(tuple(Rotation.from_rotvec(winner.x[:3]).as_quat()), tuple(winner.x[3:]), + *bounds, tuple(stamps[i] for i in training), tuple(stamps[i] for i in validation), adjusted) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/parameters.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/parameters.py new file mode 100644 index 0000000..dfa4d85 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/parameters.py @@ -0,0 +1,35 @@ +"""Parameters for shared square Tag pose estimation.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math + + +BRANCH_TRANSLATION_EQUIVALENCE_M = 0.001 + + +@dataclass(frozen=True) +class PoseTrackingParameters: + """One shared set of defaults, with angles stored in radians.""" + + maximum_reprojection_error_px: float = 1.5 + reprojection_tie_px: float = 0.03 + maximum_pose_jump_rad: float = math.radians(35.0) + maximum_translation_jump_m: float = 0.04 + maximum_tag_tilt_rad: float = math.radians(75.0) + reset_after_seconds: float = 5.0 + branch_confirmation_frames: int = 5 + branch_confirmation_minimum_seconds: float = 0.1 + branch_equivalence_rad: float = math.radians(1.0) + + +DEFAULT_POSE_TRACKING_PARAMETERS = PoseTrackingParameters() +DEFAULT_REPROJECTION_TIE_PX = DEFAULT_POSE_TRACKING_PARAMETERS.reprojection_tie_px +POSE_TRACKING_POLICY_VERSION = "confirmed_branch_v8_training_model_selection" +FROZEN_BRANCH_POLICY_VERSIONS = frozenset({ + "confirmed_branch_v1", "confirmed_branch_v2_fixed_reference", + "confirmed_branch_v3_recoverable_ambiguity", "confirmed_branch_v5_image_motion", + "confirmed_branch_v6_source_geometry", "confirmed_branch_v7_final_image_sampling", + POSE_TRACKING_POLICY_VERSION, +}) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/pose_bridge.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/pose_bridge.py new file mode 100644 index 0000000..773bff2 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/pose_bridge.py @@ -0,0 +1,175 @@ +"""Independent, same-posture images connect two hinges sharing a rigid Tag. + +The old hinge is never applied while the new hinge moves. Only the shared +stationary posture anchors the new fit and constrains candidate eligibility. +The new hinge axis and pivot come from its preparation arc. No SDK value is +interpreted as radians. +""" + +from dataclasses import dataclass, replace +import math +from typing import TYPE_CHECKING + +import numpy as np +from scipy.spatial.transform import Rotation + +from .motion_evidence import MotionRelation +from .motion_image_types import ImageMotionFrame +from .relative import _relative_pose + +SHARED_TAG_SELECTION_POLICY = "training_squared_loss_shared_pose_holm_v2" +OBSERVER_POSE_SELECTION_POLICY = "training_measured_observer_pose_holm_v1" +RIGID_OBSERVER_SELECTION_POLICY = "training_rigid_pair_observer_pose_holm_v1" +SHARED_TAG_CONDITIONED_POLICY = "training_shared_zero_orientation_holm_v3" +SHARED_ZERO_CONDITIONING = "shared_zero_orientation_v1" +SHARED_POSE_CONDITIONING = "shared_zero_pose_v2" +SHARED_TAG_POSE_CONDITIONED_POLICY = "training_shared_zero_pose_holm_v4" +SHARED_TAG_HANDOFF_POLICY = "training_shared_zero_pose_handoff_v1" +SHARED_TAG_CONDITIONING_POLICIES = { + SHARED_TAG_SELECTION_POLICY: None, + SHARED_TAG_CONDITIONED_POLICY: SHARED_ZERO_CONDITIONING, + SHARED_TAG_POSE_CONDITIONED_POLICY: SHARED_POSE_CONDITIONING, + SHARED_TAG_HANDOFF_POLICY: SHARED_POSE_CONDITIONING, +} +OBSERVER_POSE_SELECTION_POLICIES = { + OBSERVER_POSE_SELECTION_POLICY: None, + RIGID_OBSERVER_SELECTION_POLICY: None, + **{f'{policy}_observer_v1': policy for policy in SHARED_TAG_CONDITIONING_POLICIES}, +} + + +def is_handoff_policy(policy): + return OBSERVER_POSE_SELECTION_POLICIES.get(policy, policy) == SHARED_TAG_HANDOFF_POLICY + +if TYPE_CHECKING: + from .image_motion_model import ImageMotionModel + + +@dataclass(frozen=True) +class SharedTagPoseBridge: + relation: MotionRelation + quaternion_xyzw: tuple[float, ...] + translation_xyz_m: tuple[float, ...] + frames: tuple[ImageMotionFrame, ...] + source_model: "ImageMotionModel | None" = None + conditioning: str = SHARED_POSE_CONDITIONING + rotation_uncertainty_rad: float = 0. + translation_uncertainty_m: float = 0. + # Before the new joint moves, the source hinge verifies its own return. + # After that motion, only the recipient hinge explains the new images. + # Empty preserves the historical same-image authorization contract. + source_frames: tuple[ImageMotionFrame, ...] = () + + +def shared_pose_selection_policy(bridges): + if any(b.source_frames for b in bridges): + if not all(b.source_frames and b.source_model is not None + and b.conditioning == SHARED_POSE_CONDITIONING for b in bridges): + raise ValueError("shared_pose_handoff_policy_mixed") + return SHARED_TAG_HANDOFF_POLICY + modes = {b.conditioning for b in bridges if b.source_model is not None} + if not modes: + return SHARED_TAG_SELECTION_POLICY + if len(modes) == 1: + mode = next(iter(modes)) + for policy, conditioning in SHARED_TAG_CONDITIONING_POLICIES.items(): + if conditioning is not None and conditioning == mode: + return policy + raise ValueError("shared_pose_conditioning_policy_changed") + + +def observer_pose_selection_policy(shared_bridges): + if not shared_bridges: + return OBSERVER_POSE_SELECTION_POLICY + shared_policy = shared_pose_selection_policy(shared_bridges) + return next(policy for policy, source in OBSERVER_POSE_SELECTION_POLICIES.items() + if source == shared_policy) + + +@dataclass(frozen=True) +class PoseBridgeCheck: + joint: str + status: str + reason: str + maximum_rotation_rad: float = 0. + maximum_translation_m: float = 0. + + +def check_source_pose(bridge): + """Check the old hinge only on new, held-zero images, in its own coordinates. + + This is independent of the new hinge fit. A frozen zero pose may only + condition a new model after the source itself still explains today's pose. + No old scan or old image is solved again. + """ + from .motion_evidence import RoleCandidates + from .rigid_tag_pair import RIGID_PAIR_CONDITIONING, check_rigid_pair_endpoint + if bridge.conditioning == RIGID_PAIR_CONDITIONING and bridge.source_model is None: + return check_rigid_pair_endpoint(bridge) + + source = bridge.source_model + if source is None or len(source.geometry) != 1: + return PoseBridgeCheck(bridge.relation.joint, "unresolved", "shared_pose_source_model_invalid") + relation = source.geometry[0].relation + if ((relation.parent_role, relation.child_role) != + (bridge.relation.parent_role, bridge.relation.child_role)): + return PoseBridgeCheck(bridge.relation.joint, "unresolved", "shared_pose_source_roles_changed") + references = {ref.role: ref for ref in source.reference_frames} + source_frames = bridge.source_frames or bridge.frames + if bridge.source_frames and (not bridge.frames or + max(f.evidence.stamp_ns for f in source_frames) >= min(f.evidence.stamp_ns for f in bridge.frames)): + return PoseBridgeCheck(bridge.relation.joint, "unresolved", "shared_pose_handoff_order_invalid") + frames = tuple(replace(frame, reference_frames=source.reference_frames, + evidence=replace(frame.evidence, roles=tuple( + RoleCandidates(role.role, (references[role.role].pose,), True) + if role.role in references else role for role in frame.evidence.roles))) for frame in source_frames) + return check_pose_bridge(source, replace(bridge, relation=relation, frames=frames, source_model=None)) + + +def check_pose_bridge(model, bridge): + """Accept close poses; exclude only disjoint pose-tolerance regions. + + Each estimate gets the existing 2 degree / 5 mm pose-reuse allowance. + Distances between one and two allowances are inconclusive, not rejection. + These are conservative consistency margins, not covariance/confidence claims. + Fresh-image scatter must also pass the existing 1 degree / 1 mm hold gate. + """ + from .image_motion_projection import select_image_motion_frame + + name = bridge.relation.joint + def unknown(reason): + return PoseBridgeCheck(name, "unresolved", reason) + if (bridge.relation not in model.relations or len(bridge.frames) < 10 + or len({f.evidence.stamp_ns for f in bridge.frames}) != len(bridge.frames) + or set(model.source_stamps_ns) & {f.evidence.stamp_ns for f in bridge.frames}): + return unknown("shared_pose_support_invalid") + rotations, points = [], [] + for frame in bridge.frames: + checked = select_image_motion_frame(model, frame) + poses = {s.role: s.pose for s in checked.selections} + if not checked.resolved: + return unknown(f"shared_pose_current_image_unresolved:{checked.reason}:stamp={frame.evidence.stamp_ns}") + try: + rotation, point = _relative_pose(poses[bridge.relation.parent_role], poses[bridge.relation.child_role]) + except KeyError: + return unknown("shared_pose_roles_missing") + rotations.append(rotation.as_quat()) + points.append(point) + rotations, points = Rotation.from_quat(rotations), np.asarray(points) + if (np.max((rotations.mean().inv()*rotations).magnitude()) > math.radians(1.) + or np.max(np.linalg.norm(points-np.median(points, axis=0), axis=1)) > .001): + return unknown("shared_pose_current_images_not_stable") + angles = (Rotation.from_quat(bridge.quaternion_xyzw).inv()*rotations).magnitude() + distances = np.linalg.norm(points-np.asarray(bridge.translation_xyz_m), axis=1) + rotation_limit, translation_limit = math.radians(2.), .005 + angle_bound, point_bound = bridge.rotation_uncertainty_rad, bridge.translation_uncertainty_m + if (not all(math.isfinite(v) and v >= 0 for v in (angle_bound, point_bound)) + or angle_bound > math.radians(1.) or point_bound > .001): + return unknown("shared_pose_source_uncertainty_invalid") + if np.max(angles)+angle_bound <= rotation_limit and np.max(distances)+point_bound <= translation_limit: + status, reason = "consistent", "" + elif np.min(angles)-angle_bound > 2*rotation_limit or np.min(distances)-point_bound > 2*translation_limit: + status, reason = "conflicting", "shared_pose_outside_both_pose_margins" + else: + status, reason = "unresolved", "shared_pose_tolerance_regions_overlap" + return PoseBridgeCheck(name, status, reason, float(np.max(angles)), float(np.max(distances))) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/production_image_motion.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/production_image_motion.py new file mode 100644 index 0000000..b3aeb26 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/production_image_motion.py @@ -0,0 +1,305 @@ +"""Pre-zero motion authorization from images, followed by frozen image geometry. + +A hinge bundle minimizes measured corner errors, not the poorly conditioned +single-image PnP depth estimates. All IPPE families seed independent fits. A +model is authorized only with observable geometry, absolute image quality and +held-out, motion-stratified evidence separating every distinct alternative. +This preparation-image check does not replace final fourth-round acceptance. +""" +from dataclasses import dataclass, replace +from itertools import product + +import numpy as np + +from .image_motion_model import ( + IMAGE_MOTION_MODEL_POLICY, ImageMotionModel, ImageMotionResolution, + ImageMotionHypothesis, ImageMotionFrameSelection, image_motion_model_from_dict, +) +from .image_motion_projection import select_image_motion_frame +from .motion_evidence import MotionEvidenceParameters +from .image_model_selection import ( + compare_image_losses as _comparison, equivalent_frame_selections, + holm_adjusted_probabilities, training_candidate_index, +) +from .motion_image_diagnostics import ( + _ordered_relations, _validate_frames, _sample, _subset, _quality, _pnp_diagnostics, +) +from .motion_image_solver import ImageHingeBundle +from .hinge_uncertainty import hinge_uncertainty + +__all__ = ["ImageMotionModel", "ImageMotionResolution", "ImageMotionFrameSelection", + "resolve_image_motion", "select_image_motion_frame", "image_motion_model_from_dict", + "IMAGE_MOTION_MODEL_POLICY"] + + +@dataclass(frozen=True) +class ImageMotionParameters: + maximum_training_frames: int = 72 + maximum_validation_frames: int = 72 + maximum_solver_evaluations: int = 150 + maximum_frame_evaluations: int = 40 + minimum_frames: int = 24 + maximum_hypotheses: int = 64 + maximum_relations: int = 6 + familywise_error_probability: float = .01 + report_pose_uncertainty: bool = False + maximum_solver_recovery_evaluations: int = 50 + + def __post_init__(self): + if (type(self.maximum_solver_recovery_evaluations) is not int + or not 0 <= self.maximum_solver_recovery_evaluations <= 100): + raise ValueError("maximum_solver_recovery_evaluations must be an integer in [0, 100]") + for name in ("maximum_training_frames", "maximum_validation_frames", "maximum_solver_evaluations", + "maximum_frame_evaluations", "minimum_frames", "maximum_hypotheses", "maximum_relations"): + if type(getattr(self, name)) is not int or getattr(self, name) <= 0: + raise ValueError(f"{name} must be a positive integer") + if (self.minimum_frames < 24 or self.maximum_training_frames < 12 + or self.maximum_training_frames > 144 or self.maximum_validation_frames > 144 + or self.maximum_solver_evaluations > 500 or self.maximum_frame_evaluations > 100 + or self.maximum_hypotheses > 256 or self.maximum_relations > 8 + or not 0 < self.familywise_error_probability <= .01): + raise ValueError("image_motion_limits_invalid") + + +DENSE_PREPARATION_SAMPLING = "native_command_256_split144_v1" + + +def image_parameters_for_sampling(policy=None): + """Versioned sampling budgets, including historical journal replay.""" + if policy is None: + return ImageMotionParameters() + if policy == DENSE_PREPARATION_SAMPLING: + return ImageMotionParameters(maximum_training_frames=144, maximum_validation_frames=144) + raise ValueError("image_motion_sampling_policy_invalid") + + +def _model(bundle, fit, frames, branches, training, validation): + from .cad_hinge import CadImageHingeBundle + model_type, extra = ImageMotionModel, {"reference_frames": frames[0].reference_frames} + if isinstance(bundle, CadImageHingeBundle): + from .cad_image_model import CadImageMotionModel + model_type = CadImageMotionModel + if bundle.source_hinges: + from .cad_image_model import TransferredImageMotionModel + model_type = TransferredImageMotionModel + extra["source_hinges"] = bundle.source_hinges + extra.update(constraints=bundle.constraints, source_urdf_sha256=bundle.source_urdf_sha256) + return model_type(bundle.geometry(fit.x), tuple(tuple(v) for v in frames[0].camera_matrix), + tuple((role, next(o.tag_size_m for o in frames[0].observations if o.role == role)) + for role, _ in branches), tuple(f.evidence.stamp_ns for f in frames), + tuple(frames[i].evidence.stamp_ns for i in training), + tuple(frames[i].evidence.stamp_ns for i in validation), branches, **extra) + + +def _fit_hypothesis(frames, relations, poses, branches, training, validation, limits, + *, geometry_constraints=(), source_urdf_sha256="", source_hinges=(), pose_bridges=(), + transition=None, transition_poses=None): + if any(pose is None for role in poses.values() for pose in role): + return ImageMotionHypothesis(branches, False, "incomplete_candidate_family"), None, None + try: + pnp = _pnp_diagnostics(frames, relations, poses) + selected = tuple(frames[i] for i in training) + if transition is not None: + from .transition_image_solver import TransitionImageHingeBundle + bundle = TransitionImageHingeBundle(selected, relations, _subset(poses, training), + transition, transition_poses, limits) + elif pose_bridges: + from .shared_zero_solver import SharedZeroImageHingeBundle + if geometry_constraints and not source_hinges: + raise ValueError("shared_zero_model_graph_unsupported") + bundle = SharedZeroImageHingeBundle(selected, relations, _subset(poses, training), pose_bridges, + constraints=geometry_constraints, sources=source_hinges) + elif source_hinges: + from .measured_transfer_solver import MeasuredTransferImageHingeBundle + bundle = MeasuredTransferImageHingeBundle(selected, relations, _subset(poses, training), + constraints=geometry_constraints, sources=source_hinges) + elif geometry_constraints: + from .cad_hinge import CadImageHingeBundle + bundle = CadImageHingeBundle(selected, relations, _subset(poses, training), + constraints=geometry_constraints, source_urdf_sha256=source_urdf_sha256, source_hinges=source_hinges) + else: + bundle = ImageHingeBundle(selected, relations, _subset(poses, training)) + fit = bundle.solve(limits) + model = _model(bundle, fit, frames, branches, training, validation) + training_quality = _quality(fit.fun, bundle.child_roles) + training_converged = bool(fit.success and np.all(np.isfinite(fit.fun))) + axes, pivots, child_bounds = hinge_uncertainty(bundle, fit) if training_converged else ((), (), ()) + pose_bounds = () + if limits.report_pose_uncertainty and training_converged: + from .hinge_uncertainty import preparation_pose_uncertainty + pose_bounds = preparation_pose_uncertainty(bundle, fit) + transfer_checks = () + transfer_reason = "" + if source_hinges and training_converged: + from .measured_transfer import assess_transfer_geometry, bind_measured_transfer + current_bounds = tuple((name, axis, dict(pivots)[name]) for name, axis in axes) + transfer_checks, inherited, precision_accepted = assess_transfer_geometry(model.geometry, + geometry_constraints, source_hinges, current_bounds) + axes = tuple((name, value+inherited[name][0]) for name, value in axes) + pivots = tuple((name, value+inherited[name][1]) for name, value in pivots) + child_bounds = tuple((name, axis+inherited[name][0], point+inherited[name][1]) + for name, axis, point in child_bounds) + if not precision_accepted: + transfer_reason = "image_motion_geometry_uncertain" + elif all(c.consistent for c in transfer_checks): + model = bind_measured_transfer(model, geometry_constraints, source_hinges, + source_urdf_sha256, current_bounds) + else: + transfer_reason = "image_motion_source_geometry_conflict" + p = MotionEvidenceParameters() + reason = "" if training_converged else "image_motion_optimizer_unresolved" + if not reason and any(q.maximum_frame_rms_px > model.maximum_reprojection_error_px for q in training_quality): + reason = "image_motion_reprojection_failed" + if not reason and (any(v > p.maximum_split_axis_difference_rad for _, v in axes) + or any(v > p.maximum_frame_pivot_error_m for _, v in pivots)): + reason = "image_motion_geometry_uncertain" + reason = reason or transfer_reason + training_accepted = not reason + try: + residuals, valid = bundle.validate(fit.x, tuple(frames[i] for i in validation), + _subset(poses, validation), limits) + validation_quality = _quality(residuals, bundle.child_roles) + except (ValueError, FloatingPointError, np.linalg.LinAlgError) as error: + # Keep training eligibility: a failed holdout must veto the chosen + # candidate, never silently make the next candidate the winner. + residuals, valid, validation_quality = None, False, () + reason = reason or str(error) + converged = bool(training_converged and valid and np.all(np.isfinite(residuals))) + if not reason and not converged: + reason = "image_motion_optimizer_unresolved" + if not reason and any(q.maximum_frame_rms_px > model.maximum_reprojection_error_px for q in validation_quality): + reason = "image_motion_reprojection_failed" + attempts = getattr(fit, "image_solver_attempts", ()) + hypothesis = ImageMotionHypothesis(branches, converged, reason, training_quality, validation_quality, + tuple((r.joint, r.motion_span_rad) for r in pnp), axes, pivots, + training_solver_status=int(fit.status), + training_solver_evaluations=sum(a.evaluations for a in attempts) if attempts else int(fit.nfev), + training_solver_attempts=attempts, + training_accepted=training_accepted, child_frame_uncertainty=child_bounds, + source_geometry_checks=transfer_checks, preparation_pose_uncertainty=pose_bounds) + rms = None if residuals is None else np.sqrt(np.mean(np.sum(residuals ** 2, axis=-1), axis=(1, 2))) + return hypothesis, model, rms + except (ValueError, FloatingPointError, np.linalg.LinAlgError) as error: + return ImageMotionHypothesis(branches, False, str(error)), None, None + + +def resolve_image_motion(frames, relations, *, parameters=None, geometry_constraints=(), source_urdf_sha256="", source_hinges=(), pose_bridges=()): + """Only pre-zero preparation frames may enter this expensive training API. + + Runtime owns session, motion and phase checks. This function knows no SDK + channels, baseline or round and cannot acquire extra training images itself. + Its output model retains the disjoint image identities needed for auditing. + """ + limits = parameters or ImageMotionParameters() + frames, relations = tuple(frames), tuple(relations) + from .pose_bridge import check_source_pose + from .rigid_tag_pair import RIGID_PAIR_CONDITIONING + conditioned = tuple(bridge for bridge in pose_bridges if bridge.source_model is not None + or bridge.conditioning == RIGID_PAIR_CONDITIONING) + for bridge in conditioned: + if bridge.source_frames and (not frames or max(f.evidence.stamp_ns for f in bridge.source_frames) + >= min(f.evidence.stamp_ns for f in frames)): + return ImageMotionResolution(False, 'image_motion_shared_pose_source_unverified:shared_pose_handoff_order_invalid') + checked = check_source_pose(bridge) + if checked.status != "consistent": + return ImageMotionResolution(False, "image_motion_shared_pose_source_unverified:" + checked.reason) + try: + if source_hinges and not geometry_constraints: + raise ValueError("image_motion_source_hinge_requires_geometry") + relations = _ordered_relations(relations) + if len(relations) > limits.maximum_relations: + raise ValueError("image_motion_graph_limit") + paths, roles = _validate_frames(frames, relations, limits) + if np.prod([len(paths[r]) for r in roles]) > limits.maximum_hypotheses: + raise ValueError("image_motion_hypothesis_limit") + training = _sample(list(range(0, len(frames), 2)), limits.maximum_training_frames) + validation = _sample([i for i in range(len(frames)) if i not in training], limits.maximum_validation_frames) + if min(len(training), len(validation)) < 12: + raise ValueError("image_motion_insufficient_independent_frames") + except (ValueError, TypeError) as error: + return ImageMotionResolution(False, str(error)) + hypotheses, models, residuals = [], [], [] + for indices in product(*(range(len(paths[r])) for r in roles)): + branches = tuple(zip(roles, indices)) + poses = {role: paths[role][index] for role, index in branches} + geometry = {"geometry_constraints": geometry_constraints, "source_urdf_sha256": source_urdf_sha256, + "source_hinges": source_hinges} + hypothesis, model, rms = _fit_hypothesis(frames, relations, poses, branches, training, validation, limits, + **(geometry if geometry_constraints else {}), pose_bridges=conditioned) + hypotheses.append(hypothesis) + models.append(model) + residuals.append(rms) + return select_image_hypotheses(frames, validation, hypotheses, models, residuals, limits, + pose_bridges=pose_bridges) + + +def select_image_hypotheses(frames, validation, hypotheses, models, residuals, limits, *, pose_bridges=()): + """One acceptance policy for independent and transition-conditioned fits.""" + # Independent stationary evidence is an eligibility constraint, applied + # before choosing by training error. Held-out arc scores cannot select a + # different winner. Inconclusive bridge evidence never excludes a family. + from .pose_bridge import check_pose_bridge + for index, model in enumerate(models): + if model is None or not pose_bridges: + continue + checks = tuple(check_pose_bridge(model, bridge) for bridge in pose_bridges) + hypotheses[index] = replace(hypotheses[index], pose_bridge_checks=checks) + if any(check.status == "conflicting" for check in checks): + hypotheses[index] = replace(hypotheses[index], training_accepted=False, + reason=hypotheses[index].reason or "image_motion_shared_pose_conflict") + winner = training_candidate_index(hypotheses) + if winner is None and any(h.training_solver_status == 0 for h in hypotheses): + return ImageMotionResolution(False, "image_motion_solver_budget_exhausted", hypotheses=tuple(hypotheses)) + if winner is None and any(h.reason == "image_motion_shared_pose_conflict" for h in hypotheses): + return ImageMotionResolution(False, "image_motion_shared_pose_conflict", hypotheses=tuple(hypotheses)) + if winner is None or hypotheses[winner].reason: + return ImageMotionResolution(False, "image_motion_no_observable_image_model", hypotheses=tuple(hypotheses)) + model = models[winner] + if any(check.status != "consistent" for check in hypotheses[winner].pose_bridge_checks): + return ImageMotionResolution(False, "image_motion_shared_pose_unresolved", hypotheses=tuple(hypotheses)) + checks = tuple(select_image_motion_frame(model, frames[i]) for i in validation) + if not all(c.resolved for c in checks): + return ImageMotionResolution(False, "image_motion_validation_frame_unresolved", hypotheses=tuple(hypotheses)) + angles = [[v for _, v in c.angles_rad] for c in checks] + winner_errors = np.array([np.sqrt(np.mean([q.rms_px ** 2 for q in c.quality])) for c in checks]) + comparisons = [] + for index, alternative in enumerate(models): + if index == winner: + continue + if alternative is None or residuals[index] is None or not hypotheses[index].converged: + # Missing candidate evidence is not evidence excluding a branch. + if hypotheses[index].training_solver_status == 0: + return ImageMotionResolution(False, "image_motion_solver_budget_exhausted", hypotheses=tuple(hypotheses)) + return ImageMotionResolution(False, "image_motion_alternative_not_evaluable", hypotheses=tuple(hypotheses)) + if any(check.status == "conflicting" for check in hypotheses[index].pose_bridge_checks): + continue + if hypotheses[index].reason == "image_motion_source_geometry_conflict": + continue + if hypotheses[index].reason == "image_motion_reprojection_failed": + # This converged model violates the unchanged absolute image gate + # on training/held-out images. It is already an inadmissible + # explanation, not a competing accepted family whose current-frame + # angle uncertainty should prevent the valid model being used. + continue + alternative_checks = tuple(select_image_motion_frame(alternative, frames[i]) for i in validation) + equivalent = all(equivalent_frame_selections(checked, other) + for checked, other in zip(checks, alternative_checks)) + if equivalent: + comparisons.append((index, 0.)) + continue + if not all(c.quality for c in alternative_checks): + return ImageMotionResolution(False, "image_motion_alternative_angles_unresolved", hypotheses=tuple(hypotheses)) + alternative_errors = np.array([np.sqrt(np.mean([q.rms_px ** 2 for q in c.quality])) + for c in alternative_checks]) + probability = _comparison(winner_errors, alternative_errors, angles, model.reprojection_tie_px) + comparisons.append((index, probability)) + adjusted = holm_adjusted_probabilities(comparisons) + hypotheses[winner] = replace(hypotheses[winner], comparison_p_values=tuple(comparisons), + comparison_adjusted_p_values=adjusted) + if any(probability > limits.familywise_error_probability for _, probability in adjusted): + return ImageMotionResolution(False, "image_motion_families_not_distinguishable", hypotheses=tuple(hypotheses)) + final = select_image_motion_frame(model, frames[-1]) + if not final.resolved: + return ImageMotionResolution(False, final.reason, hypotheses=tuple(hypotheses)) + return ImageMotionResolution(True, "", model, tuple(hypotheses), final.selections, + selected_hypothesis=winner) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/relative.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/relative.py new file mode 100644 index 0000000..0fc3324 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/relative.py @@ -0,0 +1,37 @@ +"""Relative for shared square Tag pose estimation.""" + +from __future__ import annotations + +import math + +from scipy.spatial.transform import Rotation +import numpy as np + +from .types import SquareTagPose + + +def _relative_pose( + parent: SquareTagPose, + child: SquareTagPose, +) -> tuple[Rotation, np.ndarray]: + parent_rotation = Rotation.from_quat(parent.quaternion_xyzw) + child_rotation = Rotation.from_quat(child.quaternion_xyzw) + relative_rotation = parent_rotation.inv() * child_rotation + relative_translation = parent_rotation.inv().apply( + np.asarray(child.translation_xyz_m, dtype=float) + - np.asarray(parent.translation_xyz_m, dtype=float) + ) + return relative_rotation, relative_translation + + +def _normal_alignment_rad(first: SquareTagPose, second: SquareTagPose) -> float: + """Return the undirected angle between two observed Tag face normals.""" + first_normal = Rotation.from_quat(first.quaternion_xyzw).apply( + [0.0, 0.0, 1.0] + ) + second_normal = Rotation.from_quat(second.quaternion_xyzw).apply( + [0.0, 0.0, 1.0] + ) + return math.acos( + abs(float(np.clip(first_normal @ second_normal, -1.0, 1.0))) + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/rigid_group.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/rigid_group.py new file mode 100644 index 0000000..e5d9b81 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/rigid_group.py @@ -0,0 +1,880 @@ +"""Rigid group for shared square Tag pose estimation.""" + +from __future__ import annotations + +from dataclasses import replace +from itertools import product +from typing import Mapping, Sequence +import math + +from scipy.spatial.transform import Rotation +import numpy as np + +from .ippe import rotation_distance_rad +from .relative import _normal_alignment_rad, _relative_pose +from .trajectory import select_rigid_group_trajectory +from .types import SquareTagPose + + +def select_static_rigid_group_initialization( + frames: Sequence[Mapping[str, Sequence[SquareTagPose]]], + *, + roles: Sequence[str], + fixed_pairs: Sequence[tuple[str, str]], + reprojection_scale_px: float, + maximum_pose_jump_rad: float, + maximum_translation_jump_m: float, + relative_rotation_scale_rad: float, + relative_translation_scale_m: float, + normal_alignment_pairs: Sequence[tuple[str, str]] = (), + normal_alignment_scale_rad: float = math.radians(5.0), + task_reference_pairs: Mapping[ + tuple[str, str], tuple[Rotation, np.ndarray] + ] | None = None, + task_reference_rotation_scale_rad: float = math.radians(1.0), + task_reference_translation_scale_m: float = 0.01, +) -> tuple[list[dict[str, SquareTagPose]], dict[str, float | str]]: + """Select a static multi-Tag IPPE branch path in bounded time. + + Group initialization is performed while the hand is held at an endpoint, + so every frame should describe the same camera and relative Tag poses. + Enumerating a full Viterbi transition matrix for every possible first-frame + branch is therefore unnecessary: with four two-branch Tags and eight + frames it performs more than one hundred thousand scipy rotations and can + block the live ROS callback for several seconds. + + Instead, treat every first-frame combination as a possible static + reference and independently select the closest combination in each later + frame. This preserves the multi-frame rigidity and normal-alignment + evidence while changing the search from O(F*C^2*C0) to O(F*C*C0). + """ + role_names = tuple(str(role) for role in roles) + pair_names = tuple((str(parent), str(child)) for parent, child in fixed_pairs) + normal_pair_names = tuple( + (str(first), str(second)) for first, second in normal_alignment_pairs + ) + task_references = dict(task_reference_pairs or {}) + if not frames: + raise ValueError("at least one PnP frame is required") + if not role_names or len(set(role_names)) != len(role_names): + raise ValueError("roles must be non-empty and unique") + if any( + parent not in role_names or child not in role_names + for parent, child in ( + *pair_names, + *normal_pair_names, + *task_references, + ) + ): + raise ValueError("geometry pairs must reference roles") + scales = ( + float(reprojection_scale_px), + float(maximum_pose_jump_rad), + float(maximum_translation_jump_m), + float(relative_rotation_scale_rad), + float(relative_translation_scale_m), + float(normal_alignment_scale_rad), + float(task_reference_rotation_scale_rad), + float(task_reference_translation_scale_m), + ) + if min(scales) <= 0.0: + raise ValueError("static initialization scales must be positive") + ( + reprojection_scale, + pose_scale, + translation_scale, + relative_rotation_scale, + relative_translation_scale, + normal_scale, + task_reference_rotation_scale, + task_reference_translation_scale, + ) = scales + + combinations_by_frame: list[list[dict[str, SquareTagPose]]] = [] + for frame in frames: + candidate_lists = [tuple(frame.get(role, ())) for role in role_names] + if any(not candidates for candidates in candidate_lists): + raise ValueError("every frame must contain every requested role") + combinations_by_frame.append( + [ + dict(zip(role_names, combination)) + for combination in product(*candidate_lists) + ] + ) + + def score_against_reference( + reference: Mapping[str, SquareTagPose], + reference_pairs: Mapping[ + tuple[str, str], tuple[Rotation, np.ndarray] + ], + combination: Mapping[str, SquareTagPose], + ) -> float: + score = sum( + pose.reprojection_error_px for pose in combination.values() + ) / reprojection_scale + score += sum( + _normal_alignment_rad(combination[first], combination[second]) + for first, second in normal_pair_names + ) / normal_scale + score += sum( + rotation_distance_rad( + reference[role].quaternion_xyzw, + combination[role].quaternion_xyzw, + ) + / pose_scale + + float( + np.linalg.norm( + np.asarray(combination[role].translation_xyz_m, dtype=float) + - np.asarray(reference[role].translation_xyz_m, dtype=float) + ) + ) + / translation_scale + for role in role_names + ) + for pair, (reference_rotation, reference_translation) in ( + reference_pairs.items() + ): + rotation, translation = _relative_pose( + combination[pair[0]], combination[pair[1]] + ) + score += ( + float((reference_rotation.inv() * rotation).magnitude()) + / relative_rotation_scale + + float(np.linalg.norm(translation - reference_translation)) + / relative_translation_scale + ) + for pair, (task_rotation, task_translation) in task_references.items(): + rotation, translation = _relative_pose( + combination[pair[0]], combination[pair[1]] + ) + score += ( + float((task_rotation.inv() * rotation).magnitude()) + / task_reference_rotation_scale + + float(np.linalg.norm(translation - task_translation)) + / task_reference_translation_scale + ) + return float(score) + + best_total = float("inf") + best_path: list[dict[str, SquareTagPose]] | None = None + for reference in combinations_by_frame[0]: + reference_pairs = { + pair: _relative_pose(reference[pair[0]], reference[pair[1]]) + for pair in pair_names + } + path = [reference] + total = score_against_reference(reference, reference_pairs, reference) + for combinations in combinations_by_frame[1:]: + scored = [ + ( + score_against_reference( + reference, reference_pairs, combination + ), + combination, + ) + for combination in combinations + ] + cost, selected = min(scored, key=lambda item: item[0]) + total += cost + path.append(selected) + if total < best_total: + best_total = total + best_path = path + + if best_path is None: + raise RuntimeError("static group initialization produced no path") + + # Reuse the complete quality calculation with exactly one chosen branch + # per role and frame. This retains all existing quality fields without + # reintroducing the combinatorial branch search. + reduced_frames = [ + {role: (frame[role],) for role in role_names} for frame in best_path + ] + selected_path, quality = select_rigid_group_trajectory( + reduced_frames, + roles=role_names, + fixed_pairs=pair_names, + reprojection_scale_px=reprojection_scale, + rotation_scale_rad=relative_rotation_scale, + translation_scale_m=relative_translation_scale, + normal_alignment_pairs=normal_pair_names, + normal_alignment_scale_rad=normal_scale, + ) + quality = dict(quality) + quality["total_cost"] = float(best_total) + quality["initialization_search"] = "static_reference" + quality["task_reference_used"] = ( + "true" if task_references else "false" + ) + return selected_path, quality + + +class SquareTagGroupPoseTracker: + """Choose all tag branches together using thumb-chain continuity. + + A 30 px planar tag has two IPPE solutions whose reprojection errors can + exchange order from one frame to the next. Tracking each tag + independently can therefore choose an incompatible pair for a relative + joint such as T4->T5. This tracker enumerates the small Cartesian product + (at most 2**4 combinations) and favours the combination that keeps both + the camera poses and all adjacent relative poses continuous. + """ + + def __init__( + self, + *, + roles: Sequence[str], + adjacent_pairs: Sequence[tuple[str, str]], + maximum_pose_jump_rad: float, + maximum_translation_jump_m: float, + relative_rotation_scale_rad: float, + relative_translation_scale_m: float, + reprojection_scale_px: float, + reprojection_weight: float, + reset_after_seconds: float, + initialization_frames: int = 1, + normal_alignment_pairs: Sequence[tuple[str, str]] = (), + normal_alignment_scale_rad: float = math.radians(5.0), + maximum_normal_alignment_rad: float | None = None, + return_reference_rotation_scale_rad: float = math.radians(1.0), + return_reference_maximum_command_gap_u8: int = 8, + coupled_rotation_pairs: Sequence[ + tuple[str, str, str, str, float] + ] = (), + coupled_rotation_scale_rad: float = math.radians(3.0), + maximum_coupled_rotation_residual_rad: float | None = None, + ) -> None: + self.roles = tuple(str(role) for role in roles) + self.adjacent_pairs = tuple( + (str(parent), str(child)) + for parent, child in adjacent_pairs + ) + self.normal_alignment_pairs = tuple( + (str(first), str(second)) + for first, second in normal_alignment_pairs + ) + self.coupled_rotation_pairs = tuple( + ( + str(driver_parent), + str(driver_child), + str(follower_parent), + str(follower_child), + float(multiplier), + ) + for ( + driver_parent, + driver_child, + follower_parent, + follower_child, + multiplier, + ) in coupled_rotation_pairs + ) + if not self.roles or len(set(self.roles)) != len(self.roles): + raise ValueError("roles must be non-empty and unique") + if any( + parent not in self.roles or child not in self.roles + for parent, child in ( + *self.adjacent_pairs, + *self.normal_alignment_pairs, + ) + ): + raise ValueError("group geometry pairs must reference roles") + self.maximum_pose_jump_rad = float(maximum_pose_jump_rad) + self.maximum_translation_jump_m = float( + maximum_translation_jump_m + ) + self.relative_rotation_scale_rad = float( + relative_rotation_scale_rad + ) + self.relative_translation_scale_m = float( + relative_translation_scale_m + ) + self.reprojection_scale_px = float(reprojection_scale_px) + self.reprojection_weight = float(reprojection_weight) + self.initialization_frames = int(initialization_frames) + self.normal_alignment_scale_rad = float( + normal_alignment_scale_rad + ) + self.maximum_normal_alignment_rad = ( + None + if maximum_normal_alignment_rad is None + else float(maximum_normal_alignment_rad) + ) + self.return_reference_rotation_scale_rad = float( + return_reference_rotation_scale_rad + ) + self.return_reference_maximum_command_gap_u8 = int( + return_reference_maximum_command_gap_u8 + ) + self.coupled_rotation_scale_rad = float( + coupled_rotation_scale_rad + ) + self.maximum_coupled_rotation_residual_rad = ( + None + if maximum_coupled_rotation_residual_rad is None + else float(maximum_coupled_rotation_residual_rad) + ) + reset_seconds = float(reset_after_seconds) + if min( + self.maximum_pose_jump_rad, + self.maximum_translation_jump_m, + self.relative_rotation_scale_rad, + self.relative_translation_scale_m, + self.reprojection_scale_px, + self.normal_alignment_scale_rad, + self.return_reference_rotation_scale_rad, + self.coupled_rotation_scale_rad, + reset_seconds, + ) <= 0.0: + raise ValueError("group tracking scales must be positive") + if self.reprojection_weight < 0.0: + raise ValueError("reprojection_weight must be non-negative") + if self.initialization_frames < 1: + raise ValueError("initialization_frames must be positive") + if self.return_reference_maximum_command_gap_u8 < 0: + raise ValueError( + "return reference maximum command gap must be non-negative" + ) + if ( + self.maximum_normal_alignment_rad is not None + and self.maximum_normal_alignment_rad <= 0.0 + ): + raise ValueError("maximum normal alignment must be positive") + if any( + role not in self.roles + for coupling in self.coupled_rotation_pairs + for role in coupling[:4] + ): + raise ValueError("coupled rotation pairs must reference roles") + if any( + multiplier <= 0.0 + for *_, multiplier in self.coupled_rotation_pairs + ): + raise ValueError("coupled rotation multipliers must be positive") + if ( + self.maximum_coupled_rotation_residual_rad is not None + and self.maximum_coupled_rotation_residual_rad <= 0.0 + ): + raise ValueError( + "maximum coupled rotation residual must be positive" + ) + self.reset_after_ns = int(reset_seconds * 1_000_000_000) + self._previous: dict[str, SquareTagPose] = {} + self._previous_stamp_ns: int | None = None + self._initial_candidates: list[ + dict[str, tuple[SquareTagPose, ...]] + ] = [] + self._initial_stamps_ns: list[int] = [] + self.last_initialization_quality: dict[str, float | str] = {} + self.branch_correction_counts: dict[str, int] = {} + self._decreasing_relative_rotations: dict[ + int, dict[tuple[str, str], Rotation] + ] = {} + self._coupled_reference_rotations: dict[ + tuple[str, str], Rotation + ] = {} + self._task_reference_relative_poses: dict[ + tuple[str, str], tuple[Rotation, np.ndarray] + ] = {} + self.last_missing_roles: tuple[str, ...] = () + + def reset(self, *, preserve_task_reference: bool = False) -> None: + self._previous.clear() + self._previous_stamp_ns = None + self._initial_candidates.clear() + self._initial_stamps_ns.clear() + self.last_initialization_quality.clear() + self.branch_correction_counts.clear() + self._decreasing_relative_rotations.clear() + self._coupled_reference_rotations.clear() + self.last_missing_roles = () + if not preserve_task_reference: + self._task_reference_relative_poses.clear() + + def _task_reference_cost( + self, combination: Mapping[str, SquareTagPose] + ) -> float: + residual = 0.0 + for pair, (expected_rotation, expected_translation) in ( + self._task_reference_relative_poses.items() + ): + rotation, translation = _relative_pose( + combination[pair[0]], combination[pair[1]] + ) + residual += ( + float((expected_rotation.inv() * rotation).magnitude()) + / self.return_reference_rotation_scale_rad + + float(np.linalg.norm(translation - expected_translation)) + / self.relative_translation_scale_m + ) + return residual + + def _coupled_rotation_residuals( + self, combination: Mapping[str, SquareTagPose] + ) -> tuple[float, ...]: + if not self.coupled_rotation_pairs: + return () + residuals: list[float] = [] + for ( + driver_parent, + driver_child, + follower_parent, + follower_child, + multiplier, + ) in self.coupled_rotation_pairs: + driver_pair = (driver_parent, driver_child) + follower_pair = (follower_parent, follower_child) + if ( + driver_pair not in self._coupled_reference_rotations + or follower_pair not in self._coupled_reference_rotations + ): + return () + driver_rotation = _relative_pose( + combination[driver_parent], combination[driver_child] + )[0] + follower_rotation = _relative_pose( + combination[follower_parent], combination[follower_child] + )[0] + driver_travel = ( + self._coupled_reference_rotations[driver_pair].inv() + * driver_rotation + ).magnitude() + follower_travel = ( + self._coupled_reference_rotations[follower_pair].inv() + * follower_rotation + ).magnitude() + residuals.append( + abs(float(follower_travel) - multiplier * float(driver_travel)) + ) + return tuple(residuals) + + def _informative_coupled_rotation_costs( + self, + combinations: Sequence[Mapping[str, SquareTagPose]], + ) -> tuple[float, ...]: + """Return branch costs only while the weak coupling prior is credible. + + The URDF mimic ratio is useful for distinguishing two planar-IPPE + branches, but it is not measurement truth for a passive joint. Once + every otherwise viable combination disagrees with that ratio, using + it would bias the measured curve (and previously rejected every + frame). In that case fall back to visual continuity for this frame. + """ + residuals = tuple( + self._coupled_rotation_residuals(combination) + for combination in combinations + ) + if not residuals or not any(residuals): + return tuple(0.0 for _ in combinations) + if ( + self.maximum_coupled_rotation_residual_rad is not None + and not any( + values + and max(values) + <= self.maximum_coupled_rotation_residual_rad + for values in residuals + ) + ): + return tuple(0.0 for _ in combinations) + return tuple( + sum(values) / self.coupled_rotation_scale_rad + for values in residuals + ) + + def _return_reference( + self, command_u8: int | None + ) -> dict[tuple[str, str], tuple[Rotation, np.ndarray | None]]: + if command_u8 is None or not self._decreasing_relative_rotations: + return {} + command = int(command_u8) + nearest = min( + self._decreasing_relative_rotations, + key=lambda candidate: abs(candidate - command), + ) + if ( + abs(nearest - command) + > self.return_reference_maximum_command_gap_u8 + ): + return {} + references = self._decreasing_relative_rotations[nearest] + commands = sorted(self._decreasing_relative_rotations) + axes: dict[tuple[str, str], np.ndarray | None] = {} + for pair in self.adjacent_pairs: + endpoint_delta = ( + self._decreasing_relative_rotations[commands[-1]][pair].inv() + * self._decreasing_relative_rotations[commands[0]][pair] + ).as_rotvec() + norm = float(np.linalg.norm(endpoint_delta)) + axes[pair] = ( + None + if norm < math.radians(5.0) + else endpoint_delta / norm + ) + return { + pair: (rotation, axes[pair]) + for pair, rotation in references.items() + } + + def _return_reference_cost( + self, + combination: Mapping[str, SquareTagPose], + reference: Mapping[ + tuple[str, str], tuple[Rotation, np.ndarray | None] + ], + ) -> float: + residual = 0.0 + for pair, (expected, motion_axis) in reference.items(): + vector = ( + expected.inv() + * _relative_pose( + combination[pair[0]], combination[pair[1]] + )[0] + ).as_rotvec() + if motion_axis is not None: + # The outbound trajectory identifies the physical one-DOF + # motion axis. Do not penalize return travel along that axis: + # it may contain real mechanical hysteresis that calibration + # must measure. A planar-IPPE mirror branch appears primarily + # as a large orthogonal tilt and is rejected by this residual. + vector = vector - motion_axis * float(vector @ motion_axis) + residual += float(np.linalg.norm(vector)) + return residual / self.return_reference_rotation_scale_rad + + def select( + self, + candidates_by_role: Mapping[str, Sequence[SquareTagPose]], + *, + stamp_ns: int, + trajectory_command_u8: int | None = None, + trajectory_direction: str | None = None, + ) -> tuple[dict[str, SquareTagPose] | None, str]: + """Return one mutually consistent pose for every configured role.""" + direction = ( + None + if trajectory_direction is None + else str(trajectory_direction) + ) + if direction not in {None, "decreasing", "increasing"}: + raise ValueError( + "trajectory_direction must be decreasing or increasing" + ) + return_reference = ( + self._return_reference(trajectory_command_u8) + if direction == "increasing" + else {} + ) + candidate_lists = [ + tuple(candidates_by_role.get(role, ())) + for role in self.roles + ] + self.last_missing_roles = tuple( + role + for role, candidates in zip(self.roles, candidate_lists) + if not candidates + ) + if self.last_missing_roles: + return None, "group_missing_pose_candidates" + self.last_missing_roles = () + + combinations = [ + dict(zip(self.roles, combination)) + for combination in product(*candidate_lists) + ] + minimum_errors = { + role: min( + candidate.reprojection_error_px + for candidate in candidates + ) + for role, candidates in zip(self.roles, candidate_lists) + } + stamp = int(stamp_ns) + previous_is_fresh = ( + self._previous_stamp_ns is not None + and 0 <= stamp - self._previous_stamp_ns + <= self.reset_after_ns + and set(self._previous) == set(self.roles) + ) + + if not previous_is_fresh: + if self._previous_stamp_ns is not None: + self._previous.clear() + self._previous_stamp_ns = None + self._initial_candidates.clear() + self._initial_stamps_ns.clear() + self.last_initialization_quality.clear() + if self.initialization_frames > 1: + if self._initial_stamps_ns and not ( + 0 <= stamp - self._initial_stamps_ns[-1] + <= self.reset_after_ns + ): + self._initial_candidates.clear() + self._initial_stamps_ns.clear() + self._initial_candidates.append( + { + role: tuple(candidates_by_role.get(role, ())) + for role in self.roles + } + ) + self._initial_stamps_ns.append(stamp) + if len(self._initial_candidates) < self.initialization_frames: + return ( + None, + "group_initializing:" + f"{len(self._initial_candidates)}/" + f"{self.initialization_frames}", + ) + selected_path, initialization_quality = ( + select_static_rigid_group_initialization( + self._initial_candidates, + roles=self.roles, + fixed_pairs=self.adjacent_pairs, + reprojection_scale_px=self.reprojection_scale_px, + maximum_pose_jump_rad=self.maximum_pose_jump_rad, + maximum_translation_jump_m=( + self.maximum_translation_jump_m + ), + relative_rotation_scale_rad=( + self.relative_rotation_scale_rad + ), + relative_translation_scale_m=( + self.relative_translation_scale_m + ), + normal_alignment_pairs=( + self.normal_alignment_pairs + ), + normal_alignment_scale_rad=( + self.normal_alignment_scale_rad + ), + task_reference_pairs=( + self._task_reference_relative_poses + ), + task_reference_rotation_scale_rad=( + self.return_reference_rotation_scale_rad + ), + task_reference_translation_scale_m=( + self.relative_translation_scale_m + ), + ) + ) + selected = selected_path[-1] + stamp = self._initial_stamps_ns[-1] + self.last_initialization_quality = dict( + initialization_quality + ) + self._initial_candidates.clear() + self._initial_stamps_ns.clear() + if ( + self.maximum_normal_alignment_rad is not None + and float( + initialization_quality[ + "maximum_normal_alignment_rad" + ] + ) + > self.maximum_normal_alignment_rad + ): + return None, "group_normal_alignment" + else: + coupling_costs = self._informative_coupled_rotation_costs( + combinations + ) + selected = min( + zip(combinations, coupling_costs), + key=lambda item: ( + sum( + pose.reprojection_error_px + for pose in item[0].values() + ) + / self.reprojection_scale_px + + sum( + _normal_alignment_rad( + item[0][first], item[0][second] + ) + for first, second in self.normal_alignment_pairs + ) + / self.normal_alignment_scale_rad + + self._return_reference_cost( + item[0], return_reference + ) + + item[1] + + self._task_reference_cost(item[0]) + ), + )[0] + maximum_alignment = max( + ( + _normal_alignment_rad( + selected[first], selected[second] + ) + for first, second in self.normal_alignment_pairs + ), + default=0.0, + ) + self.last_initialization_quality = { + "maximum_normal_alignment_rad": maximum_alignment + } + if ( + self.maximum_normal_alignment_rad is not None + and maximum_alignment + > self.maximum_normal_alignment_rad + ): + return None, "group_normal_alignment" + else: + previous_relative = { + pair: _relative_pose( + self._previous[pair[0]], + self._previous[pair[1]], + ) + for pair in self.adjacent_pairs + } + base_scored: list[tuple[float, dict[str, SquareTagPose]]] = [] + for combination in combinations: + absolute_rotation_motion = 0.0 + absolute_translation_motion = 0.0 + rejected = False + for role in self.roles: + rotation_motion = rotation_distance_rad( + self._previous[role].quaternion_xyzw, + combination[role].quaternion_xyzw, + ) + translation_motion = float( + np.linalg.norm( + np.asarray( + combination[role].translation_xyz_m, + dtype=float, + ) + - np.asarray( + self._previous[role].translation_xyz_m, + dtype=float, + ) + ) + ) + if ( + rotation_motion > self.maximum_pose_jump_rad + or translation_motion + > self.maximum_translation_jump_m + ): + rejected = True + break + absolute_rotation_motion += rotation_motion + absolute_translation_motion += translation_motion + if rejected: + continue + + relative_rotation_motion = 0.0 + relative_translation_motion = 0.0 + for pair in self.adjacent_pairs: + rotation, translation = _relative_pose( + combination[pair[0]], + combination[pair[1]], + ) + old_rotation, old_translation = previous_relative[pair] + relative_rotation_motion += float( + (old_rotation.inv() * rotation).magnitude() + ) + relative_translation_motion += float( + np.linalg.norm(translation - old_translation) + ) + + reprojection_penalty = sum( + max( + 0.0, + combination[role].reprojection_error_px + - minimum_errors[role], + ) + for role in self.roles + ) / self.reprojection_scale_px + score = ( + absolute_rotation_motion + / self.maximum_pose_jump_rad + + absolute_translation_motion + / self.maximum_translation_jump_m + + relative_rotation_motion + / self.relative_rotation_scale_rad + + relative_translation_motion + / self.relative_translation_scale_m + + self.reprojection_weight * reprojection_penalty + + self._return_reference_cost( + combination, return_reference + ) + ) + base_scored.append((float(score), combination)) + + if not base_scored: + return None, "group_pose_jump" + coupling_costs = self._informative_coupled_rotation_costs( + [combination for _, combination in base_scored] + ) + scored = [ + (base_score + coupling_cost, combination) + for (base_score, combination), coupling_cost in zip( + base_scored, coupling_costs + ) + ] + selected = min(scored, key=lambda item: item[0])[1] + + aligned: dict[str, SquareTagPose] = {} + for role in self.roles: + pose = selected[role] + if previous_is_fresh: + old_quaternion = np.asarray( + self._previous[role].quaternion_xyzw, + dtype=float, + ) + quaternion = np.asarray( + pose.quaternion_xyzw, + dtype=float, + ) + if float(np.dot(old_quaternion, quaternion)) < 0.0: + pose = replace( + pose, + quaternion_xyzw=tuple( + float(value) for value in -quaternion + ), + ) + best_reprojection = min( + candidate_lists[self.roles.index(role)], + key=lambda candidate: candidate.reprojection_error_px, + ) + if pose != best_reprojection: + self.branch_correction_counts[role] = ( + self.branch_correction_counts.get(role, 0) + 1 + ) + aligned[role] = pose + + self._previous = aligned + self._previous_stamp_ns = stamp + if ( + direction == "decreasing" + and trajectory_command_u8 is not None + and not self._coupled_reference_rotations + ): + for ( + driver_parent, + driver_child, + follower_parent, + follower_child, + _multiplier, + ) in self.coupled_rotation_pairs: + for pair in ( + (driver_parent, driver_child), + (follower_parent, follower_child), + ): + self._coupled_reference_rotations[pair] = _relative_pose( + aligned[pair[0]], aligned[pair[1]] + )[0] + if direction == "decreasing" and trajectory_command_u8 is not None: + self._decreasing_relative_rotations[ + int(trajectory_command_u8) + ] = { + pair: _relative_pose( + aligned[pair[0]], aligned[pair[1]] + )[0] + for pair in self.adjacent_pairs + } + if not self._task_reference_relative_poses: + self._task_reference_relative_poses = { + pair: _relative_pose( + aligned[pair[0]], aligned[pair[1]] + ) + for pair in self.adjacent_pairs + } + return dict(aligned), "" diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/rigid_tag_pair.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/rigid_tag_pair.py new file mode 100644 index 0000000..8a5c3a7 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/rigid_tag_pair.py @@ -0,0 +1,246 @@ +"""Relative pose of two held Tags from their joint, independent image evidence. + +Both parent and child pixels are fitted. Each training image has its own parent +pose nuisance variables, so a previously fitted hinge is an initializer, not a +second observation or an exact camera pose. Schur marginalization retains that +nuisance uncertainty in the reported relative-pose bounds. +""" +from dataclasses import dataclass +import math + +import numpy as np +from scipy.optimize import least_squares +from scipy.sparse import lil_matrix +from scipy.spatial.transform import Rotation + +from .ippe import square_object_points +from .relative import _relative_pose +from .observer_pose import ObserverPose, OBSERVER_POSE_LIMITS +from .image_model_selection import compare_image_losses, holm_adjusted_probabilities + +RIGID_PAIR_CONDITIONING = 'rigid_tag_pair_pose_v1' +RIGID_PAIR_TRAJECTORY_POLICY = 'rigid_pair_full_trajectory_v3' + + +def _pose_vector(pose): + return np.r_[Rotation.from_quat(pose.quaternion_xyzw).as_rotvec(), pose.translation_xyz_m] + + +@dataclass +class _PairImages: + parent_pixels: np.ndarray + child_pixels: np.ndarray + matrices: np.ndarray + parent_points: np.ndarray + child_points: np.ndarray + initial_parents: np.ndarray + + def residual(self, parameters, indices): + child = Rotation.from_rotvec(parameters[:3]).apply(self.child_points)+parameters[3:6] + local = parameters[6:].reshape(-1, 6) + rotations = Rotation.from_rotvec(local[:, :3]).as_matrix() + points = np.concatenate((self.parent_points, child)) + camera = np.einsum('nij,kj->nki', rotations, points)+local[:, None, 3:] + if np.any(camera[:, :, 2] <= 0): + return np.full(len(indices)*16, 1e6) + projected = np.einsum('nij,nkj->nki', self.matrices[indices], camera) + pixels = projected[:, :, :2]/projected[:, :, 2:] + observed = np.concatenate((self.parent_pixels[indices], self.child_pixels[indices]), axis=1) + return (pixels-observed).ravel() + + def fit(self, relative, indices): + count = len(indices) + sparsity = lil_matrix((16*count, 6+6*count), dtype=int) + for i in range(count): + sparsity[16*i+8:16*(i+1), :6] = 1 + sparsity[16*i:16*(i+1), 6+6*i:12+6*i] = 1 + return least_squares(self.residual, np.r_[relative, self.initial_parents[indices].ravel()], + args=(indices,), jac_sparsity=sparsity.tocsr(), jac='3-point', + x_scale=np.tile([1., 1., 1., .03, .03, .03], count+1), max_nfev=150, + ftol=1e-9, xtol=1e-9, gtol=1e-9) + + def fit_with_parent_candidates(self, relative, indices, parent_candidates): + """Resolve training-frame nuisance branches before comparing installations. + + A joint least-squares solve can retain a wrong planar parent branch + in individual frames. Three bounded alternating refinements search + those local branches using training pixels only. Every global seed + keeps its own initial conditions; held-out pixels never enter here. + """ + initial = self.initial_parents.copy() + try: + result = self.fit(relative, indices) + _require_fit(result) + for _ in range(3): + _, nuisance = self.validate(result.x[:6], indices, + parent_candidates=parent_candidates) + self.initial_parents[indices] = nuisance + improved = self.fit(result.x[:6], indices) + _require_fit(improved) + if improved.cost >= result.cost: + break + improvement = result.cost-improved.cost + result = improved + if improvement < 1e-7: + break + return result + finally: + self.initial_parents = initial + + def validate(self, relative, indices, *, parent_candidates=None): + # Only independent image pose nuisance variables are solved here; + # the relative Tag installation remains frozen at its training value. + residuals, poses = [], [] + for i in indices: + seeds = (self.initial_parents[i],) if parent_candidates is None else tuple( + _pose_vector(p) for p in parent_candidates[i]) + fits = [] + for seed in seeds: + fit = least_squares(lambda value: self.residual(np.r_[relative, value], [i]), + seed, x_scale=[1., 1., 1., .03, .03, .03], jac='3-point', + max_nfev=80 if parent_candidates is None else 320) + _require_fit(fit) + fits.append(fit) + # These are same-image nuisance poses with frozen installation, + # not a choice between global models on holdout data. + fit = min(fits, key=lambda f: f.cost) + residuals.append(fit.fun) + poses.append(fit.x) + return np.asarray(residuals).ravel(), np.asarray(poses) + + +def _require_fit(fit): + if not fit.success or not np.all(np.isfinite(fit.x)) or not np.all(np.isfinite(fit.fun)): + raise ValueError('rigid_pair_candidate_not_evaluable') + + +def _errors(residual): + return np.sqrt(np.mean(np.sum(np.asarray(residual).reshape(-1, 2, 4, 2)**2, axis=3), axis=2)) + + +def _image_gate(residual): + if np.max(_errors(residual)) > 1.5: + raise ValueError('rigid_pair_image_validation_failed') + + +def _pose_bounds(fit, count): + jacobian = fit.jac.toarray() + information = np.zeros((6, 6)) + for i in range(count): + block = jacobian[16*i:16*(i+1)] + relative, parent = block[:, :6], block[:, 6+6*i:12+6*i] + singular = np.linalg.svd(parent, compute_uv=False) + if singular[-1] <= singular[0]*np.finfo(float).eps*max(parent.shape): + raise ValueError('rigid_pair_parent_rank_deficient') + basis, _ = np.linalg.qr(parent, mode='reduced') + projected = relative-basis@(basis.T@relative) + information += projected.T@projected + eigenvalues = np.linalg.eigvalsh(information) + if eigenvalues[0] <= eigenvalues[-1]*np.finfo(float).eps*6: + raise ValueError('rigid_pair_relative_rank_deficient') + variance = max(.03**2, float(fit.fun@fit.fun/(len(fit.fun)-len(fit.x)))) + covariance = np.linalg.inv(information)*variance + return tuple(float(3*np.sqrt(max(0., np.linalg.eigvalsh(covariance[i:i+3, i:i+3])[-1]))) + for i in (0, 3)) + + +def fit_rigid_tag_pair(parents, candidates, corners, matrices, size, stamps, *, parent_corners, parent_size, + parent_candidates=None, trajectory_states=None): + count = len(stamps) + if count < 24 or tuple(stamps) != tuple(sorted(set(stamps))) or any(not c for c in candidates): + raise ValueError('rigid_pair_independent_images_missing') + if parent_candidates is not None and (len(parent_candidates) != count or any(not p for p in parent_candidates)): + raise ValueError('rigid_pair_parent_candidates_missing') + if trajectory_states is not None: + states = tuple(trajectory_states) + if len(states) != count or any(len(value) != 2 for value in states): + raise ValueError('rigid_pair_trajectory_state_missing') + phases = np.asarray([value[0] for value in states], dtype=int) + commands = np.asarray([value[1] for value in states], dtype=float) + differences = np.diff(commands) + if (not np.all(np.isfinite(commands)) or np.ptp(commands) <= 0 + or not {1, 2} <= set(phases) + or not np.any(differences > 0) or not np.any(differences < 0)): + raise ValueError('rigid_pair_trajectory_direction_insufficient') + images = _PairImages(np.asarray(parent_corners), np.asarray(corners), np.asarray(matrices), + square_object_points(parent_size), square_object_points(size), np.asarray([_pose_vector(p) for p in parents])) + if (images.parent_pixels.shape != (count, 4, 2) or images.child_pixels.shape != (count, 4, 2) + or images.matrices.shape != (count, 3, 3) + or not all(np.all(np.isfinite(a)) for a in (images.parent_pixels, images.child_pixels, images.matrices))): + raise ValueError('rigid_pair_pixels_invalid') + training, validation = np.arange(0, count, 2), np.arange(1, count, 2) + training = training[np.linspace(0, len(training)-1, min(72, len(training))).round().astype(int)] + validation = validation[np.linspace(0, len(validation)-1, min(72, len(validation))).round().astype(int)] + rotations = Rotation.from_quat([p.quaternion_xyzw for p in parents]) + for indices in (training, validation): + if max((rotations[indices[0]].inv()*rotations[indices]).magnitude()) < math.radians(5): + raise ValueError('rigid_pair_viewpoint_span_insufficient') + fits = [] + seeds = (parents,) if parent_candidates is None else tuple( + tuple(poses[min(branch, len(poses)-1)] for poses in parent_candidates) + for branch in range(len(parent_candidates[training[0]]))) + for seed in seeds: + images.initial_parents = np.asarray([_pose_vector(p) for p in seed]) + for candidate in candidates[training[0]]: + rotation, point = _relative_pose(seed[training[0]], candidate) + relative = np.r_[rotation.as_rotvec(), point] + fit = (images.fit(relative, training) if parent_candidates is None else + images.fit_with_parent_candidates(relative, training, parent_candidates)) + _require_fit(fit) + fits.append(fit) + images.initial_parents = np.asarray([_pose_vector(p) for p in parents]) + winner = min(range(len(fits)), key=lambda i: fits[i].cost) + _image_gate(fits[winner].fun) + residuals = [images.validate(fit.x[:6], validation, parent_candidates=parent_candidates)[0] for fit in fits] + _image_gate(residuals[winner]) + comparisons = [] + angles = (rotations[0].inv()*rotations[validation]).as_rotvec() + for i, fit in enumerate(fits): + if i == winner: + continue + change = (Rotation.from_rotvec(fits[winner].x[:3]).inv()*Rotation.from_rotvec(fit.x[:3])).magnitude() + equivalent = change <= math.radians(.1) and np.linalg.norm(fits[winner].x[3:6]-fit.x[3:6]) <= .0001 + probability = (0. if equivalent or np.max(_errors(fit.fun)) > 1.5 else + compare_image_losses(np.sqrt(np.mean(_errors(residuals[winner])**2, axis=1)), + np.sqrt(np.mean(_errors(residuals[i])**2, axis=1)), angles, .03)) + comparisons.append((i, probability)) + adjusted = holm_adjusted_probabilities(comparisons) + if any(p > .01 for _, p in adjusted): + raise ValueError('rigid_pair_candidates_unresolved') + bounds = _pose_bounds(fits[winner], len(training)) + if any(not math.isfinite(v) or v > limit for v, limit in zip(bounds, OBSERVER_POSE_LIMITS)): + raise ValueError('rigid_pair_pose_uncertain') + x = fits[winner].x + return ObserverPose(tuple(Rotation.from_rotvec(x[:3]).as_quat()), tuple(x[3:6]), *bounds, + tuple(stamps[i] for i in training), tuple(stamps[i] for i in validation), adjusted) + + +def check_rigid_pair_endpoint(bridge): + """Fresh stationary pixels must support the independently fitted rigid pair.""" + from .pose_bridge import PoseBridgeCheck + def rejected(reason): + return PoseBridgeCheck(bridge.relation.joint, 'unresolved', reason) + frames = bridge.frames + if len(frames) < 10 or len({f.evidence.stamp_ns for f in frames}) != len(frames): + return rejected('rigid_pair_endpoint_missing') + if any(v < 0 or not math.isfinite(v) or v > limit for v, limit in zip( + (bridge.rotation_uncertainty_rad, bridge.translation_uncertainty_m), OBSERVER_POSE_LIMITS)): + return rejected('rigid_pair_source_uncertainty_invalid') + parent, child = bridge.relation.parent_role, bridge.relation.child_role + try: + observations = [{o.role: o for o in f.observations} for f in frames] + poses = [next(r for r in f.evidence.roles if r.role == parent).candidates[0] for f in frames] + images = _PairImages(np.asarray([o[parent].corners_xy for o in observations]), + np.asarray([o[child].corners_xy for o in observations]), np.asarray([f.camera_matrix for f in frames]), + square_object_points(observations[0][parent].tag_size_m), square_object_points(observations[0][child].tag_size_m), + np.asarray([_pose_vector(p) for p in poses])) + residual, fitted = images.validate(np.r_[Rotation.from_quat(bridge.quaternion_xyzw).as_rotvec(), + bridge.translation_xyz_m], np.arange(len(frames))) + _image_gate(residual) + rotations = Rotation.from_rotvec(fitted[:, :3]) + if (max((rotations.mean().inv()*rotations).magnitude()) > math.radians(1) + or np.max(np.linalg.norm(fitted[:, 3:]-np.median(fitted[:, 3:], axis=0), axis=1)) > .001): + return rejected('rigid_pair_endpoint_unstable') + except (ValueError, KeyError, IndexError, StopIteration) as error: + return rejected(str(error)) + return PoseBridgeCheck(bridge.relation.joint, 'consistent', '') diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/shared_zero_solver.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/shared_zero_solver.py new file mode 100644 index 0000000..8b83485 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/shared_zero_solver.py @@ -0,0 +1,124 @@ +"""Fit a new hinge using an independently measured shared zero pose. + +Axis, pivot and every image angle are measured anew. The Tag mount follows from +the shared pose and the new pivot, not from the old hinge's mount or axis. +Current stationary witness images are validation-only; the shared pose comes +from the previous passed zero. Both IPPE initializations still +run, and the independent arc holdout retains every ordinary image quality gate. +""" + +import numpy as np +from scipy.sparse import lil_matrix +from scipy.spatial.transform import Rotation + +from .motion_image_solver import ImageHingeBundle +from .relative import _relative_pose +from .pose_bridge import SHARED_POSE_CONDITIONING, SHARED_ZERO_CONDITIONING +from .image_bundle_optimizer import solve_image_bundle + + +class SharedZeroImageHingeBundle(ImageHingeBundle): + """Remove shared zero variables, keep all image angles free. + + The anchor fixes the angle gauge at the earlier measured zero, not at the + first preparation image. A new angle is therefore needed for that image. + Independent roots use free hinge geometry. A declared moving-parent transfer + retains its existing bounded axis and distance parameterization. + """ + + def __init__(self, frames, relations, poses, bridges, *, constraints=(), sources=()): + super().__init__(frames, relations, poses) + anchors = {bridge.relation: bridge for bridge in bridges} + if (set(anchors) != set(relations) or len(anchors) != len(bridges) + or any(r.parent_role in self.child_roles for r in relations)): + raise ValueError("shared_zero_model_graph_unsupported") + modes = {bridge.conditioning for bridge in bridges} + from .rigid_tag_pair import RIGID_PAIR_CONDITIONING + if len(modes) != 1 or not modes <= {SHARED_POSE_CONDITIONING, SHARED_ZERO_CONDITIONING, RIGID_PAIR_CONDITIONING}: + raise ValueError("shared_pose_conditioning_policy_changed") + # Retain the orientation-only parameterization for explicit legacy + # replay; new acquisitions share the full physical zero posture. + self.share_translation = modes != {SHARED_ZERO_CONDITIONING} + self.geometry_width = 4 if self.share_translation else 7 + original = self.initial.copy() + self.transfer = None + if sources: + if not self.share_translation: + raise ValueError('shared_zero_transfer_requires_full_pose') + from .measured_transfer_solver import MeasuredTransferImageHingeBundle + self.transfer = MeasuredTransferImageHingeBundle(frames, relations, poses, + constraints=constraints, sources=sources) + original = self.transfer.initial + self.anchors = tuple(Rotation.from_quat(anchors[r].quaternion_xyzw) for r in relations) + self.zero_points = tuple(np.asarray(anchors[r].translation_xyz_m) for r in relations) + geometry, angles = [], [] + for index, relation in enumerate(relations): + values = original[index*10:(index+1)*10] + geometry.extend((*values[:2], *values[5:7])) + if not self.share_translation: + geometry.extend(values[7:10]) + angles.append([float((_relative_pose(parent, child)[0] * self.anchors[index].inv() + ).as_rotvec() @ self.axes[index]) for parent, child in + zip(poses[relation.parent_role], poses[relation.child_role])]) + self.initial = np.r_[geometry, np.asarray(angles).T.ravel()] + self.scale = np.r_[np.tile([1., 1.] + [.05]*(self.geometry_width-2), self.joints), + np.ones(self.count*self.joints)] + self.bounds = (-np.inf, np.inf) + if self.transfer is not None: + # Keep exactly the existing bounded tilt/radius domain. The other + # six static freedoms are supplied by the independent shared pose. + indices = [i*10+j for i in range(self.joints) for j in (0, 1, 5, 6)] + self.scale[:self.static_parameter_count] = self.transfer.scale[indices] + self.bounds = (np.r_[self.transfer.lower[indices], np.full(self.count*self.joints, -np.inf)], + np.r_[self.transfer.upper[indices], np.full(self.count*self.joints, np.inf)]) + + @property + def static_parameter_count(self): + return self.geometry_width*self.joints + + def geometry_parameter_indices(self, index): + return tuple(range(self.geometry_width*index, self.geometry_width*(index+1))) + + def geometry_values(self, parameters, index): + values = parameters[index*self.geometry_width:(index+1)*self.geometry_width] + change = Rotation.from_rotvec(self.bases[index] @ values[:2]) + pivot = change.apply(self.bases[index] @ values[2:4]) + axis = change.apply(self.axes[index]) + if self.transfer is not None: + expanded = self.transfer.initial.copy() + expanded[[index*10+j for j in (0, 1, 5, 6)]] = values[:4] + axis, _, pivot, _ = self.transfer.geometry_values(expanded, index) + reference = self.anchors[index] + # At shared zero: t0 = pivot + R0 * mount. A free mount would + # reintroduce three competing estimates of the same known posture. + mount = (reference.inv().apply(self.zero_points[index]-pivot) + if self.share_translation else values[4:7]) + return axis, reference, pivot, mount + + def residual(self, parameters): + angles = parameters[self.static_parameter_count:].reshape(self.count, self.joints) + pixels, _ = self.project(parameters, angles, self.root_transforms, self.matrices, self.objects) + return (pixels-self.observed).ravel() + + def solve(self, limits): + width = 8*self.joints + sparsity = lil_matrix((self.count*width, len(self.initial)), dtype=int) + for frame in range(self.count): + for joint in range(self.joints): + rows = slice(frame*width+joint*8, frame*width+(joint+1)*8) + sparsity[rows, self.geometry_parameter_indices(joint)] = 1 + sparsity[rows, self.static_parameter_count+frame*self.joints+joint] = 1 + return solve_image_bundle(self.residual, self.initial, sparsity=sparsity.tocsr(), + scale=self.scale, limits=limits, bounds=self.bounds) + + def uncertainty_problem(self, fit): + """Evaluate full image sensitivity without treating the anchor as exact. + + Restore all orientation and translation freedoms for the uncertainty test. + This does not refit or alter the accepted model: one Jacobian evaluation + keeps its projected pixels identical. A conditioning prior must never + turn weak image geometry into a spuriously precise axis or pivot. + """ + from .hinge_uncertainty import unconstrained_hinge_linearization + angles = fit.x[self.static_parameter_count:].reshape(self.count, self.joints) + return unconstrained_hinge_linearization(self, fit, angles) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/source_hinge.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/source_hinge.py new file mode 100644 index 0000000..33ab8a1 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/source_hinge.py @@ -0,0 +1,42 @@ +"""A measured hinge installation transported with its rigid physical Tag.""" + +from dataclasses import dataclass +import math +import numpy as np + +from .motion_evidence import MotionRelation +from .motion_image_types import ImageHingeGeometry + + +def hinge_from_dict(item): + return ImageHingeGeometry(MotionRelation(**item["relation"]), tuple(item["axis_parent_xyz"]), + tuple(item["reference_quaternion_xyzw"]), tuple(item["pivot_parent_xyz_m"]), + tuple(item["mount_child_xyz_m"])) + + +@dataclass(frozen=True) +class SourceHinge: + geometry: ImageHingeGeometry + evidence_id: str + model_sha256: str + child_axis_uncertainty_rad: float + child_point_uncertainty_m: float + + def __post_init__(self): + for identity in (self.evidence_id, self.model_sha256): + if not isinstance(identity, str) or len(identity) != 64 or any(c not in "0123456789abcdef" for c in identity): + raise ValueError("source_hinge_identity_invalid") + if any(not math.isfinite(v) or v <= 0 for v in ( + self.child_axis_uncertainty_rad, self.child_point_uncertainty_m)): + raise ValueError("source_hinge_uncertainty_missing") + g = self.geometry + if (not np.all(np.isfinite((*g.axis_parent_xyz, *g.reference_quaternion_xyzw, + *g.pivot_parent_xyz_m, *g.mount_child_xyz_m))) + or not np.isclose(np.linalg.norm(g.axis_parent_xyz), 1., atol=1e-7) + or not np.isclose(np.linalg.norm(g.reference_quaternion_xyzw), 1., atol=1e-7)): + raise ValueError("source_hinge_geometry_invalid") + + +def source_hinge_from_dict(value): + return SourceHinge(hinge_from_dict(value["geometry"]), value["evidence_id"], value["model_sha256"], + float(value["child_axis_uncertainty_rad"]), float(value["child_point_uncertainty_m"])) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/tracking.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/tracking.py new file mode 100644 index 0000000..7463c4f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/tracking.py @@ -0,0 +1,575 @@ +"""Tracking for shared square Tag pose estimation.""" + +from __future__ import annotations + +from contextlib import ExitStack +from copy import deepcopy +from ..frozen_evidence import image_model_evidence + +from dataclasses import asdict, dataclass, field, replace +from threading import RLock +from typing import Sequence +import math + +from scipy.spatial.transform import Rotation +import cv2 +import numpy as np + +from .ippe import fixed_pose_reprojection_error, rotation_distance_rad, solve_square_tag_ippe +from .branch_confirmation import BranchConfirmation +from .fixed_reference import FixedTagReference +from .parameters import DEFAULT_POSE_TRACKING_PARAMETERS, DEFAULT_REPROJECTION_TIE_PX, PoseTrackingParameters +from .types import SquareTagPose +from .image_motion_commit import (VerifiedImageMotionDecision, + verify_image_motion_frame, commit_image_motion_frame) + + +@dataclass(frozen=True) +class TrackerImageObservation: + """Exact immutable pixels and optics retained independently of callers.""" + + stamp_ns: int + corners_xy: tuple[tuple[float, float], ...] + camera_matrix: tuple[tuple[float, float, float], ...] + tag_size_m: float + + +@dataclass(frozen=True) +class MotionTrackerSnapshot: + """One image's immutable inputs for a lock-free geometric decision.""" + + tracker: SquareTagPoseTracker = field(repr=False) + role: str + epoch: int + stamp_ns: int + revision: int + frozen: bool + candidates: tuple[SquareTagPose, ...] + previous_pose: SquareTagPose | None + evidence_id: str | None + motion_managed: bool + image_observation: TrackerImageObservation | None = None + + +@dataclass(frozen=True) +class MotionPoseSelection: + """A candidate selected by a previously checked geometric constraint.""" + + snapshot: MotionTrackerSnapshot + pose: SquareTagPose + evidence_id: str + + +@dataclass(frozen=True) +class MotionFrameCommit: + accepted: bool + reason: str + selections: tuple[MotionPoseSelection, ...] = () + observation_snapshots: tuple[MotionObservationSnapshot, ...] = () + + +@dataclass(frozen=True) +class MotionObservationSnapshot: + """Detached evidence captured in the same critical section as selection.""" + + tracker: SquareTagPoseTracker = field(repr=False) + role: str + stamp_ns: int + candidates: tuple[SquareTagPose, ...] + diagnostics: dict[str, object] + corrections: int + + +def _validate_reprojection_thresholds(maximum_error: float, tie_error: float) -> None: + if not math.isfinite(maximum_error) or maximum_error <= 0: + raise ValueError("maximum_reprojection_error_px must be finite and positive") + if not math.isfinite(tie_error) or not 0 <= tie_error < maximum_error: + raise ValueError( + "reprojection_tie_px must be finite, non-negative and smaller than " + "maximum_reprojection_error_px; image acceptance is not a branch tie" + ) + + +def select_continuous_pose( + candidates: Sequence[SquareTagPose], + *, + previous: SquareTagPose | None, + maximum_reprojection_error_px: float, + reprojection_tie_px: float, + maximum_pose_jump_rad: float, + maximum_translation_jump_m: float, + maximum_tag_tilt_rad: float, +) -> tuple[SquareTagPose | None, str]: + """Select the best IPPE branch using image fit and temporal continuity.""" + maximum_error = float(maximum_reprojection_error_px) + tie_error = float(reprojection_tie_px) + _validate_reprojection_thresholds(maximum_error, tie_error) + maximum_rotation = float(maximum_pose_jump_rad) + maximum_translation = float(maximum_translation_jump_m) + maximum_tilt = float(maximum_tag_tilt_rad) + if any(not math.isfinite(value) or value <= 0 for value in ( + maximum_error, maximum_rotation, maximum_translation, maximum_tilt)): + raise ValueError("PnP selection thresholds must be finite and positive") + + eligible: list[SquareTagPose] = [] + for candidate in candidates: + if candidate.reprojection_error_px > maximum_error: + continue + normal = Rotation.from_quat(candidate.quaternion_xyzw).as_matrix()[:, 2] + tilt = math.acos(float(np.clip(abs(normal[2]), 0.0, 1.0))) + if tilt > maximum_tilt: + continue + eligible.append(candidate) + if not eligible: + return None, "no_pose_within_reprojection_or_tilt_limit" + + eligible.sort(key=lambda item: item.reprojection_error_px) + best = eligible[0] + if previous is None: + return best, "" + + # Image fit identifies a proposed branch. A stateless selector cannot + # confirm a large correction; the tracker below owns that evidence and + # knows whether a reference has already been frozen. + competitive = [ + candidate + for candidate in eligible + if candidate.reprojection_error_px + <= best.reprojection_error_px + tie_error + ] + if len(competitive) == 1: + nearest = min(eligible, key=lambda candidate: + rotation_distance_rad(previous.quaternion_xyzw, candidate.quaternion_xyzw) / maximum_rotation + + np.linalg.norm(np.asarray(previous.translation_xyz_m) - candidate.translation_xyz_m) / maximum_translation) + if (rotation_distance_rad(previous.quaternion_xyzw, best.quaternion_xyzw) > maximum_rotation + or np.linalg.norm(np.asarray(previous.translation_xyz_m) - best.translation_xyz_m) > maximum_translation + or rotation_distance_rad(nearest.quaternion_xyzw, best.quaternion_xyzw) + > DEFAULT_POSE_TRACKING_PARAMETERS.branch_equivalence_rad): + return None, "pose_branch_unconfirmed" + return best, "" + + previous_translation = np.asarray(previous.translation_xyz_m, dtype=float) + scored: list[tuple[float, SquareTagPose]] = [] + for candidate in competitive: + rotation_jump = rotation_distance_rad( + previous.quaternion_xyzw, + candidate.quaternion_xyzw, + ) + translation_jump = float( + np.linalg.norm( + np.asarray(candidate.translation_xyz_m, dtype=float) + - previous_translation + ) + ) + if ( + rotation_jump > maximum_rotation + or translation_jump > maximum_translation + ): + continue + score = ( + ( + candidate.reprojection_error_px + - best.reprojection_error_px + ) + / max(tie_error, np.finfo(float).eps) + + rotation_jump / maximum_rotation + + translation_jump / maximum_translation + ) + scored.append((float(score), candidate)) + if not scored: + return None, "pose_jump" + + selected = min(scored, key=lambda item: item[0])[1] + previous_quaternion = np.asarray(previous.quaternion_xyzw, dtype=float) + selected_quaternion = np.asarray(selected.quaternion_xyzw, dtype=float) + if float(np.dot(previous_quaternion, selected_quaternion)) < 0.0: + selected = replace( + selected, + quaternion_xyzw=tuple( + float(value) for value in -selected_quaternion + ), + ) + return selected, "" + + +class SquareTagPoseTracker: + """Maintain the selected planar-PnP branch independently for each tag.""" + + def __init__( + self, + *, + maximum_reprojection_error_px: float = DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px, + reprojection_tie_px: float = DEFAULT_REPROJECTION_TIE_PX, + maximum_pose_jump_rad: float = DEFAULT_POSE_TRACKING_PARAMETERS.maximum_pose_jump_rad, + maximum_translation_jump_m: float = DEFAULT_POSE_TRACKING_PARAMETERS.maximum_translation_jump_m, + maximum_tag_tilt_rad: float = DEFAULT_POSE_TRACKING_PARAMETERS.maximum_tag_tilt_rad, + reset_after_seconds: float = DEFAULT_POSE_TRACKING_PARAMETERS.reset_after_seconds, + branch_confirmation_frames: int = DEFAULT_POSE_TRACKING_PARAMETERS.branch_confirmation_frames, + branch_confirmation_minimum_seconds: float = DEFAULT_POSE_TRACKING_PARAMETERS.branch_confirmation_minimum_seconds, + branch_equivalence_rad: float = DEFAULT_POSE_TRACKING_PARAMETERS.branch_equivalence_rad, + ) -> None: + self.maximum_reprojection_error_px = float( + maximum_reprojection_error_px + ) + self.reprojection_tie_px = float(reprojection_tie_px) + _validate_reprojection_thresholds( + self.maximum_reprojection_error_px, self.reprojection_tie_px + ) + self.maximum_pose_jump_rad = float(maximum_pose_jump_rad) + self.maximum_translation_jump_m = float(maximum_translation_jump_m) + self.maximum_tag_tilt_rad = float(maximum_tag_tilt_rad) + if any(not math.isfinite(v) or v <= 0 for v in ( + self.maximum_pose_jump_rad, self.maximum_translation_jump_m, + self.maximum_tag_tilt_rad, float(reset_after_seconds))): + raise ValueError("PnP tracking limits must be finite and positive") + self.reset_after_ns = int(float(reset_after_seconds) * 1_000_000_000) + if self.reset_after_ns <= 0: + raise ValueError("reset_after_seconds must be positive") + self.branch_confirmation_frames = branch_confirmation_frames + self.branch_confirmation_minimum_seconds = float(branch_confirmation_minimum_seconds) + self.branch_equivalence_rad = float(branch_equivalence_rad) + self._lock = RLock() + self._epoch = 0 + self._branches = BranchConfirmation(PoseTrackingParameters( + self.maximum_reprojection_error_px, self.reprojection_tie_px, + self.maximum_pose_jump_rad, self.maximum_translation_jump_m, + self.maximum_tag_tilt_rad, float(reset_after_seconds), + branch_confirmation_frames, self.branch_confirmation_minimum_seconds, self.branch_equivalence_rad)) + self.last_candidates_by_role: dict[ + str, tuple[SquareTagPose, ...] + ] = {} + self.last_candidate_diagnostics_by_role: dict[ + str, dict[str, object] + ] = {} + self.branch_correction_counts = self._branches.corrections + self._motion_candidates_by_role: dict[str, tuple[SquareTagPose, ...]] = {} + self._image_observations_by_role: dict[str, TrackerImageObservation] = {} + self._image_model_sha256_by_role: dict[str, str] = {} + + def reset(self) -> None: + with self._lock: + self._epoch += 1 + self._branches.reset() + self.last_candidates_by_role.clear() + self.last_candidate_diagnostics_by_role.clear() + self._motion_candidates_by_role.clear() + self._image_observations_by_role.clear() + self._image_model_sha256_by_role.clear() + + def reset_roles(self, roles): + """Invalidate old image decisions before a declared new motion model.""" + with self._lock: + self._epoch += 1 + for role in roles: + for values in (self._branches.states, self._branches.corrections, + self.last_candidates_by_role, self.last_candidate_diagnostics_by_role, + self._motion_candidates_by_role, self._image_observations_by_role, + self._image_model_sha256_by_role): + values.pop(role, None) + + def observation_snapshot(self, role, stamp_ns): + """Copy one image's evidence atomically, never a subsequent callback.""" + with self._lock: + diagnostics = self.last_candidate_diagnostics_by_role.get(role, {}) + if diagnostics.get("observation_stamp_ns") != stamp_ns: + return None + return (self.last_candidates_by_role.get(role, ()), deepcopy(diagnostics), + self.branch_correction_counts.get(role, 0)) + + def motion_snapshot(self, role: str, stamp_ns: int) -> MotionTrackerSnapshot | None: + """Copy candidates and version metadata; callers solve outside locks.""" + with self._lock: + state = self._branches.states.get(role) + diagnostics = self.last_candidate_diagnostics_by_role.get(role, {}) + if state is None or diagnostics.get("observation_stamp_ns") != stamp_ns: + return None + return MotionTrackerSnapshot(self, role, self._epoch, stamp_ns, + state.revision, state.frozen, self._motion_candidates_by_role.get(role, ()), + state.pose, state.motion_evidence_id, diagnostics.get("motion_managed") is True, + self._image_observations_by_role.get(role)) + + @staticmethod + def _motion_snapshot_is_current(snapshot: MotionTrackerSnapshot) -> bool: + """Check metadata while the caller holds the corresponding tracker lock.""" + tracker = snapshot.tracker + state = tracker._branches.states.get(snapshot.role) + diagnostics = tracker.last_candidate_diagnostics_by_role.get(snapshot.role, {}) + return (tracker._epoch == snapshot.epoch and state is not None + and state.observed_ns == snapshot.stamp_ns and state.revision == snapshot.revision + and state.frozen == snapshot.frozen and state.motion_evidence_id == snapshot.evidence_id + and diagnostics.get("motion_managed") is True and snapshot.motion_managed + and diagnostics.get("motion_selection_committed") is not True) + + @staticmethod + def _motion_observation_snapshots(snapshots: Sequence[MotionTrackerSnapshot] + ) -> tuple[MotionObservationSnapshot, ...]: + """Detach diagnostics under the same locks used for a frame decision.""" + return tuple(MotionObservationSnapshot(snapshot.tracker, snapshot.role, snapshot.stamp_ns, + snapshot.tracker.last_candidates_by_role[snapshot.role], + deepcopy(snapshot.tracker.last_candidate_diagnostics_by_role[snapshot.role]), + snapshot.tracker.branch_correction_counts.get(snapshot.role, 0)) for snapshot in snapshots) + + @staticmethod + def reject_motion_frame(snapshots: Sequence[MotionTrackerSnapshot], reason: str + ) -> MotionFrameCommit: + """Discard one unresolved image without changing a reference or model.""" + snapshots = tuple(snapshots) + if not snapshots or not isinstance(reason, str) or not reason: + return MotionFrameCommit(False, "pose_motion_selection_invalid") + keys = {(snapshot.tracker, snapshot.role) for snapshot in snapshots} + if len(keys) != len(snapshots): + return MotionFrameCommit(False, "pose_motion_selection_duplicate_role") + with ExitStack() as stack: + for tracker in sorted({tracker for tracker, _ in keys}, key=id): + stack.enter_context(tracker._lock) + if not all(SquareTagPoseTracker._motion_snapshot_is_current(snapshot) for snapshot in snapshots): + return MotionFrameCommit(False, "pose_observation_superseded") + result_reason = reason + for snapshot in snapshots: + tracker, role = snapshot.tracker, snapshot.role + state = tracker._branches.states[role] + state.pending = None + if state.conflict: + result_reason = "pose_branch_conflict" + tracker._branches.reject(state, result_reason, "frozen_conflict") + else: + tracker._branches.reject(state, reason, "motion_unavailable") + diagnostics = tracker.last_candidate_diagnostics_by_role[role] + diagnostics.update(tracker._branches.diagnostics(role)) + diagnostics["motion_selection_committed"] = True + diagnostics["pose_constraint"] = "motion_geometry" + return MotionFrameCommit(False, result_reason, observation_snapshots= + SquareTagPoseTracker._motion_observation_snapshots(snapshots)) + + @staticmethod + def commit_motion_frame(selections: Sequence[MotionPoseSelection], *, + establish: bool = False) -> MotionFrameCommit: + """Commit a joint geometric decision without interleaving image metadata. + + No candidate evaluation or model fitting happens here. Every candidate + must have passed this tracker's original image and tilt gates; every + snapshot must still identify the same image and reference revision. + Existing evidence identities, especially frozen ones, are immutable. + """ + selections = tuple(selections) + if not selections: + return MotionFrameCommit(False, "pose_motion_selection_missing") + keys = {(item.snapshot.tracker, item.snapshot.role) for item in selections} + if len(keys) != len(selections): + return MotionFrameCommit(False, "pose_motion_selection_duplicate_role") + with ExitStack() as stack: + for tracker in sorted({tracker for tracker, _ in keys}, key=id): + stack.enter_context(tracker._lock) + for item in selections: + snapshot = item.snapshot + tracker = snapshot.tracker + if not SquareTagPoseTracker._motion_snapshot_is_current(snapshot): + return MotionFrameCommit(False, "pose_observation_superseded") + if (not isinstance(item.evidence_id, str) or not item.evidence_id + or item.pose not in snapshot.candidates + or item.pose not in tracker._motion_candidates_by_role.get(snapshot.role, ())): + return MotionFrameCommit(False, "pose_motion_selection_invalid") + if any(item.snapshot.role in item.snapshot.tracker._image_model_sha256_by_role + for item in selections): + return MotionFrameCommit(False, "pose_motion_solver_changed") + return SquareTagPoseTracker._commit_motion_selections_locked(selections, establish=establish) + + @staticmethod + def _commit_motion_selections_locked(selections, *, establish, image_decision=None): + """Share the recovery/identity transaction across both trusted solvers.""" + trials = [] + for item in selections: + tracker, role = item.snapshot.tracker, item.snapshot.role + original = tracker._branches.states[role] + trial = replace(original, + pending=None if original.pending is None else replace(original.pending)) + pose, reason = tracker._branches.select_motion(trial, item.pose, + item.evidence_id, establish=establish) + trials.append((tracker, role, trial, pose, reason)) + failure = next((reason for _, _, _, pose, reason in trials if pose is None), "") + for tracker, role, trial, pose, _ in trials: + diagnostics = tracker.last_candidate_diagnostics_by_role[role] + diagnostics["motion_selection_committed"] = True + # Recovery needs several images, even if another role is not yet + # ready. A successful role cannot advance or establish a new + # identity when the joint decision as a whole was rejected. + if failure and pose is not None: + continue + original = tracker._branches.states[role] + if (not failure and original.motion_evidence_id is None and original.pose is not None + and not tracker._branches.continuous(original.pose, trial.pose)): + tracker.branch_correction_counts[role] = tracker.branch_correction_counts.get(role, 0) + 1 + tracker._branches.states[role] = trial + diagnostics.update(tracker._branches.diagnostics(role)) + diagnostics["pose_constraint"] = "motion_geometry" + if image_decision is not None and not failure: + diagnostics.update({ + "pose_constraint": "image_motion_geometry", + "pose_source": "image_constrained_current_image", + "frozen_image_model": image_model_evidence(image_decision.model), + "image_model_sha256": image_decision.model_sha256, + "image_motion_quality": [asdict(item) for item in image_decision.quality], + }) + tracker._image_model_sha256_by_role[role] = image_decision.model_sha256 + observations = SquareTagPoseTracker._motion_observation_snapshots( + tuple(item.snapshot for item in selections)) + if failure: + return MotionFrameCommit(False, failure, observation_snapshots=observations) + return MotionFrameCommit(True, "", selections, observations) + + verify_image_motion_frame = staticmethod(verify_image_motion_frame) + commit_image_motion_frame = staticmethod(commit_image_motion_frame) + + def freeze_roles(self, expected_revisions, *, require_motion_evidence=False): + return self.freeze_references([(self, role, revision) for role, revision in expected_revisions.items()], + require_motion_evidence=require_motion_evidence) + + @staticmethod + def freeze_references(references, *, require_motion_evidence=False): + """Atomically freeze metadata across views after evidence validation. + + Callers may hold the session lock. No PnP work takes place under these + locks, and tracker code never acquires the session lock in reverse. + """ + references = tuple(references) + if not references: + return False + roles = {(tracker, role) for tracker, role, _ in references} + required = (roles if require_motion_evidence is True else set() + if require_motion_evidence is False else set(require_motion_evidence)) + if not required.issubset(roles): + return False + with ExitStack() as stack: + for tracker in sorted({tracker for tracker, _, _ in references}, key=id): + stack.enter_context(tracker._lock) + for tracker, role, revision in references: + state = tracker._branches.states.get(role) + if (type(revision) is not int or state is None or state.revision != revision or state.status != "tracking" + or state.pending is not None or state.conflict or state.recovery_required): + return False + if (tracker, role) in required and state.motion_evidence_id is None: + return False + for tracker, role, _ in references: + tracker._branches.states[role].frozen = True + tracker.last_candidate_diagnostics_by_role[role]["branch_frozen"] = True + return True + + def estimate( + self, + role: str, + corners_xy: Sequence[Sequence[float]], + *, + tag_size_m: float, + camera_matrix: Sequence[Sequence[float]], + stamp_ns: int, + reprojection_tie_px: float | None = None, + fixed_reference: FixedTagReference | None = None, + motion_managed: bool = False, + ) -> tuple[SquareTagPose | None, str]: + with self._lock: + epoch = self._epoch + image_observation = TrackerImageObservation(int(stamp_ns), + tuple(tuple(float(v) for v in point) for point in corners_xy), + tuple(tuple(float(v) for v in row) for row in camera_matrix), float(tag_size_m)) + corners_xy, camera_matrix = image_observation.corners_xy, image_observation.camera_matrix + try: + candidates = solve_square_tag_ippe( + corners_xy, + tag_size_m=tag_size_m, + camera_matrix=camera_matrix, + ) + except (ValueError, cv2.error): + candidates = [] + reprojection_candidates = [ + candidate + for candidate in candidates + if candidate.reprojection_error_px + <= self.maximum_reprojection_error_px + ] + candidate_tilts_rad: list[float] = [] + independent_candidates: list[SquareTagPose] = [] + for candidate in reprojection_candidates: + normal = Rotation.from_quat( + candidate.quaternion_xyzw + ).as_matrix()[:, 2] + tilt = math.acos( + float(np.clip(abs(normal[2]), 0.0, 1.0)) + ) + candidate_tilts_rad.append(float(tilt)) + if tilt <= self.maximum_tag_tilt_rad: + independent_candidates.append(candidate) + + # Candidate generation and candidate selection have different + # contracts. The per-Tag tilt limit protects a pose used without any + # other geometry, but it must not erase a finite, low-reprojection + # IPPE solution before SquareTagGroupPoseTracker can evaluate it + # against the fixed palm reference, the articulated chain and the + # preceding group pose. At a strongly oblique view the planar + # ambiguity is usually smaller, and rejecting both branches at a + # fixed angle caused deterministic mid-sweep holes despite continuous + # image detections. Group tracking therefore receives every + # reprojection-valid candidate; independent tracking below retains the + # original tilt safety gate. + diagnostics: dict[str, object] = { + "motion_managed": bool(motion_managed and fixed_reference is None), + "motion_selection_committed": False, + "solved_candidate_count": len(candidates), + "reprojection_candidate_count": len(reprojection_candidates), + "independent_tilt_candidate_count": len(independent_candidates), + "maximum_reprojection_error_px": float( + self.maximum_reprojection_error_px + ), + "maximum_independent_tilt_deg": math.degrees( + self.maximum_tag_tilt_rad + ), + } + if candidates: + diagnostics["minimum_reprojection_error_px"] = min(c.reprojection_error_px for c in candidates) + if candidate_tilts_rad: + diagnostics["minimum_candidate_tilt_deg"] = math.degrees( + min(candidate_tilts_rad) + ) + diagnostics["maximum_candidate_tilt_deg"] = math.degrees( + max(candidate_tilts_rad) + ) + tie = self.reprojection_tie_px if reprojection_tie_px is None else float(reprojection_tie_px) + _validate_reprojection_thresholds(self.maximum_reprojection_error_px, tie) + checked_fixed_pose = None + if fixed_reference is not None: + # Projection is outside the metadata lock, just like IPPE. Keep + # all current candidates as evidence, even when their ranking + # changes while the frozen fixed pose still explains the image. + diagnostics["pose_constraint"] = "fixed_reference" + try: + error = fixed_pose_reprojection_error(fixed_reference.pose, corners_xy, + tag_size_m=tag_size_m, camera_matrix=camera_matrix) + normal = Rotation.from_quat(fixed_reference.pose.quaternion_xyzw).as_matrix()[:, 2] + tilt = math.acos(float(np.clip(abs(normal[2]), 0.0, 1.0))) + diagnostics["fixed_reference_reprojection_error_px"] = error + if (error <= self.maximum_reprojection_error_px + and tilt <= self.maximum_tag_tilt_rad and independent_candidates): + checked_fixed_pose = replace(fixed_reference.pose, reprojection_error_px=error) + except (ValueError, cv2.error): + pass + diagnostics["fixed_reference_verified"] = checked_fixed_pose is not None + with self._lock: + if epoch != self._epoch: + return None, "pose_observation_superseded" + if fixed_reference is None and motion_managed: + selected, reason = self._branches.observe_motion(str(role), independent_candidates, int(stamp_ns)) + elif fixed_reference is None: + selected, reason = self._branches.update(str(role), independent_candidates, int(stamp_ns), tie) + else: + selected, reason = self._branches.update_fixed(str(role), fixed_reference, + checked_fixed_pose, int(stamp_ns)) + if reason == "pose_observation_not_new": + return None, reason + if not candidates and reason == "no_pose_within_reprojection_or_tilt_limit": + reason = "pnp_solve_failed" + self._branches.states[str(role)].reason = reason + diagnostics.update(self._branches.diagnostics(str(role))) + self.last_candidates_by_role[str(role)] = tuple(reprojection_candidates) + self._motion_candidates_by_role[str(role)] = tuple(independent_candidates) + self._image_observations_by_role[str(role)] = image_observation + self.last_candidate_diagnostics_by_role[str(role)] = diagnostics + return selected, reason diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/trajectory.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/trajectory.py new file mode 100644 index 0000000..a82be08 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/trajectory.py @@ -0,0 +1,424 @@ +"""Trajectory for shared square Tag pose estimation.""" + +from __future__ import annotations + +from itertools import product +from typing import Mapping, Sequence + +from scipy.spatial.transform import Rotation +import numpy as np + +from .ippe import rotation_distance_rad +from .relative import _normal_alignment_rad, _relative_pose +from .types import SquareTagPose + + +def select_rigid_group_trajectory( + frames: Sequence[Mapping[str, Sequence[SquareTagPose]]], + *, + roles: Sequence[str], + fixed_pairs: Sequence[tuple[str, str]], + reprojection_scale_px: float, + rotation_scale_rad: float, + translation_scale_m: float, + pair_geometry: str = "pose", + normal_alignment_pairs: Sequence[tuple[str, str]] = (), + normal_alignment_scale_rad: float | None = None, +) -> tuple[ + list[dict[str, SquareTagPose]], + dict[str, float | str], +]: + """Resolve planar branches using geometry that should stay rigid. + + Every possible branch combination in the first frame is treated as a + candidate rigid reference. For each such reference, every later frame + independently chooses the combination with the lowest reprojection plus + geometric-drift cost. ``pose`` compares relative rotation and translation; + ``distance`` compares only Euclidean centre distances and therefore does + not allow planar-PnP orientation jitter into centre-trajectory angles. + The globally cheapest reference and path win. + """ + role_names = tuple(str(role) for role in roles) + pair_names = tuple((str(parent), str(child)) for parent, child in fixed_pairs) + normal_pair_names = tuple( + (str(first), str(second)) + for first, second in normal_alignment_pairs + ) + if not frames: + raise ValueError("at least one PnP frame is required") + if len(set(role_names)) != len(role_names) or not role_names: + raise ValueError("roles must be non-empty and unique") + if any( + parent not in role_names or child not in role_names + for parent, child in (*pair_names, *normal_pair_names) + ): + raise ValueError("geometry pairs must reference roles") + reprojection_scale = float(reprojection_scale_px) + rotation_scale = float(rotation_scale_rad) + translation_scale = float(translation_scale_m) + geometry_mode = str(pair_geometry) + normal_scale = ( + rotation_scale + if normal_alignment_scale_rad is None + else float(normal_alignment_scale_rad) + ) + if min( + reprojection_scale, + rotation_scale, + translation_scale, + normal_scale, + ) <= 0.0: + raise ValueError("trajectory selection scales must be positive") + if geometry_mode not in {"pose", "distance"}: + raise ValueError("pair_geometry must be pose or distance") + + combinations_by_frame: list[list[dict[str, SquareTagPose]]] = [] + for frame in frames: + candidate_lists = [tuple(frame.get(role, ())) for role in role_names] + if any(not candidates for candidates in candidate_lists): + raise ValueError("every frame must contain every requested role") + combinations_by_frame.append( + [ + dict(zip(role_names, combination)) + for combination in product(*candidate_lists) + ] + ) + + best_total = float("inf") + best_path: list[dict[str, SquareTagPose]] | None = None + + def emission( + combination: Mapping[str, SquareTagPose], + reference_pairs: Mapping[ + tuple[str, str], tuple[Rotation, np.ndarray] + ], + reference_distances: Mapping[tuple[str, str], float], + ) -> tuple[float, float, float]: + reprojection_cost = sum( + pose.reprojection_error_px + for pose in combination.values() + ) / reprojection_scale + normal_alignment_cost = sum( + _normal_alignment_rad( + combination[first], combination[second] + ) + for first, second in normal_pair_names + ) / normal_scale + rotation_drifts: list[float] = [] + translation_drifts: list[float] = [] + distance_drifts: list[float] = [] + for pair, ( + reference_rotation, + reference_translation, + ) in reference_pairs.items(): + rotation, translation = _relative_pose( + combination[pair[0]], + combination[pair[1]], + ) + rotation_drifts.append( + float( + (reference_rotation.inv() * rotation).magnitude() + ) + ) + translation_drifts.append( + float( + np.linalg.norm( + translation - reference_translation + ) + ) + ) + current_distance = float( + np.linalg.norm( + np.asarray( + combination[pair[1]].translation_xyz_m, + dtype=float, + ) + - np.asarray( + combination[pair[0]].translation_xyz_m, + dtype=float, + ) + ) + ) + distance_drifts.append( + abs(current_distance - reference_distances[pair]) + ) + if geometry_mode == "distance": + geometry_cost = sum(distance_drifts) / translation_scale + else: + geometry_cost = ( + sum(rotation_drifts) / rotation_scale + + sum(translation_drifts) / translation_scale + ) + return ( + reprojection_cost + geometry_cost + normal_alignment_cost, + max(rotation_drifts, default=0.0), + ( + max(distance_drifts, default=0.0) + if geometry_mode == "distance" + else max(translation_drifts, default=0.0) + ), + ) + + def transition_cost( + previous: Mapping[str, SquareTagPose], + current: Mapping[str, SquareTagPose], + ) -> float: + rotation_motion = sum( + rotation_distance_rad( + previous[role].quaternion_xyzw, + current[role].quaternion_xyzw, + ) + for role in role_names + ) + translation_motion = sum( + float( + np.linalg.norm( + np.asarray(current[role].translation_xyz_m) + - np.asarray(previous[role].translation_xyz_m) + ) + ) + for role in role_names + ) + if geometry_mode == "distance": + return translation_motion / translation_scale + return ( + rotation_motion / rotation_scale + + translation_motion / translation_scale + ) + + for reference_index, reference_combination in enumerate( + combinations_by_frame[0] + ): + reference_pairs = { + pair: _relative_pose( + reference_combination[pair[0]], + reference_combination[pair[1]], + ) + for pair in pair_names + } + reference_distances = { + pair: float( + np.linalg.norm( + np.asarray( + reference_combination[pair[1]].translation_xyz_m, + dtype=float, + ) + - np.asarray( + reference_combination[pair[0]].translation_xyz_m, + dtype=float, + ) + ) + ) + for pair in pair_names + } + first_emission = emission( + reference_combination, + reference_pairs, + reference_distances, + ) + previous_costs = np.full( + len(combinations_by_frame[0]), + np.inf, + dtype=float, + ) + previous_costs[reference_index] = first_emission[0] + back_pointers: list[list[int]] = [] + for frame_index in range(1, len(combinations_by_frame)): + previous_combinations = combinations_by_frame[frame_index - 1] + combinations = combinations_by_frame[frame_index] + frame_emissions = [ + emission( + combination, + reference_pairs, + reference_distances, + ) + for combination in combinations + ] + current_costs = np.full(len(combinations), np.inf, dtype=float) + frame_back_pointers: list[int] = [] + for current_index, combination in enumerate(combinations): + transition_costs = [ + previous_costs[previous_index] + + transition_cost( + previous_combination, + combination, + ) + for previous_index, previous_combination in enumerate( + previous_combinations + ) + ] + best_previous = int(np.argmin(transition_costs)) + frame_back_pointers.append(best_previous) + current_costs[current_index] = ( + transition_costs[best_previous] + + frame_emissions[current_index][0] + ) + back_pointers.append(frame_back_pointers) + previous_costs = current_costs + + final_index = int(np.argmin(previous_costs)) + total = float(previous_costs[final_index]) + path_indices = [final_index] + for frame_back_pointers in reversed(back_pointers): + path_indices.append( + frame_back_pointers[path_indices[-1]] + ) + path_indices.reverse() + path = [ + combinations[index] + for combinations, index in zip( + combinations_by_frame, + path_indices, + ) + ] + if total < best_total: + best_total = total + best_path = path + + if best_path is None: + raise RuntimeError("trajectory branch selection produced no path") + + # The marker-to-marker mounting transforms are unknown, so the rigid + # reference must be estimated from the complete sweep. Using frame zero + # as both the optimisation seed and the reported quality reference made + # one noisy endpoint frame look like drift in every other frame. A + # rotation medoid and component-wise translation median are insensitive + # to that endpoint noise while still exposing a persistent mirror branch. + robust_reference_pairs: dict[ + tuple[str, str], tuple[Rotation, np.ndarray] + ] = {} + for pair in pair_names: + pair_poses = [ + _relative_pose(frame[pair[0]], frame[pair[1]]) + for frame in best_path + ] + pair_rotations = [pose[0] for pose in pair_poses] + angular_costs = np.asarray( + [ + sum( + float((candidate.inv() * other).magnitude()) + for other in pair_rotations + ) + for candidate in pair_rotations + ], + dtype=float, + ) + rotation_medoid = pair_rotations[int(np.argmin(angular_costs))] + translation_median = np.median( + np.asarray([pose[1] for pose in pair_poses], dtype=float), + axis=0, + ) + robust_reference_pairs[pair] = ( + rotation_medoid, + translation_median, + ) + + rotation_drifts_by_frame: list[float] = [] + translation_drifts_by_frame: list[float] = [] + pair_distances_by_pair = { + pair: np.asarray( + [ + np.linalg.norm( + np.asarray(frame[pair[1]].translation_xyz_m, dtype=float) + - np.asarray( + frame[pair[0]].translation_xyz_m, dtype=float + ) + ) + for frame in best_path + ], + dtype=float, + ) + for pair in pair_names + } + robust_pair_distances = { + pair: float(np.median(distances)) + for pair, distances in pair_distances_by_pair.items() + } + distance_drifts_by_frame: list[float] = [] + for frame in best_path: + frame_rotation_drifts: list[float] = [] + frame_translation_drifts: list[float] = [] + frame_distance_drifts: list[float] = [] + for pair, ( + reference_rotation, + reference_translation, + ) in robust_reference_pairs.items(): + rotation, translation = _relative_pose( + frame[pair[0]], frame[pair[1]] + ) + frame_rotation_drifts.append( + float((reference_rotation.inv() * rotation).magnitude()) + ) + frame_translation_drifts.append( + float(np.linalg.norm(translation - reference_translation)) + ) + distance = float( + np.linalg.norm( + np.asarray(frame[pair[1]].translation_xyz_m, dtype=float) + - np.asarray( + frame[pair[0]].translation_xyz_m, dtype=float + ) + ) + ) + frame_distance_drifts.append( + abs(distance - robust_pair_distances[pair]) + ) + rotation_drifts_by_frame.append( + max(frame_rotation_drifts, default=0.0) + ) + translation_drifts_by_frame.append( + max(frame_translation_drifts, default=0.0) + ) + distance_drifts_by_frame.append( + max(frame_distance_drifts, default=0.0) + ) + + rotation_drifts = np.asarray(rotation_drifts_by_frame, dtype=float) + translation_drifts = np.asarray( + translation_drifts_by_frame, dtype=float + ) + distance_drifts = np.asarray(distance_drifts_by_frame, dtype=float) + normal_alignments = np.asarray( + [ + max( + ( + _normal_alignment_rad(frame[first], frame[second]) + for first, second in normal_pair_names + ), + default=0.0, + ) + for frame in best_path + ], + dtype=float, + ) + return best_path, { + "total_cost": float(best_total), + "pair_geometry": geometry_mode, + "maximum_normal_alignment_rad": float( + np.max(normal_alignments, initial=0.0) + ), + "maximum_pair_rotation_drift_rad": float( + np.max(rotation_drifts, initial=0.0) + ), + "p95_pair_rotation_drift_rad": float( + np.percentile(rotation_drifts, 95.0) + ), + "median_pair_rotation_drift_rad": float( + np.median(rotation_drifts) + ), + "maximum_pair_translation_drift_m": float( + np.max(translation_drifts, initial=0.0) + ), + "p95_pair_translation_drift_m": float( + np.percentile(translation_drifts, 95.0) + ), + "maximum_pair_distance_drift_m": float( + np.max(distance_drifts, initial=0.0) + ), + "p95_pair_distance_drift_m": float( + np.percentile(distance_drifts, 95.0) + ), + "median_pair_distance_drift_m": float( + np.median(distance_drifts) + ), + } diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/transition_image_solver.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/transition_image_solver.py new file mode 100644 index 0000000..b1d68cf --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/transition_image_solver.py @@ -0,0 +1,213 @@ +"""Joint image fit of an existing posture transition and the next preparation. + +The two arcs share their physically held endpoint. The earlier measured zero +anchors the first arc; SDK values identify held postures, never camera angles. +The transition is a nuisance motion, not a newly certified calibration joint. +All its images retain a separate, predetermined training/validation partition. +""" + +from dataclasses import dataclass, replace +from itertools import product + +import numpy as np +from scipy.optimize import least_squares +from .image_bundle_optimizer import solve_image_bundle +from scipy.sparse import lil_matrix +from scipy.spatial.transform import Rotation + +from .motion_image_solver import ImageHingeBundle +from .motion_image_types import ImageMotionFrame +from .motion_evidence import MotionRelation +from .motion_image_diagnostics import _sample, _subset, _validate_frames +from .relative import _relative_pose + + +TRANSITION_SELECTION_POLICY = "training_shared_transition_images_holm_v1" + + +@dataclass(frozen=True) +class PreparationTransition: + relation: MotionRelation + frames: tuple[ImageMotionFrame, ...] + endpoints: tuple[int, ...] # -1: moving; 0: earlier zero; 1: shared endpoint + quaternion_xyzw: tuple + translation_xyz_m: tuple + current_zero_stamps: tuple[int, ...] + + +class TransitionImageHingeBundle(ImageHingeBundle): + """Two measured hinges connected at a shared pose, with bounded work.""" + + def __init__(self, frames, relations, poses, transition, transition_poses, limits): + super().__init__(frames, relations, poses) + if len(relations) != 1: + raise ValueError("preparation_transition_requires_single_hinge") + original = self.initial.copy() + self.transition = transition + self.zero_rotation = Rotation.from_quat(transition.quaternion_xyzw) + self.zero_translation = np.asarray(transition.translation_xyz_m) + count = len(transition.frames) + self.aux_training = _sample(list(range(0, count, 2)), limits.maximum_training_frames) + self.aux_validation = _sample(list(range(1, count, 2)), limits.maximum_validation_frames) + self.aux_poses = transition_poses + self.aux = ImageHingeBundle(tuple(transition.frames[i] for i in self.aux_training), + (transition.relation,), _subset(transition_poses, self.aux_training)) + self.endpoints = np.asarray(transition.endpoints)[self.aux_training] + self.free_aux = np.flatnonzero(self.endpoints == -1) + zeros = set(transition.current_zero_stamps) + self.free_main = np.asarray([i for i, frame in enumerate(frames) + if frame.evidence.stamp_ns not in zeros], dtype=int) + parent, child = relations[0].parent_role, relations[0].child_role + ending = [i for i in self.aux_training if transition.endpoints[i] == 1][-1] + end_rotation, _ = _relative_pose(transition_poses[parent][ending], transition_poses[child][ending]) + end_angle = float((end_rotation*self.zero_rotation.inv()).as_rotvec() @ self.aux.axes[0]) + main_angles = [float((_relative_pose(p, c)[0]*end_rotation.inv()).as_rotvec() @ self.axes[0]) + for p, c in zip(poses[parent], poses[child])] + aux_angles = [float((_relative_pose(p, c)[0]*self.zero_rotation.inv()).as_rotvec() @ self.aux.axes[0]) + for p, c in zip(self.aux.poses[parent], self.aux.poses[child])] + self.initial = np.r_[0., 0., original[5:7], 0., 0., self.aux.initial[5:7], end_angle, + np.asarray(main_angles)[self.free_main], np.asarray(aux_angles)[self.free_aux]] + self.scale = np.r_[1., 1., .05, .05, 1., 1., .05, .05, 1., + np.ones(len(self.free_main)+len(self.free_aux))] + + @property + def static_parameter_count(self): + return 9 + + def auxiliary_geometry(self, parameters): + turn = Rotation.from_rotvec(self.aux.bases[0] @ parameters[4:6]) + axis = turn.apply(self.aux.axes[0]) + pivot = turn.apply(self.aux.bases[0] @ parameters[6:8]) + mount = self.zero_rotation.inv().apply(self.zero_translation-pivot) + return axis, pivot, mount + + def geometry_values(self, parameters, index): + axis, pivot, mount = self.auxiliary_geometry(parameters) + reference = Rotation.from_rotvec(axis*parameters[8])*self.zero_rotation + point = pivot+reference.apply(mount) + turn = Rotation.from_rotvec(self.bases[index] @ parameters[:2]) + current_pivot = turn.apply(self.bases[index] @ parameters[2:4]) + return turn.apply(self.axes[index]), reference, current_pivot, reference.inv().apply(point-current_pivot) + + def main_angles(self, parameters): + angles = np.zeros((self.count, 1)) + angles[self.free_main, 0] = parameters[9:9+len(self.free_main)] + return angles + + def auxiliary_pixels(self, parameters, angles, roots, matrices, objects): + axis, pivot, mount = self.auxiliary_geometry(parameters) + relative = Rotation.from_rotvec(np.asarray(angles)[:, None]*axis)*self.zero_rotation + parent_rotation, parent_translation = roots[self.relations[0].parent_role] + rotation = parent_rotation*relative + translation = parent_translation+parent_rotation.apply(pivot+relative.apply(mount)) + points = np.einsum('nij,kj->nki', rotation.as_matrix(), objects[self.child_roles[0]]) + points += translation[:, None, :] + pixels = np.einsum('nij,nkj->nki', matrices, points) + return pixels[:, :, :2]/np.maximum(pixels[:, :, 2:], 1e-6), bool(np.all(points[:, :, 2] > 1e-6)) + + def residual(self, parameters): + pixels, _ = self.project(parameters, self.main_angles(parameters), + self.root_transforms, self.matrices, self.objects) + angles = np.where(self.endpoints == 1, parameters[8], 0.) + angles[self.free_aux] = parameters[9+len(self.free_main):] + auxiliary, _ = self.auxiliary_pixels(parameters, angles, self.aux.root_transforms, + self.aux.matrices, self.aux.objects) + return np.r_[(pixels-self.observed).ravel(), (auxiliary-self.aux.observed[:, 0]).ravel()] + + def solve(self, limits): + sparsity = lil_matrix((8*(self.count+self.aux.count), len(self.initial)), dtype=int) + sparsity[:, :9] = 1 + for column, frame in enumerate(self.free_main): + sparsity[frame*8:(frame+1)*8, 9+column] = 1 + for column, frame in enumerate(self.free_aux): + start = (self.count+frame)*8 + sparsity[start:start+8, 9+len(self.free_main)+column] = 1 + return solve_image_bundle(self.residual, self.initial, sparsity=sparsity.tocsr(), + scale=self.scale, limits=limits) + + def validate(self, parameters, frames, poses, limits): + residuals, valid = super().validate(parameters, frames, poses, limits) + # Shared endpoint identity is a physical constraint, not a free angle. + roots, matrices, observed, objects = self._image_inputs(frames, poses) + zeros = set(self.transition.current_zero_stamps) + for i, frame in enumerate(frames): + if frame.evidence.stamp_ns in zeros: + frame_roots = {role: (r[i:i+1], t[i:i+1]) for role, (r, t) in roots.items()} + pixels, positive = self.project(parameters, np.zeros((1, 1)), frame_roots, + matrices[i:i+1], objects) + residuals[i] = (pixels[0]-observed[i]).reshape(1, 4, 2) + valid = valid and positive + selected = tuple(self.transition.frames[i] for i in self.aux_validation) + aux_poses = _subset(self.aux_poses, self.aux_validation) + roots, matrices, observed, objects = self.aux._image_inputs(selected, aux_poses) + auxiliary = [] + for position, index in enumerate(self.aux_validation): + frame_roots = {role: (r[position:position+1], t[position:position+1]) + for role, (r, t) in roots.items()} + def error(theta): + pixels, _ = self.auxiliary_pixels(parameters, theta, frame_roots, + matrices[position:position+1], objects) + return (pixels[0]-observed[position, 0]).ravel() + mode = self.transition.endpoints[index] + if mode >= 0: + theta = [parameters[8] if mode == 1 else 0.] + else: + relative, _ = _relative_pose(aux_poses[self.relations[0].parent_role][position], + aux_poses[self.child_roles[0]][position]) + axis, _, _ = self.auxiliary_geometry(parameters) + initial = float((relative*self.zero_rotation.inv()).as_rotvec() @ axis) + fit = least_squares(error, [initial], max_nfev=limits.maximum_frame_evaluations, + ftol=1e-9, xtol=1e-9, gtol=1e-7) + theta = fit.x + valid = valid and bool(fit.success) + _, positive = self.auxiliary_pixels(parameters, theta, frame_roots, + matrices[position:position+1], objects) + valid = valid and positive + auxiliary.append(error(theta).reshape(1, 4, 2)) + return np.concatenate((residuals, auxiliary)), valid + + def uncertainty_problem(self, fit): + # As for a shared-zero fit, restore every target geometry freedom. + # Neither the old anchor nor repeated transition images may manufacture + # precise current geometry by removing uncertain variables. + from .hinge_uncertainty import unconstrained_hinge_linearization + return unconstrained_hinge_linearization(self, fit, self.main_angles(fit.x)) + + +def resolve_transition_motion(frames, relations, transition, *, parameters=None): + from .production_image_motion import ImageMotionParameters, _fit_hypothesis, select_image_hypotheses + from .image_motion_model import ImageMotionResolution + limits = parameters or ImageMotionParameters() + try: + paths, roles = _validate_frames(frames, relations, limits) + auxiliary, auxiliary_roles = _validate_frames(transition.frames, (transition.relation,), limits) + if (len(relations) != 1 or roles != auxiliary_roles + or len(transition.frames) != len(transition.endpoints) + or any(value not in {-1, 0, 1} for value in transition.endpoints) + or 0 not in transition.endpoints or transition.endpoints.count(1) < 10 + or not transition.current_zero_stamps + or not set(transition.current_zero_stamps) <= {f.evidence.stamp_ns for f in frames} + or max(f.evidence.stamp_ns for f in transition.frames) >= frames[0].evidence.stamp_ns + or any(f.camera_matrix != frames[0].camera_matrix + or f.reference_frames != frames[0].reference_frames for f in transition.frames)): + raise ValueError("preparation_transition_support_invalid") + training = _sample(list(range(0, len(frames), 2)), limits.maximum_training_frames) + validation = _sample(list(range(1, len(frames), 2)), limits.maximum_validation_frames) + families = np.prod([len(paths[r])*len(auxiliary[r]) for r in roles]) + if families > limits.maximum_hypotheses: + raise ValueError("preparation_transition_hypothesis_limit") + except (ValueError, TypeError, KeyError) as error: + return ImageMotionResolution(False, str(error)) + hypotheses, models, residuals = [], [], [] + for indices in product(*(range(len(paths[r])) for r in roles)): + branches = tuple(zip(roles, indices)) + poses = {role: paths[role][i] for role, i in branches} + for choices in product(*(range(len(auxiliary[r])) for r in roles)): + other = tuple(zip(roles, choices)) + auxiliary_poses = {role: auxiliary[role][i] for role, i in other} + hypothesis, model, errors = _fit_hypothesis(frames, relations, poses, branches, + training, validation, limits, transition=transition, transition_poses=auxiliary_poses) + hypotheses.append(replace(hypothesis, transition_branches=other)) + models.append(model) + residuals.append(errors) + return select_image_hypotheses(frames, validation, hypotheses, models, residuals, limits) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/types.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/types.py new file mode 100644 index 0000000..8eb7a8d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/types.py @@ -0,0 +1,14 @@ +"""Types for shared square Tag pose estimation.""" + +from __future__ import annotations + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class SquareTagPose: + """One tag-to-camera pose candidate returned by IPPE.""" + + quaternion_xyzw: tuple[float, float, float, float] + translation_xyz_m: tuple[float, float, float] + reprojection_error_px: float diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/urdf_command_images.py b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/urdf_command_images.py new file mode 100644 index 0000000..02687df --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/geometry/tag_pose/urdf_command_images.py @@ -0,0 +1,527 @@ +"""Shared image solver with immutable CAD topology and command coordinates. + +One palm pose and one installation per physical role explain every task. +There are no task-local rigid transforms. The original axes also define the +nonparallel thumb. A baseline parameter is estimated, never read from PnP's +first image; only explicitly acknowledged CAD leaf zeros are fixed. +""" +import numpy as np +from scipy.spatial.transform import Rotation + +from .finger_chain_images import FingerChainImages +from .ippe import solve_square_tag_ippe, square_object_points +from .motion_evidence import _axis, RoleCandidates, connect_candidate_families +from ...domain.capture_plan import task_for_joint +from ...domain.motion_path import task_segment +from ...domain.sampling import command_nodes +from ...domain.result import JointMapping +from ...fitting.motion_fit import channel_for_joint, joint_input_direction + + +def rigid(values): + result = np.eye(4) + result[:3, :3] = Rotation.from_rotvec(np.array(values[:3], copy=True)).as_matrix() + result[:3, 3] = values[3:6] + return result + + +def pose_vector(matrix): + return np.r_[Rotation.from_matrix(matrix[:3, :3]).as_rotvec(), matrix[:3, 3]] + + +def skew(vectors): + vectors = np.asarray(vectors) + result = np.zeros((*vectors.shape[:-1], 3, 3)) + result[..., 0, 1], result[..., 0, 2] = -vectors[..., 2], vectors[..., 1] + result[..., 1, 0], result[..., 1, 2] = vectors[..., 2], -vectors[..., 0] + result[..., 2, 0], result[..., 2, 1] = -vectors[..., 1], vectors[..., 0] + return result + + +def right_jacobian(rotvec): + theta = np.linalg.norm(rotvec) + cross = skew(rotvec) + if theta < 1e-5: + return np.eye(3)-cross/2+cross@cross/6 + return np.eye(3)-(1-np.cos(theta))/theta**2*cross+(theta-np.sin(theta))/theta**3*(cross@cross) + + +class UrdfCommandImages(FingerChainImages): + """CAD-constrained specialization of the shared bounded image optimizer.""" + @property + def solver_options(self): + lower, upper = np.full(len(self.scale), -np.inf), np.full(len(self.scale), np.inf) + # The established absolute-zero authorization is a model constraint, + # not a reason to explore physically unauthorized half-turn solutions. + for column in self.zero_columns.values(): + lower[column], upper[column] = -np.radians(20), np.radians(20) + for columns in self.curve_columns.values(): + lower[columns[columns >= 0]] = 0. + return dict(tr_options=dict(atol=1e-10, btol=1e-10), bounds=(lower, upper)) + + def solver_jacobian(self, parameters): + from scipy.sparse import csr_matrix + return csr_matrix(self.jacobian(parameters)) + + def __init__(self, profile, model, extrinsics, rows, tag_links): + self.profile, self.model, self.extrinsics = profile, model, extrinsics + self.rows = tuple(r for r in rows if r.get('sample_phase') == 'steady' + and r.get('accepted_sample_window_open') is True) + if not self.rows or any(r.get('cycle') not in (0, 1) for r in self.rows): + raise ValueError('urdf_images_training_partition_invalid') + self.joints = tuple(sorted(profile.zero.active_joints)) + self.channels = {name: channel_for_joint(profile, name) for name in self.joints} + self.cad_names = {name: profile.command.urdf_joint_by_joint.get(name, name) for name in self.joints} + self.commands = np.asarray([r['command_vector'] for r in self.rows], dtype=float) + if (self.commands.shape != (len(self.rows), profile.command.command_count) + or not np.all(np.isfinite(self.commands))): + raise ValueError('urdf_images_command_shape_invalid') + self.directions = self._directions(self.rows) + self.knots, self.curve_columns, self.zero_columns = {}, {}, {} + scale = [1.]*3 + [.1]*3 + for name in self.joints: + knots = np.asarray(command_nodes(profile, task_for_joint(profile, name))) + self.knots[name] = knots + baseline = profile.command.baseline_values[self.channels[name]] + matches = np.flatnonzero(knots == baseline) + if len(matches) != 1: + raise ValueError('urdf_images_baseline_not_in_training_grid:' + name) + columns = np.full((2, len(knots)), -1, dtype=int) + for direction in range(2): + for index in range(len(knots)): + if index != matches[0]: + columns[direction, index] = len(scale) + scale.append(1.) + self.curve_columns[name] = columns + if name not in profile.zero.cad_zero_assumptions: + self.zero_columns[name] = len(scale) + scale.append(.1) + self.tags = {tag.role: (view.name, tag) for view in profile.vision.views + for tag in view.tags if not tag.fixed_reference} + self.tag_links = {role: tag_links[role] for role in self.tags} + self.mount_columns, self.observations = {}, {} + for role, (view, tag) in self.tags.items(): + indices = [i for i, r in enumerate(self.rows) + if r['view'] == view and role in r.get('tags', {}) + and np.asarray(r['tags'][role].get('corners_xy')).shape == (4, 2)] + if not indices: + raise ValueError('urdf_images_training_tag_missing:' + role) + self.mount_columns[role] = len(scale) + scale.extend([1.]*3 + [.03]*3) + pixels = np.asarray([self.rows[i]['tags'][role]['corners_xy'] for i in indices]) + matrices = np.asarray([self.rows[i]['camera_matrix'] for i in indices]) + if not np.all(np.isfinite(pixels)) or not np.all(np.isfinite(matrices)): + raise ValueError('urdf_images_pixels_or_intrinsics_invalid') + self.observations[role] = (np.asarray(indices), pixels, matrices, square_object_points(tag.size_m)) + self.scale = np.asarray(scale) + self.static_width = len(scale) + self._pnps = {} + self._initialization_costs = {} + self.maximum_joint_evaluations = 200-5*len(self.tags) + self.chains = {role: model._chain(model.parent_joint_by_child[link]) + for role, link in self.tag_links.items()} + from ...fitting.command_support import compile_turnaround_constraints + self.turnaround_constraints = compile_turnaround_constraints(self) + derived = {row['column'] for rows in self.turnaround_constraints.values() for row in rows} + self.optimization_columns = np.asarray([i for i in range(len(scale)) if i not in derived]) + + def _directions(self, rows): + result = [] + for row in rows: + history = row.get('command_direction_by_index') + if (not isinstance(history, (tuple, list)) or len(history) != self.profile.command.command_count + or any(d not in ('', 'increasing', 'decreasing') for d in history)): + raise ValueError('urdf_images_direction_history_missing') + result.append([0 if d == 'increasing' else 1 if d == 'decreasing' else -1 for d in history]) + return np.asarray(result) + + def mappings(self, parameters): + result = {} + for name, columns in self.curve_columns.items(): + values = np.zeros(columns.shape) + mask = columns >= 0 + values[mask] = parameters[columns[mask]] + result[name] = values @ self.curve_basis(name, self.knots[name]).T + for row in self.turnaround_constraints.get(name, ()): + result[name][row['recipient'], row['node']] = result[name][row['donor'], row['node']] + return result + + def curve_weights(self, name, commands, directions): + """Derivative of the constrained curves in the original parameter layout.""" + basis = self.curve_basis(name, commands) + weights = np.stack([basis*np.where(directions == -1, .5, + directions == direction)[:, None] for direction in (0, 1)], axis=1) + for row in self.turnaround_constraints.get(name, ()): + hat = np.zeros(len(self.knots[name])); hat[row['node']] = 1. + weight = np.interp(commands, self.knots[name], hat)*np.where( + directions == -1, .5, directions == row['recipient']) + endpoint = self.curve_basis(name, [row['command']])[0] + weights[:, row['recipient']] -= weight[:, None]*endpoint + weights[:, row['donor']] += weight[:, None]*endpoint + return weights + + def curve_basis(self, name, commands): + """Nonnegative increments enforce the declared native SDK direction.""" + knots = self.knots[name] + baseline = self.profile.command.baseline_values[self.channels[name]] + sign = joint_input_direction(self.profile, self.model, name) + values = np.asarray(commands) + basis = np.zeros((len(values), len(knots))) + for index, knot in enumerate(knots): + if knot < baseline: + basis[:,index] = -sign*np.clip((knots[index+1]-values)/(knots[index+1]-knot), 0, 1) + elif knot > baseline: + basis[:,index] = sign*np.clip((values-knots[index-1])/(knot-knots[index-1]), 0, 1) + return basis + + def set_initial_curve(self, parameters, name, direction, values): + baseline = self.profile.command.baseline_values[self.channels[name]] + sign = joint_input_direction(self.profile, self.model, name) + for index, column in enumerate(self.curve_columns[name][direction]): + if column >= 0: + change = (values[index+1]-values[index] if self.knots[name][index] < baseline + else values[index]-values[index-1]) + parameters[column] = max(1e-8, sign*change) + + def zero_offsets(self, parameters): + return {name: float(parameters[self.zero_columns[name]]) if name in self.zero_columns else 0. + for name in self.joints} + + def joint_angles(self, parameters, commands, directions): + curves, offsets = self.mappings(parameters), self.zero_offsets(parameters) + angles = {} + for name, values in curves.items(): + channel, knots = self.channels[name], self.knots[name] + if np.any(commands[:, channel] < knots[0]) or np.any(commands[:, channel] > knots[-1]): + raise ValueError('urdf_images_command_outside_training_support:' + name) + inc = np.interp(commands[:, channel], knots, values[0]) + dec = np.interp(commands[:, channel], knots, values[1]) + angles[self.cad_names[name]] = offsets[name] + np.where(directions[:, channel] == 0, + inc, np.where(directions[:, channel] == 1, dec, (inc+dec)/2)) + return angles + + def link_poses(self, parameters, commands, directions, angle_corrections=None): + angles = self.joint_angles(parameters, commands, directions) + for name, values in (angle_corrections or {}).items(): + angles[self.cad_names[name]] = angles[self.cad_names[name]] + values + transforms = {self.model.root_link: np.broadcast_to(rigid(parameters[:6]), + (len(commands), 4, 4)).copy()} + for chain in self.chains.values(): + for joint in chain: + if joint.child in transforms: + continue + motion = np.broadcast_to(np.eye(4), (len(commands), 4, 4)).copy() + if joint.kind != 'fixed': + if joint.kind != 'revolute' or joint.name not in angles: + raise ValueError('urdf_images_unsupported_joint:' + joint.name) + motion[:, :3, :3] = Rotation.from_rotvec(angles[joint.name][:, None]*joint.axis).as_matrix() + transforms[joint.child] = transforms[joint.parent] @ joint.origin @ motion + return transforms + + def project_observations(self, parameters, commands, directions, observations, angle_corrections=None): + transforms = self.link_poses(parameters, commands, directions, angle_corrections) + result = {} + for role, (indices, _pixels, matrices, objects) in observations.items(): + column = self.mount_columns[role] + view = self.tags[role][0] + camera = np.linalg.inv(self.extrinsics.transform(view)) @ transforms[self.tag_links[role]][indices] + camera = camera @ rigid(parameters[column:column+6]) + points = np.einsum('nij,kj->nki', camera[:, :3, :3], objects)+camera[:, None, :3, 3] + projected = np.einsum('nij,nkj->nki', matrices, points) + result[role] = (projected[:, :, :2]/np.maximum(points[:, :, 2:], 1e-6) + if np.all(points[:, :, 2] > 1e-6) else np.full((len(indices), 4, 2), 1e6)) + return result + + def residual(self, parameters): + predicted = self.project_observations(parameters, self.commands, self.directions, self.observations) + return np.concatenate([(predicted[role]-data[1]).ravel() + for role, data in self.observations.items()]) + + def jacobian(self, parameters): + """Analytic CAD chain derivatives; no second optimizer or relaxed budget.""" + poses = self.link_poses(parameters, self.commands, self.directions) + total = sum(len(data[0])*8 for data in self.observations.values()) + jac = np.zeros((total, len(parameters))) + palm = rigid(parameters[:6]) + offset = 0 + local_names = {cad: name for name, cad in self.cad_names.items()} + for role, (indices, _pixels, matrices, objects) in self.observations.items(): + count = len(indices) + output_rows = offset+np.arange(count*8).reshape(count, 8) + offset += count*8 + column = self.mount_columns[role] + mount = rigid(parameters[column:column+6]) + link = poses[self.tag_links[role]][indices] + common_from_tag = link @ mount + common_points = np.einsum('nij,kj->nki', common_from_tag[:, :3, :3], objects) + common_points += common_from_tag[:, None, :3, 3] + camera = np.linalg.inv(self.extrinsics.transform(self.tags[role][0])) + points = common_points @ camera[:3, :3].T + camera[:3, 3] + if np.any(points[:, :, 2] <= 1e-6): + continue + projected = np.einsum('nij,nkj->nki', matrices, points) + derivative = (matrices[:, None, :2, :]*projected[:, :, None, 2:] + -projected[:, :, :2, None]*matrices[:, None, 2:3, :])/projected[:, :, None, 2:]**2 + camera_derivative = derivative @ camera[:3, :3] + base_points = (common_points-palm[:3, 3]) @ palm[:3, :3] + d_rotation = -palm[:3, :3] @ skew(base_points) @ right_jacobian(parameters[:3]) + jac[output_rows.ravel(), :3] = (camera_derivative @ d_rotation).reshape(-1, 3) + jac[output_rows.ravel(), 3:6] = camera_derivative.reshape(-1, 3) + d_mount = -common_from_tag[:, None, :3, :3] @ skew(objects)[None] @ right_jacobian(parameters[column:column+3]) + jac[output_rows.ravel(), column:column+3] = (camera_derivative @ d_mount).reshape(-1, 3) + jac[output_rows.ravel(), column+3:column+6] = (camera_derivative @ link[:, None, :3, :3]).reshape(-1, 3) + for joint in self.chains[role]: + if joint.kind == 'fixed': + continue + name = local_names[joint.name] + frame = poses[joint.parent][indices] @ joint.origin + axis = frame[:, :3, :3] @ joint.axis + velocity = np.cross(axis[:, None, :], common_points-frame[:, None, :3, 3]) + pixel_velocity = np.einsum('nkij,nkj->nki', camera_derivative, velocity).reshape(count, 8) + if name in self.zero_columns: + jac[output_rows, self.zero_columns[name]] = pixel_velocity + channel = self.channels[name] + weights = self.curve_weights(name, self.commands[indices, channel], + self.directions[indices, channel]) + for direction in range(2): + for node, column in enumerate(self.curve_columns[name][direction]): + if column >= 0: + jac[output_rows, column] += pixel_velocity*weights[:,direction,node,None] + return jac + + def _pose_candidates(self, index, role): + key = index, role + if key not in self._pnps: + row, tag = self.rows[index], self.tags[role][1] + self._pnps[key] = tuple(p for p in solve_square_tag_ippe(row['tags'][role]['corners_xy'], + tag_size_m=tag.size_m, camera_matrix=row['camera_matrix']) if p.reprojection_error_px <= 1.5) + candidates = self._pnps[key] + if not candidates: + raise ValueError('urdf_images_initialization_candidates_missing:' + role) + return candidates + + def _pose_matrix(self, role, pose): + camera = np.eye(4) + camera[:3, :3] = Rotation.from_quat(pose.quaternion_xyzw).as_matrix() + camera[:3, 3] = pose.translation_xyz_m + return self.extrinsics.transform(self.tags[role][0]) @ camera + + def _pose(self, index, role, branch): + candidates = self._pose_candidates(index, role) + return self._pose_matrix(role, candidates[min(branch, len(candidates)-1)]) + + def motion_indices(self, name, direction, cycle): + """Scan membership includes its start, regardless of incoming history. + + Actual per-channel history remains the forward model's hysteresis + input. Constant channels in another joint's support segment are omitted. + """ + task = task_for_joint(self.profile, name) + spec = self.profile.measurement.measurements[name] + channel = self.channels[name] + indices = [] + for i, row in enumerate(self.rows): + if (row['task_name'] != task.key or row['view'] != spec.view + or row['cycle'] != cycle or spec.child_role not in row.get('tags', {})): + continue + if task.segments: + segment = task_segment(task, row.get('segment_key', '')) + if name not in segment.joints or channel not in segment.moving_channels: + continue + increasing = dict(segment.end_commands)[channel] > dict(segment.start_commands)[channel] + else: + increasing = row['direction'] == 'increasing' + if int(not increasing) == direction: + indices.append(i) + return sorted(indices, key=lambda i: self.commands[i, channel]) + + def motion_poses(self, indices, role, branch): + items = [RoleCandidates(role, self._pose_candidates(i, role)) for i in indices] + families, _ = connect_candidate_families(items, strict=False) + # A single available family is one seed, not evidence of a second one. + family = families[min(branch, len(families)-1)] + observed = [(i, pose) for i, pose in zip(indices, family) if pose is not None] + if len(observed) < 3: + raise ValueError('urdf_images_motion_family_incomplete:' + role) + return [i for i, _ in observed], np.asarray([self._pose_matrix(role, p) for _, p in observed]) + + def initialize(self, branches): + if len(branches) != 6 or any(b not in (0, 1) for b in branches): + raise ValueError('urdf_images_seed_invalid') + initial = np.zeros(len(self.scale)) + for name, columns in self.curve_columns.items(): + joint = self.model.joints[self.cad_names[name]] + span = (joint.upper-joint.lower) if joint.lower is not None else 1. + baseline = self.profile.command.baseline_values[self.channels[name]] + values = (self.knots[name]-baseline)/np.ptp(self.knots[name])*span*joint_input_direction( + self.profile, self.model, name) + for direction in range(2): + self.set_initial_curve(initial, name, direction, values) + # Training motion supplies the initial curves. CAD angular limits are + # not measurements of servo travel and must not initialize it as truth. + motion_lines = {} + for name in self.joints: + task = task_for_joint(self.profile, name) + spec = self.profile.measurement.measurements[name] + channel = self.channels[name] + for direction in range(2): + indices = self.motion_indices(name, direction, 0) + if len(indices) < 3: + raise ValueError('urdf_images_directional_training_missing:' + name) + # A common motion-curve guess is only a numerical initializer. + # Each candidate retains its own installation seeds below; + # no PnP branch or zero is frozen by this starting guess. + indices, poses = self.motion_poses(indices, spec.child_role, 0) + rotations = Rotation.from_matrix(poses[:, :3, :3]) + axis, phase = _axis(rotations) + sign = joint_input_direction(self.profile, self.model, name) + if (phase[-1]-phase[0])*sign < 0: + axis, phase = -axis, -phase + commands = self.commands[indices, channel] + baseline = self.profile.command.baseline_values[channel] + phase = phase-np.interp(baseline, commands, phase) + self.set_initial_curve(initial, name, direction, np.interp(self.knots[name], commands, phase)) + if direction == 0: + turns = poses[:, :3, :3] @ poses[0, :3, :3].T + blocks = np.eye(3)-turns + target = poses[:, :3, 3]-np.einsum('nij,j->ni', turns, poses[0, :3, 3]) + point = np.linalg.lstsq(blocks.reshape(-1, 3), target.ravel(), rcond=1e-6)[0] + motion_lines[name] = (axis, point, indices[0]) + roots = [name for name in self.joints if not any(j.name in self.cad_names.values() + for j in self.model._chain(self.cad_names[name])[:-1])] + if len(roots) != 5: + raise ValueError('urdf_images_requires_five_hand_roots') + cad_axes, observed_axes, cad_points, observed_points = [], [], [], [] + for root, branch in zip(roots, branches): + task = task_for_joint(self.profile, root) + spec = self.profile.measurement.measurements[root] + role = spec.child_role + indices = self.motion_indices(root, 0, 0) + if len(indices) < 3: + raise ValueError('urdf_images_root_observations_missing:' + root) + indices, poses = self.motion_poses(indices, role, branch) + rotations = Rotation.from_matrix(poses[:, :3, :3]) + axis, _ = _axis(rotations) + progression = (rotations[-1]*rotations[0].inv()).as_rotvec() @ axis + if progression*joint_input_direction(self.profile, self.model, root) < 0: + axis = -axis + turns = poses[:, :3, :3] @ poses[0, :3, :3].T + blocks = np.eye(3)-turns + target = poses[:, :3, 3]-np.einsum('nij,j->ni', turns, poses[0, :3, 3]) + point = np.linalg.lstsq(blocks.reshape(-1, 3), target.ravel(), rcond=1e-6)[0] + cad_axis, cad_point = self.model.axis_line(self.cad_names[root], zero_offsets={}, joint_angles={}) + cad_axes.append(cad_axis); cad_points.append(cad_point) + observed_axes.append(axis); observed_points.append(point) + # Five parallel root directions do not observe palm roll. Their named + # transverse line pattern does; never let numerical axis noise supply + # an enormous fictitious translation along the common direction. + cad_axes, observed_axes = np.asarray(cad_axes), np.asarray(observed_axes) + cad_points, observed_points = np.asarray(cad_points), np.asarray(observed_points) + cad_mean = np.mean(cad_axes, axis=0); cad_mean /= np.linalg.norm(cad_mean) + observed_mean = np.mean(observed_axes, axis=0); observed_mean /= np.linalg.norm(observed_mean) + cad_pattern = (cad_points-np.mean(cad_points, axis=0)) @ (np.eye(3)-np.outer(cad_mean, cad_mean)) + observed_pattern = (observed_points-np.mean(observed_points, axis=0)) @ (np.eye(3)-np.outer(observed_mean, observed_mean)) + pattern_scale = np.max(np.linalg.norm(cad_pattern, axis=1)) + if pattern_scale < .003: + raise ValueError('urdf_images_root_line_pattern_degenerate') + rotation, _ = Rotation.align_vectors(np.vstack((observed_axes, observed_pattern/pattern_scale)), + np.vstack((cad_axes, cad_pattern/pattern_scale))) + blocks = np.asarray([np.eye(3)-np.outer(a, a) for a in observed_axes]) + target = np.einsum('nij,nj->ni', blocks, + np.asarray(observed_points)-rotation.apply(cad_points)) + initial[:3] = rotation.as_rotvec() + initial[3:6] = np.linalg.lstsq(blocks.reshape(-1, 3), target.ravel(), rcond=1e-6)[0] + # Child axes supply the translation component unobservable from the + # parallel roots alone. This is initialization, not a frozen datum. + angle_values = self.joint_angles(initial, self.commands, self.directions) + # The nonparallel child axes also stabilize rotation. Aligning only + # noisy, almost parallel root axes can put a valid IPPE seed outside + # the joint optimizer's basin. Use every observed hinge in this same + # training graph; the final image solve still estimates all zeros. + cad_directions, measured_directions = [], [] + for name, (axis, _point, index) in motion_lines.items(): + cad_axis, _ = self.model.axis_line(self.cad_names[name], zero_offsets={}, + joint_angles={joint: values[index] for joint, values in angle_values.items()}, + independent_mimic_angles=True) + cad_directions.append(cad_axis); measured_directions.append(axis) + cad_directions, measured_directions = np.asarray(cad_directions), np.asarray(measured_directions) + for _ in range(3): + errors = np.linalg.norm(rotation.apply(cad_directions)-measured_directions, axis=1) + weights = 1/np.sqrt(1+(errors/(2*np.sin(np.radians(3)/2)))**2) + rotation, _ = Rotation.align_vectors(measured_directions, cad_directions, weights=weights) + initial[:3] = rotation.as_rotvec() + blocks, targets = [], [] + for name, (axis, point, index) in motion_lines.items(): + _, cad_point = self.model.axis_line(self.cad_names[name], zero_offsets={}, + joint_angles={joint: values[index] for joint, values in angle_values.items()}, + independent_mimic_angles=True) + block = np.eye(3)-np.outer(axis, axis) + blocks.append(block); targets.append(block @ (point-rotation.apply(cad_point))) + initial[3:6] = np.linalg.lstsq(np.asarray(blocks).reshape(-1, 3), + np.asarray(targets).ravel(), rcond=1e-6)[0] + transforms = self.link_poses(initial, self.commands, self.directions) + root_branches = {self.profile.measurement.measurements[name].child_role: branch + for name, branch in zip(roots, branches)} + for role, column in self.mount_columns.items(): + index = self.observations[role][0][0] + mount = np.linalg.inv(transforms[self.tag_links[role]][index]) @ self._pose(index, role, + root_branches.get(role, branches[5])) + initial[column:column+6] = pose_vector(mount) + self._initialization_costs[tuple(branches)] = self._refine_mount_guesses(initial, transforms) + return initial + + def _refine_mount_guesses(self, initial, transforms, *, observations=None): + """Bounded block initialization on the SAME training image objective. + + Five evaluations per installation plus the remaining joint evaluations + total at most 200. No mount is frozen and no candidate is selected here. + """ + from scipy.optimize import least_squares + evaluations = 0 + observations = self.observations if observations is None else observations + for role, column in self.mount_columns.items(): + indices, observed, matrices, objects = observations[role] + camera = np.linalg.inv(self.extrinsics.transform(self.tags[role][0])) @ transforms[self.tag_links[role]][indices] + def project(values): + mount = rigid(values) + local = objects @ mount[:3,:3].T + mount[:3,3] + points = np.einsum('nij,kj->nki', camera[:,:3,:3], local)+camera[:,None,:3,3] + homogeneous = np.einsum('nij,nkj->nki', matrices, points) + return points, homogeneous + def residual(values): + points, pixels = project(values) + if np.any(points[:,:,2] <= 1e-6): + return np.full(observed.size, 1e6) + return (pixels[:,:,:2]/pixels[:,:,2:]-observed).ravel() + def jacobian(values): + points, pixels = project(values) + if np.any(points[:,:,2] <= 1e-6): + return np.zeros((observed.size,6)) + derivative = (matrices[:,None,:2,:]*pixels[:,:,None,2:] + -pixels[:,:,:2,None]*matrices[:,None,2:3,:])/pixels[:,:,None,2:]**2 + camera_derivative = derivative @ camera[:,None,:3,:3] + rotation = -rigid(values)[:3,:3] @ skew(objects) @ right_jacobian(values[:3]) + return np.concatenate((camera_derivative @ rotation[None], camera_derivative), axis=-1).reshape(-1,6) + fit = least_squares(residual, initial[column:column+6], jac=jacobian, + x_scale=[1.,1.,1.,.03,.03,.03], max_nfev=5, ftol=1e-9, xtol=1e-9, gtol=1e-7) + initial[column:column+6] = fit.x + evaluations += fit.nfev + return evaluations + + def covariance(self, fit): + active = self.optimization_columns + jac = (fit.jac.toarray() if hasattr(fit.jac, 'toarray') else np.asarray(fit.jac))[:, active]*self.scale[active] + information = jac.T @ jac + eigen = np.linalg.eigvalsh(information) + if len(fit.fun) <= len(active) or eigen[0] <= eigen[-1]*np.finfo(float).eps*len(active): + raise ValueError('urdf_images_geometry_rank_deficient') + variance = max(.03**2, float(fit.fun @ fit.fun/(len(fit.fun)-len(active)))) + covariance = np.zeros((len(self.scale), len(self.scale))) + covariance[np.ix_(active, active)] = (np.linalg.inv(information)*variance + *self.scale[active, None]*self.scale[None, active]) + return covariance + + def output_mappings(self, parameters): + return {name: JointMapping(name, self.channels[name], 'command_u8', tuple(self.knots[name]), + tuple(np.mean(values, axis=0)), tuple(values[0]), tuple(values[1])) + for name, values in self.mappings(parameters).items()} diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/__init__.py new file mode 100644 index 0000000..6766385 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/__init__.py @@ -0,0 +1,41 @@ +"""URDF correction authorization and validation types.""" + +from .plan import ( + StandardUrdfPlan, UrdfCorrectionPlan, build_correction_plan, + build_standard_correction_plan, +) +from .validate import ( + URDF_FIELD_TO_XML, + validate_runtime_curve_limits, + validate_structural_urdf_diff, +) +from .patch import ( + MujocoEqualityPatch, + UrdfJointPatch, + UrdfPatchSet, + apply_urdf_patch_text, + corrected_origin_rpy, + materialize_relative_mesh_assets, + parse_vector3, + validate_urdf_mimic_ranges, + write_urdf_patches, +) + +__all__ = [ + "MujocoEqualityPatch", + "UrdfCorrectionPlan", + "StandardUrdfPlan", + "UrdfJointPatch", + "UrdfPatchSet", + "URDF_FIELD_TO_XML", + "apply_urdf_patch_text", + "build_correction_plan", + "build_standard_correction_plan", + "corrected_origin_rpy", + "materialize_relative_mesh_assets", + "parse_vector3", + "validate_urdf_mimic_ranges", + "validate_runtime_curve_limits", + "validate_structural_urdf_diff", + "write_urdf_patches", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/acceptance.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/acceptance.py new file mode 100644 index 0000000..097e652 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/acceptance.py @@ -0,0 +1,405 @@ +"""Acceptance of serialized standard-URDF motion, not a substitute JSON model.""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import math +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + +from .kinematics import UrdfKinematicModel +from .patch import validate_urdf_mimic_ranges +from .validate import validate_runtime_curve_limits, validate_structural_urdf_diff + + +ANGLE_MAE_LIMIT_DEG = 1.0 +ANGLE_P95_LIMIT_DEG = 2.0 +ANGLE_MAXIMUM_LIMIT_DEG = 3.0 + + +@dataclass(frozen=True) +class JointHoldout: + """Independent observation in the corrected coordinate convention. + + Inputs retain their recorded SDK domain. No validation-time tag mounting, + zero, branch selection, curve fit or base registration is permitted. + """ + + sample_id: str + joint: str + sdk_values: tuple[float, ...] + observed_rad: float + direction: str + cycle: int = 3 + # Optional independent child-link pose in the *training-locked* base frame. + base_from_link: tuple[tuple[float, ...], ...] | None = None + # An active scan direction must not be assigned to every held axis. + sdk_directions_by_joint: Mapping[str, str] | None = None + + +@dataclass(frozen=True) +class ErrorMetrics: + count: int + mae_deg: float + p95_deg: float + maximum_deg: float + + @property + def passed(self) -> bool: + return (self.count > 0 and self.mae_deg <= ANGLE_MAE_LIMIT_DEG + and self.p95_deg <= ANGLE_P95_LIMIT_DEG + and self.maximum_deg <= ANGLE_MAXIMUM_LIMIT_DEG) + + +def angular_metrics(errors_rad: Sequence[float]) -> ErrorMetrics: + errors = np.abs(np.asarray(errors_rad, dtype=float)) + if errors.ndim != 1 or not errors.size or not np.all(np.isfinite(errors)): + raise ValueError("angular validation requires finite independent errors") + degrees = np.rad2deg(errors) + return ErrorMetrics(len(errors), float(np.mean(degrees)), float(np.percentile(degrees, 95)), float(np.max(degrees))) + + +class SerializedJointMapping: + """Read the numeric legacy v4/v6/v7 curve shapes without model imports. + + Legacy byte tables and byte commands retain nearest-integer lookup. + Unified feedback uses its declared piecewise-linear knots, including + feedback interpolated to image time. Neither path silently clamps inputs. + """ + + def __init__(self, payload: Mapping[str, Any], *, input_kind=None) -> None: + self.payload = payload + from .partial_scope import retained_from_payload + self.retained_joints = retained_from_payload(payload) + self.measured = payload.get("format") in {"unified_calibration_v3", "unified_calibration_report_v3"} + self.compact = payload.get("format") in {"unified_calibration_v2", "unified_calibration_v3"} + command_report = (payload.get("format") == "unified_calibration_report_v3" + and payload.get("quality", {}).get("release_basis") == "steady_command") + input_kind = input_kind or ("command" if self.compact or command_report else "feedback") + declared_directions = payload.get("directional_command_joints", []) + if (not isinstance(declared_directions, list) or any(not isinstance(n, str) for n in declared_directions) + or len(set(declared_directions)) != len(declared_directions) + or not set(declared_directions) <= payload.get("joints", {}).keys() + or declared_directions and not self.measured): + raise ValueError("invalid directional command declaration") + self.directional_joints = frozenset(declared_directions) if input_kind == "command" else frozenset() + self.baseline = payload.get("baseline_command", ()) + self.unified = payload.get("format") in {"unified_calibration_v1", "unified_calibration_report_v3"} + if self.compact: + if input_kind != "command" or payload.get("schema_version") != (3 if self.measured else 2): + raise ValueError("compact JSON is command-only; feedback mapping belongs to the report") + unit = payload.get("input_unit") + if unit not in {"rad", "u8"}: + raise ValueError("invalid compact input unit") + joints = {} + for name, row in payload.get("joints", {}).items(): + expected = {"sdk_channel", "angle_rad"} | ({"input_values"} if unit == "rad" else set()) + if name in self.directional_joints: + expected |= {"increasing_rad", "decreasing_rad"} + index = row.get("sdk_channel") + if set(row) != expected or type(index) is not int or index < 0: + raise ValueError(f"invalid compact joint/channel fields:{name}") + joints[name] = {"motor_index": index, "angle_rad": row["angle_rad"], + "curve_input_knots_rad": row.get("input_values", ())} + if name in self.directional_joints: + joints[name].update({key: row[key] for key in ("increasing_rad", "decreasing_rad")}) + payload = {"joints": joints, "curve_input_domain": f"command_{unit}"} + elif self.unified: + if input_kind not in {"command", "feedback"} or payload.get("schema_version") != (3 if self.measured else 1): + raise ValueError("unsupported unified mapping kind/version") + joints = {} + unit = payload["command_unit"] + count = len(payload["command_names"]) + if unit not in {"rad", "u8"} or count == 0: + raise ValueError("invalid unified SDK layout") + for name, row in payload["joints"].items(): + if row.get("urdf_joint") != name: + raise ValueError("unified keys must be original URDF joint names") + if row.get("passive") and not self.measured: + if "command_to_rad" in row or "feedback_to_rad" in row: + raise ValueError("passive runtime curves cannot bypass standard URDF mimic") + continue + data = row[f"{input_kind}_to_rad"] + if (data["input_domain"] != f"{input_kind}_{unit}" or data["input_unit"] != unit + or data["output_unit"] != "rad" or data["interpolation"] != "piecewise_linear" + or data["extrapolation"] != "reject" or not 0 <= data["channel_index"] < count + or data["valid_input_range"] != [data["knots"][0], data["knots"][-1]]): + raise ValueError("unified mapping coordinate contract changed") + joints[name] = {**data, "motor_index": data["channel_index"], + "curve_input_knots_rad": data["knots"], "urdf_joint": name} + payload = {**payload, "joints": joints, "curve_input_domain": f"{input_kind}_{unit}"} + self.domain = str(payload.get("curve_input_domain", "command_u8" if payload.get("schema_version") == 4 else "")) + if self.domain not in {"command_u8", "feedback_u8", "feedback_rad", "command_rad"}: + raise ValueError("serialized SDK input domain is missing or unsupported") + self.joints: dict[str, Mapping[str, Any]] = {} + for name, row in payload.get("joints", {}).items(): + target = str(row.get("urdf_joint", name)) + if target in self.joints: + raise ValueError(f"duplicate serialized joint: {target}") + self.joints[target] = row + if int(row["motor_index"]) < 0: + raise ValueError("negative serialized motor index") + for branch in ("angle_rad", "increasing_rad", "decreasing_rad"): + values = np.asarray(row.get(branch, row["angle_rad"]), dtype=float) + if values.ndim != 1 or len(values) < 2 or not np.all(np.isfinite(values)): + raise ValueError(f"invalid serialized curve: {target}:{branch}") + differences = np.diff(values) + if not (np.all(differences >= -1e-9) or np.all(differences <= 1e-9)): + raise ValueError(f"serialized curve is not monotonic: {target}:{branch}") + if self.domain.endswith("_u8") and not self.unified: + if len(values) != 256: + raise ValueError("byte mapping requires 256 entries") + else: + knots = np.asarray(row.get("curve_input_knots_rad", ()), dtype=float) + if knots.shape != values.shape or not np.all(np.isfinite(knots)) or np.any(np.diff(knots) <= 0): + raise ValueError(f"continuous curve requires strictly ordered finite knots: {target}") + if not self.joints: + raise ValueError("serialized calibration has no joint mappings") + + def evaluate(self, sdk_values: Sequence[float], direction: str, *, active_joints: Sequence[str], directions_by_joint: Mapping[str, str] | None = None) -> dict[str, float]: + if direction not in {"increasing", "decreasing", ""}: + raise ValueError("invalid recorded SDK direction") + output: dict[str, float] = {} + for name in active_joints: + row = self.joints.get(name) + if row is None: + raise ValueError(f"serialized mapping is missing active joint: {name}") + index = int(row["motor_index"]) + if index >= len(sdk_values): + raise ValueError("holdout SDK vector has missing channels") + value = float(sdk_values[index]) + if not math.isfinite(value): + raise ValueError("holdout SDK input is nonfinite") + selected = direction if directions_by_joint is None else directions_by_joint.get(name, "") + if selected not in {"increasing", "decreasing", ""}: + raise ValueError("invalid per-joint SDK direction") + if name in self.directional_joints and not selected: + if index >= len(self.baseline) or value != self.baseline[index]: + raise ValueError(f"directional_command_requires_direction:{name}") + if self.domain.endswith("_rad") and selected: + increasing_branch = str(row.get("raw_increasing_curve_branch", "increasing")) + if increasing_branch not in {"increasing", "decreasing"}: + raise ValueError("invalid serialized direction convention") + selected = increasing_branch if selected == "increasing" else ("decreasing" if increasing_branch == "increasing" else "increasing") + values = row.get(f"{selected}_rad", row["angle_rad"]) if selected else row["angle_rad"] + if self.domain.endswith("_u8") and not self.unified: + if not 0 <= value <= 255: + raise ValueError("holdout input is outside serialized byte domain") + angle = float(values[int(math.floor(value + 0.5))]) + else: + knots = row["curve_input_knots_rad"] + if not knots[0] <= value <= knots[-1]: + raise ValueError(f"holdout input is outside serialized knot domain: {name}") + if self.domain == "command_u8": + value = float(math.floor(value+0.5)) + angle = float(np.interp(value, knots, values)) + output[name] = angle + return output + + +def validate_standard_urdf_holdout( + *, corrected_urdf: str | Path, payload: Mapping[str, Any], + observations: Sequence[JointHoldout], required_joints: Sequence[str], + required_pose_joints: Sequence[str] = (), holdout_cycle: int = 3, + minimum_samples: int = 40, +) -> dict[str, ErrorMetrics]: + """Resolve passive joints exclusively from the written URDF and validate. + + A perfect nonlinear passive JSON curve cannot make a wrong linear URDF + pass. Missing observations, duplicate-only samples and training rows fail. + """ + model = UrdfKinematicModel(corrected_urdf) + mapping = SerializedJointMapping(payload) + required = frozenset(required_joints) + pose_required = frozenset(required_pose_joints) + if not required or not pose_required <= required or not required <= model.joints.keys(): + raise ValueError("holdout requires declared, existing measured joints") + if minimum_samples < 1: + raise ValueError("minimum holdout samples must be positive") + active = tuple(name for name, joint in model.joints.items() if joint.kind != "fixed" and joint.mimic_joint is None) + errors: dict[str, list[float]] = {name: [] for name in required} + pose_errors: dict[str, list[tuple[float, float]]] = {name: [] for name in pose_required} + seen: set[tuple[str, str]] = set() + for row in observations: + if row.cycle != holdout_cycle: + raise ValueError("training data cannot enter serialized URDF holdout") + if row.joint not in required: + continue + identity = (row.joint, row.sample_id) + if not row.sample_id or identity in seen: + raise ValueError("holdout sample identity is empty or duplicated") + seen.add(identity) + if not math.isfinite(row.observed_rad): + raise ValueError("nonfinite holdout observation") + angles = mapping.evaluate(row.sdk_values, row.direction, active_joints=active, + directions_by_joint=row.sdk_directions_by_joint) + resolved = model.resolve_angles(angles) + for name, angle in resolved.items(): + joint = model.joints[name] + if joint.lower is not None and not joint.lower - 1e-9 <= angle <= joint.upper + 1e-9: + raise ValueError(f"serialized URDF motion exceeds joint limit: {name}") + errors[row.joint].append(resolved[row.joint] - row.observed_rad) + if row.joint in pose_required: + observed = np.asarray(row.base_from_link, dtype=float) + if observed.shape != (4, 4) or not np.all(np.isfinite(observed)): + raise ValueError(f"missing independent locked-base pose: {row.joint}") + rotation = observed[:3, :3] + if not np.allclose(observed[3], (0, 0, 0, 1), atol=1e-9) or not np.allclose(rotation.T @ rotation, np.eye(3), atol=1e-6) or not np.isclose(np.linalg.det(rotation), 1, atol=1e-6): + raise ValueError("holdout pose is not a rigid transform") + predicted = model.link_transform(row.joint, zero_offsets={}, joint_angles=angles) + angular = float(Rotation.from_matrix(predicted[:3, :3].T @ rotation).magnitude()) + translation = float(np.linalg.norm(predicted[:3, 3] - observed[:3, 3])) + pose_errors[row.joint].append((angular, translation)) + result: dict[str, ErrorMetrics] = {} + for name, values in errors.items(): + if len(values) < minimum_samples: + raise ValueError(f"missing independent URDF holdout samples: {name}:{len(values)}") + metrics = angular_metrics(values) + if not metrics.passed: + code = "standard_urdf_mimic_not_accurate" if model.joints[name].mimic_joint else "serialized_active_mapping_not_accurate" + raise ValueError(f"{code}:{name}:mae={metrics.mae_deg:.6f}:p95={metrics.p95_deg:.6f}:max={metrics.maximum_deg:.6f}") + result[name] = metrics + for name, values in pose_errors.items(): + metrics = angular_metrics([value[0] for value in values]) + # Existing independent combination-pose acceptance: 3 mm P95 / 2 deg P95. + if not metrics.passed or float(np.percentile([value[1] for value in values], 95)) > 0.003: + raise ValueError(f"serialized_urdf_spatial_holdout_failed:{name}") + return result + + +def validate_artifact_structure(*, source_urdf: str | Path, corrected_urdf: str | Path, + source_sha256: str, authorized_fields: Mapping[str, Sequence[str]], + payload: Mapping[str, Any], zero_offsets_rad: Mapping[str, float], + range_evidence=None) -> tuple[str, ...]: + """Validate source/safety bounds or exact trusted training motion ranges.""" + if len(source_sha256) != 64 or hashlib.sha256(Path(source_urdf).read_bytes()).hexdigest() != source_sha256: + raise ValueError("protected source URDF SHA256 mismatch") + before, after = UrdfKinematicModel(source_urdf), UrdfKinematicModel(corrected_urdf) + from .joint_control import independent_joint_sources, independent_export_authorization, validate_independent_output, uses_source_mimic + mapping = SerializedJointMapping(payload) + sources = independent_joint_sources(payload) + if sources is not None: + channels = {name: row["motor_index"] for name, row in mapping.joints.items()} + authorized_fields = independent_export_authorization(before, channels, sources, authorized_fields) + validate_independent_output(after, channels, sources) + changes = validate_structural_urdf_diff(source_urdf, corrected_urdf, + authorized_fields=authorized_fields, expected_source_sha256=source_sha256) + from .limits import validate_range_evidence + motion_ranges = dict(range_evidence or {}) + if not set(motion_ranges) <= before.joints.keys(): + raise ValueError("range evidence references unknown joints") + if not set(zero_offsets_rad) <= before.joints.keys(): + raise ValueError("declared coordinate zero targets missing joints") + envelopes = {} + if uses_source_mimic(payload): + from .source_mimic import compile_source_mimic_envelopes, validate_source_mimic_elements, validate_serialized_mimic_envelopes + validate_source_mimic_elements(source_urdf, corrected_urdf) + envelopes = compile_source_mimic_envelopes(before, + {name: (j.lower, j.upper) for name, j in after.joints.items() if j.lower is not None}, + zero_offsets_rad, motion_ranges) + validate_serialized_mimic_envelopes(payload, after) + from dataclasses import asdict + for name, envelope in envelopes.items(): + declared = payload["urdf_correction"]["mimic_envelopes"][name] + if any(not np.allclose(values, declared[key], atol=1e-10, rtol=0) + for key, values in asdict(envelope).items()): + raise ValueError(f"source_mimic_envelope_differs_from_trusted_ranges:{name}") + # No model bypass, no inherited-CAD excess allowance at final acceptance. + validate_urdf_mimic_ranges(corrected_urdf) + for name, joint in after.joints.items(): + original = before.joints[name] + delta = float(zero_offsets_rad.get(name, 0.0)) + if not math.isfinite(delta): + raise ValueError("nonfinite coordinate zero") + if joint.lower is not None and original.lower is not None: + if name in motion_ranges: + interval = envelopes[name].base_limits_rad if name in envelopes else (joint.lower, joint.upper) + validate_range_evidence(name, original, delta, interval, motion_ranges[name]) + elif joint.lower + delta < original.lower - 1e-8 or joint.upper + delta > original.upper + 1e-8: + raise ValueError(f"corrected range exceeds source mechanical range: {name}") + expected = original.origin @ before._motion(original, delta) + if not np.allclose(expected, joint.origin, atol=1e-8, rtol=0): + raise ValueError(f"URDF origin does not match declared coordinate zero: {name}") + if mapping.compact: + validate_compact_urdf_tables(payload, after) + for branch in ("angle_rad", "increasing_rad", "decreasing_rad"): + validate_runtime_curve_limits(corrected_urdf, + {name: row.get(branch, row["angle_rad"]) for name, row in mapping.joints.items()}) + if payload.get("format") in {"unified_calibration_v1", "unified_calibration_report_v3"}: + commands = SerializedJointMapping(payload, input_kind="command") + for branch in ("angle_rad", "increasing_rad", "decreasing_rad"): + validate_runtime_curve_limits(corrected_urdf, + {name: row[branch] for name, row in commands.joints.items()}) + for name, row in payload["joints"].items(): + if sources is not None: + if row.get("passive") != (name in sources): + raise ValueError(f"passive_provenance_differs_from_source_urdf:{name}") + if name in sources and (row.get("mimic_approximation", {}).get("joint") != sources[name] + or row["mimic_approximation"].get("usage") != "diagnostic_only_not_exported"): + raise ValueError(f"diagnostic_mimic_source_differs:{name}") + continue + if row.get("passive"): + joint = after.joints[name] + expected = {"joint": joint.mimic_joint, "multiplier": joint.mimic_multiplier, + "offset_rad": joint.mimic_offset} + actual = row.get("mimic_approximation" if mapping.measured else "mimic", {}) + if (actual.get("joint") != expected["joint"] or any(not math.isclose( + float(actual.get(field, float("nan"))), expected[field], abs_tol=1e-8, rel_tol=0) + for field in ("multiplier", "offset_rad"))): + raise ValueError(f"JSON mimic differs from exported URDF:{name}") + return changes + + +def validate_compact_urdf_tables(payload, model): + """Validate curve ranges and the declared URDF angle-provider contract.""" + mapping = SerializedJointMapping(payload, input_kind="command") + from .joint_control import independent_joint_sources, validate_independent_output, uses_affine_mimic_approximation, uses_source_mimic + sources = independent_joint_sources(payload) + preserved = uses_source_mimic(payload) + affine = uses_affine_mimic_approximation(payload) or preserved + if preserved: + from .source_mimic import validate_serialized_mimic_envelopes + validate_serialized_mimic_envelopes(payload, model) + if sources is not None: + validate_independent_output(model, {name: row["motor_index"] for name, row in mapping.joints.items()}, sources) + moving = {name for name, joint in model.joints.items() if joint.kind != "fixed"} + if set(mapping.joints) | set(mapping.retained_joints) != moving: + raise ValueError("compact JSON joints differ from the exported URDF") + from .partial_scope import retained_from_payload + retained_from_payload(payload, model) + for name, row in mapping.joints.items(): + joint = model.joints[name] + values = np.asarray(row["angle_rad"]) + for branch in ("angle_rad", "increasing_rad", "decreasing_rad"): + branch_values = np.asarray(row.get(branch, row["angle_rad"])) + if joint.lower is not None and (np.min(branch_values) < joint.lower-1e-9 or np.max(branch_values) > joint.upper+1e-9): + raise ValueError(f"compact table exceeds exported URDF range:{name}:{branch}") + if joint.mimic_joint: + parent = mapping.joints[joint.mimic_joint] + if mapping.measured: + if row["motor_index"] != parent["motor_index"] or (not affine and abs(joint.mimic_offset) > 1e-10): + raise ValueError(f"v3 mimic channel or shared zero differs:{name}") + continue + if (row["motor_index"] != parent["motor_index"] + or row["curve_input_knots_rad"] != parent["curve_input_knots_rad"] + or len(values) != len(parent["angle_rad"]) + or not np.allclose(values, joint.mimic_multiplier*np.asarray(parent["angle_rad"]) + + joint.mimic_offset, atol=1e-8, rtol=0)): + raise ValueError(f"compact passive table differs from exported URDF mimic:{name}") + if mapping.measured: + baseline = payload.get("baseline_command", ()) + if not baseline or not np.all(np.isfinite(baseline)): + raise ValueError("v3 baseline vector is missing or invalid") + for name, row in mapping.joints.items(): + index = row["motor_index"] + if index >= len(baseline): + raise ValueError("v3 baseline channel missing") + branches = ("", "increasing", "decreasing") if name in mapping.directional_joints else ("",) + for direction in branches: + value = mapping.evaluate(baseline, direction, active_joints=(name,))[name] + if abs(value) > 1e-10: + raise ValueError(f"v3 baseline is not zero:{name}:{direction}") diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/image_acceptance.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/image_acceptance.py new file mode 100644 index 0000000..f6fb32b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/image_acceptance.py @@ -0,0 +1,171 @@ +"""Validate frozen final-file motion and its independent image evidence. + +Primary measured poses must explain their original pixels. Their difference +from final-file motion is judged in degrees and metres, not by reusing the PnP +pixel limit for the sum of measurement and motion error. Extra views provide a +separate consistency check, never a substitute for independent 3-D accuracy. +No shared calibration parameter is estimated or changed during acceptance. +""" + +from dataclasses import asdict, dataclass + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..fitting.tag_installation import rigid_matrix +from ..geometry.tag_pose.ippe import square_object_points +from ..geometry.tag_pose.parameters import DEFAULT_POSE_TRACKING_PARAMETERS +from .acceptance import SerializedJointMapping, angular_metrics +from .image_consistency import find_projection_witness, projection_error +from .kinematics import UrdfKinematicModel +from .joint_control import independent_joint_sources +from .tag_acceptance import POSITION_P95_LIMIT_M + + +FINAL_IMAGE_ACCEPTANCE_POLICY = "independent_measurement_and_physical_consistency_v2" + + +@dataclass(frozen=True) +class TagImageObservation: + sample_id: str + role: str + cycle: int + sdk_values: tuple[float, ...] + directions: tuple[tuple[str, str], ...] + view: str + tag_size_m: float + corners_xy: tuple[tuple[float, float], ...] + camera_matrix: tuple[tuple[float, float, float], ...] + view_from_common: tuple[tuple[float, ...], ...] + task_name: str = "" + + +class ImageHoldoutFailure(ValueError): + def __init__(self, report, *, input_kind, holdout_cycle): + self.report = report + self.input_kind = input_kind + self.holdout_cycle = holdout_cycle + failed = [role for role, metrics in report.items() if not metrics["passed"]] + super().__init__("final_image_holdout_failed:" + input_kind + ":" + ",".join(failed)) + + +def _physical_metrics(values): + angles = angular_metrics([angle for angle, _ in values]) + position = float(np.percentile([distance for _, distance in values], 95)) + return {**asdict(angles), "translation_p95_m": position, + "passed": angles.passed and position <= POSITION_P95_LIMIT_M} + + +def _pixel_metrics(values): + return {"rms_px": float(np.sqrt(np.mean(np.square(values)))), + "p95_px": float(np.percentile(values, 95)), "maximum_px": max(values)} + + +def _image_geometry(row): + if not np.isfinite(row.tag_size_m) or row.tag_size_m <= 0: + raise ValueError("final_image_holdout_size_invalid") + matrix, measured = np.asarray(row.camera_matrix), np.asarray(row.corners_xy) + if (matrix.shape != (3, 3) or measured.shape != (4, 2) + or not np.all(np.isfinite(matrix)) or not np.all(np.isfinite(measured)) + or matrix[0, 0] <= 0 or matrix[1, 1] <= 0 or not np.array_equal(matrix[2], [0, 0, 1])): + raise ValueError("final_image_holdout_projection_invalid") + return matrix, measured, square_object_points(row.tag_size_m) + + +def validate_serialized_image_holdout(*, corrected_urdf, payload, common_from_base, + installations, observations, independent_observations, required_roles, input_kind, + holdout_cycle, minimum_samples): + """Keep 1.5 px measurement accuracy and the original 3-D motion limits. + + Auxiliary witnesses only prove image compatibility within those limits. + They are grouped by motion task so stationary images cannot dilute the + errors in a different moving task. Independent poses remain mandatory. + """ + roles = frozenset(required_roles) + if (holdout_cycle not in {3, 5} or not roles or not roles <= installations.keys() + or minimum_samples < 1): + raise ValueError("final_image_holdout_contract_invalid") + model = UrdfKinematicModel(corrected_urdf) + mapping = SerializedJointMapping(payload, input_kind=input_kind) + active = tuple(name for name, joint in model.joints.items() + if joint.kind != "fixed" and (mapping.measured or joint.mimic_joint is None)) + if mapping.retained_joints: + from .partial_scope import retained_from_payload, require_retained_pose + retained_from_payload(payload, model) + active = tuple(name for name in active if name not in mapping.retained_joints) + base = rigid_matrix(common_from_base) + training_ids = {sample for mount in installations.values() for sample in mount.training_sample_ids} + independent = {} + for pose in independent_observations: + identity = (pose.role, pose.sample_id) + if (identity in independent or pose.role not in roles or not pose.sample_id + or pose.cycle != holdout_cycle or pose.sample_id in training_ids): + raise ValueError("final_image_holdout_independent_identity_invalid") + independent[identity] = pose + errors = {role: [] for role in roles} + motion = {role: [] for role in roles} + auxiliary = {role: {} for role in roles} + seen = set() + limit = DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px + for row in observations: + identity = (row.role, row.sample_id) + if (row.cycle != holdout_cycle or row.sample_id in training_ids or not row.sample_id + or identity in seen or row.role not in roles): + raise ValueError("final_image_holdout_identity_invalid") + seen.add(identity) + mount = installations[row.role] + if mount.role != row.role or mount.link not in model.links: + raise ValueError("final_image_holdout_installation_invalid") + if mapping.retained_joints: + require_retained_pose(mapping.retained_joints, row.sdk_values, model=model, link=mount.link) + angles = mapping.evaluate(row.sdk_values, "", active_joints=active, + directions_by_joint=dict(row.directions)) + link = np.eye(4) if mount.link == model.root_link else model.link_transform( + model.parent_joint_by_child[mount.link], zero_offsets={}, joint_angles=angles, + independent_mimic_angles=mapping.measured and independent_joint_sources(payload) is None) + predicted = rigid_matrix(row.view_from_common) @ base @ link @ rigid_matrix(mount.link_from_tag) + camera, pixels, objects = _image_geometry(row) + nominal = projection_error(predicted, camera, objects, pixels) + measured = independent.get(identity) + if measured is not None: + if (tuple(measured.sdk_values) != row.sdk_values + or dict(measured.sdk_directions_by_joint) != dict(row.directions)): + raise ValueError("final_image_holdout_independent_input_changed") + observed = rigid_matrix(row.view_from_common) @ rigid_matrix(measured.common_from_tag) + residual = projection_error(observed, camera, objects, pixels) + angle = float(Rotation.from_matrix(predicted[:3, :3].T @ observed[:3, :3]).magnitude()) + distance = float(np.linalg.norm(predicted[:3, 3]-observed[:3, 3])) + motion[row.role].append((angle, distance)) + else: + if not row.task_name: + raise ValueError("final_image_holdout_auxiliary_task_missing") + witness = find_projection_witness(predicted, camera, objects, pixels, image_limit_px=limit) + residual = witness.residual_px + auxiliary[row.role].setdefault(row.task_name, []).append(witness) + errors[row.role].append((row, nominal, residual)) + results = {} + for role in sorted(roles): + if len(motion[role]) < minimum_samples: + raise ValueError(f"final_image_holdout_missing:{role}:{len(motion[role])}") + values = errors[role] + residuals = [value[2] for value in values] + physical = _physical_metrics(motion[role]) + tasks = {} + for task, witnesses in auxiliary[role].items(): + metrics = _physical_metrics([(row.angle_rad, row.position_m) for row in witnesses]) + tasks[task] = {**metrics, "interpretation": "feasible_pose_displacement_only", + "optimizer_not_converged_count": sum(not row.optimizer_converged for row in witnesses), + "maximum_px": max(row.residual_px for row in witnesses)} + tasks[task]["passed"] = metrics["passed"] and tasks[task]["maximum_px"] <= limit + worst = values[int(np.argmax(residuals))][0] + results[role] = {"count": len(values), **_pixel_metrics(residuals), "limit_px": limit, + "nominal_projection": _pixel_metrics([value[1] for value in values]), + "independent_motion": physical, "auxiliary_consistency_by_task": tasks, + "worst_sample_id": worst.sample_id, "view": worst.view, + "passed": (max(residuals) <= limit and physical["passed"] + and all(value["passed"] for value in tasks.values()))} + if not independent.keys() <= seen: + raise ValueError("final_image_holdout_independent_source_missing") + if not all(metrics["passed"] for metrics in results.values()): + raise ImageHoldoutFailure(results, input_kind=input_kind, holdout_cycle=holdout_cycle) + return results diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/image_consistency.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/image_consistency.py new file mode 100644 index 0000000..b0b0fd3 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/image_consistency.py @@ -0,0 +1,109 @@ +"""Check whether extra-view pixels admit a pose within a physical error budget. + +A local pose is an existence witness, not an independently measured pose. It +never changes the base, mounting, camera, joints or exported calibration. The +caller must separately validate independent 3-D observations and check the +witness displacement against the same physical accuracy limits. +""" + +from dataclasses import dataclass + +import numpy as np +from scipy.optimize import minimize +from scipy.spatial.transform import Rotation + +from .acceptance import ANGLE_MAXIMUM_LIMIT_DEG +from .tag_acceptance import POSITION_P95_LIMIT_M + + +@dataclass(frozen=True) +class ProjectionConsistency: + nominal_px: float + residual_px: float + angle_rad: float + position_m: float + iterations: int + optimizer_converged: bool + + +def _cross_matrix(vector): + a, b, c = vector + return np.array([[0., -c, b], [c, 0., -a], [-b, a, 0.]]) + + +def _rigid_projection(x, pose, camera, objects, measured, angle_scale, position_scale): + """Pixel residual and analytic Jacobian for a Tag-centred rigid displacement.""" + vector = x[:3] * angle_scale + theta = float(np.linalg.norm(vector)) + skew = _cross_matrix(vector) + if theta < 1e-4: + left = np.eye(3) + (.5-theta**2/24)*skew + (1/6-theta**2/120)*(skew @ skew) + else: + left = (np.eye(3) + (1-np.cos(theta))/theta**2*skew + + (theta-np.sin(theta))/theta**3*(skew @ skew)) + rotated = objects @ (Rotation.from_rotvec(vector).as_matrix() @ pose[:3, :3]).T + points = rotated + pose[:3, 3] + x[3:] * position_scale + if not np.all(np.isfinite(points)) or np.any(points[:, 2] <= 0): + raise ValueError("final_image_holdout_projection_invalid") + homogeneous = points @ camera.T + pixels = homogeneous[:, :2] / homogeneous[:, 2:] + point_jacobian = np.empty((4, 3, 6)) + point_jacobian[:, :, :3] = [-_cross_matrix(point) @ left * angle_scale for point in rotated] + point_jacobian[:, :, 3:] = np.eye(3) * position_scale + projection = ((camera[:2, :][None] - pixels[:, :, None]*camera[2, :][None, None]) + / homogeneous[:, 2, None, None]) + return pixels-measured, np.einsum("nki,nij->nkj", projection, point_jacobian) + + +def projection_error(pose, camera, objects, measured): + residual, _ = _rigid_projection(np.zeros(6), pose, camera, objects, measured, 1., 1.) + return float(np.sqrt(np.mean(np.sum(residual**2, axis=1)))) + + +def find_projection_witness(pose, camera, objects, measured, *, image_limit_px): + """Find a feasible pose; optimizer success alone never establishes acceptance. + + The objective favours a small displacement in physical units. Its returned + displacement is not claimed to be globally minimal. The caller checks both + the directly evaluated pixel residual and the physical displacement. + """ + angle_scale = np.deg2rad(ANGLE_MAXIMUM_LIMIT_DEG) + position_scale = POSITION_P95_LIMIT_M + + def evaluate(x): + return _rigid_projection(x, pose, camera, objects, measured, angle_scale, position_scale) + + def rms(x): + residual, _ = evaluate(x) + return float(np.sqrt(np.mean(np.sum(residual**2, axis=1)))) + + zero = np.zeros(6) + nominal = rms(zero) + if nominal <= image_limit_px: + return ProjectionConsistency(nominal, nominal, 0., 0., 0, True) + # A small inward margin avoids accepting a constraint rounded above its + # limit. It does not enlarge either image or physical tolerances. + target = image_limit_px * (1.-1e-6) + + def constraint_jacobian(x): + residual, jacobian = evaluate(x) + return -2*np.mean(np.einsum("nk,nkj->nj", residual, jacobian), axis=0) + + constraint = {"type": "ineq", "fun": lambda x: target**2-rms(x)**2, + "jac": constraint_jacobian} + # Bounds limit numerical exploration, not the permitted physical error. + # Ensure every explored point remains in front of the image plane. + depth = pose[2, 3] - float(np.max(np.linalg.norm(objects, axis=1))) + lower_z = max(-5., -depth / position_scale * (1.-1e-6)) + if lower_z >= 0: + raise ValueError("final_image_holdout_projection_invalid") + bounds = [(-5., 5.)]*5 + [(lower_z, 5.)] + result = minimize(lambda x: float(x @ x), zero, jac=lambda x: 2*x, + constraints=constraint, bounds=bounds, method="SLSQP", + options={"maxiter": 60, "ftol": 1e-10}) + if not np.all(np.isfinite(result.x)): + raise ValueError("final_image_holdout_witness_nonfinite") + return ProjectionConsistency(nominal, rms(result.x), + float(np.linalg.norm(result.x[:3])*angle_scale), + float(np.linalg.norm(result.x[3:])*position_scale), + int(result.nit), bool(result.success)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/joint_control.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/joint_control.py new file mode 100644 index 0000000..8951e8e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/joint_control.py @@ -0,0 +1,78 @@ +"""Versioned roles of measured JSON and standard URDF mimic approximations. + +Production keeps mimic for standalone linear motion and uses explicit JSON +angles for measured motion. Version 2's mimic-free export remains readable; +its removal rights never authorize extra geometry or SDK actuation changes. +""" + +JSON_JOINT_ANGLES = "calibration_json" +AFFINE_MIMIC_APPROXIMATION = "range_bounded_affine_approximation" +PRESERVE_SOURCE_MIMIC = "preserve_source_mimic" + + +def uses_source_mimic(payload): + correction = payload.get("urdf_correction", {}) + if correction.get("schema_version") != 4: + return False + if (payload.get("format") not in {"unified_calibration_v3", "unified_calibration_report_v3"} + or correction.get("joint_angle_source") != JSON_JOINT_ANGLES + or correction.get("mimic_policy") != PRESERVE_SOURCE_MIMIC): + raise ValueError("unsupported_source_mimic_contract") + return True + + +def uses_affine_mimic_approximation(payload): + correction = payload.get("urdf_correction", {}) + if correction.get("schema_version") != 3: + return False + if (payload.get("format") not in {"unified_calibration_v3", "unified_calibration_report_v3"} + or correction.get("joint_angle_source") != JSON_JOINT_ANGLES + or correction.get("mimic_policy") != AFFINE_MIMIC_APPROXIMATION): + raise ValueError("unsupported_urdf_mimic_approximation_contract") + return True + + +def independent_joint_sources(payload): + """None denotes a URDF retaining its linear mimic constraints.""" + correction = payload.get("urdf_correction", {}) + version = correction.get("schema_version", 1) + if version == 1 or uses_affine_mimic_approximation(payload) or uses_source_mimic(payload): + return None + if (version != 2 + or payload.get("format") not in {"unified_calibration_v3", "unified_calibration_report_v3"} + or correction.get("joint_angle_source") != JSON_JOINT_ANGLES): + raise ValueError("unsupported_urdf_joint_control_contract") + sources = correction.get("passive_joint_sources") + if not isinstance(sources, dict) or any( + not isinstance(name, str) or not isinstance(parent, str) or name == parent + for name, parent in sources.items() + ): + raise ValueError("invalid_independent_passive_joint_sources") + return sources + + +def validate_joint_channels(model, channels, sources): + moving = {name for name, joint in model.joints.items() if joint.kind != "fixed"} + if set(channels) != moving or any(type(index) is not int or index < 0 for index in channels.values()): + raise ValueError("independent_joint_channel_coverage_differs") + for name, parent in sources.items(): + if name not in moving or parent not in moving or channels[name] != channels[parent]: + raise ValueError(f"independent_passive_sdk_channel_differs:{name}") + + +def independent_export_authorization(model, channels, sources, authorized_fields): + """Authorize only the exact source mimic removals, after binding validation.""" + original = {name: joint.mimic_joint for name, joint in model.joints.items() if joint.mimic_joint} + if sources != original: + raise ValueError("independent_passive_sources_differ_from_source_urdf") + validate_joint_channels(model, channels, sources) + rights = {name: tuple(fields) for name, fields in authorized_fields.items()} + for name in sources: + rights[name] = tuple(sorted(set(rights.get(name, ())) | {"mimic.remove"})) + return rights + + +def validate_independent_output(model, channels, sources): + validate_joint_channels(model, channels, sources) + if any(joint.mimic_joint is not None for joint in model.joints.values()): + raise ValueError("json_joint_angles_must_not_be_overridden_by_urdf_mimic") diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/kinematics.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/kinematics.py new file mode 100644 index 0000000..e7c65ad --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/kinematics.py @@ -0,0 +1,200 @@ +"""Standard URDF kinematics; independent of SDK, ROS and product profiles. + +Measured passive angles are useful to estimate geometry, but release validation +must resolve the *serialized* mimic graph, never those independent observations. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from pathlib import Path +from typing import Mapping, Sequence +import xml.etree.ElementTree as ET + +import numpy as np +from scipy.spatial.transform import Rotation + + +def _parse_triplet(value: str) -> np.ndarray: + result = np.asarray([float(v) for v in str(value).split()], dtype=float) + if result.shape != (3,) or not np.all(np.isfinite(result)): + raise ValueError(f"invalid URDF vector: {value}") + return result + + +def _axis_rotation(axis: Sequence[float], angle: float) -> np.ndarray: + vector = np.asarray(axis, dtype=float) + if vector.shape != (3,) or not np.all(np.isfinite(vector)): + raise ValueError("joint axis must be a finite 3-vector") + norm = float(np.linalg.norm(vector)) + if norm <= 1e-12 or not math.isfinite(float(angle)): + raise ValueError("joint axis/angle is invalid") + transform = np.eye(4) + transform[:3, :3] = Rotation.from_rotvec(vector / norm * float(angle)).as_matrix() + return transform + + +@dataclass(frozen=True) +class UrdfJoint: + name: str + parent: str + child: str + origin: np.ndarray + axis: np.ndarray + mimic_joint: str | None + mimic_multiplier: float + mimic_offset: float + kind: str = "revolute" + lower: float | None = None + upper: float | None = None + + +class UrdfKinematicModel: + def __init__(self, source: str | Path) -> None: + self.source = Path(source).expanduser().resolve() + root = ET.parse(self.source).getroot() + if root.tag != "robot": + raise ValueError("URDF root must be robot") + names = [element.get("name", "") for element in root.findall("link")] + if not names or "" in names or len(set(names)) != len(names): + raise ValueError("URDF link names must be nonempty and unique") + self.links = frozenset(names) + self.joints: dict[str, UrdfJoint] = {} + self.parent_joint_by_child: dict[str, str] = {} + for element in root.findall("joint"): + name = element.get("name", "") + kind = element.get("type", "") + if not name or name in self.joints: + raise ValueError("URDF joint names must be nonempty and unique") + if kind not in {"fixed", "revolute", "continuous", "prismatic"}: + raise ValueError(f"unsupported calibration joint type: {name}:{kind}") + parent, child = element.find("parent"), element.find("child") + if parent is None or child is None: + raise ValueError(f"URDF joint is missing parent/child: {name}") + parent_name, child_name = parent.get("link", ""), child.get("link", "") + if parent_name not in self.links or child_name not in self.links: + raise ValueError(f"URDF joint references a missing link: {name}") + if child_name in self.parent_joint_by_child: + raise ValueError(f"URDF link has multiple parents: {child_name}") + origin_node, axis_node = element.find("origin"), element.find("axis") + xyz = _parse_triplet("0 0 0" if origin_node is None else origin_node.get("xyz", "0 0 0")) + rpy = _parse_triplet("0 0 0" if origin_node is None else origin_node.get("rpy", "0 0 0")) + axis = _parse_triplet("1 0 0" if axis_node is None else axis_node.get("xyz", "1 0 0")) + if float(np.linalg.norm(axis)) <= 1e-12: + raise ValueError(f"URDF joint has a zero axis: {name}") + axis /= np.linalg.norm(axis) + origin = np.eye(4) + origin[:3, :3] = Rotation.from_euler("xyz", rpy).as_matrix() + origin[:3, 3] = xyz + mimic, limit = element.find("mimic"), element.find("limit") + multiplier = 1.0 if mimic is None else float(mimic.get("multiplier", "1")) + offset = 0.0 if mimic is None else float(mimic.get("offset", "0")) + if not math.isfinite(multiplier) or not math.isfinite(offset): + raise ValueError(f"URDF mimic is nonfinite: {name}") + lower = None if limit is None or kind in {"fixed", "continuous"} else float(limit.get("lower", "nan")) + upper = None if lower is None else float(limit.get("upper", "nan")) + if lower is not None and (not math.isfinite(lower) or not math.isfinite(upper) or lower > upper): + raise ValueError(f"URDF joint has invalid limits: {name}") + self.joints[name] = UrdfJoint(name, parent_name, child_name, origin, axis, + None if mimic is None else mimic.get("joint", ""), multiplier, offset, + kind, lower, upper) + self.parent_joint_by_child[child_name] = name + roots = self.links - self.parent_joint_by_child.keys() + if len(roots) != 1: + raise ValueError("URDF must have exactly one root link") + self.root_link = next(iter(roots)) + for name in self.joints: + self._chain(name) + self.resolve_angles({}) # Validate the complete mimic graph, including siblings. + + def _chain(self, target_joint: str) -> list[UrdfJoint]: + if target_joint not in self.joints: + raise ValueError(f"URDF is missing joint {target_joint}") + chain: list[UrdfJoint] = [] + seen: set[str] = set() + current = self.joints[target_joint] + while True: + if current.name in seen: + raise ValueError(f"URDF kinematic cycle: {current.name}") + seen.add(current.name) + chain.append(current) + parent = self.parent_joint_by_child.get(current.parent) + if parent is None: + if current.parent != self.root_link: + raise ValueError("URDF contains a disconnected joint") + return list(reversed(chain)) + current = self.joints[parent] + + def resolve_angles(self, joint_angles: Mapping[str, float], *, independent_mimic_angles: bool = False) -> dict[str, float]: + supplied = {str(k): float(v) for k, v in joint_angles.items()} + if not all(math.isfinite(v) for v in supplied.values()): + raise ValueError("joint angles must be finite") + resolved: dict[str, float] = {} + visiting: set[str] = set() + + def resolve(name: str) -> float: + if name in resolved: + return resolved[name] + if name in visiting or name not in self.joints: + raise ValueError(f"invalid URDF mimic dependency: {name}") + visiting.add(name) + joint = self.joints[name] + if joint.kind == "fixed": + angle = 0.0 + elif joint.mimic_joint is not None and not (independent_mimic_angles and name in supplied): + angle = joint.mimic_multiplier * resolve(joint.mimic_joint) + joint.mimic_offset + else: + angle = supplied.get(name, 0.0) + if not math.isfinite(angle): + raise ValueError(f"nonfinite resolved URDF angle: {name}") + visiting.remove(name) + resolved[name] = angle + return angle + + for name in self.joints: + resolve(name) + return resolved + + @staticmethod + def _motion(joint: UrdfJoint, angle: float) -> np.ndarray: + if joint.kind == "fixed": + return np.eye(4) + if joint.kind == "prismatic": + transform = np.eye(4) + transform[:3, 3] = joint.axis * angle + return transform + return _axis_rotation(joint.axis, angle) + + def link_transform(self, target_joint: str, *, zero_offsets: Mapping[str, float], joint_angles: Mapping[str, float], independent_mimic_angles: bool = False) -> np.ndarray: + """Base-to-child-link pose. Independent passive input is measurement-only.""" + resolved = self.resolve_angles(joint_angles, independent_mimic_angles=independent_mimic_angles) + transform = np.eye(4) + for joint in self._chain(target_joint): + transform = transform @ joint.origin @ self._motion(joint, float(zero_offsets.get(joint.name, 0.0)) + resolved[joint.name]) + return transform + + def axis_line(self, target_joint: str, *, zero_offsets: Mapping[str, float], joint_angles: Mapping[str, float], independent_mimic_angles: bool = False) -> tuple[np.ndarray, np.ndarray]: + resolved = self.resolve_angles(joint_angles, independent_mimic_angles=independent_mimic_angles) + transform = np.eye(4) + for joint in self._chain(target_joint): + frame = transform @ joint.origin @ self._motion(joint, float(zero_offsets.get(joint.name, 0.0))) + if joint.name == target_joint: + return frame[:3, :3] @ joint.axis, frame[:3, 3].copy() + transform = frame @ self._motion(joint, resolved[joint.name]) + raise ValueError(f"cannot resolve joint axis: {target_joint}") + + +def corrected_origin_rpy(joint: UrdfJoint, offset_rad: float) -> tuple[float, float, float]: + """q_CAD = q_output + offset; compose about the local axis, not an RPY component.""" + if joint.kind not in {"revolute", "continuous"}: + raise ValueError("angular zero correction requires a revolute joint") + matrix = joint.origin @ _axis_rotation(joint.axis, offset_rad) + return tuple(float(v) for v in Rotation.from_matrix(matrix[:3, :3]).as_euler("xyz")) + + +def corrected_mimic_offset(multiplier: float, offset: float, parent_zero: float, child_zero: float) -> float: + values = (multiplier, offset, parent_zero, child_zero) + if not all(math.isfinite(float(v)) for v in values): + raise ValueError("mimic coordinate correction must be finite") + return float(offset + multiplier * parent_zero - child_zero) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/limits.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/limits.py new file mode 100644 index 0000000..7a056bc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/limits.py @@ -0,0 +1,115 @@ +"""Training-supported URDF motion envelopes and independent safety bounds. + +CAD limits remain hard bounds unless the protected Profile explicitly declares +them to be nominal motion envelopes. This module never changes SDK commands, +adds tolerance padding, fits a curve, or consumes validation observations. +""" + +from dataclasses import dataclass +import math +from ..domain.capture_plan import training_cycles, LEGACY_TRAINING + + +@dataclass(frozen=True) +class MotionRangeEvidence: + joint: str + source_joint: str + independently_measured: bool + source_limits_cad_rad: tuple[float, float] + output_limits_rad: tuple[float, float] + feedback_bounds_rad: tuple[float, float] | None + command_bounds_rad: tuple[float, float] + zero_offset_rad: float + baseline_command: float + training_cycles: tuple[int, ...] + training_sample_ids: tuple[str, ...] + reference_sample_ids: tuple[str, ...] + source_limits: str + evidence_source: str + independent_safety_limits_cad_rad: tuple[float, float] | None + safety_evidence_source: str + command_training_cycles: tuple[int, ...] = (0, 1, 2) + command_training_sample_ids: tuple[str, ...] = () + release_basis: str = "feedback_and_command" + command_support: dict | None = None + + +def _interval(value): + return len(value) == 2 and all(math.isfinite(v) for v in value) and value[0] < value[1] + + +def validate_range_evidence(name, original, delta, interval, evidence, *, allow_single_training_cycle=False): + """Validate trusted fit evidence at both planning and final read-back.""" + cycles = {LEGACY_TRAINING, LEGACY_TRAINING[:2]} + if allow_single_training_cycle: + cycles |= {(0,), (1,)} # Explicit uncertified draft only; never holdout. + if (not isinstance(evidence, MotionRangeEvidence) or evidence.joint != name + or evidence.source_limits != "calibrated_motion_envelope" or not evidence.evidence_source.strip() + or evidence.training_cycles not in cycles or not evidence.training_sample_ids + or evidence.command_training_cycles not in cycles | {(4,)} + or (evidence.command_training_cycles == (4,) and not evidence.command_training_sample_ids) + or not evidence.reference_sample_ids or not evidence.source_joint + or evidence.independently_measured != (evidence.source_joint == name) + or evidence.source_limits_cad_rad != (original.lower, original.upper) + or evidence.zero_offset_rad != delta + or evidence.release_basis not in {"feedback_and_command", "steady_command"} + or (evidence.release_basis == "steady_command" and evidence.feedback_bounds_rad is not None) + or (evidence.release_basis == "feedback_and_command" and + (evidence.feedback_bounds_rad is None or not _interval(evidence.feedback_bounds_rad))) + or not _interval(evidence.command_bounds_rad)): + raise ValueError(f"invalid_training_motion_range_evidence:{name}") + motion_bounds = evidence.feedback_bounds_rad or evidence.command_bounds_rad + expected = (min(0.0, motion_bounds[0], evidence.command_bounds_rad[0]), + max(0.0, motion_bounds[1], evidence.command_bounds_rad[1])) + if evidence.output_limits_rad != expected or not _interval(interval) \ + or any(abs(a-b) > 1e-10 for a, b in zip(interval, expected)): + raise ValueError(f"motion_range_differs_from_training_support:{name}") + safety = evidence.independent_safety_limits_cad_rad + if safety is None: + if evidence.safety_evidence_source: + raise ValueError(f"independent_safety_evidence_without_bounds:{name}") + elif (not _interval(safety) or not evidence.safety_evidence_source.strip() + or interval[0]+delta < safety[0]-1e-9 or interval[1]+delta > safety[1]+1e-9): + raise ValueError(f"measured_motion_exceeds_independent_safety_range:{name}") + + +def compile_motion_ranges(profile, model, fit): + """Freeze bounds from existing 3-cycle fitted mappings, without a refit. + + Copied curves retain donor image identities and never become independent + recipient measurements. All angular values already share the frozen zero. + """ + result = {} + from ..domain.sampling import command_training_cycles + for name, policy in profile.urdf_limit_policies.items(): + source = profile.measurement.transferred_motion_sources.get(name, name) + command_cycles = command_training_cycles(profile, joint=source) + motion_cycles = training_cycles(profile, joint=source) + curve = fit.curves[source] + reference = fit.joint_zero_references[source] + command_evidence = fit.command_holdout_metrics[source] + if (tuple(curve.circle.get("training_cycles", ())) != motion_cycles + or tuple(command_evidence.get("training_cycles", ())) != command_cycles + or not curve.circle.get("training_sample_ids") + or not reference.samples): + raise ValueError(f"motion_range_requires_training_provenance:{name}") + primary, command = fit.output_mappings[name], fit.command_mappings[name] + if (primary.transferred_from != (source if source != name else None) + or command.transferred_from != primary.transferred_from + or abs(command.evaluate(reference.baseline_command)) > 1e-10): + raise ValueError(f"motion_range_requires_shared_baseline_and_donor:{name}") + bounds = (min(0.0, primary.bounds_rad[0], command.bounds_rad[0]), + max(0.0, primary.bounds_rad[1], command.bounds_rad[1])) + original = model.joints[name] + evidence = MotionRangeEvidence(name, source, source == name, + (original.lower, original.upper), bounds, + None if profile.command_based_release else primary.bounds_rad, command.bounds_rad, + fit.zero_offsets_rad[name], reference.baseline_command, motion_cycles, + tuple(sorted(curve.circle["training_sample_ids"])), + tuple(sorted(f"{sample.view}:{sample.image_stamp_ns}" for sample in reference.samples)), + policy.source_limits, policy.evidence_source, policy.independent_safety_limits_cad_rad, + policy.safety_evidence_source, command_cycles, + tuple(command_evidence.get("training_sample_ids", ())), profile.measurement.release_basis) + validate_range_evidence(name, original, fit.zero_offsets_rad[name], bounds, evidence) + result[name] = evidence + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/linear_drive.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/linear_drive.py new file mode 100644 index 0000000..51cabfc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/linear_drive.py @@ -0,0 +1,45 @@ +"""Validate the actual limits-linear SDK driver without refitting any curve.""" +import numpy as np + +from ..geometry.tag_pose.urdf_command_images import UrdfCommandImages +from ..fitting.motion_fit import joint_input_direction + + +class UrdfLinearImages: + """Keep frozen camera/mount geometry, replacing only the angle provider.""" + def __init__(self, bundle, corrected): + self.bundle, self.corrected = bundle, corrected + + def __getattr__(self, name): + return getattr(self.bundle, name) + + def joint_angles(self, parameters, commands, directions): + offsets = self.bundle.zero_offsets(parameters) + angles = {} + for name, channel in self.channels.items(): + cad = self.cad_names[name] + joint = self.corrected.joints[cad] + ratio = np.asarray(commands[:, channel], dtype=float)/255. + if np.any((ratio < 0) | (ratio > 1)): + raise ValueError('urdf_linear_command_outside_byte_range') + if joint_input_direction(self.profile, self.model, name) < 0: + ratio = 1-ratio + # The projector keeps the original CAD origin. Account for the + # exported origin exactly once, including nonzero byte baselines. + angles[cad] = offsets[name]+joint.lower+(joint.upper-joint.lower)*ratio + return angles + + def link_poses(self, parameters, commands, directions, angle_corrections=None): + return UrdfCommandImages.link_poses(self, parameters, commands, directions, angle_corrections) + + def project_observations(self, parameters, commands, directions, observations, angle_corrections=None): + return UrdfCommandImages.project_observations(self, parameters, commands, directions, + observations, angle_corrections) + + +def validate_urdf_linear_drive(bundle, parameters, corrected, holdout, *, report_joints=None): + from types import SimpleNamespace + from ..fitting.raw_joint_validation import validate_raw_joint_candidate + result = validate_raw_joint_candidate(UrdfLinearImages(bundle, corrected), + SimpleNamespace(parameters=parameters), holdout, report_joints=report_joints) + return dict(result, drive='urdf_limits_linear_sdk_u8', parameters_refitted=False) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/measured_acceptance.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/measured_acceptance.py new file mode 100644 index 0000000..f79eb5c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/measured_acceptance.py @@ -0,0 +1,57 @@ +"""Read-back v3 command errors against raw, independent fourth-round angles.""" + +from dataclasses import asdict + +from .acceptance import SerializedJointMapping, angular_metrics +from ..fitting.spatial import measure_joint_curve_observation + + +def validate_transferred_joint_tables(payload, measured_joints, transferred_motion_sources): + """Check declared copies without inventing measurements for recipients.""" + mapping = SerializedJointMapping(payload, input_kind="command") + observed, transfers = set(measured_joints), dict(transferred_motion_sources) + if (not mapping.measured or not mapping.compact or not observed + or set(mapping.joints) != observed | transfers.keys() or observed & transfers.keys() + or any(source not in observed for source in transfers.values())): + raise ValueError("v3 final mapping differs from independently measured joints") + baseline = payload["baseline_command"] + for target, source in transfers.items(): + recipient, donor = mapping.joints[target], mapping.joints[source] + if (recipient["angle_rad"] != donor["angle_rad"] + or recipient["curve_input_knots_rad"] != donor["curve_input_knots_rad"] + or baseline[recipient["motor_index"]] != baseline[donor["motor_index"]]): + raise ValueError(f"transferred_final_table_differs_from_source:{target}") + for branch in ("increasing_rad", "decreasing_rad"): + if recipient.get(branch) != donor.get(branch): + raise ValueError(f"transferred_final_table_differs_from_source:{target}:{branch}") + + +def validate_measured_joint_holdout(payload, curves, observations, *, transferred_motion_sources=None, + holdout_cycle=3): + if holdout_cycle not in {3, 5}: + raise ValueError("command validation requires a declared independent partition") + validate_transferred_joint_tables(payload, curves, transferred_motion_sources or {}) + mapping = SerializedJointMapping(payload, input_kind="command") + errors = {name: {d: [] for d in ("increasing", "decreasing")} for name in curves} + seen = set() + unit = payload["input_unit"] + for row in observations: + name, identity = row["joint"], row["sample_id"] + if name not in curves or row["cycle"] != holdout_cycle or row.get("sample_phase") != "steady": + raise ValueError("v3 angle holdout has wrong partition or joint") + if (name, identity) in seen or identity in curves[name].circle["training_sample_ids"]: + raise ValueError("v3 angle holdout duplicates or overlaps training") + seen.add((name, identity)) + measured = measure_joint_curve_observation(curves[name], quaternion_xyzw=row["relative_quaternion_xyzw"]) + predicted = mapping.evaluate(row[f"command_vector_{unit}"], + row["direction"] if name in mapping.directional_joints else "", active_joints=(name,))[name] + errors[name][row["direction"]].append(predicted-measured) + results = {} + for name, branches in errors.items(): + if any(len(values) < 3 for values in branches.values()): + raise ValueError(f"missing_v3_joint_holdout:{name}") + metrics = {direction: angular_metrics(values) for direction, values in branches.items()} + if not all(value.passed for value in metrics.values()): + raise ValueError(f"serialized_measured_mapping_inaccurate:{name}:{metrics}") + results[name] = {key: asdict(value) for key, value in metrics.items()} + return results diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/partial_scope.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/partial_scope.py new file mode 100644 index 0000000..35a8036 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/partial_scope.py @@ -0,0 +1,95 @@ +"""Explicit retained-CAD scope shared by fitting, serialization and replay. + +An omitted curve never becomes an all-zero curve. CAD q=0 is used only as a +declared geometry premise while a relevant ancestor is held at its baseline. +""" + +import math + + +def profile_scope(profile): + if not profile.retained_joints: + return None + policy = profile.scope.retained_cad_scopes[profile.scope.default_scope] + return {"name": profile.scope.default_scope, "complete_hand": False, + "calibrated_joints": sorted(profile.zero.active_joints - profile.retained_joints), + "retained_joints": {name: {"sdk_channel": profile.command.command_index_by_joint[name], + "held_command": profile.command.baseline_values[profile.command.command_index_by_joint[name]], + "status": "not_calibrated", "urdf_policy": "preserve_source", + "geometry_assumption": "source_cad_zero_at_held_command", "reason": policy.reason} + for name in sorted(profile.retained_joints)}} + + +def retained_from_payload(payload, model=None): + scope = payload.get("calibration_scope") + if scope is None: + retained = {} + else: + if (payload.get("format") not in {"unified_calibration_v3", "unified_calibration_report_v3"} + or payload.get("transferred_motion_sources") + or payload.get("format") == "unified_calibration_report_v3" + and payload.get("quality", {}).get("release_basis") != "steady_command"): + raise ValueError("partial_scope_requires_independent_command_v3") + if (not isinstance(scope, dict) or set(scope) != { + "name", "complete_hand", "calibrated_joints", "retained_joints"} + or scope["complete_hand"] is not False or not isinstance(scope["name"], str) + or not scope["name"] or scope["name"] == "full" + or scope["calibrated_joints"] != sorted(payload.get("joints", {}))): + raise ValueError("invalid_partial_calibration_scope") + retained = scope["retained_joints"] + baseline = payload.get("baseline_command", ()) + if not isinstance(retained, dict) or not retained or retained.keys() & payload["joints"].keys(): + raise ValueError("invalid_retained_joint_partition") + channels = set() + for name, row in retained.items(): + if (not isinstance(row, dict) or set(row) != {"sdk_channel", "held_command", "status", + "urdf_policy", "geometry_assumption", "reason"}): + raise ValueError(f"invalid_retained_joint_contract:{name}") + index = row["sdk_channel"] + if (type(index) is not int or not 0 <= index < len(baseline) or index in channels + or row["held_command"] != baseline[index] + or not math.isfinite(float(row["held_command"])) + or row["status"] != "not_calibrated" or row["urdf_policy"] != "preserve_source" + or row["geometry_assumption"] != "source_cad_zero_at_held_command" + or not isinstance(row["reason"], str) or not row["reason"].strip()): + raise ValueError(f"invalid_retained_joint_contract:{name}") + channels.add(index) + mapped_channels = {row.get("sdk_channel", row.get("command_to_rad", {}).get("channel_index")) + for row in payload["joints"].values()} + if channels & mapped_channels: + raise ValueError("retained_channel_has_a_calibration_curve") + if retained.keys() & payload.get("urdf_correction", {}).get("joint_patches", {}).keys(): + raise ValueError("retained_joint_has_urdf_correction") + if model is not None: + moving = {n for n, j in model.joints.items() if j.kind != "fixed"} + if set(payload["joints"]) | set(retained) != moving: + raise ValueError("compact JSON joints differ from the exported URDF") + if any(model.joints[n].mimic_joint is not None for n in retained): + raise ValueError("retained scope only supports independent active joints") + return retained + + +def out_of_scope_ancestors(retained, sdk_values, *, model=None, link=None): + relevant = set(retained) + if model is not None and link is not None: + parent = model.parent_joint_by_child.get(link) + relevant &= set() if parent is None else {j.name for j in model._chain(parent)} + outside = [] + for name in sorted(relevant): + row = retained[name] + index = row["sdk_channel"] + if index >= len(sdk_values) or sdk_values[index] != row["held_command"]: + outside.append(name) + return tuple(outside) + + +def require_retained_pose(retained, sdk_values, *, model=None, link=None): + outside = out_of_scope_ancestors(retained, sdk_values, model=model, link=link) + if outside: + raise ValueError(f"uncalibrated_ancestor_not_at_declared_hold:{','.join(outside)}") + + +def require_profile_held_pose(profile, model, sdk_values, link): + scope = profile_scope(profile) + if scope: + require_retained_pose(scope["retained_joints"], sdk_values, model=model, link=link) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/patch.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/patch.py new file mode 100644 index 0000000..edeabcf --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/patch.py @@ -0,0 +1,525 @@ +"""Byte-preserving, declarative URDF patch application. + +Model profiles decide *what* values are authorized. This module owns the +shared mechanics of locating those fields in the original XML text, changing +only the declared attributes or explicit mimic removals, materializing mesh resources and atomically +publishing a new file. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import hashlib +import math +import os +from pathlib import Path +import re +import shutil +import tempfile +from typing import Callable, Mapping, Sequence +import xml.etree.ElementTree as ET + +import numpy as np +from scipy.spatial.transform import Rotation + + +@dataclass(frozen=True) +class UrdfJointPatch: + """Attribute edits or explicit removal of one joint's linear mimic.""" + + origin_rpy: str | None = None + limit_lower: str | None = None + limit_upper: str | None = None + mimic_multiplier: str | None = None + mimic_offset: str | None = None + remove_mimic: bool = False + + def __post_init__(self) -> None: + if type(self.remove_mimic) is not bool or (self.remove_mimic and ( + self.mimic_multiplier is not None or self.mimic_offset is not None + )): + raise ValueError("mimic removal cannot also replace its coefficients") + + def requested_fields(self) -> tuple[str, ...]: + return tuple(f"{element}.{attribute}" for element, attribute, _ in self.replacements()) + ( + ("mimic.remove",) if self.remove_mimic else ()) + + def replacements(self) -> tuple[tuple[str, str, str], ...]: + values = ( + ("origin", "rpy", self.origin_rpy), + ("limit", "lower", self.limit_lower), + ("limit", "upper", self.limit_upper), + ("mimic", "multiplier", self.mimic_multiplier), + ("mimic", "offset", self.mimic_offset), + ) + return tuple( + (element, attribute, str(value)) + for element, attribute, value in values + if value is not None + ) + + + +@dataclass(frozen=True) +class MujocoEqualityPatch: + """Replacement and optional topology assertion for one equality joint.""" + + polycoef: str + expected_joint1: str | None = None + expected_joint2: str | None = None + + +@dataclass(frozen=True) +class UrdfPatchSet: + """Complete declarative edit set for one generated URDF.""" + + joints: Mapping[str, UrdfJointPatch] + mujoco_equalities: Mapping[str, MujocoEqualityPatch] = field( + default_factory=dict + ) + + def __post_init__(self) -> None: + empty = [ + name for name, patch in self.joints.items() if not patch.requested_fields() + ] + if empty: + raise ValueError( + "URDF joint patch contains no replacements: " + + ",".join(sorted(empty)) + ) + + +def parse_vector3(value: str) -> np.ndarray: + """Parse and validate a finite three-component URDF vector.""" + result = np.asarray([float(item) for item in str(value).split()], dtype=float) + if result.shape != (3,) or not np.all(np.isfinite(result)): + raise ValueError(f"invalid URDF vector: {value}") + return result + + +def corrected_origin_rpy(joint: ET.Element, offset_rad: float) -> str: + """Rotate a joint origin about its declared axis while preserving zero edits.""" + origin = joint.find("origin") + if origin is None or origin.get("rpy") is None: + raise ValueError(f"joint {joint.get('name')} has no origin.rpy") + if abs(float(offset_rad)) <= 1.0e-12: + return str(origin.get("rpy")) + axis_node = joint.find("axis") + axis = parse_vector3( + "1 0 0" if axis_node is None else axis_node.get("xyz", "1 0 0") + ) + norm = float(np.linalg.norm(axis)) + if norm <= 1.0e-12: + raise ValueError(f"joint {joint.get('name')} has a degenerate axis") + source = Rotation.from_euler( + "xyz", parse_vector3(origin.get("rpy", "0 0 0")) + ) + corrected = source * Rotation.from_rotvec( + axis / norm * float(offset_rad) + ) + return " ".join( + f"{float(value):.15g}" for value in corrected.as_euler("xyz") + ) + + +def _replace_attribute( + block: str, element: str, attribute: str, value: str +) -> str: + pattern = re.compile( + rf"(<{element}\b[^>]*\b{attribute}\s*=\s*)([\"'])" + rf"(?P[^\"']*)\2", + re.DOTALL, + ) + match = pattern.search(block) + if match is None: + # URDF permits omitted mimic coefficients (defaults: 1 and 0). A + # coordinate change must be able to materialize an authorized offset. + if (element, attribute) not in {("mimic", "offset"), ("mimic", "multiplier")}: + raise ValueError(f"{element} has no {attribute} attribute") + opening = re.search(rf"<{element}\b[^>]*>", block) + if opening is None: + raise ValueError(f"{element} has no {attribute} attribute: joint has no {element} element") + position = opening.end() - (2 if opening.group(0).endswith("/>") else 1) + return block[:position] + f' {attribute}="{value}"' + block[position:] + start, end = match.span("value") + return block[:start] + str(value) + block[end:] + + +def apply_urdf_patch_text( + original_text: str, + root: ET.Element, + patches: UrdfPatchSet, +) -> str: + """Apply declared patches without serializing unaffected XML.""" + top_level_joints = { + str(joint.get("name")): joint for joint in root.findall("joint") + } + missing_joints = set(patches.joints) - set(top_level_joints) + if missing_joints: + raise ValueError( + "source URDF is missing target joints: " + + ",".join(sorted(missing_joints)) + ) + + equality_nodes = { + str(joint.get("name")): joint + for joint in root.findall("./mujoco/equality/joint") + } + missing_equalities = set(patches.mujoco_equalities) - set(equality_nodes) + if missing_equalities: + raise ValueError( + "source URDF is missing MuJoCo equalities: " + + ",".join(sorted(missing_equalities)) + ) + for name, patch in patches.mujoco_equalities.items(): + node = equality_nodes[name] + if ( + patch.expected_joint1 is not None + and node.get("joint1") != patch.expected_joint1 + ): + raise ValueError(f"MuJoCo equality joint1 differs for {name}") + if ( + patch.expected_joint2 is not None + and node.get("joint2") != patch.expected_joint2 + ): + raise ValueError(f"MuJoCo equality joint2 differs for {name}") + + # Requiring the URDF ``type`` attribute excludes transmission and MuJoCo + # elements which also use the tag name ``joint``. + joint_pattern = re.compile( + r"]*\btype\s*=)[^>]*\bname\s*=\s*" + r"([\"'])(?P[^\"']+)\1[^>]*>" + r".*?", + re.DOTALL, + ) + applied_joints: set[str] = set() + + def replace_joint(match: re.Match[str]) -> str: + name = match.group("name") + patch = patches.joints.get(name) + if patch is None: + return match.group(0) + if name in applied_joints: + raise ValueError(f"duplicate top-level URDF joint text: {name}") + block = match.group(0) + for element, attribute, value in patch.replacements(): + block = _replace_attribute(block, element, attribute, value) + if patch.remove_mimic: + if len(top_level_joints[name].findall("mimic")) != 1: + raise ValueError(f"mimic removal requires one original constraint:{name}") + block, count = re.subn(r"]*(?:/>|>\s*)", "", block) + if count != 1: + raise ValueError(f"could not uniquely remove mimic constraint:{name}") + applied_joints.add(name) + return block + + corrected = joint_pattern.sub(replace_joint, original_text) + if applied_joints != set(patches.joints): + missing = set(patches.joints) - applied_joints + raise ValueError( + "could not locate every target joint in source URDF text: " + + ",".join(sorted(missing)) + ) + + applied_equalities: set[str] = set() + for name, patch in patches.mujoco_equalities.items(): + equality_pattern = re.compile( + rf"(]*\bname\s*=\s*([\"']))" + rf"{re.escape(name)}\2[^>]*>", + re.DOTALL, + ) + matches = list(equality_pattern.finditer(corrected)) + if len(matches) != 1: + raise ValueError(f"could not uniquely locate MuJoCo equality {name}") + match = matches[0] + replacement = _replace_attribute( + match.group(0), "joint", "polycoef", patch.polycoef + ) + corrected = corrected[: match.start()] + replacement + corrected[match.end() :] + applied_equalities.add(name) + if applied_equalities != set(patches.mujoco_equalities): + raise ValueError("could not apply every MuJoCo equality patch") + return corrected + + +def _files_have_identical_contents(left: Path, right: Path) -> bool: + if left.stat().st_size != right.stat().st_size: + return False + with left.open("rb") as left_stream, right.open("rb") as right_stream: + while True: + left_chunk = left_stream.read(1024 * 1024) + right_chunk = right_stream.read(1024 * 1024) + if left_chunk != right_chunk: + return False + if not left_chunk: + return True + + +def _mimic_reachable_ranges( + root: ET.Element, +) -> tuple[dict[str, tuple[float, float]], dict[str, float]]: + """Resolve full mimic chains and report limit excess for each joint.""" + nodes = { + str(node.get("name")): node + for node in root.findall("joint") + if node.get("type") in {"revolute", "prismatic"} + } + resolved: dict[str, tuple[float, float]] = {} + resolving: set[str] = set() + + def resolve(name: str) -> tuple[float, float]: + if name in resolved: + return resolved[name] + if name in resolving: + raise ValueError(f"URDF mimic cycle contains joint: {name}") + node = nodes.get(name) + if node is None: + raise ValueError(f"URDF mimic source joint does not exist: {name}") + limit = node.find("limit") + if limit is None: + raise ValueError(f"bounded URDF joint has no limit: {name}") + lower = float(limit.get("lower", "nan")) + upper = float(limit.get("upper", "nan")) + if not math.isfinite(lower) or not math.isfinite(upper) or lower >= upper: + raise ValueError(f"URDF joint has invalid limits: {name}") + resolving.add(name) + mimic = node.find("mimic") + if mimic is None: + reachable = (lower, upper) + else: + source = str(mimic.get("joint", "")) + multiplier = float(mimic.get("multiplier", "1")) + offset = float(mimic.get("offset", "0")) + if not math.isfinite(multiplier) or not math.isfinite(offset): + raise ValueError(f"URDF joint has invalid mimic values: {name}") + source_range = resolve(source) + endpoints = ( + offset + multiplier * source_range[0], + offset + multiplier * source_range[1], + ) + reachable = (min(endpoints), max(endpoints)) + resolving.remove(name) + resolved[name] = reachable + return reachable + + for joint_name in nodes: + resolve(joint_name) + excess: dict[str, float] = {} + for name, reachable in resolved.items(): + node = nodes[name] + if node.find("mimic") is None: + continue + limit = node.find("limit") + assert limit is not None + lower = float(limit.get("lower", "nan")) + upper = float(limit.get("upper", "nan")) + excess[name] = max(0.0, lower - reachable[0], reachable[1] - upper) + return resolved, excess + + +def validate_urdf_mimic_ranges( + urdf: str | Path, + *, + reference_urdf: str | Path | None = None, + tolerance: float = 1.0e-9, +) -> Mapping[str, tuple[float, float]]: + """Reject new physical-limit violations anywhere in a mimic chain. + + ``reference_urdf`` permits only an already-present CAD rounding excess of + the same joint. Calibration may never enlarge that excess. + """ + root = ET.parse(Path(urdf)).getroot() + ranges, excess = _mimic_reachable_ranges(root) + reference_excess: Mapping[str, float] = {} + if reference_urdf is not None: + _, reference_excess = _mimic_reachable_ranges( + ET.parse(Path(reference_urdf)).getroot() + ) + failures = { + name: value + for name, value in excess.items() + if value > float(reference_excess.get(name, 0.0)) + float(tolerance) + } + if failures: + details = ",".join( + f"{name}={value:.9f}rad" for name, value in sorted(failures.items()) + ) + raise ValueError(f"URDF mimic reachable range exceeds limits: {details}") + return ranges + + +def materialize_relative_mesh_assets( + *, source: Path, output: Path, urdf_root: ET.Element +) -> tuple[Path, ...]: + """Copy safe relative mesh resources beside the generated URDF.""" + filenames = sorted( + { + str(mesh.get("filename", "")).strip() + for mesh in urdf_root.findall(".//mesh") + if str(mesh.get("filename", "")).strip() + } + ) + materialized: list[Path] = [] + for filename in filenames: + if "://" in filename or filename.startswith("package:"): + continue + relative = Path(filename) + if relative.is_absolute() or ".." in relative.parts: + raise ValueError( + f"URDF mesh path must be a safe relative path or URI: {filename}" + ) + source_asset = (source.parent / relative).resolve() + if not source_asset.is_file(): + raise ValueError(f"URDF mesh resource does not exist: {source_asset}") + destination_asset = (output / relative).resolve() + try: + destination_asset.relative_to(output) + except ValueError as error: + raise ValueError( + f"URDF mesh destination escapes output directory: {filename}" + ) from error + if destination_asset == source_asset: + materialized.append(destination_asset) + continue + destination_asset.parent.mkdir(parents=True, exist_ok=True) + if destination_asset.exists(): + if not destination_asset.is_file() or not _files_have_identical_contents( + source_asset, destination_asset + ): + raise ValueError( + "refusing to overwrite a different mesh resource: " + f"{destination_asset}" + ) + materialized.append(destination_asset) + continue + temporary_asset = destination_asset.with_name( + f".{destination_asset.name}.{os.getpid()}.tmp" + ) + if temporary_asset.exists(): + raise ValueError(f"temporary mesh path is occupied: {temporary_asset}") + try: + shutil.copy2(source_asset, temporary_asset) + os.replace(temporary_asset, destination_asset) + finally: + if temporary_asset.exists(): + temporary_asset.unlink() + materialized.append(destination_asset) + return tuple(materialized) + + +def _copy_complete_mesh_directory(source: Path, output: Path) -> None: + source_meshes = source.parent / "meshes" + if not source_meshes.is_dir(): + return + destination_meshes = output / "meshes" + destination_meshes.mkdir(parents=True, exist_ok=True) + for mesh in source_meshes.iterdir(): + if mesh.is_file(): + shutil.copy2(mesh, destination_meshes / mesh.name) + + +def write_urdf_patches( + *, + source_urdf: str | Path, + destination_urdf: str | Path, + patches: UrdfPatchSet, + forbidden_source_stem_patterns: Sequence[str] = (), + copy_complete_mesh_directory: bool = False, + authorized_fields: Mapping[str, Sequence[str]] | None = None, + validate_mimic_ranges: bool = True, + expected_source_sha256: str | None = None, + validate_output: Callable[[Path], None] | None = None, +) -> Path: + """Validate and atomically materialize one patched URDF.""" + source = Path(source_urdf).expanduser().resolve() + destination = Path(destination_urdf).expanduser().resolve() + if not source.is_file(): + raise ValueError(f"source URDF does not exist: {source}") + source_bytes = source.read_bytes() + source_digest = hashlib.sha256(source_bytes).hexdigest() + if expected_source_sha256 is not None and source_digest != expected_source_sha256: + raise ValueError("source URDF SHA256 differs from protected input") + for pattern in forbidden_source_stem_patterns: + if re.search(str(pattern), source.stem, re.IGNORECASE): + raise ValueError( + "source URDF must be the immutable original CAD URDF" + ) + if destination == source or destination.exists() or destination.is_symlink(): + raise ValueError(f"refusing to overwrite URDF: {destination}") + destination.parent.mkdir(parents=True, exist_ok=True) + root = ET.fromstring(source_bytes) + corrected = apply_urdf_patch_text( + source_bytes.decode("utf-8"), root, patches + ) + descriptor, temporary_name = tempfile.mkstemp(prefix=".urdf-validation-", suffix=".urdf", dir=destination.parent) + temporary = Path(temporary_name) + try: + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + stream.write(corrected) + stream.flush() + os.fsync(stream.fileno()) + # Reparse both documents and prove that patching preserved topology, + # mesh/inertial/collision/visual data, and every non-requested field. + # The local import avoids a module cycle with ``validate``. + from .validate import validate_structural_urdf_diff + + requested_authorization = { + name: patch.requested_fields() + for name, patch in patches.joints.items() + } + authorization = ( + requested_authorization + if authorized_fields is None + else { + str(name): tuple(str(field) for field in fields) + for name, fields in authorized_fields.items() + } + ) + for name, requested in requested_authorization.items(): + unauthorized = set(requested) - set(authorization.get(name, ())) + if unauthorized: + raise ValueError( + "URDF patch requested fields absent from Profile authorization: " + f"{name}:" + ",".join(sorted(unauthorized)) + ) + validate_structural_urdf_diff( + source, + temporary, + authorized_fields=authorization, + authorized_mujoco_equalities=tuple(patches.mujoco_equalities), + expected_source_sha256=source_digest, + ) + # This belongs to the common writer rather than individual model + # serializers: every emitted URDF must have valid finite joint limits, + # existing mimic sources, acyclic chains, and no newly enlarged mimic + # range violation. Pre-existing CAD rounding excess is tolerated only + # when calibration does not make it worse. + if validate_mimic_ranges: + validate_urdf_mimic_ranges(temporary, reference_urdf=source) + if validate_output is not None: + validate_output(temporary) + materialize_relative_mesh_assets( + source=source, output=destination.parent, urdf_root=root + ) + if copy_complete_mesh_directory: + _copy_complete_mesh_directory(source, destination.parent) + if hashlib.sha256(source.read_bytes()).hexdigest() != source_digest: + raise ValueError("source URDF changed during validation") + # Atomic no-clobber installation. A concurrent writer (or user file) + # must never be overwritten or removed by our failure cleanup. + os.link(temporary, destination) + finally: + if temporary.exists(): + temporary.unlink() + return destination + + +__all__ = [ + "MujocoEqualityPatch", + "UrdfJointPatch", + "UrdfPatchSet", + "apply_urdf_patch_text", + "materialize_relative_mesh_assets", + "validate_urdf_mimic_ranges", + "write_urdf_patches", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/plan.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/plan.py new file mode 100644 index 0000000..39783a9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/plan.py @@ -0,0 +1,309 @@ +"""One authorization plan shared by URDF writers and validators.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import hashlib +from pathlib import Path +from typing import Mapping, Sequence +import math +import xml.etree.ElementTree as ET + +from ..domain import CalibrationProfile +from ..fitting.coupling import LinearMimicFit +from .kinematics import UrdfKinematicModel, corrected_mimic_offset +from .patch import UrdfJointPatch, UrdfPatchSet, corrected_origin_rpy, write_urdf_patches +from .limits import MotionRangeEvidence, validate_range_evidence +from .joint_control import independent_export_authorization, AFFINE_MIMIC_APPROXIMATION, PRESERVE_SOURCE_MIMIC +from .source_mimic import MimicEnvelope, compile_source_mimic_envelopes + + +@dataclass(frozen=True) +class StandardUrdfPlan: + """Frozen coordinate transform plus independently declared field rights. + + Limits are expressed in output coordinates. Mimic fits enter in CAD + coordinates and are transformed exactly once here, including chains whose + parent is a passive joint. Current measured exports preserve source mimic + parameters as a standalone fallback; their JSON curves remain independent. + """ + + source_sha256: str + zero_offsets_rad: Mapping[str, float] + limits_output_rad: Mapping[str, tuple[float, float]] + mimic_output: Mapping[str, tuple[str, float, float]] + patches: UrdfPatchSet + authorized_fields: Mapping[str, Sequence[str]] + range_evidence: Mapping[str, MotionRangeEvidence] = field(default_factory=dict) + independent_joint_sources: Mapping[str, str] | None = None + mimic_policy: str | None = None + mimic_envelopes: Mapping[str, MimicEnvelope] = field(default_factory=dict) + + def write(self, source_urdf: str | Path, destination_urdf: str | Path) -> Path: + source = Path(source_urdf) + if hashlib.sha256(source.read_bytes()).hexdigest() != self.source_sha256: + raise ValueError("protected source URDF SHA256 changed before write") + return write_urdf_patches( + source_urdf=source, destination_urdf=destination_urdf, + patches=self.patches, authorized_fields=self.authorized_fields, + expected_source_sha256=self.source_sha256, + ) + + +def build_standard_correction_plan( + *, source_urdf: str | Path, source_sha256: str, + zero_offsets_rad: Mapping[str, float], + authorized_fields: Mapping[str, Sequence[str]], + measured_ranges_output_rad: Mapping[str, tuple[float, float]] | None = None, + fitted_mimics_cad: Mapping[str, LinearMimicFit] | None = None, + transferred_zero_sources: Mapping[str, str] | None = None, + require_shared_mimic_zero: bool = False, + range_evidence: Mapping[str, MotionRangeEvidence] | None = None, + independent_joint_channels: Mapping[str, int] | None = None, + fitted_mimics_output: Mapping[str, LinearMimicFit] | None = None, + preserve_source_mimic: bool = False, + allow_single_training_cycle: bool = False, +) -> StandardUrdfPlan: + """Generate authorized standard-URDF edits, never clamp an invalid fit. + + q_CAD = q_output + delta. Consequently both bounds shift by -delta and + b_output = b_CAD + a*delta_parent - delta_child. Unobserved joints retain + their own CAD geometry and physical range, including transferred joints. + An explicit training-supported motion envelope can replace nominal CAD + limits; separately declared hardware safety bounds remain mandatory. + With preserve_source_mimic, the original coefficients are kept verbatim + as an approximation in output coordinates, not rebased as a physical law. + """ + source = Path(source_urdf) + if hashlib.sha256(source.read_bytes()).hexdigest() != source_sha256: + raise ValueError("protected source URDF SHA256 mismatch") + model = UrdfKinematicModel(source) + if preserve_source_mimic and (fitted_mimics_cad is not None or fitted_mimics_output is not None + or require_shared_mimic_zero or independent_joint_channels is not None): + raise ValueError("preserved_source_mimic_cannot_be_fitted_rebased_or_removed") + approximations = dict(fitted_mimics_output or {}) + if fitted_mimics_output is not None: + if fitted_mimics_cad or require_shared_mimic_zero or independent_joint_channels is not None: + raise ValueError("affine_mimic_export_requires_output_coordinate_approximations") + if set(approximations) != {name for name, joint in model.joints.items() if joint.mimic_joint}: + raise ValueError("affine_mimic_export_requires_all_source_couplings") + independent_sources = None + if independent_joint_channels is not None: + if fitted_mimics_cad or require_shared_mimic_zero: + raise ValueError("independent_joint_export_cannot_apply_linear_mimic_fits") + independent_sources = {name: joint.mimic_joint for name, joint in model.joints.items() + if joint.mimic_joint is not None} + authorized_fields = independent_export_authorization( + model, independent_joint_channels, independent_sources, authorized_fields) + nodes = {str(node.get("name")): node for node in ET.parse(source).getroot().findall("joint")} + offsets = {str(name): float(value) for name, value in zero_offsets_rad.items()} + ranges = dict(measured_ranges_output_rad or {}) + mimics = dict(fitted_mimics_cad or {}) + motion_ranges = dict(range_evidence or {}) + if not motion_ranges.keys() <= ranges.keys(): + raise ValueError("motion range evidence requires explicit output ranges") + requested = set(offsets) | set(ranges) | set(mimics) | set(approximations) + if not requested <= model.joints.keys(): + raise ValueError("correction references a missing URDF joint") + for target, donor in (transferred_zero_sources or {}).items(): + if target == donor or target not in offsets or donor not in offsets: + raise ValueError("transfer requires distinct, explicitly solved donor and recipient") + if not math.isclose(offsets[target], offsets[donor], rel_tol=0, abs_tol=1e-12): + raise ValueError("transferred scalar zero differs from its declared donor") + if target in ranges: + raise ValueError("unmeasured transfer must retain recipient CAD physical range") + for name, value in offsets.items(): + if not math.isfinite(value) or model.joints[name].kind not in {"revolute", "continuous"}: + raise ValueError("zero corrections require finite revolute coordinates") + envelopes = {} + if preserve_source_mimic: + base_ranges = {name: tuple(ranges.get(name, (joint.lower-offsets.get(name, 0), + joint.upper-offsets.get(name, 0)))) for name, joint in model.joints.items() if joint.lower is not None} + envelopes = compile_source_mimic_envelopes(model, base_ranges, offsets, motion_ranges) + edits: dict[str, UrdfJointPatch] = {} + output_ranges: dict[str, tuple[float, float]] = {} + output_mimics: dict[str, tuple[str, float, float]] = {} + for name, joint in model.joints.items(): + delta = offsets.get(name, 0.0) + fields: dict[str, str | bool] = {} + if delta != 0: + fields["origin_rpy"] = corrected_origin_rpy(nodes[name], delta) + if joint.lower is not None: + mechanical = (joint.lower - delta, joint.upper - delta) + interval = tuple(float(v) for v in ranges.get(name, mechanical)) + if len(interval) != 2 or not all(math.isfinite(v) for v in interval) or interval[0] >= interval[1]: + raise ValueError(f"invalid corrected interval: {name}") + if name in motion_ranges: + validate_range_evidence(name, joint, delta, interval, motion_ranges[name], + allow_single_training_cycle=allow_single_training_cycle) + elif interval[0] < mechanical[0] - 1e-9 or interval[1] > mechanical[1] + 1e-9: + raise ValueError(f"corrected range exceeds source mechanical range: {name}") + if name in envelopes: + if interval != envelopes[name].base_limits_rad: + raise ValueError(f"source_mimic_base_range_differs_from_policy:{name}") + interval = envelopes[name].output_limits_rad + output_ranges[name] = interval + if interval[0] != joint.lower: + fields["limit_lower"] = f"{interval[0]:.15g}" + if interval[1] != joint.upper: + fields["limit_upper"] = f"{interval[1]:.15g}" + elif name in ranges: + raise ValueError(f"cannot bound an unbounded joint without changing its contract: {name}") + if name in mimics and joint.mimic_joint is None: + raise ValueError(f"cannot create a new mimic topology: {name}") + if joint.mimic_joint is not None and independent_sources is not None: + fields["remove_mimic"] = True + elif joint.mimic_joint is not None: + fit = approximations.get(name, mimics.get(name)) + if fit is not None: + if not isinstance(fit, LinearMimicFit) or fit.target_joint != name or fit.source_joint != joint.mimic_joint: + raise ValueError(f"mimic fit does not match source URDF topology: {name}") + if fit.training_cycles != (0, 1, 2) or not fit.residuals_rad or not all(math.isfinite(v) for v in fit.residuals_rad): + raise ValueError(f"mimic fit lacks training-only evidence: {name}") + if name not in approximations and not fit.offset_observed and not math.isclose(fit.offset_rad, joint.mimic_offset, rel_tol=0, abs_tol=1e-12): + raise ValueError(f"unobservable passive static offset must retain CAD: {name}") + multiplier, offset = fit.multiplier, fit.offset_rad + else: + multiplier, offset = joint.mimic_multiplier, joint.mimic_offset + if not math.isfinite(multiplier) or not math.isfinite(offset): + raise ValueError(f"nonfinite mimic fit: {name}") + shifted = offset if preserve_source_mimic or name in approximations else corrected_mimic_offset( + multiplier, offset, offsets.get(joint.mimic_joint, 0), delta) + if require_shared_mimic_zero: + if fit is None or not fit.offset_observed or abs(shifted) > 1e-12: + raise ValueError(f"mimic lacks two supported baseline datums:{name}") + shifted = 0.0 # Normalize only floating-point cancellation in the coordinate conversion. + output_mimics[name] = (joint.mimic_joint, multiplier, shifted) + if multiplier != joint.mimic_multiplier: + fields["mimic_multiplier"] = f"{multiplier:.15g}" + if shifted != joint.mimic_offset: + fields["mimic_offset"] = f"{shifted:.15g}" + if fields: + patch = UrdfJointPatch(**fields) + rights = set(authorized_fields.get(name, ())) + if not set(patch.requested_fields()) <= rights: + raise ValueError(f"correction requests a field absent from Profile authorization: {name}") + edits[name] = patch + # Reject inconsistent full mimic ranges before creating any artifacts. + reachable: dict[str, tuple[float, float]] = {} + + def resolve(name: str) -> tuple[float, float]: + if name in reachable: + return reachable[name] + if name in output_mimics: + parent, a, b = output_mimics[name] + bounds = resolve(parent) + values = (a*bounds[0] + b, a*bounds[1] + b) + interval = (min(values), max(values)) + elif name in output_ranges: + interval = output_ranges[name] + else: + raise ValueError(f"mimic source has no bounded mechanical interval: {name}") + if name in output_ranges and (interval[0] < output_ranges[name][0] - 1e-9 or interval[1] > output_ranges[name][1] + 1e-9): + raise ValueError(f"URDF mimic reachable range exceeds limits: {name}") + reachable[name] = interval + return interval + + for name in output_mimics: + resolve(name) + return StandardUrdfPlan(source_sha256, offsets, output_ranges, output_mimics, + UrdfPatchSet(edits), {name: tuple(fields) for name, fields in authorized_fields.items()}, + motion_ranges, independent_sources, + PRESERVE_SOURCE_MIMIC if preserve_source_mimic else ( + AFFINE_MIMIC_APPROXIMATION if fitted_mimics_output is not None else None), envelopes) + + +@dataclass(frozen=True) +class UrdfCorrectionPlan: + source_sha256: str + allowed_active_joints: frozenset[str] + endpoint_limit_joints: frozenset[str] + mimic_source_by_joint: Mapping[str, str] + frozen_joints: frozenset[str] + frozen_offsets_rad: Mapping[str, float] = field(default_factory=dict) + forbid_calibrated_source: bool = True + forbid_overwrite: bool = True + preserve_passive_joints: bool = True + authorized_fields: Mapping[str, Sequence[str]] = field(default_factory=dict) + + def __post_init__(self) -> None: + if len(self.source_sha256) != 64 or any( + character not in "0123456789abcdef" + for character in self.source_sha256.lower() + ): + raise ValueError("source URDF SHA-256 is invalid") + if self.allowed_active_joints & self.frozen_joints: + raise ValueError("allowed and frozen URDF joints overlap") + applied = self.allowed_active_joints | set(self.frozen_offsets_rad) + if not set(self.frozen_offsets_rad).issubset(self.frozen_joints): + raise ValueError("frozen offsets must belong to frozen joints") + if not self.endpoint_limit_joints.issubset(applied): + raise ValueError("endpoint limit joint is not an applied active joint") + if set(self.mimic_source_by_joint) & self.allowed_active_joints: + raise ValueError("dependent mimic joints cannot be active edit targets") + + def authorize_offsets(self, offsets_rad: Mapping[str, float]) -> None: + required = self.allowed_active_joints | set(self.frozen_offsets_rad) + unexpected = set(offsets_rad) - required + if unexpected: + raise ValueError( + "URDF correction contains unauthorized joints: " + + ", ".join(sorted(unexpected)) + ) + missing = required - set(offsets_rad) + if missing: + raise ValueError( + "URDF correction is missing active joints: " + + ", ".join(sorted(missing)) + ) + changed_frozen = { + name + for name, expected in self.frozen_offsets_rad.items() + if abs(float(offsets_rad[name]) - float(expected)) > 1.0e-12 + } + if changed_frozen: + raise ValueError( + "URDF correction changed frozen offsets: " + + ", ".join(sorted(changed_frozen)) + ) + + def verify_source(self, source_urdf: str | Path) -> None: + digest = hashlib.sha256(Path(source_urdf).read_bytes()).hexdigest() + if digest != self.source_sha256.lower(): + raise ValueError("source URDF SHA-256 differs from correction plan") + + +def build_correction_plan( + profile: CalibrationProfile, + *, + source_sha256: str, + scope: str, + frozen_offsets_rad: Mapping[str, float] | None = None, +) -> UrdfCorrectionPlan: + """Build one scope-aware edit authorization from typed policies.""" + selected = profile.scope.selected_joints(scope) + frozen = profile.scope.frozen_joints[str(scope)] + expected_frozen = { + str(name): float(value) + for name, value in dict(frozen_offsets_rad or {}).items() + } + if set(expected_frozen) != set(frozen): + missing = set(frozen) - set(expected_frozen) + extra = set(expected_frozen) - set(frozen) + raise ValueError( + "frozen URDF offset state differs from scope policy: " + f"missing={','.join(sorted(missing)) or '-'};" + f"extra={','.join(sorted(extra)) or '-'}" + ) + applied = selected | frozen + return UrdfCorrectionPlan( + source_sha256=source_sha256, + allowed_active_joints=selected, + endpoint_limit_joints=( + profile.zero.mechanical_endpoint_joints & applied + ), + mimic_source_by_joint=profile.zero.mimic_source_by_joint, + frozen_joints=frozen | profile.zero.cad_frozen_joints, + frozen_offsets_rad=expected_frozen, + authorized_fields=profile.urdf_authorized_fields, + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/result_plan.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/result_plan.py new file mode 100644 index 0000000..9b43676 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/result_plan.py @@ -0,0 +1,88 @@ +"""Prepare one standard-coordinate artifact result before serialization.""" + +from __future__ import annotations + +from dataclasses import dataclass, replace +from pathlib import Path +from typing import Mapping + +from ..domain.profile import CalibrationProfile +from ..domain.result import CalibrationResult, JointMapping +from .kinematics import UrdfKinematicModel +from .plan import StandardUrdfPlan, build_standard_correction_plan + + +@dataclass(frozen=True) +class PreparedCalibration: + plan: StandardUrdfPlan + mappings: Mapping[str, JointMapping] + + +def prepare_standard_result(profile: CalibrationProfile, source: Path, + source_sha256: str, fit: CalibrationResult) -> PreparedCalibration: + model = UrdfKinematicModel(source) + if profile.artifacts.output_schema_version >= 3: + return prepare_measured_result(profile, model, source_sha256, fit) + mimics = {name: evidence.fit for name, evidence in fit.standard_mimic_evidence.items()} + for target, donor in profile.zero.transferred_mimic_sources.items(): + original = model.joints[target] + mimics[target] = replace(mimics[donor], target_joint=target, + source_joint=original.mimic_joint, offset_rad=original.mimic_offset) + ranges = {name: mapping.bounds_rad for name, mapping in fit.output_mappings.items() + if name not in profile.zero.transferred_zero_sources} + for name, mapping in fit.command_mappings.items(): + if name in ranges: + lo, hi = ranges[name] + ranges[name] = (min(lo, mapping.bounds_rad[0]), max(hi, mapping.bounds_rad[1])) + plan = build_standard_correction_plan(source_urdf=source, source_sha256=source_sha256, + zero_offsets_rad=fit.zero_offsets_rad, measured_ranges_output_rad=ranges, + fitted_mimics_cad=mimics, transferred_zero_sources=profile.zero.transferred_zero_sources, + authorized_fields=profile.urdf_authorized_fields) + mappings = dict(fit.output_mappings) + for name, mapping in mappings.items(): + lo, hi = plan.limits_output_rad[name] + actual_lo, actual_hi = mapping.bounds_rad + if actual_lo < lo - 1e-9 or actual_hi > hi + 1e-9: + raise ValueError(f"transferred mapping exceeds recipient CAD physical range:{name}") + def resolve(joint): + if joint in mappings: + return mappings[joint] + source_joint, multiplier, offset = plan.mimic_output[joint] + parent = resolve(source_joint) + branches = [tuple(offset + multiplier*v for v in values) + for values in (parent.angle_rad, parent.increasing_rad, parent.decreasing_rad)] + mappings[joint] = JointMapping(joint, parent.motor_index, parent.input_domain, + parent.knots, *branches, profile.zero.transferred_mimic_sources.get(joint)) + return mappings[joint] + for joint in plan.mimic_output: + resolve(joint) + return PreparedCalibration(plan, mappings) + + +def prepare_measured_result(profile, model, source_sha256, fit): + moving = {name for name, joint in model.joints.items() if joint.kind != "fixed"} + moving -= profile.retained_joints + missing = moving - fit.output_mappings.keys() + geometry = moving - fit.zero_offsets_rad.keys() + if missing or geometry: + raise ValueError(f"independent_release_incomplete:unmeasured={sorted(missing)}:absolute_geometry={sorted(geometry)}") + if set(fit.output_mappings) != moving: + raise ValueError("independent_release_contains_transferred_or_unknown_joints") + from ..fitting.motion_transfer import validate_mapping_provenance, validate_zero_provenance + validate_mapping_provenance(profile, fit) + validate_zero_provenance(profile, fit) + passive = {name for name, joint in model.joints.items() if joint.mimic_joint} + # Measured support and the original linear fallback have separate envelopes. + # Only explicit nominal-limit policies permit expansion beyond CAD bounds. + ranges = {name: (min(fit.output_mappings[name].bounds_rad[0], fit.command_mappings[name].bounds_rad[0], 0), + max(fit.output_mappings[name].bounds_rad[1], fit.command_mappings[name].bounds_rad[1], 0)) + for name in moving - passive} + from .limits import compile_motion_ranges + range_evidence = compile_motion_ranges(profile, model, fit) + ranges.update({name: evidence.output_limits_rad for name, evidence in range_evidence.items()}) + plan = build_standard_correction_plan(source_urdf=model.source, source_sha256=source_sha256, + zero_offsets_rad=fit.zero_offsets_rad, measured_ranges_output_rad=ranges, + authorized_fields=profile.urdf_authorized_fields, + preserve_source_mimic=True, + range_evidence=range_evidence) + return PreparedCalibration(plan, dict(fit.output_mappings)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/source_mimic.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/source_mimic.py new file mode 100644 index 0000000..395371e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/source_mimic.py @@ -0,0 +1,120 @@ +"""Original CAD mimic fallback and its minimal representation envelopes. + +The measured JSON curves own actual joint motion. A retained CAD mimic is a +standalone approximation, including its original offset in output coordinates. +Its envelope is recorded separately from training evidence, never as additional +measured travel. Declared hardware bounds and default hard CAD bounds still apply. +""" + +from dataclasses import asdict, dataclass +import math +import xml.etree.ElementTree as ET + + +@dataclass(frozen=True) +class MimicEnvelope: + base_limits_rad: tuple[float, float] + mimic_reachable_limits_rad: tuple[float, float] + output_limits_rad: tuple[float, float] + + +def _resolve_envelopes(model, ranges, bases): + reachable, envelopes, visiting = {}, {}, set() + + def resolve(name): + if name in reachable: + return reachable[name] + if name in visiting: + raise ValueError(f"source_mimic_cycle:{name}") + if name not in model.joints: + raise ValueError(f"source_mimic_parent_missing:{name}") + visiting.add(name) + joint = model.joints[name] + if joint.mimic_joint is None: + if name not in ranges: + raise ValueError(f"source_mimic_requires_bounded_parent:{name}") + interval = ranges[name] + if (len(interval) != 2 or any(v is None or not math.isfinite(v) for v in interval) + or interval[0] >= interval[1]): + raise ValueError(f"invalid_source_mimic_parent_range:{name}") + else: + if not all(math.isfinite(v) for v in (joint.mimic_multiplier, joint.mimic_offset)): + raise ValueError(f"invalid_source_mimic_coefficients:{name}") + parent = resolve(joint.mimic_joint) + endpoints = [joint.mimic_multiplier*v+joint.mimic_offset for v in parent] + interval = (min(endpoints), max(endpoints)) + base = bases[name] + if len(base) != 2 or not all(math.isfinite(v) for v in base) or base[0] >= base[1]: + raise ValueError(f"invalid_source_mimic_base_range:{name}") + output = (min(base[0], interval[0]), max(base[1], interval[1])) + envelopes[name] = MimicEnvelope(base, interval, output) + visiting.remove(name) + reachable[name] = interval + return interval + + for name in bases: + resolve(name) + return envelopes + + +def compile_source_mimic_envelopes(model, ranges, offsets, motion_ranges): + """Compute from source coefficients and trusted ranges; never refit or pad.""" + bases = {} + for name, joint in model.joints.items(): + if joint.mimic_joint is None: + continue + if joint.lower is None: + raise ValueError(f"source_mimic_requires_bounded_child:{name}") + delta = offsets.get(name, 0.0) + bases[name] = (motion_ranges[name].output_limits_rad if name in motion_ranges else + (joint.lower-delta, joint.upper-delta)) + envelopes = _resolve_envelopes(model, ranges, bases) + for name, envelope in envelopes.items(): + evidence = motion_ranges.get(name) + delta = offsets.get(name, 0.0) + safety = (evidence.independent_safety_limits_cad_rad if evidence is not None else + (model.joints[name].lower, model.joints[name].upper)) + if safety is not None: + lo, hi = envelope.output_limits_rad + if lo+delta < safety[0]-1e-9 or hi+delta > safety[1]+1e-9: + raise ValueError(f"source_mimic_exceeds_safety_range:{name}:" + f"required_cad_rad=({lo+delta:.9g},{hi+delta:.9g}):" + f"allowed_cad_rad=({safety[0]:.9g},{safety[1]:.9g})") + return envelopes + + +def validate_source_mimic_elements(source, output): + """Even omitted coefficient attributes must stay omitted in new exports.""" + def elements(path): + return {node.get("name"): [ET.tostring(item, encoding="unicode").strip() + for item in node.findall("mimic")] + for node in ET.parse(path).getroot().findall("joint")} + if elements(source) != elements(output): + raise ValueError("exported_mimic_differs_from_source_urdf") + + +def validate_serialized_mimic_envelopes(payload, model): + """Check declared minimal envelopes against the actual exported model.""" + declared = payload["urdf_correction"].get("mimic_envelopes") + passive = {name for name, joint in model.joints.items() if joint.mimic_joint is not None} + if not isinstance(declared, dict) or set(declared) != passive: + raise ValueError("source_mimic_envelope_coverage_differs") + keys = {"base_limits_rad", "mimic_reachable_limits_rad", "output_limits_rad"} + for name, row in declared.items(): + if not isinstance(row, dict) or set(row) != keys: + raise ValueError(f"invalid_source_mimic_envelope:{name}") + for key, values in row.items(): + if (not isinstance(values, (list, tuple)) or len(values) != 2 + or any(type(v) not in (float, int) or not math.isfinite(v) for v in values) + or values[0] > values[1] + or (key != "mimic_reachable_limits_rad" and values[0] == values[1])): + raise ValueError(f"invalid_source_mimic_envelope:{name}:{key}") + ranges = {name: (j.lower, j.upper) for name, j in model.joints.items() if j.lower is not None} + expected = _resolve_envelopes(model, ranges, + {name: tuple(row["base_limits_rad"]) for name, row in declared.items()}) + for name, envelope in expected.items(): + for key, values in asdict(envelope).items(): + if any(abs(a-b) > 1e-10 for a, b in zip(values, declared[name][key])): + raise ValueError(f"source_mimic_envelope_differs:{name}:{key}") + if any(abs(a-b) > 1e-10 for a, b in zip(envelope.output_limits_rad, ranges[name])): + raise ValueError(f"source_mimic_envelope_differs_from_urdf:{name}") diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/tag_acceptance.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/tag_acceptance.py new file mode 100644 index 0000000..14a2ca7 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/tag_acceptance.py @@ -0,0 +1,107 @@ +"""Replay raw fourth-cycle Tag poses with the *written* URDF and JSON. + +Mounting transforms and base registration are frozen from training. Measured +v3 motion uses the complete JSON mapping, including nonlinear passive joints; +standard URDF mimic is evaluated separately as an approximation. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..fitting.tag_installation import FrozenTagInstallation, rigid_matrix +from .acceptance import SerializedJointMapping, angular_metrics +from .kinematics import UrdfKinematicModel +from .joint_control import independent_joint_sources + + +POSITION_P95_LIMIT_M = 0.003 + + +@dataclass(frozen=True) +class TagHoldout: + sample_id: str + role: str + cycle: int + sdk_values: tuple[float, ...] + sdk_directions_by_joint: Mapping[str, str] + common_from_tag: tuple[tuple[float, ...], ...] + + +def validate_serialized_tag_holdout( + *, corrected_urdf: str | Path, payload: Mapping[str, Any], + common_from_base, installations: Mapping[str, FrozenTagInstallation], + observations: Sequence[TagHoldout], required_roles: Sequence[str], + minimum_samples: int = 40, + input_kind: str = "feedback", + mimic_approximation: bool = False, + enforce_precision: bool = True, + holdout_cycle: int = 3, +) -> dict[str, dict[str, Any]]: + if holdout_cycle not in {3, 5}: + raise ValueError("Tag validation requires a declared independent partition") + model = UrdfKinematicModel(corrected_urdf) + mapping = SerializedJointMapping(payload, input_kind=input_kind) + base = rigid_matrix(common_from_base) + roles = frozenset(required_roles) + if not roles or not roles <= installations.keys() or minimum_samples < 1: + raise ValueError("final Tag holdout requires declared frozen installations") + active = tuple(name for name, joint in model.joints.items() + if joint.kind != "fixed" and joint.mimic_joint is None) + # Full measured motion must use the JSON angles rather than the approximate + # mimic. Correction version 2 is the historical mimic-free export. + independent = mapping.measured and not mimic_approximation and independent_joint_sources(payload) is None + if independent: + active = tuple(name for name, joint in model.joints.items() if joint.kind != "fixed") + if mapping.retained_joints: + from .partial_scope import retained_from_payload, require_retained_pose + retained_from_payload(payload, model) + active = tuple(name for name in active if name not in mapping.retained_joints) + training_ids = {sample for mount in installations.values() for sample in mount.training_sample_ids} + seen = set() + errors: dict[str, list[tuple[float, float]]] = {role: [] for role in roles} + for row in observations: + if row.cycle != holdout_cycle or not row.sample_id or row.sample_id in training_ids: + raise ValueError("final Tag holdout overlaps training or has no image identity") + if row.role not in roles: + raise ValueError("final Tag holdout contains an undeclared Tag") + identity = (row.role, row.sample_id) + if identity in seen: + raise ValueError("duplicate final Tag holdout image") + seen.add(identity) + mount = installations[row.role] + if mount.role != row.role or mount.link not in model.links: + raise ValueError("frozen Tag installation has a different role/link") + if mapping.retained_joints: + require_retained_pose(mapping.retained_joints, row.sdk_values, model=model, link=mount.link) + angles = mapping.evaluate(row.sdk_values, "", active_joints=active, + directions_by_joint=row.sdk_directions_by_joint) + for name, value in model.resolve_angles(angles, independent_mimic_angles=independent).items(): + joint = model.joints[name] + if joint.lower is not None and not joint.lower - 1e-9 <= value <= joint.upper + 1e-9: + raise ValueError(f"serialized URDF motion exceeds joint limit:{name}") + transform = np.eye(4) if mount.link == model.root_link else model.link_transform( + model.parent_joint_by_child[mount.link], zero_offsets={}, joint_angles=angles, + independent_mimic_angles=independent) + predicted = base @ transform @ rigid_matrix(mount.link_from_tag) + observed = rigid_matrix(row.common_from_tag) + angle = float(Rotation.from_matrix(predicted[:3, :3].T @ observed[:3, :3]).magnitude()) + distance = float(np.linalg.norm(predicted[:3, 3] - observed[:3, 3])) + errors[row.role].append((angle, distance)) + results = {} + for role, values in errors.items(): + if len(values) < minimum_samples: + raise ValueError(f"missing independent Tag holdout samples:{role}:{len(values)}") + metrics = angular_metrics([value[0] for value in values]) + translation_p95 = float(np.percentile([value[1] for value in values], 95)) + if enforce_precision and (not metrics.passed or translation_p95 > POSITION_P95_LIMIT_M): + raise ValueError(f"serialized_urdf_tag_holdout_failed:{role}:mae_deg={metrics.mae_deg}:p95_deg={metrics.p95_deg}:max_deg={metrics.maximum_deg}:translation_p95_m={translation_p95}") + results[role] = {"count": metrics.count, "mae_deg": metrics.mae_deg, + "p95_deg": metrics.p95_deg, "maximum_deg": metrics.maximum_deg, + "translation_p95_m": translation_p95} + return results diff --git a/src/linkerhand_calibration/linkerhand_calibration/core/urdf/validate.py b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/validate.py new file mode 100644 index 0000000..987c127 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/core/urdf/validate.py @@ -0,0 +1,188 @@ +"""Post-write structural and runtime-range validation for corrected URDFs.""" + +from __future__ import annotations + +import hashlib +import math +from pathlib import Path +from typing import Mapping, Sequence +import xml.etree.ElementTree as ET + + +URDF_FIELD_TO_XML = { + "origin.rpy": ("origin", "rpy"), + "limit.lower": ("limit", "lower"), + "limit.upper": ("limit", "upper"), + "mimic.multiplier": ("mimic", "multiplier"), + "mimic.offset": ("mimic", "offset"), +} + + +def validate_structural_urdf_diff( + source_urdf: str | Path, + corrected_urdf: str | Path, + *, + authorized_fields: Mapping[str, Sequence[str]], + authorized_mujoco_equalities: Sequence[str] = (), + expected_source_sha256: str | None = None, +) -> tuple[str, ...]: + """Prove that every parsed XML difference is explicitly authorized.""" + source_path = Path(source_urdf) + corrected_path = Path(corrected_urdf) + digest = hashlib.sha256(source_path.read_bytes()).hexdigest() + if expected_source_sha256 is not None and digest != str( + expected_source_sha256 + ).lower(): + raise ValueError("source URDF SHA256 differs from protected input") + source = ET.parse(source_path).getroot() + corrected = ET.parse(corrected_path).getroot() + allowed = { + str(joint): frozenset(str(field) for field in fields) + for joint, fields in authorized_fields.items() + } + allowed_equalities = frozenset( + str(name) for name in authorized_mujoco_equalities + ) + unsupported = { + field + for fields in allowed.values() + for field in fields + if field not in URDF_FIELD_TO_XML and field != "mimic.remove" + } + if unsupported: + raise ValueError( + "unsupported authorized URDF fields: " + ",".join(sorted(unsupported)) + ) + changes: list[str] = [] + + def compare( + left: ET.Element, + right: ET.Element, + path: str, + joint_name: str | None, + joint_child_tag: str | None, + ) -> None: + if left.tag != right.tag: + raise ValueError(f"URDF topology changed at {path}") + current_joint = joint_name + current_child = joint_child_tag + if path == "/robot" and left.tag != "robot": + raise ValueError("URDF root is not robot") + if left.tag == "joint" and path.count("/") == 2: + if left.get("name") != right.get("name"): + raise ValueError(f"URDF joint topology changed at {path}") + current_joint = str(left.get("name", "")) + current_child = None + elif current_joint is not None and path.count("/") == 3: + current_child = left.tag + else: + # Authorization applies only to direct children of robot/joint. + # An extension's nested origin is not the kinematic joint origin. + current_child = None + if (left.text or "").strip() != (right.text or "").strip(): + raise ValueError(f"URDF element text changed at {path}") + keys = set(left.attrib) | set(right.attrib) + for attribute in sorted(keys): + before = left.attrib.get(attribute) + after = right.attrib.get(attribute) + if before == after: + continue + equality_change = bool( + left.tag == "joint" + and "/mujoco" in path + and str(left.get("name", "")) in allowed_equalities + and attribute == "polycoef" + ) + if equality_change: + changes.append( + f"mujoco.equality.{left.get('name')}.polycoef" + ) + continue + field = next( + ( + name + for name, location in URDF_FIELD_TO_XML.items() + if location == (current_child, attribute) + ), + None, + ) + if ( + current_joint is None + or field is None + or field not in allowed.get(current_joint, frozenset()) + ): + raise ValueError( + "corrected URDF changed an unauthorized field: " + f"{path}@{attribute}" + ) + changes.append(f"{current_joint}.{field}") + left_children = list(left) + right_children = list(right) + if (left.tag == "joint" and path.count("/") == 2 + and "mimic.remove" in allowed.get(current_joint, ()) + and len(left.findall("mimic")) == 1 and not right.findall("mimic")): + left_children = [child for child in left_children if child.tag != "mimic"] + changes.append(f"{current_joint}.mimic.remove") + if len(left_children) != len(right_children): + raise ValueError(f"URDF topology changed at {path}") + for index, (left_child, right_child) in enumerate( + zip(left_children, right_children) + ): + left_identity = ( + left_child.tag, + left_child.get("name"), + left_child.get("link"), + ) + right_identity = ( + right_child.tag, + right_child.get("name"), + right_child.get("link"), + ) + if left_identity != right_identity: + raise ValueError(f"URDF child ordering/topology changed at {path}") + compare( + left_child, + right_child, + f"{path}/{left_child.tag}[{index}]", + current_joint, + current_child, + ) + + compare(source, corrected, "/robot", None, None) + return tuple(changes) + + +def validate_runtime_curve_limits( + corrected_urdf: str | Path, + curves_rad: Mapping[str, Sequence[float]], +) -> None: + """Reject JSON/runtime curves that exceed their corrected URDF limits.""" + root = ET.parse(Path(corrected_urdf)).getroot() + joints = {str(node.get("name")): node for node in root.findall("joint")} + for name, values in curves_rad.items(): + node = joints.get(str(name)) + if node is None: + raise ValueError(f"runtime curve targets missing URDF joint: {name}") + limit = node.find("limit") + if limit is None: + raise ValueError(f"runtime curve joint has no URDF limit: {name}") + lower = float(limit.get("lower", "nan")) + upper = float(limit.get("upper", "nan")) + samples = tuple(float(value) for value in values) + if ( + not samples + or not math.isfinite(lower) + or not math.isfinite(upper) + or any( + not math.isfinite(value) or value < lower - 1e-9 or value > upper + 1e-9 + for value in samples + ) + ): + raise ValueError(f"runtime curve exceeds corrected URDF limits: {name}") + + +__all__ = [ + "URDF_FIELD_TO_XML", + "validate_runtime_curve_limits", + "validate_structural_urdf_diff", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/diagnostics.py b/src/linkerhand_calibration/linkerhand_calibration/diagnostics.py new file mode 100644 index 0000000..8519170 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/diagnostics.py @@ -0,0 +1,287 @@ +"""Human-readable diagnostics for the calibration status topic.""" + +from __future__ import annotations + +from typing import Any, Mapping + +from .acquisition import TagQuality + + +ROLE_NAMES_ZH = { + "t0": "掌心T0", + "t3": "拇指根部T3", + "t4": "拇指中节T4", + "t5": "拇指末节T5", +} + +STATE_NAMES_ZH = { + "PREFLIGHT": "设备和标签预检", + "WAIT_ROOT_CONFIRM": "等待开始根部标定", + "SCAN_ROOT": "正在标定拇指根部", + "WAIT_TIP_CONFIRM": "等待开始尖部标定", + "SCAN_TIP": "正在标定拇指尖部", + "VALIDATING": "正在随机复测", + "PAUSED": "标定已暂停", + "ABORTED": "标定已终止", + "COMPLETE": "标定已完成", +} + +_REJECTION_ZH = { + "camera_info_not_ready": "相机内参尚未就绪", + "tag_not_detected": "当前画面未检测到标签", + "tag_quality_invalid": "标签图像质量未达到门限", + "no_pose_within_reprojection_or_tilt_limit": ( + "PnP重投影误差过大或标签倾斜角过大" + ), + "pose_jump": "PnP位置或姿态发生突跳", + "pnp_solve_failed": "PnP三维位置求解失败", + "group_missing_pose_candidates": "标签组缺少可用的PnP候选解", + "group_pose_jump": "标签组PnP结果发生突跳", +} + + +def pnp_rejection_zh(reason: str) -> str: + """Translate a PnP rejection code without hiding its machine value.""" + return _REJECTION_ZH.get(str(reason), f"PnP拒绝:{reason}") + + +def build_tag_quality_diagnostics( + tag_config: Mapping[str, Mapping[str, Any]], + qualities: Mapping[str, TagQuality], + rejections: Mapping[str, str], + reprojection_errors_px: Mapping[str, float], + *, + maximum_hamming: int, + minimum_decision_margin: float, + minimum_edge_pixels: float, + maximum_reprojection_error_px: float, +) -> dict[str, dict[str, Any]]: + """Return compact per-tag values, failures and Chinese explanations.""" + result: dict[str, dict[str, Any]] = {} + for role, config in tag_config.items(): + quality = qualities.get(role) + rejection = rejections.get(role) + problems: list[str] = [] + if quality is None: + problems.append("当前画面未检测到") + else: + if int(quality.hamming) > int(maximum_hamming): + problems.append( + f"hamming={quality.hamming},要求≤{maximum_hamming}" + ) + if float(quality.decision_margin) < float( + minimum_decision_margin + ): + problems.append( + "识别置信度" + f"{quality.decision_margin:.1f},要求≥" + f"{minimum_decision_margin:.1f}" + ) + if float(quality.edge_pixels) < float(minimum_edge_pixels): + problems.append( + f"边长{quality.edge_pixels:.1f}px,要求≥" + f"{minimum_edge_pixels:.1f}px" + ) + reprojection = reprojection_errors_px.get(role) + if ( + reprojection is not None + and float(reprojection) > float(maximum_reprojection_error_px) + ): + problems.append( + f"重投影误差{reprojection:.2f}px,要求≤" + f"{maximum_reprojection_error_px:.2f}px" + ) + if rejection is not None and not problems: + problems.append(pnp_rejection_zh(rejection)) + + detection_valid = bool( + quality is not None + and int(quality.hamming) <= int(maximum_hamming) + and float(quality.decision_margin) + >= float(minimum_decision_margin) + and float(quality.edge_pixels) >= float(minimum_edge_pixels) + ) + individual_valid = bool( + detection_valid + and rejection is None + and ( + reprojection is None + or float(reprojection) + <= float(maximum_reprojection_error_px) + ) + ) + name_zh = ROLE_NAMES_ZH.get(role, role) + result[role] = { + "id": int(config["id"]), + "name_zh": name_zh, + "detected": quality is not None, + "individual_valid": individual_valid, + "hamming": None if quality is None else int(quality.hamming), + "decision_margin": ( + None + if quality is None + else round(float(quality.decision_margin), 2) + ), + "edge_pixels": ( + None + if quality is None + else round(float(quality.edge_pixels), 2) + ), + "reprojection_error_px": ( + None + if reprojection is None + else round(float(reprojection), 3) + ), + "rejection": rejection, + "problems_zh": problems, + "summary_zh": ( + f"{name_zh}正常" + if not problems + else f"{name_zh}:" + ";".join(problems) + ), + } + return result + + +def status_guidance_zh( + state: str, + reason: str, + tag_diagnostics: Mapping[str, Mapping[str, Any]], +) -> tuple[str, str]: + """Return a concise Chinese reason and the next practical action.""" + reason_text = str(reason) + invalid_tags = [ + item + for item in tag_diagnostics.values() + if not bool(item.get("individual_valid", False)) + ] + tag_failure = ( + ";".join(str(item["summary_zh"]) for item in invalid_tags) + if invalid_tags + else "" + ) + if "invalid_tag_frame" in reason_text or ( + state == "PREFLIGHT" and invalid_tags + ): + actions: list[str] = [] + problem_text = ";".join( + str(problem) + for item in invalid_tags + for problem in item.get("problems_zh", []) + ) + if "未检测到" in problem_text: + actions.append("调整遮挡或画面范围,让四张标签同时可见") + if "边长" in problem_text: + actions.append("将相机稍微靠近,建议标签边长稳定大于32px") + if "识别置信度" in problem_text: + actions.append("改善照明、对焦并避免标签反光") + if "hamming" in problem_text: + actions.append("清洁或重新打印标签,并检查对焦") + if "相机内参" in problem_text: + actions.append("确认CameraInfo话题正常") + if not actions: + actions.append("保持机械手不动,检查标签和相机画面") + actions.append("修正后调用resume继续") + return ( + f"标签帧无效,无法采集。{tag_failure}", + ";".join(dict.fromkeys(actions)), + ) + + exact = { + "waiting_for_camera_tags_and_sdk": ( + "正在等待相机、四张标签和灵巧手SDK就绪", + "保持设备连接,观察预检状态", + ), + "call_start": ( + "预检已通过,等待开始标定", + "调用/g20_thumb_calibration/start", + ), + "call_confirm_root_full_range": ( + "预检已通过,等待开始拇指根部全行程标定", + "调用/g20_thumb_calibration/start", + ), + "operator_pause": ( + "操作员已暂停标定", + "确认安全后调用resume继续", + ), + "calibration_complete": ( + "标定和随机复测已经完成", + "检查最终JSON中的quality.passed", + ), + } + if reason_text in exact: + return exact[reason_text] + if reason_text.startswith("collecting_detection_preflight"): + return "正在采集标签预检帧", "保持相机和机械手静止" + if reason_text.startswith("detection_hz_too_low"): + return ( + f"AprilTag检测频率过低({reason_text.split(':')[-1]}Hz)", + "关闭图像显示等额外订阅,检查相机和检测节点负载", + ) + if reason_text.startswith("detection_rate_too_low"): + return "四张标签同时有效的比例过低", "检查遮挡、边长和照明" + if "not_stable" in reason_text: + return "标签三维中心尚未稳定,无法完成静态采集", ( + "不要触碰相机和机械手,检查标签固定及关节抖动后调用resume" + ) + if reason_text.startswith("continuous_sweep_insufficient_coverage"): + return "连续扫描采样覆盖不足", "降低标定速度或提高AprilTag检测频率后重扫" + if "synchronised_tag_state_timeout" in reason_text: + return ( + "运动过程中连续3秒没有取得同时有效的标签帧和电机状态;" + "暂停后当前画面恢复正常也不会自动继续", + "确认四张标签全行程稳定可见,并检查/g20/cb_left_hand_state;" + "修正后调用resume继续,不要调用start", + ) + if "timeout" in reason_text: + return f"等待超时:{reason_text}", "检查标签、同步状态和机械手是否到位" + if reason_text.startswith("pnp_trajectory"): + return f"三维轨迹质量检查未通过:{reason_text}", ( + "检查标签固定、相机稳定和机械抖动" + ) + if reason_text.startswith("root:continuous"): + return "正在连续采集拇指根部轨迹", "无需操作,等待该方向完成" + if reason_text.startswith("tip:continuous"): + return "正在连续采集拇指尖部轨迹", "无需操作,等待该方向完成" + return ( + f"{STATE_NAMES_ZH.get(state, state)}:{reason_text}", + "根据英文reason机器码检查详细原因", + ) + + +def render_status_text_zh( + state_zh: str, + reason_zh: str, + action_zh: str, + tag_diagnostics: Mapping[str, Mapping[str, Any]], +) -> str: + """Render a terminal-friendly multiline Chinese status message.""" + lines = [ + f"状态:{state_zh}", + f"原因:{reason_zh}", + f"建议:{action_zh}", + "标签:", + ] + for item in tag_diagnostics.values(): + detected = bool(item.get("detected", False)) + valid = bool(item.get("individual_valid", False)) + if detected: + metrics = ( + f"边长{float(item['edge_pixels']):.1f}px," + f"置信度{float(item['decision_margin']):.1f}," + f"hamming={int(item['hamming'])}" + ) + reprojection = item.get("reprojection_error_px") + if reprojection is not None: + metrics += f",重投影{float(reprojection):.2f}px" + else: + metrics = "未检测到" + problems = item.get("problems_zh", []) + problem_suffix = ( + "" if not problems else ";" + ";".join(map(str, problems)) + ) + lines.append( + f"- {item['name_zh']}(ID {item['id']}):" + f"{'正常' if valid else '异常'},{metrics}{problem_suffix}" + ) + return "\n".join(lines) diff --git a/src/linkerhand_calibration/linkerhand_calibration/extrinsics.py b/src/linkerhand_calibration/linkerhand_calibration/extrinsics.py new file mode 100644 index 0000000..71ad5e5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/extrinsics.py @@ -0,0 +1,150 @@ +"""Three-view compatibility policy over generic camera extrinsics.""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Mapping, Sequence + +import numpy as np +import yaml + +from .core.geometry.extrinsics import ( + CameraCalibrationIdentity, + CameraExtrinsics, + camera_info_fingerprint, + load_camera_extrinsics, + matrix_payload, + transform_matrix, + validate_camera_extrinsics_payload, +) + + +VIEWS: tuple[str, ...] = ("front", "side", "top") +_QUALITY_LIMITS = { + "reprojection_rms_px": 1.2, + "maximum_rotation_repeatability_deg": 0.3, + "maximum_translation_repeatability_m": 0.0015, +} +_MINIMUM_CAPTURE_COUNTS = { + "front_side_captures": 15, + "front_top_captures": 15, +} + + +@dataclass(frozen=True) +class ThreeCameraExtrinsics: + """Transforms points from each camera optical frame into front optical.""" + + cameras: Mapping[str, CameraCalibrationIdentity] + front_from_view: Mapping[str, np.ndarray] + quality: Mapping[str, float] + + def transform(self, view: str) -> np.ndarray: + if view not in self.front_from_view: + raise KeyError(f"extrinsics do not contain view {view}") + return np.asarray(self.front_from_view[view], dtype=float).copy() + + def camera_matches( + self, + view: str, + *, + serial_number: str, + width: int, + height: int, + intrinsics_sha256: str, + ) -> bool: + expected = self.cameras.get(view) + return bool( + expected is not None + and expected.serial_number == str(serial_number) + and expected.width == int(width) + and expected.height == int(height) + and expected.intrinsics_sha256 == str(intrinsics_sha256) + ) + + +def validate_extrinsics_payload(payload: Mapping[str, Any]) -> None: + validate_camera_extrinsics_payload( + payload, + required_views=VIEWS, + reference_view="front", + quality_limits=_QUALITY_LIMITS, + minimum_capture_counts=_MINIMUM_CAPTURE_COUNTS, + ) + + +def load_three_camera_extrinsics( + path: str | Path, + *, + quality_limits: Mapping[str, float] | None = None, + minimum_capture_counts: Mapping[str, int] | None = None, +) -> ThreeCameraExtrinsics: + generic = load_camera_extrinsics( + path, + required_views=VIEWS, + reference_view="front", + quality_limits=( + _QUALITY_LIMITS if quality_limits is None else quality_limits + ), + minimum_capture_counts=( + _MINIMUM_CAPTURE_COUNTS + if minimum_capture_counts is None + else minimum_capture_counts + ), + ) + return ThreeCameraExtrinsics( + cameras=generic.cameras, + front_from_view=generic.reference_from_view, + quality=generic.quality, + ) + + +def dump_three_camera_extrinsics( + path: str | Path, + *, + cameras: Mapping[str, Mapping[str, Any]], + front_from_view: Mapping[str, Sequence[Sequence[float]]], + quality: Mapping[str, Any], + quality_limits: Mapping[str, float] | None = None, +) -> None: + payload = { + "schema_version": 1, + "reference_view": "front", + "cameras": {view: dict(cameras[view]) for view in VIEWS}, + "front_from_view": { + view: matrix_payload(front_from_view[view]) for view in VIEWS + }, + "quality": dict(quality), + } + validate_camera_extrinsics_payload( + payload, + required_views=VIEWS, + reference_view="front", + quality_limits=( + _QUALITY_LIMITS if quality_limits is None else quality_limits + ), + minimum_capture_counts=_MINIMUM_CAPTURE_COUNTS, + ) + destination = Path(path).expanduser().resolve() + destination.parent.mkdir(parents=True, exist_ok=True) + temporary = destination.with_suffix(destination.suffix + ".tmp") + with temporary.open("w", encoding="utf-8") as stream: + yaml.safe_dump(payload, stream, allow_unicode=True, sort_keys=False) + temporary.replace(destination) + + +__all__ = [ + "CameraCalibrationIdentity", + "CameraExtrinsics", + "ThreeCameraExtrinsics", + "VIEWS", + "camera_info_fingerprint", + "dump_three_camera_extrinsics", + "load_camera_extrinsics", + "load_three_camera_extrinsics", + "matrix_payload", + "transform_matrix", + "validate_camera_extrinsics_payload", + "validate_extrinsics_payload", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/extrinsics_node.py b/src/linkerhand_calibration/linkerhand_calibration/extrinsics_node.py new file mode 100644 index 0000000..47d3549 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/extrinsics_node.py @@ -0,0 +1,1642 @@ +"""Interactive one-time three-camera checkerboard extrinsic calibration.""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass +import math +import os +from pathlib import Path +import time +from typing import Any + +import cv2 +from cv_bridge import CvBridge +import numpy as np +import rclpy +from rclpy.node import Node +from rclpy.qos import qos_profile_sensor_data +from scipy.spatial.transform import Rotation +from sensor_msgs.msg import CameraInfo, Image +from std_srvs.srv import Trigger + +from .core import robust_rotation_summary +from .extrinsics import ( + VIEWS, + camera_info_fingerprint, + dump_three_camera_extrinsics, +) +from .hikrobot_camera import configure_fastdds_large_image_transport + + +@dataclass(frozen=True) +class BoardPose: + stamp_ns: int + camera_from_board_candidates: tuple[np.ndarray, ...] + reprojection_rms_px: float + image_points: np.ndarray | None = None + + +@dataclass(frozen=True) +class ImageFrame: + stamp_ns: int + message: Image + + +@dataclass(frozen=True) +class PairAssessment: + other: str + ready: bool + reason_code: str + message: str + front_frame: ImageFrame | None = None + selected_frame: ImageFrame | None = None + front_pose: BoardPose | None = None + selected_pose: BoardPose | None = None + skew_ns: int | None = None + pair_reprojection_rms_px: float | None = None + transform_candidates: tuple[np.ndarray, ...] = () + provisional_rotation_error_rad: float | None = None + provisional_translation_error_m: float | None = None + + +@dataclass(frozen=True) +class StereoCapture: + front_points_px: np.ndarray + other_points_px: np.ndarray + transform_candidates: tuple[np.ndarray, ...] + pair_reprojection_rms_px: float + skew_ns: int + front_reprojection_rms_px: float = float("nan") + other_reprojection_rms_px: float = float("nan") + + +@dataclass(frozen=True) +class StereoFitResult: + front_from_other: np.ndarray + stereo_rms_px: float + per_view_rms_px: tuple[float, ...] + inlier_indices: tuple[int, ...] + rejected_indices: tuple[int, ...] + rotation_stability_rad: float + translation_stability_m: float + passed: bool + + +def _individual_reprojection_passes( + front_rms_px: float, + other_rms_px: float, + maximum_rms_px: float, +) -> bool: + """Do not let one sharp camera hide a poor observation in the other.""" + values = np.asarray([front_rms_px, other_rms_px], dtype=float) + return bool( + np.all(np.isfinite(values)) + and np.all(values >= 0.0) + and np.all(values <= maximum_rms_px) + ) + + +def _pose_is_novel( + pose: np.ndarray, + previous_poses: list[np.ndarray], + *, + minimum_rotation_rad: float, + minimum_translation_m: float, +) -> bool: + """Require a new board pose to differ from every accepted pose. + + Comparing only with the most recent capture lets an operator alternate + between two almost identical poses and create a large but poorly + conditioned data set. A pose is new when it differs in rotation or + translation from every pose already retained. + """ + return all( + rotation >= minimum_rotation_rad + or translation >= minimum_translation_m + for rotation, translation in ( + _transform_residual(previous, pose) for previous in previous_poses + ) + ) + + +def _stereo_fit_failures( + result: StereoFitResult, + *, + minimum_inliers: int, + maximum_rms_px: float, + maximum_rotation_stability_rad: float, + maximum_translation_stability_m: float, +) -> tuple[str, ...]: + """Return stable, user-facing names for failed final quality gates.""" + failures: list[str] = [] + if len(result.inlier_indices) < minimum_inliers: + failures.append("INLIERS") + if result.stereo_rms_px > maximum_rms_px: + failures.append("RMS") + if result.rotation_stability_rad > maximum_rotation_stability_rad: + failures.append("ROT") + if result.translation_stability_m > maximum_translation_stability_m: + failures.append("TRANS") + return tuple(failures) + + +def _select_latest_synchronised_pair( + front_history: list[Any] | deque[Any], + other_history: list[Any] | deque[Any], + maximum_skew_ns: int, +) -> tuple[Any, Any, int] | None: + """Select the newest available pair whose image stamps are close enough. + + Keep image callbacks cheap and pair their timestamps before running the + expensive checkerboard detector. This prevents image-processing latency + from turning into a false camera synchronization failure. + """ + candidates: list[tuple[int, int, Any, Any]] = [] + for front in front_history: + for other in other_history: + skew = abs(int(front.stamp_ns) - int(other.stamp_ns)) + if skew <= int(maximum_skew_ns): + common_stamp = min(int(front.stamp_ns), int(other.stamp_ns)) + candidates.append((common_stamp, -skew, front, other)) + if not candidates: + return None + _, negative_skew, front, other = max( + candidates, key=lambda item: (item[0], item[1]) + ) + return front, other, -negative_skew + + +def _minimum_history_skew_ns( + front_history: list[Any] | deque[Any], + other_history: list[Any] | deque[Any], +) -> int | None: + if not front_history or not other_history: + return None + return min( + abs(int(front.stamp_ns) - int(other.stamp_ns)) + for front in front_history + for other in other_history + ) + + +def _stamp_ns(message: Image) -> int: + return ( + int(message.header.stamp.sec) * 1_000_000_000 + + int(message.header.stamp.nanosec) + ) + + +def _inverse(transform: np.ndarray) -> np.ndarray: + result = np.eye(4) + result[:3, :3] = transform[:3, :3].T + result[:3, 3] = -result[:3, :3] @ transform[:3, 3] + return result + + +def _mean_transform(transforms: list[np.ndarray]) -> np.ndarray: + quaternion = robust_rotation_summary( + [Rotation.from_matrix(value[:3, :3]).as_quat() for value in transforms] + )[0] + result = np.eye(4) + result[:3, :3] = Rotation.from_quat(quaternion).as_matrix() + result[:3, 3] = np.median( + np.asarray([value[:3, 3] for value in transforms]), axis=0 + ) + return result + + +def _transform_residual( + reference: np.ndarray, observed: np.ndarray +) -> tuple[float, float]: + rotation = Rotation.from_matrix(reference[:3, :3]).inv() * Rotation.from_matrix( + observed[:3, :3] + ) + translation = observed[:3, 3] - reference[:3, 3] + return float(rotation.magnitude()), float(np.linalg.norm(translation)) + + +def _select_consistent_transforms( + candidates_by_capture: list[list[np.ndarray]], +) -> tuple[np.ndarray, list[np.ndarray]]: + """Resolve the checkerboard's 180-degree corner-order ambiguity.""" + if not candidates_by_capture or not candidates_by_capture[0]: + raise ValueError("no checkerboard transform candidates") + best_score = float("inf") + best_reference = np.eye(4) + best_selected: list[np.ndarray] = [] + for seed in candidates_by_capture[0]: + reference = seed + selected: list[np.ndarray] = [] + for _ in range(5): + selected = [] + for candidates in candidates_by_capture: + selected.append( + min( + candidates, + key=lambda candidate: ( + _transform_residual(reference, candidate)[0] + / math.radians(0.3) + + _transform_residual(reference, candidate)[1] + / 0.0015 + ), + ) + ) + updated = _mean_transform(selected) + if _transform_residual(reference, updated)[0] < 1.0e-10: + reference = updated + break + reference = updated + score = sum( + (rotation / math.radians(0.3)) ** 2 + + (translation / 0.0015) ** 2 + for rotation, translation in ( + _transform_residual(reference, observed) + for observed in selected + ) + ) + if score < best_score: + best_score = score + best_reference = reference + best_selected = selected + return best_reference, best_selected + + +def _summarize_transform_repeatability( + candidates_by_capture: list[list[np.ndarray]], +) -> tuple[np.ndarray, list[np.ndarray], float, float]: + """Fit one transform and return worst rotation/translation residuals.""" + reference, selected = _select_consistent_transforms(candidates_by_capture) + residuals = [ + _transform_residual(reference, observed) for observed in selected + ] + return ( + reference, + selected, + max(rotation for rotation, _ in residuals), + max(translation for _, translation in residuals), + ) + + +def _stereo_fit_once( + captures: list[StereoCapture], + indices: list[int], + object_points: np.ndarray, + front_matrix: np.ndarray, + other_matrix: np.ndarray, + image_size: tuple[int, int], +) -> tuple[float, np.ndarray, np.ndarray]: + if len(indices) < 3: + raise ValueError("stereo calibration requires at least three views") + objects = [ + np.asarray(object_points, dtype=np.float32).copy() for _ in indices + ] + candidate_sets = [ + list(captures[index].transform_candidates) for index in indices + ] + _, selected_transforms = _select_consistent_transforms(candidate_sets) + front_points: list[np.ndarray] = [] + other_points: list[np.ndarray] = [] + for capture_index, selected_transform in zip( + indices, selected_transforms + ): + capture = captures[capture_index] + candidate_index = min( + range(len(capture.transform_candidates)), + key=lambda index: sum( + _transform_residual( + selected_transform, + capture.transform_candidates[index], + ) + ), + ) + candidates_per_camera = int( + round(math.sqrt(len(capture.transform_candidates))) + ) + if candidates_per_camera * candidates_per_camera != len( + capture.transform_candidates + ): + raise ValueError("checkerboard pose candidate layout is invalid") + front_reversed = candidate_index // candidates_per_camera != 0 + other_reversed = candidate_index % candidates_per_camera != 0 + front = np.asarray(capture.front_points_px, dtype=np.float32) + other = np.asarray(capture.other_points_px, dtype=np.float32) + front_points.append(front[::-1].copy() if front_reversed else front) + other_points.append(other[::-1].copy() if other_reversed else other) + result = cv2.stereoCalibrateExtended( + objects, + front_points, + other_points, + np.asarray(front_matrix, dtype=float).copy(), + np.zeros(5), + np.asarray(other_matrix, dtype=float).copy(), + np.zeros(5), + tuple(int(value) for value in image_size), + np.eye(3), + np.zeros((3, 1)), + flags=cv2.CALIB_FIX_INTRINSIC, + criteria=( + cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, + 100, + 1.0e-7, + ), + ) + rms = float(result[0]) + other_from_front = np.eye(4) + other_from_front[:3, :3] = np.asarray(result[5], dtype=float) + other_from_front[:3, 3] = np.asarray(result[6], dtype=float).reshape(3) + per_camera_errors = np.asarray(result[9], dtype=float).reshape( + len(indices), -1 + ) + per_view_errors = np.sqrt( + np.mean(np.square(per_camera_errors), axis=1) + ) + return rms, _inverse(other_from_front), per_view_errors + + +def _fit_stereo_robust( + captures: list[StereoCapture], + object_points: np.ndarray, + front_matrix: np.ndarray, + other_matrix: np.ndarray, + image_size: tuple[int, int], + *, + minimum_inliers: int, + maximum_rms_px: float, + maximum_rotation_stability_rad: float, + maximum_translation_stability_m: float, +) -> StereoFitResult: + """Jointly fit one stereo transform and remove gross pose outliers.""" + if len(captures) < 3: + raise ValueError("at least three stereo captures are required") + active = list(range(len(captures))) + fit_rms = float("inf") + transform = np.eye(4) + per_view = np.full(len(active), float("inf")) + # Always compute a provisional fit from three captures onward so the GUI + # can guide the operator before the final count is reached. Remove only + # unmistakable geometric/reprojection outliers, and never trim below the + # required final inlier count. + while len(active) >= 3: + fit_rms, transform, per_view = _stereo_fit_once( + captures, + active, + object_points, + front_matrix, + other_matrix, + image_size, + ) + median = float(np.median(per_view)) + mad = float(np.median(np.abs(per_view - median))) + reprojection_limit = max( + maximum_rms_px * 1.5, + median + 3.0 * 1.4826 * max(mad, 1.0e-6), + ) + rotation_limit = max( + math.radians(1.2), 4.0 * maximum_rotation_stability_rad + ) + translation_limit = max( + 0.008, 4.0 * maximum_translation_stability_m + ) + scores: list[float] = [] + for local_index, capture_index in enumerate(active): + residuals = [ + _transform_residual(transform, candidate) + for candidate in captures[capture_index].transform_candidates + ] + rotation_error, translation_error = min( + residuals, + key=lambda value: ( + value[0] / rotation_limit + + value[1] / translation_limit + ), + ) + scores.append( + max( + float(per_view[local_index]) / reprojection_limit, + rotation_error / rotation_limit, + translation_error / translation_limit, + ) + ) + worst_local = int(np.argmax(scores)) + if scores[worst_local] <= 1.0 or len(active) <= minimum_inliers: + break + active.pop(worst_local) + + # Moderate bad views (typically 1.2--1.8 px) are not gross outliers, but + # accumulating them can keep the batch RMS just above the hard gate + # forever. Trim only a view whose own joint stereo error exceeds the + # unchanged final RMS limit, refitting after every removal. This is + # bounded by minimum_inliers and cannot turn an intrinsically poor data set + # into a formal result merely by relaxing the threshold. + while len(active) > minimum_inliers and fit_rms > maximum_rms_px: + worst_local = int(np.argmax(per_view)) + if float(per_view[worst_local]) <= maximum_rms_px: + break + active.pop(worst_local) + fit_rms, transform, per_view = _stereo_fit_once( + captures, + active, + object_points, + front_matrix, + other_matrix, + image_size, + ) + + rotation_stability = float("inf") + translation_stability = float("inf") + if len(active) >= 6: + rotation_values: list[float] = [] + translation_values: list[float] = [] + for held_out_fold in range(3): + subset = [ + index + for position, index in enumerate(active) + if position % 3 != held_out_fold + ] + _, subset_transform, _ = _stereo_fit_once( + captures, + subset, + object_points, + front_matrix, + other_matrix, + image_size, + ) + rotation_error, translation_error = _transform_residual( + transform, subset_transform + ) + rotation_values.append(rotation_error) + translation_values.append(translation_error) + rotation_stability = max(rotation_values) + translation_stability = max(translation_values) + + rejected = tuple( + index for index in range(len(captures)) if index not in set(active) + ) + provisional = StereoFitResult( + front_from_other=transform, + stereo_rms_px=fit_rms, + per_view_rms_px=tuple(float(value) for value in per_view), + inlier_indices=tuple(active), + rejected_indices=rejected, + rotation_stability_rad=rotation_stability, + translation_stability_m=translation_stability, + passed=False, + ) + failures = _stereo_fit_failures( + provisional, + minimum_inliers=minimum_inliers, + maximum_rms_px=maximum_rms_px, + maximum_rotation_stability_rad=maximum_rotation_stability_rad, + maximum_translation_stability_m=maximum_translation_stability_m, + ) + return StereoFitResult( + front_from_other=provisional.front_from_other, + stereo_rms_px=provisional.stereo_rms_px, + per_view_rms_px=provisional.per_view_rms_px, + inlier_indices=provisional.inlier_indices, + rejected_indices=provisional.rejected_indices, + rotation_stability_rad=provisional.rotation_stability_rad, + translation_stability_m=provisional.translation_stability_m, + passed=not failures, + ) + + +class ThreeCameraExtrinsicsNode(Node): + GUI_WINDOW = "G20 Three-Camera Extrinsics" + + def __init__(self) -> None: + super().__init__("g20_camera_extrinsics") + self._declare_parameters() + self._load_parameters() + self.optical_captures = [] + self.bridge = CvBridge() + self.camera_matrices: dict[str, np.ndarray] = {} + self.camera_identities: dict[str, dict[str, Any]] = {} + # Do not run expensive 2 MP checkerboard detection in the image + # callbacks. That made a single-threaded executor compare frames that + # were processed at different times. Cache messages cheaply, select a + # synchronized pair first, then detect only those two images on demand. + self.image_history: dict[str, deque[ImageFrame]] = { + view: deque(maxlen=12) for view in VIEWS + } + self.captures: dict[str, list[list[np.ndarray]]] = { + "side": [], + "top": [], + } + self.capture_reprojection: dict[str, list[float]] = { + "side": [], + "top": [], + } + self.stereo_captures: dict[str, list[StereoCapture]] = { + "side": [], + "top": [], + } + self.fit_results: dict[str, StereoFitResult | None] = { + "side": None, + "top": None, + } + self.captured_front_board: dict[str, list[np.ndarray]] = { + "side": [], + "top": [], + } + self.gui_active_other = "side" + self.gui_last_assessment: PairAssessment | None = None + self.gui_feedback = "Move the checkerboard into both views" + self.gui_action: str | None = None + self.gui_auto_capture = self.auto_capture_default + self.gui_auto_pose: np.ndarray | None = None + self.gui_auto_stable_since: float | None = None + self.gui_enabled = bool(self.enable_gui and os.environ.get("DISPLAY")) + for view in VIEWS: + self.create_subscription( + CameraInfo, + self.info_topics[view], + lambda message, selected=view: self._info_callback( + selected, message + ), + qos_profile_sensor_data, + ) + self.create_subscription( + Image, + self.image_topics[view], + lambda message, selected=view: self._image_callback( + selected, message + ), + qos_profile_sensor_data, + ) + self.create_service( + Trigger, "~/capture_front_side", self._capture_front_side + ) + self.create_service( + Trigger, "~/capture_front_top", self._capture_front_top + ) + self.create_service(Trigger, "~/save", self._save) + self.create_service(Trigger, "~/reset", self._reset) + if self.enable_gui and not self.gui_enabled: + self.get_logger().warning( + "Extrinsics GUI requested but DISPLAY is unavailable; GUI disabled" + ) + if self.gui_enabled: + try: + cv2.namedWindow(self.GUI_WINDOW, cv2.WINDOW_NORMAL) + cv2.resizeWindow(self.GUI_WINDOW, 1400, 760) + cv2.setMouseCallback( + self.GUI_WINDOW, self._gui_mouse_callback + ) + self.gui_timer = self.create_timer( + 1.0 / self.gui_refresh_hz, self._gui_timer_callback + ) + except cv2.error as error: + self.gui_enabled = False + self.get_logger().error( + f"Failed to create extrinsics GUI; GUI disabled: {error}" + ) + self.get_logger().info( + "Checkerboard extrinsic calibration ready: " + f"inner corners={self.columns}x{self.rows}, " + f"square={self.square_size_m * 1000.0:.3f} mm" + ) + + def _declare_parameters(self) -> None: + self.declare_parameter("output_file", "camera_extrinsics.yaml") + self.declare_parameter("verification_extrinsics_file", "") + self.declare_parameter("checkerboard_columns", 8) + self.declare_parameter("checkerboard_rows", 5) + self.declare_parameter("square_size_m", 0.027) + self.declare_parameter("minimum_captures_per_pair", 15) + self.declare_parameter("maximum_pair_skew_ms", 100.0) + self.declare_parameter("maximum_reprojection_rms_px", 1.2) + self.declare_parameter( + "maximum_candidate_pair_reprojection_rms_px", 1.5 + ) + self.declare_parameter( + "maximum_single_camera_reprojection_rms_px", 1.5 + ) + self.declare_parameter("maximum_rotation_repeatability_deg", 0.3) + self.declare_parameter("maximum_translation_repeatability_m", 0.0015) + self.declare_parameter("enable_gui", False) + self.declare_parameter("gui_refresh_hz", 2.0) + self.declare_parameter("auto_capture_default", False) + self.declare_parameter("auto_capture_stable_seconds", 1.0) + for view in VIEWS: + self.declare_parameter(f"{view}_camera_serial", "") + self.declare_parameter( + f"{view}_image_topic", + f"/g20_extrinsics/{view}/camera/image_rect", + ) + self.declare_parameter( + f"{view}_camera_info_topic", + f"/g20_extrinsics/{view}/camera/camera_info", + ) + + def _load_parameters(self) -> None: + def value(name: str) -> Any: + return self.get_parameter(name).value + + self.output_file = Path(str(value("output_file"))).expanduser().resolve() + self.verification_extrinsics_file = str(value("verification_extrinsics_file")) + if self.verification_extrinsics_file and self.output_file == Path(self.verification_extrinsics_file).expanduser().resolve(): + raise ValueError('optical_verification_must_not_overwrite_camera_parameters') + self.columns = int(value("checkerboard_columns")) + self.rows = int(value("checkerboard_rows")) + self.square_size_m = float(value("square_size_m")) + self.minimum_captures = int(value("minimum_captures_per_pair")) + self.maximum_pair_skew_ns = int( + float(value("maximum_pair_skew_ms")) * 1_000_000.0 + ) + if self.verification_extrinsics_file: + self.maximum_pair_skew_ns = min(self.maximum_pair_skew_ns, 50_000_000) + self.maximum_reprojection_rms_px = float( + value("maximum_reprojection_rms_px") + ) + self.maximum_candidate_pair_reprojection_rms_px = float( + value("maximum_candidate_pair_reprojection_rms_px") + ) + self.maximum_single_camera_reprojection_rms_px = float( + value("maximum_single_camera_reprojection_rms_px") + ) + self.maximum_rotation_repeatability_rad = math.radians( + float(value("maximum_rotation_repeatability_deg")) + ) + self.maximum_translation_repeatability_m = float( + value("maximum_translation_repeatability_m") + ) + self.enable_gui = bool(value("enable_gui")) + self.gui_refresh_hz = float(value("gui_refresh_hz")) + self.auto_capture_default = bool(value("auto_capture_default")) + self.auto_capture_stable_seconds = float( + value("auto_capture_stable_seconds") + ) + self.serials = { + view: str(value(f"{view}_camera_serial")) for view in VIEWS + } + self.image_topics = { + view: str(value(f"{view}_image_topic")) for view in VIEWS + } + self.info_topics = { + view: str(value(f"{view}_camera_info_topic")) for view in VIEWS + } + if self.columns < 3 or self.rows < 3 or self.square_size_m <= 0.0: + raise ValueError("checkerboard geometry is invalid") + if self.minimum_captures < 15: + raise ValueError("minimum_captures_per_pair must be at least 15") + if self.maximum_reprojection_rms_px <= 0.0: + raise ValueError("maximum_reprojection_rms_px must be positive") + if ( + self.maximum_candidate_pair_reprojection_rms_px + < self.maximum_reprojection_rms_px + ): + raise ValueError( + "maximum_candidate_pair_reprojection_rms_px must be at " + "least maximum_reprojection_rms_px" + ) + if ( + self.maximum_single_camera_reprojection_rms_px + < self.maximum_candidate_pair_reprojection_rms_px + ): + raise ValueError( + "maximum_single_camera_reprojection_rms_px must be at " + "least maximum_candidate_pair_reprojection_rms_px" + ) + if self.gui_refresh_hz <= 0.0 or self.gui_refresh_hz > 10.0: + raise ValueError("gui_refresh_hz must be in (0, 10]") + if self.auto_capture_stable_seconds < 0.5: + raise ValueError("auto_capture_stable_seconds must be at least 0.5") + if any(not serial for serial in self.serials.values()): + raise ValueError("all three camera serial numbers are required") + + @property + def object_points(self) -> np.ndarray: + points = np.zeros((self.columns * self.rows, 3), dtype=np.float32) + points[:, :2] = np.mgrid[0:self.columns, 0:self.rows].T.reshape(-1, 2) + points[:, :2] *= self.square_size_m + return points + + def _info_callback(self, view: str, message: CameraInfo) -> None: + matrix = np.asarray(message.p, dtype=float).reshape(3, 4)[:, :3] + if ( + int(message.width) <= 0 + or int(message.height) <= 0 + or not np.all(np.isfinite(matrix)) + or matrix[0, 0] <= 0.0 + or matrix[1, 1] <= 0.0 + ): + self.camera_matrices.pop(view, None) + self.camera_identities.pop(view, None) + return + self.camera_matrices[view] = matrix + self.camera_identities[view] = { + "serial_number": self.serials[view], + "width": int(message.width), + "height": int(message.height), + "intrinsics_sha256": camera_info_fingerprint( + width=message.width, + height=message.height, + camera_matrix=message.k, + distortion=message.d, + rectification=message.r, + projection=message.p, + ), + } + + def _image_callback(self, view: str, message: Image) -> None: + stamp_ns = _stamp_ns(message) + if stamp_ns <= 0: + return + self.image_history[view].append( + ImageFrame(stamp_ns=stamp_ns, message=message) + ) + + def _detect_board_pose( + self, view: str, message: Image + ) -> BoardPose | None: + matrix = self.camera_matrices.get(view) + if matrix is None: + return None + image = self.bridge.imgmsg_to_cv2(message, desired_encoding="mono8") + found, corners = cv2.findChessboardCornersSB( + image, + (self.columns, self.rows), + flags=cv2.CALIB_CB_NORMALIZE_IMAGE, + ) + if not found or corners is None: + return None + image_points = np.asarray(corners, dtype=np.float32).reshape(-1, 2) + pose_candidates: list[np.ndarray] = [] + reprojection_values: list[float] = [] + for ordered_points in (image_points, image_points[::-1].copy()): + solved, rotation_vector, translation = cv2.solvePnP( + self.object_points, + ordered_points, + matrix, + np.zeros(5), + flags=cv2.SOLVEPNP_IPPE, + ) + if not solved: + continue + # IPPE supplies a stable planar initial pose. LM refinement then + # minimizes the exact reprojection residual used by the quality + # gate, avoiding an avoidable analytical-solver error floor. + rotation_vector, translation = cv2.solvePnPRefineLM( + self.object_points, + ordered_points, + matrix, + np.zeros(5), + rotation_vector, + translation, + ) + projected, _ = cv2.projectPoints( + self.object_points, + rotation_vector, + translation, + matrix, + np.zeros(5), + ) + residual = projected.reshape(-1, 2) - ordered_points + reprojection_values.append( + float(np.sqrt(np.mean(np.sum(np.square(residual), axis=1)))) + ) + rotation_matrix, _ = cv2.Rodrigues(rotation_vector) + transform = np.eye(4) + transform[:3, :3] = rotation_matrix + transform[:3, 3] = np.asarray(translation).reshape(3) + pose_candidates.append(transform) + if not pose_candidates: + return None + return BoardPose( + stamp_ns=_stamp_ns(message), + camera_from_board_candidates=tuple(pose_candidates), + reprojection_rms_px=min(reprojection_values), + image_points=image_points, + ) + + def _assess_pair(self, other: str) -> PairAssessment: + """Evaluate the newest synchronized pair without recording it.""" + if not self.image_history["front"] or not self.image_history[other]: + return PairAssessment( + other, False, "waiting_for_images", f"front/{other}尚未收到图像" + ) + frame_pair = _select_latest_synchronised_pair( + self.image_history["front"], + self.image_history[other], + self.maximum_pair_skew_ns, + ) + if frame_pair is None: + minimum_skew = _minimum_history_skew_ns( + self.image_history["front"], self.image_history[other] + ) + message = ( + f"front/{other}没有可配对的图像" + if minimum_skew is None + else ( + f"front/{other}最近图像历史的最小时间差" + f"{minimum_skew / 1e6:.1f}ms,超过" + f"{self.maximum_pair_skew_ns / 1e6:.1f}ms门限" + ) + ) + return PairAssessment( + other, False, "image_skew_too_large", message + ) + + front_frame, selected_frame, skew = frame_pair + front = self._detect_board_pose("front", front_frame.message) + selected = self._detect_board_pose(other, selected_frame.message) + missing = [ + view + for view, pose in (("front", front), (other, selected)) + if pose is None + ] + if missing: + return PairAssessment( + other=other, + ready=False, + reason_code="checkerboard_missing", + message=( + f"同步图像已找到(时间差{skew / 1e6:.1f}ms)," + f"但{'/'.join(missing)}没有检测到完整棋盘" + ), + front_frame=front_frame, + selected_frame=selected_frame, + front_pose=front, + selected_pose=selected, + skew_ns=skew, + ) + + assert front is not None and selected is not None + pair_rms = float( + np.sqrt( + np.mean( + np.square( + [ + front.reprojection_rms_px, + selected.reprojection_rms_px, + ] + ) + ) + ) + ) + common = { + "other": other, + "front_frame": front_frame, + "selected_frame": selected_frame, + "front_pose": front, + "selected_pose": selected, + "skew_ns": skew, + "pair_reprojection_rms_px": pair_rms, + } + camera_rms_failed = not _individual_reprojection_passes( + front.reprojection_rms_px, + selected.reprojection_rms_px, + self.maximum_single_camera_reprojection_rms_px, + ) + if ( + camera_rms_failed + or pair_rms + > self.maximum_candidate_pair_reprojection_rms_px + ): + return PairAssessment( + ready=False, + reason_code="reprojection_rms_too_large", + message=( + f"当前组未通过采集门限,未计入。单相机上限=" + f"{self.maximum_single_camera_reprojection_rms_px:.3f}px," + "候选组合上限=" + f"{self.maximum_candidate_pair_reprojection_rms_px:.3f}px," + f"最终批次上限={self.maximum_reprojection_rms_px:.3f}px;" + f"组合RMS={pair_rms:.3f}px," + f"front={front.reprojection_rms_px:.3f}px," + f"{other}={selected.reprojection_rms_px:.3f}px;" + f"已保留{len(self.captures[other])}/{self.minimum_captures}组" + ), + **common, + ) + + transform_candidates = tuple( + front_pose @ _inverse(other_pose) + for front_pose in front.camera_from_board_candidates + for other_pose in selected.camera_from_board_candidates + ) + previous = self.captures[other] + board_poses = self.captured_front_board[other] + if board_poses: + if not _pose_is_novel( + front.camera_from_board_candidates[0], + board_poses, + minimum_rotation_rad=math.radians(2.0), + minimum_translation_m=0.015, + ): + return PairAssessment( + ready=False, + reason_code="board_pose_too_close", + message=( + "棋盘姿态与上次过近," + "请改变位置或倾角后再采集" + ), + transform_candidates=transform_candidates, + **common, + ) + + current_fit = self.fit_results[other] + rotation_error = ( + None + if current_fit is None + else current_fit.rotation_stability_rad + ) + translation_error = ( + None + if current_fit is None + else current_fit.translation_stability_m + ) + metrics = { + "transform_candidates": transform_candidates, + "provisional_rotation_error_rad": rotation_error, + "provisional_translation_error_m": translation_error, + } + return PairAssessment( + ready=True, + reason_code="ready", + message=( + f"当前姿态合格,可加入候选;" + f"已采集{len(previous)}组" + ), + **common, + **metrics, + ) + + def _update_stereo_fit(self, other: str) -> StereoFitResult | None: + captures = self.stereo_captures[other] + if len(captures) < 3: + self.fit_results[other] = None + return None + identity = self.camera_identities.get("front") + front_matrix = self.camera_matrices.get("front") + other_matrix = self.camera_matrices.get(other) + if identity is None or front_matrix is None or other_matrix is None: + self.fit_results[other] = None + return None + try: + result = _fit_stereo_robust( + captures, + self.object_points, + front_matrix, + other_matrix, + (int(identity["width"]), int(identity["height"])), + minimum_inliers=self.minimum_captures, + maximum_rms_px=self.maximum_reprojection_rms_px, + maximum_rotation_stability_rad=( + self.maximum_rotation_repeatability_rad + ), + maximum_translation_stability_m=( + self.maximum_translation_repeatability_m + ), + ) + except (ValueError, cv2.error) as error: + self.fit_results[other] = None + self.get_logger().warning( + f"front/{other} joint stereo fit unavailable: {error}" + ) + return None + self.fit_results[other] = result + return result + + def _capture_pair( + self, other: str, response: Trigger.Response + ) -> Trigger.Response: + assessment = self._assess_pair(other) + if other == self.gui_active_other: + self.gui_last_assessment = assessment + if not assessment.ready: + response.success = False + response.message = assessment.message + return response + + assert assessment.front_pose is not None + assert assessment.selected_pose is not None + assert assessment.skew_ns is not None + assert assessment.pair_reprojection_rms_px is not None + assert assessment.front_pose.image_points is not None + assert assessment.selected_pose.image_points is not None + previous = self.captures[other] + previous.append(list(assessment.transform_candidates)) + self.stereo_captures[other].append( + StereoCapture( + front_points_px=assessment.front_pose.image_points.copy(), + other_points_px=assessment.selected_pose.image_points.copy(), + transform_candidates=assessment.transform_candidates, + pair_reprojection_rms_px=( + assessment.pair_reprojection_rms_px + ), + skew_ns=assessment.skew_ns, + front_reprojection_rms_px=( + assessment.front_pose.reprojection_rms_px + ), + other_reprojection_rms_px=( + assessment.selected_pose.reprojection_rms_px + ), + ) + ) + self.captured_front_board[other].append( + assessment.front_pose.camera_from_board_candidates[0].copy() + ) + self.capture_reprojection[other].extend( + [ + assessment.front_pose.reprojection_rms_px, + assessment.selected_pose.reprojection_rms_px, + ] + ) + if self.verification_extrinsics_file: + views = {} + for view, pose in (('front', assessment.front_pose), (other, assessment.selected_pose)): + views[view] = dict(serial_number=self.serials[view], image_stamp_ns=pose.stamp_ns, + camera_matrix=self.camera_matrices[view].tolist(), input_is_rectified=True, + corners_xy=pose.image_points.tolist()) + self.optical_captures.append(dict(views=views)) + fit = None if self.verification_extrinsics_file else self._update_stereo_fit(other) + fit_text = "联合拟合需要至少3组" + if fit is not None: + fit_text = ( + f"联合RMS={fit.stereo_rms_px:.3f}px," + f"内点={len(fit.inlier_indices)}/{len(previous)}," + f"稳定性={math.degrees(fit.rotation_stability_rad):.3f}°/" + f"{fit.translation_stability_m * 1000.0:.3f}mm" + ) + response.success = True + response.message = ( + f"front/{other}已加入候选 {len(previous)}组," + f"时间差{assessment.skew_ns / 1e6:.1f}ms," + f"重投影RMS={assessment.pair_reprojection_rms_px:.3f}px," + f"{fit_text}" + ) + return response + + @staticmethod + def _fit_gui_image(image: np.ndarray, width: int, height: int) -> np.ndarray: + canvas = np.full((height, width, 3), 24, dtype=np.uint8) + scale = min(width / image.shape[1], height / image.shape[0]) + resized = cv2.resize( + image, + ( + max(1, int(round(image.shape[1] * scale))), + max(1, int(round(image.shape[0] * scale))), + ), + interpolation=cv2.INTER_AREA, + ) + x = (width - resized.shape[1]) // 2 + y = (height - resized.shape[0]) // 2 + canvas[y : y + resized.shape[0], x : x + resized.shape[1]] = resized + return canvas + + def _annotated_gui_frame( + self, + frame: ImageFrame | None, + pose: BoardPose | None, + label: str, + ) -> np.ndarray: + if frame is None: + image = np.full((480, 640, 3), 24, dtype=np.uint8) + cv2.putText( + image, + f"{label}: waiting for image", + (30, 60), + cv2.FONT_HERSHEY_SIMPLEX, + 0.8, + (0, 180, 255), + 2, + cv2.LINE_AA, + ) + return image + mono = self.bridge.imgmsg_to_cv2( + frame.message, desired_encoding="mono8" + ) + image = cv2.cvtColor(mono, cv2.COLOR_GRAY2BGR) + if pose is not None and pose.image_points is not None: + cv2.drawChessboardCorners( + image, + (self.columns, self.rows), + pose.image_points.reshape(-1, 1, 2), + True, + ) + rms = "--" if pose is None else f"{pose.reprojection_rms_px:.3f}px" + color = (0, 180, 255) + if pose is not None: + if pose.reprojection_rms_px <= self.maximum_reprojection_rms_px: + color = (40, 220, 40) + elif ( + pose.reprojection_rms_px + <= self.maximum_single_camera_reprojection_rms_px + ): + color = (0, 210, 255) + else: + color = (0, 0, 255) + cv2.putText( + image, + f"{label.upper()} RMS {rms}", + (30, 55), + cv2.FONT_HERSHEY_SIMPLEX, + 1.1, + color, + 3, + cv2.LINE_AA, + ) + return image + + @staticmethod + def _draw_gui_button( + canvas: np.ndarray, + rectangle: tuple[int, int, int, int], + label: str, + color: tuple[int, int, int], + ) -> None: + x1, y1, x2, y2 = rectangle + cv2.rectangle(canvas, (x1, y1), (x2, y2), color, -1) + cv2.rectangle(canvas, (x1, y1), (x2, y2), (220, 220, 220), 1) + size, _ = cv2.getTextSize( + label, cv2.FONT_HERSHEY_SIMPLEX, 0.65, 2 + ) + x = x1 + max(8, (x2 - x1 - size[0]) // 2) + y = y1 + (y2 - y1 + size[1]) // 2 + cv2.putText( + canvas, + label, + (x, y), + cv2.FONT_HERSHEY_SIMPLEX, + 0.65, + (255, 255, 255), + 2, + cv2.LINE_AA, + ) + + def _gui_reason_text(self, assessment: PairAssessment) -> str: + return { + "waiting_for_images": "WAITING FOR IMAGES", + "image_skew_too_large": "IMAGE TIME DIFFERENCE TOO LARGE", + "checkerboard_missing": "FULL CHECKERBOARD NOT FOUND", + "reprojection_rms_too_large": "REPROJECTION RMS TOO HIGH", + "board_pose_too_close": "MOVE BOARD TO A NEW POSE", + "ready": "READY - ADD CANDIDATE", + }.get(assessment.reason_code, assessment.reason_code.upper()) + + def _gui_mouse_callback(self, event, x, y, flags, parameter) -> None: + del flags, parameter + if event != cv2.EVENT_LBUTTONUP: + return + buttons = getattr(self, "gui_buttons", {}) + for name, rectangle in buttons.items(): + x1, y1, x2, y2 = rectangle + if not (x1 <= x <= x2 and y1 <= y <= y2): + continue + if name in ("side", "top"): + self.gui_active_other = name + self.gui_last_assessment = None + self.gui_auto_pose = None + self.gui_auto_stable_since = None + self.gui_feedback = f"Selected FRONT + {name.upper()}" + elif name == "auto": + self.gui_auto_capture = not self.gui_auto_capture + self.gui_auto_pose = None + self.gui_auto_stable_since = None + self.gui_feedback = ( + "Auto capture enabled" + if self.gui_auto_capture + else "Auto capture disabled" + ) + elif name == "capture": + if ( + self.gui_last_assessment is not None + and self.gui_last_assessment.ready + ): + self.gui_action = "capture" + elif name == "save": + if all( + self.fit_results[view] is not None + and bool(self.fit_results[view].passed) + for view in ("side", "top") + ): + self.gui_action = "save" + break + + def _gui_timer_callback(self) -> None: + if not self.gui_enabled: + return + try: + action = self.gui_action + self.gui_action = None + if action == "capture": + response = self._capture_pair( + self.gui_active_other, Trigger.Response() + ) + if response.success: + self.gui_feedback = ( + f"Captured FRONT + {self.gui_active_other.upper()} " + f"{len(self.captures[self.gui_active_other])}/" + f"{self.minimum_captures}" + ) + self.get_logger().info(response.message) + else: + self.gui_feedback = "Capture rejected; see quality status" + self.get_logger().warning(response.message) + elif action == "save": + response = self._save(None, Trigger.Response()) + if response.success: + self.gui_feedback = f"Saved: {self.output_file}" + self.get_logger().info(response.message) + else: + self.gui_feedback = "Save failed; see terminal" + self.get_logger().warning(response.message) + + assessment = self._assess_pair(self.gui_active_other) + self.gui_last_assessment = assessment + active_fit = self.fit_results[self.gui_active_other] + if ( + self.gui_auto_capture + and active_fit is not None + and active_fit.passed + ): + self.gui_auto_capture = False + self.gui_feedback = ( + f"FRONT + {self.gui_active_other.upper()} PASSED; " + "switch pair" + ) + if self.gui_auto_capture and assessment.ready: + assert assessment.front_pose is not None + current_pose = ( + assessment.front_pose.camera_from_board_candidates[0] + ) + now = time.monotonic() + stable = False + if self.gui_auto_pose is not None: + rotation_change, translation_change = _transform_residual( + self.gui_auto_pose, current_pose + ) + stable = bool( + rotation_change <= math.radians(0.5) + and translation_change <= 0.002 + ) + if stable: + if self.gui_auto_stable_since is None: + self.gui_auto_stable_since = now + elif ( + now - self.gui_auto_stable_since + >= self.auto_capture_stable_seconds + ): + response = self._capture_pair( + self.gui_active_other, Trigger.Response() + ) + if response.success: + self.gui_feedback = ( + f"Auto captured FRONT + " + f"{self.gui_active_other.upper()} " + f"{len(self.captures[self.gui_active_other])}" + ) + self.get_logger().info(response.message) + else: + self.gui_feedback = "Auto capture rejected" + self.get_logger().warning(response.message) + self.gui_auto_pose = None + self.gui_auto_stable_since = None + assessment = self._assess_pair( + self.gui_active_other + ) + self.gui_last_assessment = assessment + else: + self.gui_auto_pose = current_pose.copy() + self.gui_auto_stable_since = now + else: + self.gui_auto_pose = None + self.gui_auto_stable_since = None + # Auto capture can update the fit during this callback. Render + # the new result immediately instead of showing stale metrics for + # one GUI period. + active_fit = self.fit_results[self.gui_active_other] + front_frame = assessment.front_frame + selected_frame = assessment.selected_frame + if front_frame is None and self.image_history["front"]: + front_frame = self.image_history["front"][-1] + if selected_frame is None and self.image_history[self.gui_active_other]: + selected_frame = self.image_history[self.gui_active_other][-1] + front_image = self._annotated_gui_frame( + front_frame, assessment.front_pose, "front" + ) + selected_image = self._annotated_gui_frame( + selected_frame, + assessment.selected_pose, + self.gui_active_other, + ) + view_width, view_height = 640, 488 + left = self._fit_gui_image(front_image, view_width, view_height) + right = self._fit_gui_image( + selected_image, view_width, view_height + ) + canvas = np.full((700, 1300, 3), 18, dtype=np.uint8) + canvas[10 : 10 + view_height, 5 : 5 + view_width] = left + canvas[10 : 10 + view_height, 655 : 655 + view_width] = right + + ready_color = (40, 220, 40) if assessment.ready else (0, 80, 230) + batch_status = "" + if active_fit is not None: + failures = _stereo_fit_failures( + active_fit, + minimum_inliers=self.minimum_captures, + maximum_rms_px=self.maximum_reprojection_rms_px, + maximum_rotation_stability_rad=( + self.maximum_rotation_repeatability_rad + ), + maximum_translation_stability_m=( + self.maximum_translation_repeatability_m + ), + ) + batch_status = ( + " | BATCH PASSED" + if not failures + else " | BATCH FAIL: " + ",".join(failures) + ) + cv2.putText( + canvas, + self._gui_reason_text(assessment) + batch_status, + (20, 530), + cv2.FONT_HERSHEY_SIMPLEX, + 0.85, + ready_color, + 2, + cv2.LINE_AA, + ) + pair_rms = ( + "--" + if assessment.pair_reprojection_rms_px is None + else f"{assessment.pair_reprojection_rms_px:.3f}" + ) + skew = ( + "--" + if assessment.skew_ns is None + else f"{assessment.skew_ns / 1e6:.1f}" + ) + batch_rms = ( + "--" if active_fit is None else f"{active_fit.stereo_rms_px:.3f}" + ) + rotation = ( + "--" + if active_fit is None + else f"{math.degrees(active_fit.rotation_stability_rad):.3f}" + ) + translation = ( + "--" + if active_fit is None + else f"{active_fit.translation_stability_m * 1000.0:.3f}" + ) + cv2.putText( + canvas, + "Pair RMS " + f"{pair_rms}/" + f"{self.maximum_candidate_pair_reprojection_rms_px:.3f}px " + f"Skew {skew}/{self.maximum_pair_skew_ns / 1e6:.1f}ms " + f"Batch RMS {batch_rms}/{self.maximum_reprojection_rms_px:.3f}px " + f"stability {rotation}/" + f"{math.degrees(self.maximum_rotation_repeatability_rad):.3f}deg " + f"{translation}/" + f"{self.maximum_translation_repeatability_m * 1000.0:.3f}mm", + (20, 562), + cv2.FONT_HERSHEY_SIMPLEX, + 0.52, + (220, 220, 220), + 1, + cv2.LINE_AA, + ) + cv2.putText( + canvas, + f"Candidates SIDE {len(self.stereo_captures['side'])} " + f"(inliers " + f"{0 if self.fit_results['side'] is None else len(self.fit_results['side'].inlier_indices)}) " + f"TOP {len(self.stereo_captures['top'])} (inliers " + f"{0 if self.fit_results['top'] is None else len(self.fit_results['top'].inlier_indices)}) | " + f"{self.gui_feedback}", + (20, 590), + cv2.FONT_HERSHEY_SIMPLEX, + 0.58, + (200, 200, 200), + 1, + cv2.LINE_AA, + ) + + self.gui_buttons = { + "side": (20, 615, 220, 680), + "top": (235, 615, 435, 680), + "auto": (450, 615, 635, 680), + "capture": (650, 615, 970, 680), + "save": (985, 615, 1280, 680), + } + self._draw_gui_button( + canvas, + self.gui_buttons["side"], + "FRONT + SIDE", + (170, 105, 20) + if self.gui_active_other == "side" + else (75, 75, 75), + ) + self._draw_gui_button( + canvas, + self.gui_buttons["top"], + "FRONT + TOP", + (170, 105, 20) + if self.gui_active_other == "top" + else (75, 75, 75), + ) + self._draw_gui_button( + canvas, + self.gui_buttons["auto"], + "AUTO ON" if self.gui_auto_capture else "AUTO OFF", + (30, 155, 30) if self.gui_auto_capture else (75, 75, 75), + ) + self._draw_gui_button( + canvas, + self.gui_buttons["capture"], + "ADD CANDIDATE" if assessment.ready else "ADD (DISABLED)", + (30, 155, 30) if assessment.ready else (65, 65, 65), + ) + save_ready = all( + self.fit_results[view] is not None + and bool(self.fit_results[view].passed) + for view in ("side", "top") + ) + self._draw_gui_button( + canvas, + self.gui_buttons["save"], + "SAVE" if save_ready else "SAVE (DISABLED)", + (30, 155, 30) if save_ready else (65, 65, 65), + ) + cv2.imshow(self.GUI_WINDOW, canvas) + cv2.waitKey(1) + except cv2.error as error: + self.gui_enabled = False + self.get_logger().error(f"Extrinsics GUI disabled: {error}") + + def _capture_front_side(self, request, response): + del request + return self._capture_pair("side", response) + + def _capture_front_top(self, request, response): + del request + return self._capture_pair("top", response) + + def _save_optical_verification(self, response): + import hashlib + from .core.artifacts.storage import atomic_write_json + from .core.geometry.extrinsics import load_camera_extrinsics + from .runtime.optical_verification import verify_optical_observations + try: + source = Path(self.verification_extrinsics_file).expanduser().resolve() + digest = hashlib.sha256(source.read_bytes()).hexdigest() + extrinsics = load_camera_extrinsics(source, required_views=VIEWS, reference_view='front') + dataset = dict(protocol='rectified_optical_check_v1', + board_id=f'checkerboard:{self.columns}x{self.rows}:{self.square_size_m:.9g}m', + camera_extrinsics_sha256=digest, object_points_m=self.object_points.tolist(), + captures=self.optical_captures) + # Keep failed observations too; the hand entry recomputes this + # numerical check and never trusts a stored passed flag. + atomic_write_json(self.output_file, dataset) + report = verify_optical_observations(dataset, extrinsics, self.camera_matrices, + extrinsics_sha256=digest) + atomic_write_json(self.output_file.with_suffix('.verification.json'), report) + response.success = True + response.message = f'冻结相机参数核验通过,原始角点已保存:{self.output_file}' + except (ValueError, OSError, KeyError, TypeError) as error: + response.success = False + response.message = f'光学核验未通过:{error}' + return response + + def _save(self, request, response): + del request + if self.verification_extrinsics_file: + return self._save_optical_verification(response) + if set(self.camera_identities) != set(VIEWS): + response.success = False + response.message = "三台相机内参尚未全部收到" + return response + if any( + len(self.stereo_captures[view]) < self.minimum_captures + for view in ("side", "top") + ): + response.success = False + response.message = ( + f"候选采集不足:side={len(self.stereo_captures['side'])}," + f"top={len(self.stereo_captures['top'])}" + ) + return response + results: dict[str, StereoFitResult] = {} + for view in ("side", "top"): + result = self._update_stereo_fit(view) + if result is None: + response.success = False + response.message = f"front/{view}联合外参拟合失败" + return response + results[view] = result + if any(not result.passed for result in results.values()): + response.success = False + diagnostics: list[str] = [] + for view, result in results.items(): + failures = _stereo_fit_failures( + result, + minimum_inliers=self.minimum_captures, + maximum_rms_px=self.maximum_reprojection_rms_px, + maximum_rotation_stability_rad=( + self.maximum_rotation_repeatability_rad + ), + maximum_translation_stability_m=( + self.maximum_translation_repeatability_m + ), + ) + diagnostics.append( + f"{view}: RMS={result.stereo_rms_px:.3f}px, " + f"内点={len(result.inlier_indices)}/" + f"{len(self.stereo_captures[view])}, " + f"旋转稳定性=" + f"{math.degrees(result.rotation_stability_rad):.3f}°, " + f"平移稳定性=" + f"{result.translation_stability_m * 1000.0:.3f}mm, " + f"未通过={','.join(failures) or '无'}" + ) + response.message = "联合外参质量不合格:" + "; ".join( + diagnostics + ) + return response + transforms = { + "front": np.eye(4), + "side": results["side"].front_from_other, + "top": results["top"].front_from_other, + } + quality = { + "passed": True, + "reprojection_rms_px": max( + result.stereo_rms_px for result in results.values() + ), + "maximum_rotation_repeatability_deg": math.degrees( + max( + result.rotation_stability_rad + for result in results.values() + ) + ), + "maximum_translation_repeatability_m": max( + result.translation_stability_m for result in results.values() + ), + "front_side_captures": len(results["side"].inlier_indices), + "front_top_captures": len(results["top"].inlier_indices), + "front_side_candidates": len(self.stereo_captures["side"]), + "front_top_candidates": len(self.stereo_captures["top"]), + "front_side_rejected": len(results["side"].rejected_indices), + "front_top_rejected": len(results["top"].rejected_indices), + } + dump_three_camera_extrinsics( + self.output_file, + cameras=self.camera_identities, + front_from_view=transforms, + quality=quality, + quality_limits={ + "reprojection_rms_px": self.maximum_reprojection_rms_px, + "maximum_rotation_repeatability_deg": math.degrees( + self.maximum_rotation_repeatability_rad + ), + "maximum_translation_repeatability_m": ( + self.maximum_translation_repeatability_m + ), + }, + ) + response.success = True + response.message = f"外参已保存:{self.output_file};{quality}" + return response + + def _reset(self, request, response): + del request + for values in self.captures.values(): + values.clear() + for values in self.capture_reprojection.values(): + values.clear() + for values in self.stereo_captures.values(): + values.clear() + for values in self.captured_front_board.values(): + values.clear() + self.fit_results = {"side": None, "top": None} + self.gui_auto_pose = None + self.gui_auto_stable_since = None + response.success = True + response.message = "已清空外参采样" + return response + + +def main(args: list[str] | None = None) -> None: + configure_fastdds_large_image_transport() + rclpy.init(args=args) + node = ThreeCameraExtrinsicsNode() + try: + rclpy.spin(node) + except KeyboardInterrupt: + pass + finally: + if node.gui_enabled: + cv2.destroyAllWindows() + node.destroy_node() + if rclpy.ok(): + rclpy.shutdown() + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/full_hand.py b/src/linkerhand_calibration/linkerhand_calibration/full_hand.py new file mode 100644 index 0000000..19dc6fd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/full_hand.py @@ -0,0 +1,7 @@ +"""One-release module alias for the relocated model profile implementation.""" + +import sys + +from linkerhand_calibration.models.g20 import profile as _implementation + +sys.modules[__name__] = _implementation diff --git a/src/linkerhand_calibration/linkerhand_calibration/hikrobot_camera.py b/src/linkerhand_calibration/linkerhand_calibration/hikrobot_camera.py new file mode 100644 index 0000000..ddb4b98 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/hikrobot_camera.py @@ -0,0 +1,675 @@ +"""ROS 2 image publisher for Hikrobot MVS USB3 Vision cameras.""" + +from __future__ import annotations + +from ctypes import byref, cast, memset, POINTER, sizeof, string_at +from dataclasses import dataclass +import importlib +import os +from pathlib import Path +import sys +from threading import Event, Lock, Thread +from typing import Any, Sequence +from urllib.parse import unquote, urlparse + +import rclpy +from rclpy.node import Node +from rclpy.qos import qos_profile_sensor_data +from sensor_msgs.msg import CameraInfo, Image +from sensor_msgs.srv import SetCameraInfo +import yaml + + +DEFAULT_MVS_PYTHON_PATH = "/opt/MVS/Samples/64/Python/MvImport" +DEFAULT_MVS_RUNTIME_PATH = "/opt/MVS/lib" + + +@dataclass(frozen=True) +class DeviceDescriptor: + """Stable identity fields for one enumerated USB3 Vision camera.""" + + index: int + model: str + serial: str + guid: str + + +@dataclass(frozen=True) +class CameraCalibration: + """Validated subset of a standard ROS camera calibration YAML file.""" + + camera_name: str + width: int + height: int + distortion_model: str + d: tuple[float, ...] + k: tuple[float, ...] + r: tuple[float, ...] + p: tuple[float, ...] + + +def decode_c_string(value: Any) -> str: + """Decode a null-terminated MVS SDK character array.""" + raw = bytes(value).split(b"\0", 1)[0] + for encoding in ("utf-8", "gbk", "latin-1"): + try: + return raw.decode(encoding) + except UnicodeDecodeError: + continue + return raw.decode("latin-1", errors="replace") + + +def select_device( + devices: Sequence[DeviceDescriptor], + selector: str, + expected_model: str, +) -> DeviceDescriptor: + """Select exactly one camera by serial or GUID and check its model.""" + if not devices: + raise RuntimeError("MVS did not enumerate any USB3 Vision cameras") + selector = selector.strip() + if selector: + matches = [ + device + for device in devices + if selector in {device.serial, device.guid} + ] + if not matches: + available = ", ".join( + f"{device.model}:{device.serial}:{device.guid}" + for device in devices + ) + raise RuntimeError( + f"camera selector {selector!r} was not found; " + f"available cameras: {available}" + ) + elif len(devices) == 1: + matches = [devices[0]] + else: + available = ", ".join(device.serial for device in devices) + raise RuntimeError( + "camera selector is required when multiple cameras are present; " + f"available serials: {available}" + ) + if len(matches) != 1: + raise RuntimeError(f"camera selector {selector!r} is not unique") + selected = matches[0] + if expected_model and expected_model not in selected.model: + raise RuntimeError( + f"camera {selected.serial} is {selected.model!r}, expected a model " + f"containing {expected_model!r}" + ) + return selected + + +def resolve_camera_info_path(url_or_path: str) -> Path | None: + """Resolve a plain path or file:// URL used for CameraInfo persistence.""" + value = url_or_path.strip() + if not value: + return None + parsed = urlparse(value) + if parsed.scheme not in {"", "file"}: + raise ValueError( + "camera_info_url must be a filesystem path or file:// URL" + ) + if parsed.scheme == "file": + if parsed.netloc not in {"", "localhost"}: + raise ValueError("remote file:// camera_info_url is not supported") + value = unquote(parsed.path) + return Path(value).expanduser().resolve() + + +def _matrix_data(mapping: dict[str, Any], name: str, length: int) -> tuple[float, ...]: + section = mapping.get(name) + if not isinstance(section, dict): + raise ValueError(f"camera calibration is missing {name}") + data = section.get("data") + if not isinstance(data, list) or len(data) != length: + raise ValueError(f"{name}.data must contain exactly {length} values") + result = tuple(float(value) for value in data) + if not all(value == value and abs(value) != float("inf") for value in result): + raise ValueError(f"{name}.data contains a non-finite value") + return result + + +def load_camera_calibration(path: Path) -> CameraCalibration: + """Load and validate a standard ROS camera calibration YAML file.""" + mapping = yaml.safe_load(path.read_text(encoding="utf-8")) + if not isinstance(mapping, dict): + raise ValueError("camera calibration YAML root must be a mapping") + width = int(mapping.get("image_width", 0)) + height = int(mapping.get("image_height", 0)) + if width <= 0 or height <= 0: + raise ValueError("camera calibration image dimensions must be positive") + distortion = mapping.get("distortion_coefficients") + if not isinstance(distortion, dict) or not isinstance( + distortion.get("data"), list + ): + raise ValueError( + "camera calibration is missing distortion_coefficients.data" + ) + d = tuple(float(value) for value in distortion["data"]) + calibration = CameraCalibration( + camera_name=str(mapping.get("camera_name", "hikrobot_camera")), + width=width, + height=height, + distortion_model=str(mapping.get("distortion_model", "plumb_bob")), + d=d, + k=_matrix_data(mapping, "camera_matrix", 9), + r=_matrix_data(mapping, "rectification_matrix", 9), + p=_matrix_data(mapping, "projection_matrix", 12), + ) + if calibration.k[0] <= 0.0 or calibration.k[4] <= 0.0: + raise ValueError("camera calibration focal lengths must be positive") + if calibration.p[0] <= 0.0 or calibration.p[5] <= 0.0: + raise ValueError("camera calibration projection focal lengths must be positive") + return calibration + + +def calibration_to_mapping( + camera_name: str, camera_info: CameraInfo +) -> dict[str, Any]: + """Convert CameraInfo into the standard ROS YAML representation.""" + return { + "image_width": int(camera_info.width), + "image_height": int(camera_info.height), + "camera_name": camera_name, + "camera_matrix": { + "rows": 3, + "cols": 3, + "data": [float(value) for value in camera_info.k], + }, + "distortion_model": camera_info.distortion_model, + "distortion_coefficients": { + "rows": 1, + "cols": len(camera_info.d), + "data": [float(value) for value in camera_info.d], + }, + "rectification_matrix": { + "rows": 3, + "cols": 3, + "data": [float(value) for value in camera_info.r], + }, + "projection_matrix": { + "rows": 3, + "cols": 4, + "data": [float(value) for value in camera_info.p], + }, + } + + +def configure_fastdds_large_image_transport() -> Path: + """Select the package's large-image SHM profile before creating ROS nodes.""" + from ament_index_python.packages import get_package_share_directory + + profile = ( + Path(get_package_share_directory("linkerhand_calibration")) + / "config" + / "fastdds_large_images.xml" + ) + if not profile.is_file(): + raise RuntimeError(f"Fast DDS large-image profile not found: {profile}") + os.environ.setdefault("FASTRTPS_DEFAULT_PROFILES_FILE", str(profile)) + return profile + + +class HikrobotCameraNode(Node): + """Publish synchronized Mono8 Image and CameraInfo messages from MVS.""" + + def __init__(self) -> None: + super().__init__("hikrobot_camera") + self._declare_parameters() + self._stop_event = Event() + self._camera_info_lock = Lock() + self._grab_thread: Thread | None = None + self._camera: Any | None = None + self._mvs: Any | None = None + self._sdk_initialized = False + self._handle_created = False + self._camera_opened = False + self._grabbing = False + self._closed = False + self._frame_count = 0 + self._timeout_count = 0 + self._camera_timing = None + + self.selector = str(self.get_parameter("serial_number").value) + self.expected_model = str(self.get_parameter("expected_model").value) + self.frame_id = str(self.get_parameter("frame_id").value) + self.camera_name = str(self.get_parameter("camera_name").value) + self.image_width = int(self.get_parameter("image_width").value) + self.image_height = int(self.get_parameter("image_height").value) + if self.image_width <= 0 or self.image_height <= 0: + raise ValueError("image_width and image_height must be positive") + if float(self.get_parameter("frame_rate").value) <= 0.0: + raise ValueError("frame_rate must be positive") + if int(self.get_parameter("grab_timeout_ms").value) <= 0: + raise ValueError("grab_timeout_ms must be positive") + self.camera_info_path = resolve_camera_info_path( + str(self.get_parameter("camera_info_url").value) + ) + self._calibration = self._load_calibration() + + self.image_publisher = self.create_publisher( + Image, "image_raw", qos_profile_sensor_data + ) + self.camera_info_publisher = self.create_publisher( + CameraInfo, "camera_info", qos_profile_sensor_data + ) + self.create_service( + SetCameraInfo, "set_camera_info", self._set_camera_info_callback + ) + + try: + self._open_camera() + self._grab_thread = Thread( + target=self._grab_loop, + name="hikrobot_mvs_grab", + daemon=True, + ) + self._grab_thread.start() + except Exception: + self.close() + raise + + def _declare_parameters(self) -> None: + self.declare_parameter("serial_number", "") + self.declare_parameter("expected_model", "MV-CS020-10UM") + self.declare_parameter("camera_name", "hikrobot_front") + self.declare_parameter("frame_id", "camera_color_optical_frame") + self.declare_parameter("image_width", 1624) + self.declare_parameter("image_height", 1240) + self.declare_parameter("frame_rate", 30.0) + self.declare_parameter("exposure_time_us", 5000.0) + self.declare_parameter("gain_db", 0.0) + self.declare_parameter("auto_exposure", False) + self.declare_parameter("camera_info_url", "") + self.declare_parameter("mvs_python_path", DEFAULT_MVS_PYTHON_PATH) + self.declare_parameter("mvs_runtime_path", DEFAULT_MVS_RUNTIME_PATH) + self.declare_parameter("grab_timeout_ms", 1000) + self.declare_parameter("timestamp_journal_path", "") + + def _load_calibration(self) -> CameraCalibration | None: + if self.camera_info_path is None or not self.camera_info_path.exists(): + target = self.camera_info_path or "an unset camera_info_url" + self.get_logger().warning( + f"No camera calibration found at {target}; publishing " + "uncalibrated CameraInfo. Trajectory calibration will remain " + "locked until valid intrinsics are installed." + ) + return None + calibration = load_camera_calibration(self.camera_info_path) + self._validate_calibration_dimensions(calibration) + self.get_logger().info( + f"Loaded camera intrinsics from {self.camera_info_path}" + ) + return calibration + + def _validate_calibration_dimensions( + self, calibration: CameraCalibration + ) -> None: + if ( + calibration.width != self.image_width + or calibration.height != self.image_height + ): + raise ValueError( + "camera calibration dimensions " + f"{calibration.width}x{calibration.height} do not match " + f"configured stream {self.image_width}x{self.image_height}" + ) + + def _import_mvs(self) -> Any: + python_path = Path( + str(self.get_parameter("mvs_python_path").value) + ).expanduser() + runtime_path = Path( + str(self.get_parameter("mvs_runtime_path").value) + ).expanduser() + if not python_path.is_dir(): + raise RuntimeError(f"MVS Python bindings not found: {python_path}") + if not runtime_path.is_dir(): + raise RuntimeError(f"MVS runtime not found: {runtime_path}") + os.environ.setdefault("MVCAM_COMMON_RUNENV", str(runtime_path)) + if str(python_path) not in sys.path: + sys.path.insert(0, str(python_path)) + return importlib.import_module("MvCameraControl_class") + + def _enumerate_usb_cameras( + self, mvs: Any + ) -> tuple[Any, list[DeviceDescriptor]]: + device_list = mvs.MV_CC_DEVICE_INFO_LIST() + result = mvs.MvCamera.MV_CC_EnumDevices( + mvs.MV_USB_DEVICE, device_list + ) + self._require_ok("enumerate USB3 Vision devices", result) + descriptors: list[DeviceDescriptor] = [] + for index in range(device_list.nDeviceNum): + device_info = cast( + device_list.pDeviceInfo[index], POINTER(mvs.MV_CC_DEVICE_INFO) + ).contents + usb_info = device_info.SpecialInfo.stUsb3VInfo + descriptors.append( + DeviceDescriptor( + index=index, + model=decode_c_string(usb_info.chModelName), + serial=decode_c_string(usb_info.chSerialNumber), + guid=decode_c_string(usb_info.chDeviceGUID), + ) + ) + return device_list, descriptors + + def _open_camera(self) -> None: + mvs = self._import_mvs() + self._mvs = mvs + self._require_ok("initialize MVS SDK", mvs.MvCamera.MV_CC_Initialize()) + self._sdk_initialized = True + device_list, descriptors = self._enumerate_usb_cameras(mvs) + selected = select_device(descriptors, self.selector, self.expected_model) + device_info = cast( + device_list.pDeviceInfo[selected.index], + POINTER(mvs.MV_CC_DEVICE_INFO), + ).contents + + camera = mvs.MvCamera() + self._require_ok("create camera handle", camera.MV_CC_CreateHandle(device_info)) + self._camera = camera + self._handle_created = True + self._require_ok( + "open camera", + camera.MV_CC_OpenDevice(mvs.MV_ACCESS_Exclusive, 0), + ) + self._camera_opened = True + + self._set_required_enum("AcquisitionMode", "Continuous") + self._set_required_enum("TriggerMode", "Off") + self._set_required_enum("PixelFormat", "Mono8") + self._set_required_integer("OffsetX", 0) + self._set_required_integer("OffsetY", 0) + self._set_required_integer("Width", self.image_width) + self._set_required_integer("Height", self.image_height) + self._set_optional_bool("AcquisitionFrameRateEnable", True) + self._set_optional_float( + "AcquisitionFrameRate", + float(self.get_parameter("frame_rate").value), + ) + if bool(self.get_parameter("auto_exposure").value): + self._set_required_enum("ExposureAuto", "Continuous") + else: + self._set_required_enum("ExposureAuto", "Off") + self._set_optional_float( + "ExposureTime", + float(self.get_parameter("exposure_time_us").value), + ) + self._set_required_enum("GainAuto", "Off") + self._set_optional_float( + "Gain", float(self.get_parameter("gain_db").value) + ) + + self._require_ok( + "set latest-frame grab strategy", + camera.MV_CC_SetGrabStrategy(mvs.MV_GrabStrategy_LatestImagesOnly), + ) + from .camera_timing import MvsCameraTiming + self._camera_timing = MvsCameraTiming(camera, mvs, + lambda: int(self.get_clock().now().nanoseconds), + exposure_us=0. if bool(self.get_parameter("auto_exposure").value) + else float(self.get_parameter("exposure_time_us").value), + journal_path=str(self.get_parameter("timestamp_journal_path").value)) + self._camera_timing.start() + self._require_ok("start image acquisition", camera.MV_CC_StartGrabbing()) + self._grabbing = True + self.get_logger().info( + "Opened Hikrobot camera " + f"model={selected.model} serial={selected.serial} " + f"guid={selected.guid} stream={self.image_width}x{self.image_height} " + "encoding=mono8" + ) + + def _set_required_enum(self, name: str, value: str) -> None: + assert self._camera is not None + self._require_ok( + f"set {name}={value}", + self._camera.MV_CC_SetEnumValueByString(name, value), + ) + + def _set_required_integer(self, name: str, value: int) -> None: + assert self._camera is not None + self._require_ok( + f"set {name}={value}", + self._camera.MV_CC_SetIntValueEx(name, value), + ) + + def _set_optional_bool(self, name: str, value: bool) -> None: + assert self._camera is not None + result = self._camera.MV_CC_SetBoolValue(name, value) + if result != 0: + self.get_logger().warning( + f"MVS could not set {name}={value}: 0x{result:08x}" + ) + + def _set_optional_float(self, name: str, value: float) -> None: + assert self._camera is not None + result = self._camera.MV_CC_SetFloatValue(name, value) + if result != 0: + self.get_logger().warning( + f"MVS could not set {name}={value}: 0x{result:08x}" + ) + + @staticmethod + def _require_ok(operation: str, result: int) -> None: + if result != 0: + hint = "" + if result == 0x80000203: + hint = ( + "; access denied: stop acquisition and close the MVS " + "viewer or any other process using this camera" + ) + raise RuntimeError( + f"MVS failed to {operation}: 0x{result:08x}{hint}" + ) + + def _grab_loop(self) -> None: + assert self._camera is not None + assert self._mvs is not None + timeout_ms = int(self.get_parameter("grab_timeout_ms").value) + recovering_clock = False + while not self._stop_event.is_set(): + try: + self._camera_timing.refresh_if_due() + except ValueError as error: + if not recovering_clock: + self.get_logger().error( + f"Camera timestamp source failed: {error}; " + "pausing images and retrying clock synchronization" + ) + self._camera_timing.invalidate(error) + recovering_clock = True + self._stop_event.wait(0.2) + continue + if recovering_clock: + self.get_logger().info( + "Camera clock synchronized again; resuming image acquisition" + ) + recovering_clock = False + frame = self._mvs.MV_FRAME_OUT() + memset(byref(frame), 0, sizeof(frame)) + result = self._camera.MV_CC_GetImageBuffer(frame, timeout_ms) + if result != 0: + self._timeout_count += 1 + if self._timeout_count == 1 or self._timeout_count % 10 == 0: + self.get_logger().warning( + "MVS image acquisition timed out or failed: " + f"0x{result:08x}; consecutive={self._timeout_count}" + ) + continue + try: + self._timeout_count = 0 + self._publish_frame(frame) + except Exception as error: + self.get_logger().error(f"Failed to publish MVS frame: {error}") + finally: + free_result = self._camera.MV_CC_FreeImageBuffer(frame) + if free_result != 0: + self.get_logger().error( + f"MVS failed to release frame: 0x{free_result:08x}" + ) + + def _publish_frame(self, frame: Any) -> None: + assert self._mvs is not None + info = frame.stFrameInfo + width = int(info.nWidth) + height = int(info.nHeight) + if width != self.image_width or height != self.image_height: + raise RuntimeError( + f"received {width}x{height}, expected " + f"{self.image_width}x{self.image_height}" + ) + if int(info.enPixelType) != int(self._mvs.PixelType_Gvsp_Mono8): + raise RuntimeError( + f"received pixel type 0x{int(info.enPixelType):x}, expected Mono8" + ) + expected_size = width * height + if int(info.nFrameLen) < expected_size: + raise RuntimeError( + f"frame contains {info.nFrameLen} bytes, expected {expected_size}" + ) + from rclpy.time import Time + received_ns = int(self.get_clock().now().nanoseconds) + stamp = Time(nanoseconds=self._camera_timing.timestamp(info, received_ns)).to_msg() + image = Image() + image.header.stamp = stamp + image.header.frame_id = self.frame_id + image.height = height + image.width = width + image.encoding = "mono8" + image.is_bigendian = 0 + image.step = width + image.data = string_at(frame.pBufAddr, expected_size) + + camera_info = self._make_camera_info(width, height) + camera_info.header.stamp = stamp + camera_info.header.frame_id = self.frame_id + self.image_publisher.publish(image) + self.camera_info_publisher.publish(camera_info) + self._frame_count += 1 + + def _make_camera_info(self, width: int, height: int) -> CameraInfo: + message = CameraInfo() + message.width = width + message.height = height + with self._camera_info_lock: + calibration = self._calibration + if calibration is None: + message.distortion_model = "plumb_bob" + message.d = [] + message.k = [0.0] * 9 + message.r = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0] + message.p = [0.0] * 12 + return message + message.distortion_model = calibration.distortion_model + message.d = list(calibration.d) + message.k = list(calibration.k) + message.r = list(calibration.r) + message.p = list(calibration.p) + return message + + def _set_camera_info_callback( + self, + request: SetCameraInfo.Request, + response: SetCameraInfo.Response, + ) -> SetCameraInfo.Response: + try: + if self.camera_info_path is None: + raise ValueError( + "camera_info_url is empty; set it before saving calibration" + ) + message = request.camera_info + if ( + int(message.width) != self.image_width + or int(message.height) != self.image_height + ): + raise ValueError( + f"calibration is {message.width}x{message.height}, expected " + f"{self.image_width}x{self.image_height}" + ) + mapping = calibration_to_mapping(self.camera_name, message) + self.camera_info_path.parent.mkdir(parents=True, exist_ok=True) + temporary_path = self.camera_info_path.with_suffix( + self.camera_info_path.suffix + ".tmp" + ) + temporary_path.write_text( + yaml.safe_dump(mapping, sort_keys=False), encoding="utf-8" + ) + temporary_path.replace(self.camera_info_path) + calibration = load_camera_calibration(self.camera_info_path) + self._validate_calibration_dimensions(calibration) + with self._camera_info_lock: + self._calibration = calibration + response.success = True + response.status_message = ( + f"saved camera calibration to {self.camera_info_path}" + ) + self.get_logger().info(response.status_message) + except Exception as error: + response.success = False + response.status_message = str(error) + self.get_logger().error( + f"Rejected camera calibration: {response.status_message}" + ) + return response + + def close(self) -> None: + if self._closed: + return + self._closed = True + self._stop_event.set() + if self._grab_thread is not None: + self._grab_thread.join(timeout=2.0) + if self._camera_timing is not None: + self._camera_timing.close() + if self._camera is not None and self._camera_opened: + if self._grabbing: + result = self._camera.MV_CC_StopGrabbing() + if result != 0: + self.get_logger().warning( + f"MVS failed to stop grabbing: 0x{result:08x}" + ) + self._grabbing = False + result = self._camera.MV_CC_CloseDevice() + if result != 0: + self.get_logger().warning( + f"MVS failed to close camera: 0x{result:08x}" + ) + self._camera.MV_CC_DestroyHandle() + elif self._camera is not None and self._handle_created: + self._camera.MV_CC_DestroyHandle() + self._camera = None + self._handle_created = False + self._camera_opened = False + if self._sdk_initialized and self._mvs is not None: + self._mvs.MvCamera.MV_CC_Finalize() + self._sdk_initialized = False + + def destroy_node(self) -> None: + self.close() + super().destroy_node() + + +def main(args: list[str] | None = None) -> None: + configure_fastdds_large_image_transport() + rclpy.init(args=args) + node: HikrobotCameraNode | None = None + try: + node = HikrobotCameraNode() + rclpy.spin(node) + except KeyboardInterrupt: + pass + finally: + if node is not None: + node.destroy_node() + if rclpy.ok(): + rclpy.shutdown() + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/models/README.md b/src/linkerhand_calibration/linkerhand_calibration/models/README.md new file mode 100644 index 0000000..b6b4400 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/models/README.md @@ -0,0 +1,8 @@ +# 按手型整理的标定内容 + +- `g20/`、`l6/`、`o12/`、`o30/`、`o6/`:各型号专属程序、配置和左右手源 URDF。 +- 每个目录下的 `config/` 是型号配置;`urdf/left` 和 `urdf/right` 是源模型。 +- `registry.py` 是旧型号插件使用的共享注册表。 +- `core/`、`runtime/`、`profiles/` 继续放通用采集、求解和验收程序,不在各型号目录复制。 + +原先的 `config/`、`urdf/`、`compat/legacy_diagnostic_tools/models/` 路径作为兼容入口保留。型号 YAML 与 URDF 文件内容没有改动,旧产品配置中的 SHA-256 和 `package://` 路径继续有效。旧目录下的型号配置和 URDF 在源码树中指向新位置,安装时会同时提供旧资源路径。 diff --git a/src/linkerhand_calibration/linkerhand_calibration/models/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/models/__init__.py new file mode 100644 index 0000000..6230ec8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/models/__init__.py @@ -0,0 +1 @@ +"""Hand-specific calibration definitions and immutable resources.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/models/registry.py b/src/linkerhand_calibration/linkerhand_calibration/models/registry.py new file mode 100644 index 0000000..6430a57 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/models/registry.py @@ -0,0 +1,99 @@ +"""Local, deterministic profile registry for this ROS package.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Callable, Iterator + +from linkerhand_calibration.core import CalibrationProfile, ProfileKey, validate_profile +from linkerhand_calibration.runtime.engine import CalibrationEngine +from linkerhand_calibration.runtime.adapters import ProfileSdkAdapter + + +@dataclass(frozen=True) +class EngineBindings: + """Small model plugin: SDK I/O hooks plus compatible CLI serializers.""" + + hand_profile: Any + zero_profile: Any + motion_command: Callable[..., list[int]] + preparation_waypoints: Callable[..., tuple[tuple[int, ...], ...]] + return_waypoints: Callable[..., tuple[tuple[int, ...], ...]] + cli_main: Callable[[list[str] | None], None] + node_main: Callable[[list[str] | None], None] + sdk_adapter_factory: Callable[[Any], ProfileSdkAdapter] = ProfileSdkAdapter + + +@dataclass(frozen=True) +class RegisteredProfile: + profile: CalibrationProfile + engine: EngineBindings + + def build_engine(self) -> CalibrationEngine: + return CalibrationEngine(self.profile) + + def build_sdk_adapter(self) -> ProfileSdkAdapter: + return self.engine.sdk_adapter_factory(self.profile.command) + + +class ProfileRegistry: + """An in-package registry; no discovery plugins or string evaluation.""" + + def __init__(self) -> None: + self._profiles: dict[ProfileKey, RegisteredProfile] = {} + + def register(self, registered: RegisteredProfile) -> None: + validate_profile(registered.profile) + key = registered.profile.key + existing = self._profiles.get(key) + if existing is not None and existing != registered: + raise ValueError(f"profile is already registered: {key.profile_id}") + self._profiles[key] = registered + + def get(self, key: ProfileKey) -> RegisteredProfile: + try: + return self._profiles[key] + except KeyError as error: + supported = ", ".join( + item.profile_id for item in sorted(self._profiles) + ) + raise ValueError( + f"unsupported calibration profile {key.profile_id}; " + f"registered={supported}" + ) from error + + def resolve( + self, + model: str, + side: str, + layout: str, + revision: int = 1, + ) -> RegisteredProfile: + return self.get(ProfileKey(model, side, layout, revision)) + + def __iter__(self) -> Iterator[RegisteredProfile]: + for key in sorted(self._profiles): + yield self._profiles[key] + + def __len__(self) -> int: + return len(self._profiles) + + +_DEFAULT_REGISTRY: ProfileRegistry | None = None + + +def get_default_registry() -> ProfileRegistry: + global _DEFAULT_REGISTRY + if _DEFAULT_REGISTRY is None: + from linkerhand_calibration.models.g20 import register_profiles + from linkerhand_calibration.models.l6 import register_profiles as register_l6_profiles + from linkerhand_calibration.models.o6 import register_profiles as register_o6_profiles + from linkerhand_calibration.models.o12 import register_profiles as register_o12_profiles + + registry = ProfileRegistry() + register_profiles(registry) + register_l6_profiles(registry) + register_o6_profiles(registry) + register_o12_profiles(registry) + _DEFAULT_REGISTRY = registry + return _DEFAULT_REGISTRY diff --git a/src/linkerhand_calibration/linkerhand_calibration/offline_replay.py b/src/linkerhand_calibration/linkerhand_calibration/offline_replay.py new file mode 100644 index 0000000..b3ff58d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/offline_replay.py @@ -0,0 +1,7 @@ +"""One-release module alias for the relocated model replay implementation.""" + +import sys + +from linkerhand_calibration.models.g20 import offline_replay as _implementation + +sys.modules[__name__] = _implementation diff --git a/src/linkerhand_calibration/linkerhand_calibration/one_command.py b/src/linkerhand_calibration/linkerhand_calibration/one_command.py new file mode 100644 index 0000000..215f599 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/one_command.py @@ -0,0 +1,9 @@ +"""Compatibility import for the generic registered-profile runner.""" + +from .runtime.runner import main + +__all__ = ["main"] + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/operator_report.py b/src/linkerhand_calibration/linkerhand_calibration/operator_report.py new file mode 100644 index 0000000..be89347 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/operator_report.py @@ -0,0 +1,642 @@ +"""Stable Chinese progress and copy/paste diagnostics for non-expert users.""" + +from __future__ import annotations + +from dataclasses import dataclass +import json +import math +from pathlib import Path +import time +from typing import Any, Mapping + +from .product import ProductConfig +from .storage import atomic_write_json +from .three_camera_diagnostics import JOINT_NAMES_ZH, STATE_NAMES_ZH, three_camera_reason_zh + + +def _duration(seconds: float | None) -> str: + if seconds is None or not math.isfinite(seconds) or seconds < 0.0: + return "计算中" + value = int(round(seconds)) + return f"{value // 60}分{value % 60:02d}秒" + + +def render_compact_progress_header_zh( + *, + serial_number: str, + progress: float, + eta: str, + stage: str, + cycle: object, + repetitions: object, + task: str, + requested: object, + actual: object, + direction: str, + tag_status: str, + ready_cameras: int, + feedback_hz: float, + valid_frames: int, + automatic_retry_count: int, +) -> list[str]: + """Render the model-independent five-line operator progress header.""" + return [ + f"[{serial_number}] 标定中 {float(progress) * 100:5.1f}% " + f"预计剩余 {eta}", + f"阶段:{stage}(第 {cycle}/{repetitions} 轮)", + f"任务:{task} 命令/反馈:{requested}/{actual} 方向:{direction}", + f"Tag:{tag_status} 相机:{int(ready_cameras)}/3 正常 " + f"反馈:{float(feedback_hz):.1f} Hz", + f"质量:有效帧 {int(valid_frames)} 已自动重扫 " + f"{int(automatic_retry_count)} 次", + ] + + +def _task_tag_id_status(views: Mapping[str, Any]) -> str: + """Render every currently required Tag ID with its live visibility.""" + labels = {"front": "正面", "side": "侧面", "top": "顶部"} + ordered_views = [ + *[name for name in ("front", "side", "top") if name in views], + *sorted(name for name in views if name not in labels), + ] + groups: list[str] = [] + for name in ordered_views: + item = views.get(name, {}) + if not isinstance(item, Mapping): + continue + required = sorted({int(value) for value in item.get("required_tag_ids", [])}) + if not required: + continue + visible = {int(value) for value in item.get("detected_tag_ids", [])} + locked = { + int(value) + for value in item.get("locked_reference_tag_ids", []) + } + ids = ",".join( + f"{tag_id}{'锁' if tag_id in locked else '✓' if tag_id in visible else '✗'}" + for tag_id in required + ) + groups.append(f"{labels.get(name, name)}[{ids}]") + if not groups: + return "" + return ( + " 当前任务ID:" + + " ".join(groups) + + "(✓实时可见/锁=基准锁定/✗不可用)" + ) + + +def _pnp_wait_status(views: Mapping[str, Any]) -> str: + """Explain why visible Tags have not produced a usable 3-D pose.""" + labels = {"front": "正面", "side": "侧面", "top": "顶部"} + details: list[str] = [] + for name in ("front", "side", "top"): + item = views.get(name, {}) + if not isinstance(item, Mapping) or item.get("pnp_pose_valid"): + continue + parts: list[str] = [] + progress = item.get("pnp_initialization_progress") + if isinstance(progress, Mapping): + parts.append( + "初始化" + f"{int(progress.get('accepted', 0))}/" + f"{int(progress.get('required', 0))}" + ) + counts: dict[str, int] = {} + for field in ("pnp_rejection_counts", "group_pnp_rejection_counts"): + values = item.get(field, {}) + if not isinstance(values, Mapping): + continue + for reason, count in values.items(): + counts[str(reason)] = counts.get(str(reason), 0) + int(count) + if counts: + common = sorted( + counts.items(), key=lambda pair: (-pair[1], pair[0]) + )[:2] + parts.append( + "拒绝=" + ",".join(f"{reason}×{count}" for reason, count in common) + ) + if parts: + details.append(f"{labels[name]} " + ";".join(parts)) + if not details: + return "" + return "PnP:" + " | ".join(details) + "(Tag可见不等于三维位姿有效)" + + +@dataclass +class ProgressEstimator: + started_at: float + last_progress: float = 0.0 + last_progress_at: float = 0.0 + seconds_per_fraction: float | None = None + + @classmethod + def start(cls) -> "ProgressEstimator": + now = time.monotonic() + return cls(started_at=now, last_progress_at=now) + + def remaining(self, progress: float, now: float | None = None) -> float | None: + current = time.monotonic() if now is None else float(now) + value = float(max(0.0, min(1.0, progress))) + delta = value - self.last_progress + elapsed = current - self.last_progress_at + if delta >= 0.002 and elapsed > 0.0: + estimate = elapsed / delta + self.seconds_per_fraction = ( + estimate + if self.seconds_per_fraction is None + else 0.8 * self.seconds_per_fraction + 0.2 * estimate + ) + self.last_progress = value + self.last_progress_at = current + if value >= 1.0: + return 0.0 + if self.seconds_per_fraction is not None: + return max(0.0, self.seconds_per_fraction * (1.0 - value)) + if value >= 0.02: + return max(0.0, (current - self.started_at) * (1.0 - value) / value) + return None + + +def render_progress_zh( + serial_number: str, + status: Mapping[str, Any], + estimator: ProgressEstimator, +) -> str: + progress = float(status.get("progress", 0.0)) + active = status.get("active", {}) + if not isinstance(active, Mapping): + active = {} + state = str(status.get("state", "PREFLIGHT")) + stage = STATE_NAMES_ZH.get(state, state) + preflight_mode = str(status.get("preflight_mode", "")) + if preflight_mode == "device_only_before_baseline": + stage = "设备连接预检" + elif preflight_mode == "recovering_baseline": + stage = "安全恢复基准形态" + elif preflight_mode == "baseline_tags_after_recovery": + stage = "基准姿态标签预检" + elif str(status.get("reason", "")) == ( + "holding_same_finger_clearance_before_next_task" + ): + stage = "保持避让姿态,切换同指下一项" + elif str(status.get("reason", "")) == ( + "waiting_for_task_tags_at_sweep_start" + ): + stage = "已到扫描起点,等待任务Tag" + joints = active.get("joints", []) + joint = "/".join(JOINT_NAMES_ZH.get(str(name), str(name)) for name in joints) + if str(active.get("task_name", "")).endswith("_roll_multiview") and joints: + joint = ( + JOINT_NAMES_ZH.get(str(joints[0]), str(joints[0])) + + "(正面+侧面同步)" + ) + if not joint: + import_progress = status.get("base_import", {}) + import_fraction = ( + float(import_progress.get("fraction", 0.0)) + if isinstance(import_progress, Mapping) + else 0.0 + ) + joint = str(active.get("label_zh", "")) or ( + f"导入基础会话 {100.0 * import_fraction:.1f}%" + if state in {"IMPORTING_BASE", "REVALIDATING_INHERITED"} + else ( + "等待设备" if state in {"PREFLIGHT", "WAIT_START"} else "全手" + ) + ) + direction = { + "decreasing": "递减", + "increasing": "递增", + }.get(str(active.get("direction", "")), "-") + cycle = active.get("cycle", "-") + repetitions = active.get("repetitions", 4) + requested = active.get( + "current_motion_target_u8", + active.get("command_u8", active.get("pose_name", "-")), + ) + actual = active.get("actual_u8", "-") + views = status.get("views", {}) + if not isinstance(views, Mapping): + views = {} + ready_cameras = sum( + bool(item.get("camera_info_valid") and item.get("camera_extrinsics_valid")) + for item in views.values() + if isinstance(item, Mapping) + ) + required_tags = sum( + len(item.get("required_tag_ids", [])) + for item in views.values() + if isinstance(item, Mapping) + ) + visible_tags = sum( + len( + { + *item.get("detected_tag_ids", []), + *item.get("locked_reference_tag_ids", []), + } + ) + for item in views.values() + if isinstance(item, Mapping) + ) + locked_tag_count = sum( + len(item.get("locked_reference_tag_ids", [])) + for item in views.values() + if isinstance(item, Mapping) + ) + configured_tags = sum( + len(item.get("configured_tag_ids", item.get("required_tag_ids", []))) + for item in views.values() + if isinstance(item, Mapping) + ) + visible_configured_tags = sum( + len( + item.get( + "visible_configured_tag_ids", + item.get("detected_tag_ids", []), + ) + ) + for item in views.values() + if isinstance(item, Mapping) + ) + occlusion_allowed = bool( + state in {"PREFLIGHT", "WAIT_START"} + or active.get("pose_name") + ) + if preflight_mode == "device_only_before_baseline": + tag_status = ( + f"当前 {visible_configured_tags}/{configured_tags}" + "(基准恢复后检查)" + ) + elif preflight_mode == "recovering_baseline": + tag_status = ( + f"当前 {visible_configured_tags}/{configured_tags}" + "(恢复中不作为门槛)" + ) + elif occlusion_allowed: + tag_status = ( + f"当前 {visible_configured_tags}/{configured_tags}(允许遮挡) " + f"本阶段必需 {visible_tags}/{required_tags}" + ) + else: + tag_status = ( + f"{visible_tags}/{required_tags} 可见" + + (f"(含锁定 {locked_tag_count})" if locked_tag_count else "") + ) + task_tag_ids = ( + _task_tag_id_status(views) + if state + in { + "PREPARE_SWEEP", + "SWEEP", + "VALIDATION_MOVE", + "VALIDATION_CAPTURE", + } + else "" + ) + retry = int(active.get("automatic_retry_count", 0)) + fit_attempt = int(active.get("fit_attempt", 1)) + fit_attempt_limit = int(active.get("fit_attempt_limit", 1)) + feedback_hz = float(status.get("feedback_hz", 0.0)) + eta = ( + "等待Tag" + if str(status.get("reason", "")) + == "waiting_for_task_tags_at_sweep_start" + else _duration(estimator.remaining(progress)) + ) + lines = render_compact_progress_header_zh( + serial_number=serial_number, + progress=progress, + eta=eta, + stage=stage, + cycle=cycle, + repetitions=repetitions, + task=joint, + requested=requested, + actual=actual, + direction=direction, + tag_status=tag_status + task_tag_ids, + ready_cameras=ready_cameras, + feedback_hz=feedback_hz, + valid_frames=int(active.get("valid_frames", 0)), + automatic_retry_count=retry, + ) + if str(status.get("reason", "")) == "waiting_for_task_tags_at_sweep_start": + pnp_wait = _pnp_wait_status(views) + if pnp_wait: + lines.append(pnp_wait) + fit_retry_cycles = [ + int(cycle) for cycle in active.get("fit_retry_cycles", []) + ] + if fit_attempt > 1 and fit_retry_cycles: + cycle_text = "/".join(str(cycle) for cycle in fit_retry_cycles) + if len(fit_retry_cycles) >= repetitions: + lines.append( + "拟合:首次拟合未能定位单一异常轮," + f"联合补采第 {cycle_text} 轮双向" + ) + else: + lines.append( + f"拟合:首次拟合定位第 {cycle_text} 轮需复核," + "仅补采对应轮次双向;其余轮次数据保留" + ) + elif fit_attempt_limit > 1: + lines.append( + f"拟合:任务级硬门限检查(最多允许 " + f"{fit_attempt_limit - 1} 次异常轮补采)" + ) + resume = status.get("resume", {}) + if isinstance(resume, Mapping): + position_policy = str(resume.get("start_position_policy", "")) + if resume.get("checkpoint_pending"): + lines.append( + "断点:正在建立本次起始位置基准,完成后再决定是否复用旧任务" + ) + elif position_policy.startswith("discard_all_tasks_"): + lines.append( + "位置:检测到标定前机械手位置已变化或旧位置无法可靠验证;" + "未混用旧断点,本次整手从头采集" + ) + elif resume.get("used"): + lines.append( + "断点:已恢复 " + f"{int(resume.get('completed_task_count', 0))}/" + f"{int(resume.get('total_task_count', 16))} 个完整任务;" + "起始位置一致,失败任务已丢弃并重新采集" + ) + return "\n".join(lines) + + +def classify_error(reason: str, status: Mapping[str, Any]) -> tuple[str, str, str]: + value = str(reason) + active = status.get("active", {}) + if not isinstance(active, Mapping): + active = {} + views = status.get("views", {}) + missing = [ + tag + for item in views.values() + if isinstance(item, Mapping) + for tag in item.get("missing_tag_ids", []) + ] if isinstance(views, Mapping) else [] + group_pnp_reasons = [ + str(item.get("group_pnp_reason")) + for item in views.values() + if isinstance(item, Mapping) and item.get("group_pnp_reason") + ] if isinstance(views, Mapping) else [] + pnp_diagnostics_present = bool( + group_pnp_reasons + or ( + isinstance(views, Mapping) + and any( + isinstance(item, Mapping) + and any( + item.get(field) + for field in ( + "pnp_rejection_counts", + "group_pnp_rejection_counts", + "pnp_initialization_progress", + "group_missing_candidate_roles", + ) + ) + for item in views.values() + ) + ) + ) + if value.startswith("CFG-"): + return value, "产品配置或文件预检失败", "不要移动相机;复制本诊断块给开发者。" + if value.startswith("DATA-CONTRACT-"): + return ( + value.split(":", 1)[0], + "标定样本的请求命令与反馈值数据契约不完整", + "机械手无需重新采集;保留原始会话并用离线重放验证," + "复制契约错误给开发者。", + ) + if value.startswith("CAM-STATUS-202"): + return ( + "CAM-STATUS-202", + "标定节点启动后未发布状态", + "机械手尚未开始运动;查看calibration.log中首个节点异常后从断点继续。", + ) + if value.startswith("MOTION-COMM-303"): + return ( + "MOTION-COMM-303", + "标定节点状态心跳停止更新", + "已采集的完整任务会保留;检查calibration.log后从断点继续,不要重新采集。", + ) + if value == "fixed_base_reference_moved": + return ( + "CAM-REFERENCE-204", + "顶部基准Tag在本次标定开始后发生移动", + "Tag 8可在新会话预检前重新摆放;固定Tag 8和顶部相机后启动新会话。", + ) + if "palm_orientation_quality_failed" in value: + return ( + "VAL-QUALITY-501", + "掌部方向校正的可观测轨迹不足", + "保持Tag安装不变;调整标定前手位,使正面Tag 10–13至少三枚" + "在对应运动起始段可见。", + ) + if "motor_state_stalled" in value: + return "MOTION-STALL-301", "电机反馈停止向目标推进,程序已保持当前位置", "先检查机械卡阻,未排除前不要重复强推。" + if any( + token in value + for token in ( + "sweep_missing_endpoint_bin", + "sweep_bins_too_few", + "sweep_bin_gap_too_large", + "task_precheck_missing_command_127", + ) + ): + return "OBS-SAMPLE-104", "当前任务的有效视觉轨迹不完整", "根据诊断中的关节、机位和缺失区间处理遮挡或反光后重新运行。" + if ( + ("synchronised" in value or "sweep_start_tag_timeout" in value) + and not missing + and pnp_diagnostics_present + ): + problem = ( + "Tag可见,但三维PnP轨迹在运动中失效" + if value.startswith("synchronised") + and int(active.get("valid_frames", 0) or 0) > 0 + else "Tag可见,但三维PnP位姿初始化未完成" + ) + return ( + "CAM-GEOMETRY-201", + problem, + "不要根据二维码可见性调整Tag;复制累计PnP拒绝原因给开发者。", + ) + if missing or "tag" in value or "detection" in value or "synchronised" in value: + return "OBS-TAG-103", f"所需Tag不可用或持续丢失:{missing}", "检查Tag是否脱落、翘起、反光或被遮挡后重新运行。" + if "state" in value and ("timeout" in value or "lost" in value): + return "MOTION-COMM-302", "机械手反馈中断或频率不足", "检查CAN接口和机械手供电后重新运行。" + if "camera" in value or "pnp" in value or "extrinsics" in value: + return "CAM-GEOMETRY-201", "相机、内外参或位姿求解未通过", "确认三台相机没有移动,然后复制本诊断块给开发者。" + if "checkpoint" in value: + return "FIT-CHECKPOINT-402", "稳态检查点采集流程未完整结束", "完整样本已保留;复制本诊断块给开发者检查采集状态机。" + if "fit" in value or "trajectory" in value or "axis" in value: + return "FIT-MODEL-401", "关节轴或动态曲线拟合未达到精度门限", "不要放宽门限;复制本诊断块给开发者分析原始样本。" + if ( + "endpoint_zero_offsets' is not defined" in value + or "validated_endpoint_zero_state" in value + ): + return ( + "PUB-ARTIFACT-601", + "已验证零位状态未能完整传递到URDF发布阶段", + "采集与验证数据仍可保留;不要移动相机或Tag,复制诊断块给开发者。", + ) + if "validation" in value or "combination" in value or "quality" in value or "zero" in value: + return "VAL-QUALITY-501", "留出验证或URDF零位验证未通过", "结果不会发布;复制本诊断块给开发者。" + if "publish" in value or "artifact" in value or "URDF" in value: + return "PUB-ARTIFACT-601", "结果文件校验或原子发布失败", "原始URDF未被覆盖;复制本诊断块给开发者。" + return "PUB-UNEXPECTED-699", "标定程序出现未分类异常", "复制本诊断块给开发者,完整堆栈已写入calibration.log。" + + +def build_failure_report( + config: ProductConfig, + session: str | Path, + status: Mapping[str, Any], + *, + reason: str, +) -> tuple[dict[str, Any], str]: + directory = Path(session).resolve() + code, problem, suggestion = classify_error(reason, status) + active = status.get("active", {}) + if not isinstance(active, Mapping): + active = {} + else: + active = dict(active) + views = status.get("views", {}) + if isinstance(views, Mapping): + group_pnp_reasons = { + str(view): str(item.get("group_pnp_reason")) + for view, item in views.items() + if isinstance(item, Mapping) and item.get("group_pnp_reason") + } + if group_pnp_reasons: + active["group_pnp_reasons"] = group_pnp_reasons + for field in ( + "pnp_rejection_counts", + "group_pnp_rejection_counts", + "pnp_initialization_progress", + "group_missing_candidate_roles", + "pnp_candidate_diagnostics", + ): + values = { + str(view): item.get(field) + for view, item in views.items() + if isinstance(item, Mapping) and item.get(field) + } + if values: + active[field] = values + try: + explanation, automatic_action = three_camera_reason_zh( + str(status.get("state", "")), reason, active + ) + except Exception: + explanation, automatic_action = problem, "已停止本次发布并保留全部诊断数据" + camera_state = { + view: ( + "OK" + if isinstance(item, Mapping) + and item.get("camera_info_valid", item.get("ready")) + and item.get("camera_extrinsics_valid", item.get("ready")) + and item.get("stream_alive", item.get("ready")) + else "NOT_READY" + ) + for view, item in (views.items() if isinstance(views, Mapping) else []) + } + session_id = f"{config.serial_number}_{directory.name}" + metrics = { + "valid_frames": active.get("valid_frames"), + "sample": active.get("sample", {}), + "detection_frames": active.get("detection_frames"), + "detection_valid_frames": active.get("detection_valid_frames"), + "detection_rate": active.get("detection_rate"), + "detection_rate_by_view": active.get("detection_rate_by_view", {}), + "automatic_retry_count": active.get("automatic_retry_count", 0), + } + pnp_diagnostics = { + str(view): { + field: item.get(field) + for field in ( + "group_pnp_reason", + "group_missing_candidate_roles", + "pnp_rejections", + "pnp_rejection_counts", + "group_pnp_rejection_counts", + "pnp_initialization_progress", + "pnp_candidate_diagnostics", + ) + if item.get(field) + } + for view, item in ( + views.items() if isinstance(views, Mapping) else [] + ) + if isinstance(item, Mapping) + and any( + item.get(field) + for field in ( + "group_pnp_reason", + "group_missing_candidate_roles", + "pnp_rejections", + "pnp_rejection_counts", + "group_pnp_rejection_counts", + "pnp_initialization_progress", + "pnp_candidate_diagnostics", + ) + ) + } + payload: dict[str, Any] = { + "schema_version": 1, + "serial_number": config.serial_number, + "session_id": session_id, + "result": "FAIL", + "error_code": code, + "stage": str(status.get("state", "startup")), + "reason": str(reason), + "problem_zh": problem, + "explanation_zh": explanation, + "automatic_action_zh": automatic_action, + "suggestion_zh": suggestion, + "metrics": metrics, + "pnp_diagnostics": pnp_diagnostics, + "camera_state": camera_state, + "feedback_hz": status.get("feedback_hz", 0.0), + "hashes": { + "product_config_sha256": __import__("hashlib").sha256(config.path.read_bytes()).hexdigest(), + "camera_extrinsics_sha256": config.camera_extrinsics_sha256, + "calibration_config_sha256": config.calibration_config_sha256, + "source_urdf_sha256": config.source_urdf_sha256, + }, + "session_dir": str(directory), + "quality": {"passed": False}, + } + atomic_write_json(directory / "calibration_summary_zh.json", payload) + block = "\n".join( + [ + "========== 请复制以下内容给开发者 ==========", + f"会话编号:{session_id}", + "结果:FAIL", + f"错误代码:{code}", + f"失败阶段:{payload['stage']}", + f"问题:{problem}", + f"详细说明:{explanation}", + f"自动处理:{automatic_action}", + f"关键指标:{json.dumps(metrics, ensure_ascii=False, separators=(',', ':'))}", + "PnP诊断:" + + json.dumps( + pnp_diagnostics, + ensure_ascii=False, + separators=(",", ":"), + ), + f"相机状态:{json.dumps(camera_state, ensure_ascii=False, separators=(',', ':'))}", + f"反馈状态:{float(payload['feedback_hz'] or 0.0):.1f} Hz", + f"配置哈希:{payload['hashes']['product_config_sha256']}", + f"外参哈希:{config.camera_extrinsics_sha256}", + f"源 URDF 哈希:{config.source_urdf_sha256}", + f"会话目录:{directory}", + f"建议:{suggestion}", + "========== 复制结束 ==========", + ] + ) + return payload, block diff --git a/src/linkerhand_calibration/linkerhand_calibration/pnp.py b/src/linkerhand_calibration/linkerhand_calibration/pnp.py new file mode 100644 index 0000000..970bf40 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/pnp.py @@ -0,0 +1,3 @@ +"""Compatibility import for the model-independent PnP implementation.""" + +from .core.geometry.pnp import * # noqa: F401,F403 diff --git a/src/linkerhand_calibration/linkerhand_calibration/product.py b/src/linkerhand_calibration/linkerhand_calibration/product.py new file mode 100644 index 0000000..3225cb5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/product.py @@ -0,0 +1,502 @@ +"""Immutable product identity and shared calibration preflight. + +Model-specific kinematics live in registered calibration contracts. The +loader itself only verifies that the selected contract, Tag configuration, +cameras and immutable artifacts agree, so adding another hand does not +require another copy of the one-command runner. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import hashlib +import math +from pathlib import Path +import re +from typing import Any, Mapping +import xml.etree.ElementTree as ET + +import yaml + +from .compat import ( + product_profile_key, + resolve_legacy_profile_alias, + resolve_renamed_package_path, +) +from .core import CalibrationProfile, ProfileKey +from .core.geometry import camera_info_fingerprint, load_camera_extrinsics +from linkerhand_calibration.compat.legacy_diagnostic_tools.models import RegisteredProfile, get_default_registry +from .profiles import load_hand_profile + + +@dataclass(frozen=True) +class ProductCalibrationContract: + """Compatibility facade over one typed, locally registered profile.""" + + registered: RegisteredProfile | None = None + declarative: CalibrationProfile | None = None + + @property + def model(self) -> str: + return self.typed_profile.key.model + + @property + def side(self) -> str: + return self.typed_profile.key.side + + @property + def layout_id(self) -> str: + return self.typed_profile.key.layout + + @property + def typed_profile(self) -> CalibrationProfile: + if self.declarative is not None: + return self.declarative + if self.registered is None: + raise ValueError("product has no calibration profile") + return self.registered.profile + + def _legacy_binding(self): + # Transitional offline/API compatibility. Product validation itself + # never resolves a Python model or constructs its online state machine. + registered = self.registered or get_default_registry().get(self.typed_profile.key) + return registered.engine + + @property + def profile(self): + return self._legacy_binding().hand_profile + + @property + def zero_profile(self): + return self._legacy_binding().zero_profile + + @property + def required_tag_ids(self) -> frozenset[int]: + return self.typed_profile.vision.tag_ids + + @property + def views(self) -> tuple[str, ...]: + return self.typed_profile.vision.view_names + + +def get_product_calibration_contract( + model: str, side: str, layout_id: str, revision: int = 1 +) -> ProductCalibrationContract: + key = resolve_legacy_profile_alias( + ProfileKey(model, side, layout_id, revision) + ) + return ProductCalibrationContract( + get_default_registry().get(key) + ) + + +def sha256_file(path: str | Path) -> str: + digest = hashlib.sha256() + with Path(path).open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +def _mapping(value: Any, name: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise ValueError(f"{name} must be a mapping") + return value + + +def _resolve_path(value: Any, *, workspace: Path, name: str) -> Path: + text = str(value).strip() + if not text: + raise ValueError(f"{name} is required") + return resolve_renamed_package_path(text, workspace) + + +def _camera_info_fingerprint(path: Path) -> str: + with path.open("r", encoding="utf-8") as stream: + payload = _mapping(yaml.safe_load(stream), str(path)) + + def values(key: str) -> list[float]: + item = _mapping(payload.get(key, {}), key) + return [float(value) for value in item.get("data", [])] + + return camera_info_fingerprint( + width=int(payload["image_width"]), + height=int(payload["image_height"]), + camera_matrix=values("camera_matrix"), + distortion=values("distortion_coefficients"), + rectification=values("rectification_matrix"), + projection=values("projection_matrix"), + ) + + +def _tag_sizes_m_by_id(path: Path) -> dict[int, float]: + with path.open("r", encoding="utf-8") as stream: + payload = _mapping(yaml.safe_load(stream), str(path)) + result: dict[int, float] = {} + for node in payload.values(): + parameters = _mapping(_mapping(node, "tag node").get("ros__parameters"), "ros__parameters") + tag = _mapping(parameters.get("tag"), "tag") + ids = [int(value) for value in tag.get("ids", [])] + sizes = [float(value) for value in tag.get("sizes", [])] + if len(ids) != len(sizes): + raise ValueError("Tag IDs and sizes must have the same length") + if set(result).intersection(ids): + raise ValueError("Tag IDs must be unique across the three views") + if any(not 0.0 < size < 0.1 for size in sizes): + raise ValueError("Tag sizes must be in (0, 0.1) metres") + result.update(zip(ids, sizes)) + return result + + +def _custom_pnp_tag_sizes_m_by_id( + path: Path, configured_ids: set[int] +) -> dict[int, float]: + with path.open("r", encoding="utf-8") as stream: + payload = _mapping(yaml.safe_load(stream), str(path)) + candidates = [ + _mapping(node, str(name)).get("ros__parameters") + for name, node in payload.items() + if isinstance(node, Mapping) + and isinstance(node.get("ros__parameters"), Mapping) + and "tag_size_m" in node["ros__parameters"] + ] + if len(candidates) != 1: + raise ValueError( + "calibration config must contain exactly one Tag-size parameter set" + ) + parameters = _mapping(candidates[0], "ros__parameters") + default = float(parameters.get("tag_size_m", 0.0)) + ids = [int(value) for value in parameters.get("tag_size_override_ids", [])] + sizes = [float(value) for value in parameters.get("tag_size_overrides_m", [])] + if len(ids) != len(sizes) or len(set(ids)) != len(ids): + raise ValueError("custom PnP Tag-size overrides are invalid") + if any(tag_id not in configured_ids for tag_id in ids): + raise ValueError("custom PnP Tag-size override ID is not configured") + result = {tag_id: default for tag_id in configured_ids} + result.update(zip(ids, sizes)) + return result + + +def _validate_profile_urdf( + profile: CalibrationProfile, source_urdf: Path +) -> None: + """Verify every zero and mimic target before a hardware command is sent.""" + root = ET.parse(source_urdf).getroot() + urdf_joints = { + str(joint.get("name")) + for joint in root.findall("joint") + if joint.get("name") + } + required = ( + set(profile.zero.active_joints) + | set(profile.zero.passive_joints) + | set(profile.zero.mimic_source_by_joint) + | set(profile.zero.mimic_source_by_joint.values()) + ) + missing = required - urdf_joints + if missing: + raise ValueError( + "source URDF is missing profile joints: " + + ", ".join(sorted(missing)) + ) + + +@dataclass(frozen=True) +class ProductConfig: + path: Path + workspace: Path + schema_version: int + profile_key: ProfileKey + namespace: str + model: str + side: str + tag_layout: str + calibration_contract: ProductCalibrationContract + serial_number: str + can_interface: str + source_urdf: Path + source_urdf_sha256: str + camera_extrinsics: Path + camera_extrinsics_sha256: str + calibration_config: Path + calibration_config_sha256: str + tag_config: Path + tag_config_sha256: str + output_root: Path + cameras: Mapping[str, Mapping[str, str]] + required_independent_passes: int + static_repeatability_rad: float + sdk_driver: str = "linker_hand_sdk" + sdk_transport: str = "socketcan" + sdk_setup: Path | None = None + sdk_config: Path | None = None + sdk_config_sha256: str = "" + sdk_python_package: Path | None = None + sdk_package_sha256: str = "" + profile_config: Path | None = None + profile_config_sha256: str = "" + resume_mode: str = "verify" + + @property + def session_root(self) -> Path: + return self.output_root / self.serial_number + + +def load_product_config( + path: str | Path, + *, + workspace: str | Path | None = None, + check_can: bool = True, +) -> ProductConfig: + """Load a protected YAML contract without requiring a Python model plugin.""" + source = Path(path).expanduser().resolve() + if not source.is_file(): + raise ValueError(f"product config does not exist: {source}") + with source.open("r", encoding="utf-8") as stream: + raw = _mapping(yaml.safe_load(stream), str(source)) + profile_key = product_profile_key(raw) + root = Path.cwd().resolve() if workspace is None else Path(workspace).resolve() + serial = str(raw.get("serial_number", "")) + if re.fullmatch(r"[A-Za-z0-9_.-]+", serial) is None: + raise ValueError("serial_number is invalid") + model = profile_key.model + side = profile_key.side + layout = profile_key.layout + profile_config: Path | None = None + profile_config_hash = "" + if raw.get("profile_config"): + profile_config = _resolve_path( + raw.get("profile_config"), workspace=root, name="profile_config" + ) + if not profile_config.is_file(): + raise ValueError(f"profile config does not exist: {profile_config}") + profile_config_hash = str(raw.get("profile_config_sha256", "")).lower() + if re.fullmatch(r"[0-9a-f]{64}", profile_config_hash) is None: + raise ValueError("profile config expected SHA-256 is invalid") + if sha256_file(profile_config) != profile_config_hash: + raise ValueError("profile config SHA-256 mismatch") + declarative = load_hand_profile(profile_config) + if declarative.key != profile_key: + raise ValueError("declarative profile identity differs from the product") + # Check again after decoding so an edited file cannot be paired with + # the hash of a previous version during a concurrent configuration edit. + if sha256_file(profile_config) != profile_config_hash: + raise ValueError("profile config changed while loading") + contract = ProductCalibrationContract(declarative=declarative) + else: + # Archived configurations without a profile path remain readable by + # offline diagnostics until their legacy format is retired. + contract = get_product_calibration_contract(model, side, layout, profile_key.revision) + namespace = str( + raw.get("namespace", contract.typed_profile.namespace) + ).strip() + if not namespace.startswith("/") or namespace.endswith("/"): + raise ValueError("namespace must be an absolute ROS namespace") + sdk_raw = _mapping(raw.get("sdk", {}), "sdk") + sdk_driver = str(sdk_raw.get("driver", "linker_hand_sdk")).strip() + sdk_transport = str(sdk_raw.get("transport", "socketcan")).strip().lower() + can_interface = str(raw.get("can_interface", "")).strip() + if sdk_transport == "socketcan": + if not can_interface: + raise ValueError("can_interface is required for SocketCAN products") + if check_can and not (Path("/sys/class/net") / can_interface).exists(): + raise ValueError(f"CAN interface does not exist: {can_interface}") + elif sdk_transport not in {"hcan", "libcanbus"}: + raise ValueError("sdk.transport must be socketcan, hcan or libcanbus") + if sdk_transport == "libcanbus" and contract.typed_profile.sdk_adapter != "o30_ros": + raise ValueError("libcanbus requires its O30 ROS SDK adapter") + + if contract.typed_profile.sdk_adapter == "o30_ros" and sdk_transport != "libcanbus": + raise ValueError("O30 calibration launch currently requires sdk.transport: libcanbus") + sdk_setup: Path | None = None + sdk_config: Path | None = None + sdk_config_hash = "" + sdk_python_package, sdk_package_hash = None, "" + if sdk_raw.get("setup") and sdk_transport != "hcan": + sdk_setup = _resolve_path(sdk_raw["setup"], workspace=root, name="sdk.setup") + if not sdk_setup.is_file(): + raise ValueError("vendor SDK overlay must exist; build the external SDK in this workspace") + if sdk_raw.get("python_package"): + sdk_python_package = _resolve_path(sdk_raw["python_package"], workspace=root, name="sdk.python_package") + sdk_package_hash = str(sdk_raw.get("package_sha256", "")).lower() + if re.fullmatch(r"[0-9a-f]{64}", sdk_package_hash) is None or not sdk_python_package.is_file() or sha256_file(sdk_python_package) != sdk_package_hash: + raise ValueError("vendor Python SDK package SHA-256 mismatch") + if sdk_transport == "hcan": + sdk_setup = _resolve_path( + sdk_raw.get("setup"), workspace=root, name="sdk.setup" + ) + sdk_config = _resolve_path( + sdk_raw.get("config"), workspace=root, name="sdk.config" + ) + if not sdk_setup.is_file() or not sdk_config.is_file(): + raise ValueError("vendor SDK overlay and config must exist") + sdk_config_hash = str(sdk_raw.get("config_sha256", "")).lower() + if re.fullmatch(r"[0-9a-f]{64}", sdk_config_hash) is None: + raise ValueError("SDK config expected SHA-256 is invalid") + actual_sdk_hash = sha256_file(sdk_config) + if actual_sdk_hash != sdk_config_hash: + raise ValueError( + "SDK config SHA-256 mismatch: " + f"expected={sdk_config_hash} actual={actual_sdk_hash}" + ) + + artifacts = _mapping(raw.get("artifacts"), "artifacts") + source_urdf = _resolve_path( + artifacts.get("source_urdf"), workspace=root, name="source_urdf" + ) + extrinsics = _resolve_path( + artifacts.get("camera_extrinsics"), + workspace=root, + name="camera_extrinsics", + ) + calibration_config = _resolve_path( + artifacts.get("calibration_config"), + workspace=root, + name="calibration_config", + ) + tag_config = _resolve_path( + artifacts.get("tag_config"), workspace=root, name="tag_config" + ) + for name, candidate in ( + ("source URDF", source_urdf), + ("camera extrinsics", extrinsics), + ("calibration config", calibration_config), + ("Tag config", tag_config), + ): + if not candidate.is_file(): + raise ValueError(f"{name} does not exist: {candidate}") + + expected_source_hash = str(artifacts.get("source_urdf_sha256", "")).lower() + expected_extrinsics_hash = str( + artifacts.get("camera_extrinsics_sha256", "") + ).lower() + expected_tag_hash = str(artifacts.get("tag_config_sha256", "")).lower() + expected_calibration_hash = str( + artifacts.get("calibration_config_sha256", "") + ).lower() + hashes = ( + ("source URDF", source_urdf, expected_source_hash), + ("camera extrinsics", extrinsics, expected_extrinsics_hash), + ("Tag config", tag_config, expected_tag_hash), + ("calibration config", calibration_config, expected_calibration_hash), + ) + for name, candidate, expected in hashes: + if re.fullmatch(r"[0-9a-f]{64}", expected) is None: + raise ValueError(f"{name} expected SHA-256 is invalid") + actual = sha256_file(candidate) + if actual != expected: + raise ValueError(f"{name} SHA-256 mismatch: expected={expected} actual={actual}") + _validate_profile_urdf(contract.typed_profile, source_urdf) + if profile_config is not None: + from .profiles.validator import validate_executable_profile + validate_executable_profile(contract.typed_profile, source_urdf) + + expected_tag_ids = set(contract.required_tag_ids) + tag_sizes = _tag_sizes_m_by_id(tag_config) + if profile_config is not None and any(not math.isclose(tag.size_m, tag_sizes.get(tag.tag_id, -1), abs_tol=1e-12) + for view in contract.typed_profile.vision.views for tag in view.tags): + raise ValueError("Profile Tag side lengths differ from the protected detector configuration") + if set(tag_sizes) != expected_tag_ids: + raise ValueError( + f"{model}/{side}/{layout} Tag IDs differ from the registered " + f"profile: expected={sorted(expected_tag_ids)} " + f"actual={sorted(tag_sizes)}" + ) + if _custom_pnp_tag_sizes_m_by_id( + calibration_config, expected_tag_ids + ) != tag_sizes: + raise ValueError( + "custom PnP Tag sizes do not match the apriltag_ros Tag config" + ) + + camera_raw = _mapping(raw.get("cameras"), "cameras") + required_views = tuple(contract.views) + if set(camera_raw) != set(required_views): + raise ValueError(f"cameras must contain {'/'.join(required_views)}") + vision = contract.typed_profile.vision + loaded_extrinsics = load_camera_extrinsics( + extrinsics, + required_views=required_views, + reference_view=vision.extrinsic_reference_view, + quality_limits=vision.extrinsics_quality_limits, + minimum_capture_counts=vision.minimum_capture_counts, + ) + cameras: dict[str, dict[str, str]] = {} + serials: set[str] = set() + for view in required_views: + item = _mapping(camera_raw[view], f"cameras.{view}") + camera_serial = str(item.get("serial_number", "")) + info_path = _resolve_path( + item.get("camera_info"), workspace=root, name=f"{view}.camera_info" + ) + if not info_path.is_file(): + raise ValueError(f"{view} camera info does not exist: {info_path}") + if camera_serial in serials: + raise ValueError("the three camera serial numbers must be unique") + serials.add(camera_serial) + identity = loaded_extrinsics.cameras[view] + fingerprint = _camera_info_fingerprint(info_path) + if camera_serial != identity.serial_number: + raise ValueError(f"{view} camera serial does not match extrinsics") + if fingerprint != identity.intrinsics_sha256: + raise ValueError(f"{view} camera intrinsics do not match extrinsics") + gain_db = float(item.get("gain_db", 0.0)) + if not math.isfinite(gain_db) or not 0.0 <= gain_db <= 24.0: + raise ValueError(f"{view} camera gain_db must be finite and in [0, 24] dB") + cameras[view] = { + "serial_number": camera_serial, + "camera_info": str(info_path), + "camera_name": str(item.get("camera_name", f"hikrobot_{view}_{camera_serial}")), + "gain_db": str(gain_db), + } + + output_root = _resolve_path( + raw.get("output_root", "calibration_output"), + workspace=root, + name="output_root", + ) + release = _mapping(raw.get("release", {}), "release") + passes = int(release.get("required_independent_passes", 2)) + if passes not in {1, 2}: + raise ValueError("required_independent_passes must be 1 or 2") + repeatability_deg = float(release.get("static_repeatability_deg", 1.0)) + if not 0.0 < repeatability_deg <= 5.0: + raise ValueError("static_repeatability_deg must be in (0, 5]") + resume_mode = str(raw.get("resume_mode", "verify")) + if resume_mode not in {"verify", "passed"}: + raise ValueError("resume_mode must be verify or passed") + return ProductConfig( + path=source, + workspace=root, + schema_version=int(raw["schema_version"]), + profile_key=profile_key, + namespace=namespace, + model=model, + side=side, + tag_layout=layout, + calibration_contract=contract, + serial_number=serial, + can_interface=can_interface, + source_urdf=source_urdf, + source_urdf_sha256=expected_source_hash, + camera_extrinsics=extrinsics, + camera_extrinsics_sha256=expected_extrinsics_hash, + calibration_config=calibration_config, + calibration_config_sha256=expected_calibration_hash, + tag_config=tag_config, + tag_config_sha256=expected_tag_hash, + output_root=output_root, + cameras=cameras, + required_independent_passes=passes, + static_repeatability_rad=repeatability_deg * 3.141592653589793 / 180.0, + sdk_driver=sdk_driver, + sdk_transport=sdk_transport, + sdk_setup=sdk_setup, + sdk_config=sdk_config, + sdk_config_sha256=sdk_config_hash, + sdk_python_package=sdk_python_package, + sdk_package_sha256=sdk_package_hash, + profile_config=profile_config, + profile_config_sha256=profile_config_hash, + resume_mode=resume_mode, + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/__init__.py new file mode 100644 index 0000000..0f4e3c6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/__init__.py @@ -0,0 +1,12 @@ +"""Declarative hand-profile loading and registration.""" + +from .export import dump_hand_profile, hand_profile_payload, write_hand_profile +from .loader import load_hand_profile, load_bundled_hand_profile + +__all__ = [ + "dump_hand_profile", + "hand_profile_payload", + "load_hand_profile", + "load_bundled_hand_profile", + "write_hand_profile", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/diagnostics.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/diagnostics.py new file mode 100644 index 0000000..6871d6b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/diagnostics.py @@ -0,0 +1,71 @@ +"""Temporary diagnostic task selections, declared beside hand Profiles.""" + +from dataclasses import dataclass + +from ..core.domain.profile import ProfileKey + + +@dataclass(frozen=True) +class DiagnosticCapturePreset: + profile_key: ProfileKey + tasks: tuple[tuple[str, tuple[str, ...]], ...] + label_zh: str = "诊断采集" + hold_command_values: tuple[float, ...] = () + hold_seconds: float = 0.0 + observer_views: tuple[str, ...] = () + chain_joints: tuple[str, ...] = () + + +DIAGNOSTIC_CAPTURE_PRESETS = { + "o30_pinky_chain": DiagnosticCapturePreset( + ProfileKey("O30", "right", "o30_right_18", 1), + tuple((f"pinky_{joint}_side", (f"pinky_{joint}",)) + for joint in ("mcp_pitch", "pip", "dip")), + label_zh="小指两轮训练+独立验证采集(原 MCP/PIP 参考交接,未验收不发布)", + chain_joints=("pinky_mcp_pitch", "pinky_pip", "pinky_dip"), + ), + "o30_all_tasks": DiagnosticCapturePreset( + ProfileKey("O30", "right", "o30_right_18", 1), + tuple((f"thumb_{joint}_{view}", (f"thumb_{joint}",)) + for joint, view in (("cmc_roll", "front"), ("mcp", "front"), + ("ip", "front"), ("cmc_yaw", "top"))) + + tuple((f"{finger}_{joint}_side", (f"{finger}_{joint}",)) + for finger in ("pinky", "ring", "middle", "index") + for joint in ("mcp_pitch", "pip", "dip")) + + (("fingers_mcp_roll_front", ("pinky_mcp_roll", "ring_mcp_roll", + "middle_mcp_roll", "index_mcp_roll")),), + label_zh="全手全部任务单轮排查(非正式验收)", + ), + "o30_finger_roll_views": DiagnosticCapturePreset( + ProfileKey("O30", "right", "o30_right_18", 1), + (("fingers_mcp_roll_front", ("pinky_mcp_roll", "ring_mcp_roll", + "middle_mcp_roll", "index_mcp_roll")),), + label_zh="既有四指侧摆任务双机位观测诊断", + observer_views=("side",), + ), + "o30_pinky_side": DiagnosticCapturePreset( + ProfileKey("O30", "right", "o30_right_18", 1), + (("pinky_mcp_pitch_side", ("pinky_mcp_pitch",)), + ("pinky_pip_side", ("pinky_pip",)), + ("pinky_dip_side", ("pinky_dip",))), + label_zh="小指侧面 MCP/PIP/DIP 诊断", + ), + "o30_thumb_roll": DiagnosticCapturePreset( + ProfileKey("O30", "right", "o30_right_18", 1), + (("thumb_cmc_roll_front", ("thumb_cmc_roll",)),), + label_zh="拇指 roll 多标签诊断", + ), + "o6_thumb": DiagnosticCapturePreset( + ProfileKey("O6", "right", "o6_right_8", 1), + (("thumb_yaw_top", ("rh_thumb_cmc_yaw",)), + ("thumb_pitch_ip_front", ("rh_thumb_cmc_pitch", "rh_thumb_ip"))), + label_zh="拇指短程诊断", + ), + "o6_yaw_hold": DiagnosticCapturePreset( + ProfileKey("O6", "right", "o6_right_8", 1), + (("thumb_yaw_top", ("rh_thumb_cmc_yaw",)),), + label_zh="拇指yaw方向差保持诊断", + hold_command_values=(64.0, 128.0, 192.0), + hold_seconds=10.0, + ), +} diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/export.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/export.py new file mode 100644 index 0000000..6ba4601 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/export.py @@ -0,0 +1,87 @@ +"""Canonical serialization for reviewed hand profiles. + +The runtime loader is deliberately independent of model Python modules. This +writer exists to migrate the four established profiles without maintaining a +second, hand-written representation of the same contract. +""" + +from __future__ import annotations + +from dataclasses import asdict +from pathlib import Path +from typing import Any, Mapping + +import yaml + +from ..core import CalibrationProfile + + +def _plain(value: Any) -> Any: + if isinstance(value, Mapping): + return {str(key): _plain(item) for key, item in value.items()} + if isinstance(value, (set, frozenset)): + return sorted(_plain(item) for item in value) + if isinstance(value, tuple): + return [_plain(item) for item in value] + if isinstance(value, list): + return [_plain(item) for item in value] + return value + + +def hand_profile_payload(profile: CalibrationProfile) -> dict[str, Any]: + """Return the complete YAML contract accepted by ``load_hand_profile``.""" + if profile.quality.task_training_cycles: + raise ValueError("executed training decisions belong to the journal, not a reusable profile") + command = _plain(asdict(profile.command)) + vision = _plain(asdict(profile.vision)) + for view in vision["views"]: + for tag in view["tags"]: + tag["id"] = tag.pop("tag_id") + payload = { + "schema_version": 1, + "profile_id": profile.key.profile_id, + "namespace": profile.namespace, + "sdk_adapter": profile.sdk_adapter, + "command": command, + "vision": vision, + "motion": _plain(asdict(profile.motion)), + "measurement": _plain(asdict(profile.measurement)), + "zero": _plain(asdict(profile.zero)), + "quality": _plain(asdict(profile.quality)), + "scope": _plain(asdict(profile.scope)), + "artifacts": _plain(asdict(profile.artifacts)), + "acquisition": _plain(asdict(profile.acquisition)), + "urdf": { + "authorized_fields": _plain(profile.urdf_authorized_fields), + **({"limit_policies": {name: _plain(asdict(policy)) + for name, policy in profile.urdf_limit_policies.items()}} + if profile.urdf_limit_policies else {}), + }, + "joint_coverage": _plain(profile.joint_coverage), + } + payload["quality"].pop("task_training_cycles") + for spec in payload["measurement"]["measurements"].values(): + if spec["observer_pose_policy"] == "frozen_parent_v1": + spec.pop("observer_pose_policy") + if not profile.motion.preparation_witnesses: + payload["motion"].pop("preparation_witnesses") + if not profile.motion.observer_preparations: + payload["motion"].pop("observer_preparations") + return payload + + +def dump_hand_profile(profile: CalibrationProfile) -> str: + return yaml.safe_dump( + hand_profile_payload(profile), + allow_unicode=True, + sort_keys=False, + default_flow_style=False, + ) + + +def write_hand_profile(profile: CalibrationProfile, path: str | Path) -> None: + """Explicit migration utility; online calibration never rewrites profiles.""" + Path(path).write_text(dump_hand_profile(profile), encoding="utf-8") + + +__all__ = ["dump_hand_profile", "hand_profile_payload", "write_hand_profile"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/loader.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/loader.py new file mode 100644 index 0000000..fe5463c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/loader.py @@ -0,0 +1,398 @@ +"""Strict YAML loader for a model that reuses the unified engine.""" + +from __future__ import annotations + +from dataclasses import fields +from pathlib import Path +import re +from typing import Any, Mapping + +import yaml +from ..core.domain.profile import ReferenceWaypoint, ModelPreparation, ParentReferenceSpec, JointZeroSpec, KnownBaselineGeometry, JointLimitPolicy, RetainedCadScope +from ..core.domain.profile import ObserverPreparationPlan +from ..core.domain.motion_path import MotionSegment + +from ..core import ( + AcquisitionPolicy, + ArtifactPolicy, + CalibrationProfile, + CommandLayout, + MeasurementPolicy, + MeasurementSpec, + MotionPolicy, + ProfileKey, + QualityPolicy, + ScopePolicy, + TagSpec, + TaskSpec, + ViewSpec, + VisionRigSpec, + ZeroSolvePolicy, + validate_profile, +) + + +def _map(value: Any, name: str) -> Mapping[str, Any]: + if not isinstance(value, Mapping): + raise ValueError(f"{name} must be a mapping") + return value + + +def _set(value: Any) -> frozenset[str]: + return frozenset(str(item) for item in (value or ())) + + +def _keys(value, allowed, name): + unknown = set(_map(value, name)) - set(allowed) + if unknown: + raise ValueError(f"unknown {name} fields: {sorted(unknown)}") + + +def _validate_keys(payload): + # Misspelled safety/geometry fields must not silently select a default. + _keys(payload, {"schema_version", "profile_id", "namespace", "sdk_adapter", "command", + "vision", "motion", "measurement", "zero", "quality", "scope", "artifacts", + "acquisition", "urdf", "joint_coverage"}, "profile") + for name, contract in (("command", CommandLayout), ("vision", VisionRigSpec), + ("motion", MotionPolicy), ("measurement", MeasurementPolicy), ("zero", ZeroSolvePolicy), + ("quality", QualityPolicy), ("scope", ScopePolicy), ("artifacts", ArtifactPolicy), + ("acquisition", AcquisitionPolicy)): + _keys(payload.get(name, {}), {f.name for f in fields(contract)}, name) + if "task_training_cycles" in payload.get("quality", {}): + raise ValueError("task_training_cycles are journal decisions, not profile configuration") + _keys(payload.get("urdf", {}), {"authorized_fields", "limit_policies"}, "urdf") + for policy in payload.get("scope", {}).get("retained_cad_scopes", {}).values(): + _keys(policy, {f.name for f in fields(RetainedCadScope)}, "retained CAD scope") + for policy in payload.get("urdf", {}).get("limit_policies", {}).values(): + _keys(policy, {f.name for f in fields(JointLimitPolicy)}, "URDF limit policy") + for view in payload.get("vision", {}).get("views", ()): + _keys(view, {"name", "tags"}, "view") + for tag in view.get("tags", ()): + _keys(tag, {"id", "role", "fixed_reference", "link", "size_m"}, "Tag") + for task in payload.get("motion", {}).get("tasks", ()): + _keys(task, {f.name for f in fields(TaskSpec)}, "task") + if task.get("parent_reference") is not None: + _keys(task["parent_reference"], {f.name for f in fields(ParentReferenceSpec)}, "parent reference") + for preparation in task.get("model_preparations", ()): + _keys(preparation, {f.name for f in fields(ModelPreparation)}, "model preparation") + for segment in task.get("segments", ()): + _keys(segment, {f.name for f in fields(MotionSegment)}, "motion segment") + for waypoint in payload.get("motion", {}).get("resume_verification_waypoints", ()): + _keys(waypoint, {f.name for f in fields(ReferenceWaypoint)}, "reference waypoint") + for spec in payload.get("motion", {}).get("joint_zero_references", {}).values(): + _keys(spec, {f.name for f in fields(JointZeroSpec)}, "joint zero reference") + for spec in payload.get("zero", {}).get("known_baseline_geometry", {}).values(): + _keys(spec, {f.name for f in fields(KnownBaselineGeometry)}, "baseline geometry") + for name, measurement in payload.get("measurement", {}).get("measurements", {}).items(): + _keys(measurement, {f.name for f in fields(MeasurementSpec)}, "measurement item") + if measurement.get("joint", name) != name: + raise ValueError("measurement key and joint field differ") + + +def load_bundled_hand_profile(layout: str, *, scope: str | None = None) -> CalibrationProfile: + """Resolve installed or source-tree YAML without constructing a model. + + No cache: a product hash check and the subsequently loaded contract must + see the same on-disk inputs, not a previous in-process Python singleton. + """ + if re.fullmatch(r"[a-z0-9_]+", str(layout)) is None: + raise ValueError("invalid bundled profile layout name") + source = Path(__file__).resolve().parents[2] / "config" / "profiles" / f"{layout}.yaml" + if source.is_file(): + return load_hand_profile(source, scope=scope) + from ament_index_python.packages import get_package_share_directory + return load_hand_profile(Path(get_package_share_directory("linkerhand_calibration")) / "config" / "profiles" / f"{layout}.yaml", scope=scope) + + +def load_hand_profile(path: str | Path, *, scope: str | None = None) -> CalibrationProfile: + """Load the complete extension contract; no Python model hook is used.""" + source = Path(path).expanduser().resolve() + payload = _map(yaml.safe_load(source.read_text(encoding="utf-8")), str(source)) + if int(payload.get("schema_version", 0)) != 1: + raise ValueError("hand profile schema_version must be 1") + _validate_keys(payload) + selected_scope = scope + command = _map(payload.get("command"), "command") + vision = _map(payload.get("vision"), "vision") + motion = _map(payload.get("motion"), "motion") + measurement = _map(payload.get("measurement"), "measurement") + zero = _map(payload.get("zero"), "zero") + quality = _map(payload.get("quality"), "quality") + scope = _map(payload.get("scope"), "scope") + artifacts = _map(payload.get("artifacts"), "artifacts") + acquisition = _map(payload.get("acquisition", {}), "acquisition") + urdf = _map(payload.get("urdf", {}), "urdf") + + command_layout = CommandLayout( + names=tuple(str(value) for value in command.get("names", ())), + baseline_u8=tuple(int(value) for value in command.get("baseline_u8", ())), + command_index_by_joint={ + str(name): int(index) + for name, index in _map( + command.get("command_index_by_joint", {}), + "command.command_index_by_joint", + ).items() + }, + disabled_indices=frozenset( + int(index) for index in command.get("disabled_indices", ()) + ), + urdf_joint_by_joint={ + str(name): str(joint) + for name, joint in _map( + command.get("urdf_joint_by_joint", {}), + "command.urdf_joint_by_joint", + ).items() + }, + feedback_name_aliases={ + str(name): str(canonical) + for name, canonical in _map( + command.get("feedback_name_aliases", {}), + "command.feedback_name_aliases", + ).items() + }, + speed_slot_by_command_index={ + int(index): int(slot) + for index, slot in _map( + command.get("speed_slot_by_command_index", {}), + "command.speed_slot_by_command_index", + ).items() + }, + unit=str(command.get("unit", "u8")), + baseline=tuple(float(value) for value in command.get("baseline", ())), + lower_bounds=tuple(float(value) for value in command.get("lower_bounds", ())), + upper_bounds=tuple(float(value) for value in command.get("upper_bounds", ())), + feedback_lower_bounds=tuple( + float(value) for value in command.get("feedback_lower_bounds", ()) + ), + feedback_upper_bounds=tuple( + float(value) for value in command.get("feedback_upper_bounds", ()) + ), + feedback_by_index=bool(command.get("feedback_by_index", False)), + sdk_to_joint_direction=tuple(command.get("sdk_to_joint_direction", ())), + maximum_velocity=tuple(float(value) for value in command.get("maximum_velocity", ())), + ) + views = tuple( + ViewSpec( + str(view["name"]), + tuple( + TagSpec( + str(tag["role"]), + int(tag["id"]), + bool(tag.get("fixed_reference", False)), + None if tag.get("link") is None else str(tag["link"]), + float(tag.get("size_m", 0.016)), + ) + for tag in view.get("tags", ()) + ), + ) + for view in vision.get("views", ()) + ) + tasks = tuple( + TaskSpec( + key=str(task["key"]), + view=str(task["view"]), + command_index=int(task["command_index"]), + joints=tuple(str(name) for name in task.get("joints", ())), + auxiliary_commands=tuple( + (int(pair[0]), float(pair[1])) + for pair in task.get("auxiliary_commands", ()) + ), + validation_only=bool(task.get("validation_only", False)), + start_u8=int(task.get("start_u8", 255)), + end_u8=int(task.get("end_u8", 0)), + preflight_speed_u8=( + None if task.get("preflight_speed_u8") is None + else int(task["preflight_speed_u8"]) + ), + formal_speed_u8=( + None if task.get("formal_speed_u8") is None + else int(task["formal_speed_u8"]) + ), + start=None if task.get("start") is None else float(task["start"]), + end=None if task.get("end") is None else float(task["end"]), + preflight_speed=( + None if task.get("preflight_speed") is None + else float(task["preflight_speed"]) + ), + formal_speed=( + None if task.get("formal_speed") is None + else float(task["formal_speed"]) + ), + preparation_groups=tuple(tuple(int(index) for index in group) for group in task.get("preparation_groups", ())), + entry_waypoints=tuple(tuple((int(index), float(value)) for index, value in waypoint) + for waypoint in task.get("entry_waypoints", ())), + exit_waypoints=tuple(tuple((int(index), float(value)) for index, value in waypoint) + for waypoint in task.get("exit_waypoints", ())), + model_preparations=tuple(ModelPreparation(str(item["joint"]), + tuple(map(float, item["command"])), + tuple(tuple(map(float, pose)) for pose in item["approach_commands"])) + for item in task.get("model_preparations", ())), + parent_reference=(ParentReferenceSpec(**task["parent_reference"]) + if task.get("parent_reference") is not None else None), + segments=tuple(MotionSegment(str(segment["key"]), + tuple((int(i), float(v)) for i, v in segment["start_commands"]), + tuple((int(i), float(v)) for i, v in segment["end_commands"]), + tuple(map(str, segment["joints"]))) for segment in task.get("segments", ())), + ) + for task in motion.get("tasks", ()) + ) + measurements = { + str(name): MeasurementSpec( + joint=str(name), + kind=str(value["kind"]), + view=None if value.get("view") is None else str(value["view"]), + parent_role=( + None if value.get("parent_role") is None + else str(value["parent_role"]) + ), + child_role=( + None if value.get("child_role") is None + else str(value["child_role"]) + ), + validation_source=( + None if value.get("validation_source") is None + else str(value["validation_source"]) + ), + pose_axis_line_required=bool( + value.get("pose_axis_line_required", True) + ), + observer_pose_policy=str(value.get("observer_pose_policy", "frozen_parent_v1")), + ) + for name, value in _map( + measurement.get("measurements", {}), + "measurement.measurements", + ).items() + } + profile = CalibrationProfile( + key=ProfileKey.parse(str(payload["profile_id"])), + namespace=str(payload["namespace"]), + command=command_layout, + vision=VisionRigSpec( + views, + str(vision["common_frame"]), + str(vision["extrinsic_reference_view"]), + dict(vision.get("extrinsics_quality_limits", {})), + dict(vision.get("minimum_capture_counts", {})), + ), + motion=MotionPolicy( + tasks, + tuple(tuple(int(item) for item in row) for row in motion.get("preparation_waypoints_u8", ())), + tuple(tuple(int(item) for item in row) for row in motion.get("safe_return_waypoints_u8", ())), + dict(motion.get("speed_parameters", {})), + bool(motion.get("precheck_sweeps", False)), + bool(motion.get("steady_command_checkpoints", False)), + tuple(tuple(int(index) for index in group) for group in motion.get("return_groups", ())), + tuple(ReferenceWaypoint(str(row["key"]), tuple(map(float, row["command"])), + {str(view): tuple(map(int, ids)) for view, ids in row["tag_ids_by_view"].items()}) + for row in motion.get("resume_verification_waypoints", ())), + {str(name): JointZeroSpec(str(row["task_key"]), tuple(map(float, row["command"])), + tuple(tuple(map(float, command)) for command in row.get("approach_commands", ())), + str(row.get("evidence_scope", "arrival"))) + for name, row in motion.get("joint_zero_references", {}).items()}, + {str(name): ModelPreparation(str(item["joint"]), tuple(map(float, item["command"])), + tuple(tuple(map(float, pose)) for pose in item["approach_commands"])) + for name, item in motion.get("preparation_witnesses", {}).items()}, + {str(name): _observer_preparation(item) + for name, item in motion.get("observer_preparations", {}).items()}, + ), + measurement=MeasurementPolicy( + measurements, + dict(measurement.get("cross_view_sources", {})), + _set(measurement.get("image_curve_joints")), + bool(measurement.get("directional_zero", False)), + bool(measurement.get("cross_view_roll_curve", False)), + bool(measurement.get("stable_cross_view_cone_bias", False)), + _set(measurement.get("candidate_selection_tasks", ())), + str(measurement.get("input_domain", "")), + dict(measurement.get("transferred_motion_sources", {})), + str(measurement.get("release_basis", "feedback_and_command")), + ), + zero=ZeroSolvePolicy( + _set(zero.get("active_joints")), + _set(zero.get("passive_joints")), + tuple(str(value) for value in zero.get("direct_zero_joints", ())), + tuple(str(value) for value in zero.get("axis_joints", ())), + _set(zero.get("mechanical_endpoint_joints")), + _set(zero.get("post_solve_endpoint_joints")), + dict(zero.get("mimic_source_by_joint", {})), + _set(zero.get("cad_frozen_joints")), + dict(zero.get("endpoint_anchor_by_joint", {})), + _set(zero.get("fitted_mimic_joints")), + dict(zero.get("coupling_model_by_joint", {})), + dict(zero.get("transferred_zero_sources", {})), + dict(zero.get("transferred_mimic_sources", {})), + dict(zero.get("spatial", {})), + {str(name): KnownBaselineGeometry(float(row["cad_angle_rad"]), + float(row["uncertainty_rad"]), str(row["evidence_source"])) + for name, row in zero.get("known_baseline_geometry", {}).items()}, + dict(zero.get("cad_zero_assumptions", {})), + ), + quality=QualityPolicy( + tuple(int(value) for value in quality.get("training_cycles", ())), + None if quality.get("holdout_cycle") is None else int(quality["holdout_cycle"]), + _set(quality.get("hard_threshold_keys")), + dict(quality.get("retry_metric_scope", {})), + bool(quality.get("isolated_holdout", False)), + str(quality.get("training_policy", "fixed")), + ), + scope=ScopePolicy( + { + str(name): _set(values) + for name, values in _map(scope.get("calibrate_joints", {}), "scope.calibrate_joints").items() + }, + { + str(name): _set(values) + for name, values in _map(scope.get("frozen_joints", {}), "scope.frozen_joints").items() + }, + str(selected_scope or scope.get("default_scope", "full")), + {str(name): RetainedCadScope(str(row["reason"]), tuple(row["root_anchor_joints"]), + str(row["orientation_anchor_joint"]), tuple(row.get("directed_base_axis_joints", ()))) + for name, row in scope.get("retained_cad_scopes", {}).items()}, + ), + artifacts=ArtifactPolicy( + int(artifacts["output_schema_version"]), + str(artifacts["calibration_filename"]), + str(artifacts["corrected_urdf_filename"]), + _set(artifacts.get("protected_input_fields")), + str(artifacts.get("publication_pointer", "latest_passed")), + _set(artifacts.get("session_compatibility_tokens")), + bool(artifacts.get("publish_corrected_urdf", False)), + _set(artifacts.get("directional_command_joints")), + ), + acquisition=AcquisitionPolicy(**dict(acquisition)), + sdk_adapter=str(payload["sdk_adapter"]), + urdf_authorized_fields={ + str(name): _set(fields) + for name, fields in _map( + urdf.get("authorized_fields", {}), "urdf.authorized_fields" + ).items() + }, + joint_coverage={ + str(name): str(value) + for name, value in _map( + payload.get("joint_coverage", {}), "joint_coverage" + ).items() + }, + urdf_limit_policies={str(name): JointLimitPolicy( + source_limits=str(row["source_limits"]), evidence_source=str(row["evidence_source"]), + independent_safety_limits_cad_rad=(None if row.get("independent_safety_limits_cad_rad") is None + else tuple(float(v) for v in row["independent_safety_limits_cad_rad"])), + safety_evidence_source=str(row.get("safety_evidence_source", ""))) + for name, row in _map(urdf.get("limit_policies", {}), "urdf.limit_policies").items()}, + ) + from .scope import compile_capture_scope + profile = compile_capture_scope(profile) + validate_profile(profile) + return profile + + +def _observer_preparation(item): + if 'actions' in item: + _keys(item, {'actions'}, 'observer preparation plan') + return ObserverPreparationPlan(tuple(_observer_preparation(action) for action in item['actions'])) + _keys(item, {f.name for f in fields(ModelPreparation)}, 'observer preparation action') + return ModelPreparation(str(item['joint']), tuple(map(float, item['command'])), + tuple(tuple(map(float, pose)) for pose in item['approach_commands'])) + + +__all__ = ["load_hand_profile", "load_bundled_hand_profile"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/observations.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/observations.py new file mode 100644 index 0000000..caf3b51 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/observations.py @@ -0,0 +1,107 @@ +"""Compile one physical Tag-to-link binding from Profile and CAD topology.""" + +from __future__ import annotations + +from ..core.domain.profile import CalibrationProfile +from ..core.urdf.kinematics import UrdfKinematicModel + + +def compile_tag_links(profile: CalibrationProfile, model: UrdfKinematicModel) -> dict[str, str]: + """A shared Tag belongs to the deepest observed link on a single chain. + + Example: the same Tag can observe a root axis with distal axes held and a + distal axis with the root held. It still has only ONE physical mounting. + Ambiguous branches require an explicit ``TagSpec.link``; no name guessing. + """ + result = {} + def bind(role, link): + if role in result and result[role] != link: + raise ValueError(f"physical Tag has conflicting link bindings:{role}") + result[role] = link + for view in profile.vision.views: + for tag in view.tags: + if tag.link is not None: + if tag.link not in model.links: + raise ValueError(f"Tag references missing URDF link:{tag.role}:{tag.link}") + bind(tag.role, tag.link) + continue + if tag.fixed_reference: + bind(tag.role, model.root_link) + continue + candidates = { + profile.command.urdf_joint_by_joint.get(name, name) + for name, spec in profile.measurement.measurements.items() + if spec.view == view.name and spec.child_role == tag.role + and spec.kind != "axis_cross_view_validation" + } + if not candidates or not candidates <= model.joints.keys(): + raise ValueError(f"Tag link cannot be derived; declare link explicitly:{tag.role}") + descendants = [name for name in candidates + if candidates <= {joint.name for joint in model._chain(name)}] + if len(descendants) != 1: + raise ValueError(f"Tag is assigned to different kinematic branches:{tag.role}") + bind(tag.role, model.joints[descendants[0]].child) + return result + + +def compile_parallel_axis_geometry(profile, model, relations): + """Read invariant geometry only when both Tags identify adjacent links.""" + import numpy as np + from ..core.geometry.tag_pose.cad_hinge import ParallelAxisGeometry + + links = compile_tag_links(profile, model) + by_child_role = {relation.child_role: relation for relation in relations} + result = [] + for child in relations: + parent = by_child_role.get(child.parent_role) + if parent is None: + continue + parent_name = profile.command.urdf_joint_by_joint.get(parent.joint, parent.joint) + child_name = profile.command.urdf_joint_by_joint.get(child.joint, child.joint) + first, second = model.joints[parent_name], model.joints[child_name] + if (first.kind not in {"revolute", "continuous"} or second.kind not in {"revolute", "continuous"} + or links[parent.child_role] != first.child or links[child.child_role] != second.child): + continue + chain = model._chain(child_name) + positions = [i for i, joint in enumerate(chain) if joint.name == parent_name] + if not positions or any(joint.kind != "fixed" for joint in chain[positions[0]+1:-1]): + continue + a, b = (model.link_transform(name, zero_offsets={}, joint_angles={}, independent_mimic_angles=True) + for name in (parent_name, child_name)) + axis_a, axis_b = a[:3, :3] @ first.axis, b[:3, :3] @ second.axis + if np.linalg.norm(np.cross(axis_a, axis_b)) > 1e-8: + continue + displacement = b[:3, 3] - a[:3, 3] + distance = float(np.linalg.norm(displacement - axis_a * (axis_a @ displacement))) + if distance > 1e-6: + result.append(ParallelAxisGeometry(parent.joint, child.joint, + 1 if axis_a @ axis_b > 0 else -1, distance)) + return tuple(result) + + +def compile_tag_feedback_channels(profile, model): + """Feedback channels able to move each physical Tag, including held ancestors. + + A distal joint or a sibling finger cannot move an upstream Tag. Passive + joints inherit their declared SDK source. This uses topology and mounting + links only; it does not assume CAD zero angles or a command/angle map. + """ + from ..core.fitting.motion_fit import channel_for_joint + + channels = { + profile.command.urdf_joint_by_joint.get(name, name): channel_for_joint(profile, name) + for name in (*profile.zero.active_joints, *profile.zero.passive_joints) + } + result = {} + for role, link in compile_tag_links(profile, model).items(): + parent = model.parent_joint_by_child.get(link) + chain = () if parent is None else model._chain(parent) + dependencies = set() + for joint in chain: + if joint.kind == "fixed": + continue + if joint.name not in channels: + raise ValueError(f"Tag motion dependency has no SDK source:{role}:{joint.name}") + dependencies.add(channels[joint.name]) + result[role] = frozenset(dependencies) + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/observer_policy.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/observer_policy.py new file mode 100644 index 0000000..8d9019b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/observer_policy.py @@ -0,0 +1,56 @@ +"""Compile observer strategy from the measurement graph, never finger names. + +Old serialized measurements retain their original meaning. New preparations +use one policy for every supported moving-parent hinge. A checkpoint upgrade +may preserve measured joints explicitly; it must not reinterpret their models. +""" + +from dataclasses import replace + +LEGACY_OBSERVER = 'frozen_parent_v1' +LEGACY_RIGID_OBSERVER = 'rigid_pair_v1' +RIGID_OBSERVER = 'rigid_pair_candidates_v2' +TRAJECTORY_OBSERVER = 'rigid_pair_trajectory_v3' + + +def is_rigid_observer(policy): + """Return whether a policy requires independent rigid-pair evidence.""" + return policy in {LEGACY_RIGID_OBSERVER, RIGID_OBSERVER, TRAJECTORY_OBSERVER} + + +def rigid_observer_dependencies(profile): + """Return recipient -> independently measured parent hinge dependencies.""" + from ..core.domain.capture_plan import PREPARATION_POLICIES + if profile.vision_motion or profile.quality.training_policy not in PREPARATION_POLICIES: + return {} + measurements = profile.measurement.measurements + tasks = {joint: task for task in profile.motion.tasks for joint in task.joints} + dependencies = {} + for joint, task in tasks.items(): + reference = task.parent_reference + spec = measurements[joint] + if reference is None or len(task.joints) != 1 or spec.kind != 'relative_rotation': + continue + donor = reference.geometry_joint + source = measurements.get(donor) + source_task = tasks.get(donor) + if (source is None or source_task is None or len(source_task.joints) != 1 + or source.kind != 'relative_rotation' or source.view != spec.view + or source.child_role != spec.parent_role or spec.child_role == spec.parent_role): + continue + dependencies[joint] = donor + return dependencies + + +def configure_observer_policy(profile, *, preserved_joints=(), policy=RIGID_OBSERVER): + """Upgrade every supported unmeasured recipient in a single graph pass.""" + if policy not in {LEGACY_RIGID_OBSERVER, RIGID_OBSERVER, TRAJECTORY_OBSERVER}: + raise ValueError('observer_policy_unknown_strategy') + preserved = frozenset(preserved_joints) + measurements = dict(profile.measurement.measurements) + if not preserved <= measurements.keys(): + raise ValueError('observer_policy_unknown_preserved_joint') + for joint in rigid_observer_dependencies(profile): + if joint not in preserved: + measurements[joint] = replace(measurements[joint], observer_pose_policy=policy) + return replace(profile, measurement=replace(profile.measurement, measurements=measurements)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/observer_preparation.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/observer_preparation.py new file mode 100644 index 0000000..55a2564 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/observer_preparation.py @@ -0,0 +1,114 @@ +"""Declare bounded, common-ancestor excitation from the physical dependency graph.""" +from dataclasses import replace +import numpy as np + +from ..core.domain.profile import ModelPreparation, ObserverPreparationPlan +from ..core.fitting.motion_fit import channel_for_joint +from .observer_policy import configure_observer_policy, rigid_observer_dependencies +from .observations import compile_tag_feedback_channels + + +def observer_actions(profile, joint): + plan = profile.motion.observer_preparations[joint] + return plan.actions if isinstance(plan, ObserverPreparationPlan) else (plan,) + + +def observer_action(profile, joint, decision): + index = decision.get('action_index', 0) + actions = observer_actions(profile, joint) + if type(index) is not int or not 0 <= index < len(actions): + raise ValueError('observer_preparation_action_index_invalid') + return actions[index] + + +def _bounded_actions(profile, first): + """Escalate once within the donor's already declared preparation envelope.""" + channel = channel_for_joint(profile, first.joint) + donor = profile.motion.joint_zero_references[first.joint] + values = [pose[channel] for pose in (*donor.approach_commands, donor.command)] + farthest = max(values, key=lambda value: abs(value-first.command[channel])) + extended = list(first.command); extended[channel] = farthest + second = ModelPreparation(first.joint, first.command, (first.command, tuple(extended))) + if abs(farthest-first.command[channel]) <= abs(first.approach_commands[1][channel]-first.command[channel]): + return ObserverPreparationPlan((first,)) + return ObserverPreparationPlan((first, second)) + + +def configure_observer_preparations(profile, model, *, preserved_joints=()): + from .observer_policy import TRAJECTORY_OBSERVER + strategy = (TRAJECTORY_OBSERVER if any( + spec.observer_pose_policy == TRAJECTORY_OBSERVER + for spec in profile.measurement.measurements.values()) else None) + profile = configure_observer_policy(profile, preserved_joints=preserved_joints, + **({"policy": strategy} if strategy else {})) + channels = compile_tag_feedback_channels(profile, model) + by_channel = {channel_for_joint(profile, name): name for name in profile.measurement.measurements} + plans = dict(profile.motion.observer_preparations) + for joint, parent in rigid_observer_dependencies(profile).items(): + if joint in preserved_joints: + continue + if joint in plans: + if isinstance(plans[joint], ModelPreparation): + plans[joint] = _bounded_actions(profile, plans[joint]) + continue + spec = profile.measurement.measurements[joint] + parent_name = profile.command.urdf_joint_by_joint.get(parent, parent) + transform = model.link_transform(parent_name, zero_offsets={}, joint_angles={}, independent_mimic_angles=True) + axis = transform[:3, :3] @ model.joints[parent_name].axis + choices = [] + for channel in sorted(channels[spec.parent_role] & channels[spec.child_role]): + donor = by_channel.get(channel) + if donor is None or donor not in profile.motion.joint_zero_references: + continue + name = profile.command.urdf_joint_by_joint.get(donor, donor) + pose = model.link_transform(name, zero_offsets={}, joint_angles={}, independent_mimic_angles=True) + score = float(np.linalg.norm(np.cross(axis, pose[:3, :3] @ model.joints[name].axis))) + if score >= .5: + choices.append((score, channel, donor)) + if not choices: + continue + _, channel, donor = max(choices, key=lambda item: (item[0], -item[1])) + command = profile.motion.joint_zero_references[joint].command + lower, upper = profile.command.minimum_values[channel], profile.command.maximum_values[channel] + step = (upper-lower)/4 + if profile.command.unit == 'u8': + step = int(step) + excursion = list(command) + excursion[channel] += -step if command[channel]-step >= lower else step + plans[joint] = _bounded_actions(profile, ModelPreparation(donor, command, (command, tuple(excursion)))) + return replace(profile, motion=replace(profile.motion, observer_preparations=plans)) + + +def validate_observer_preparations(profile, model): + channels = compile_tag_feedback_channels(profile, model) + dependencies = rigid_observer_dependencies(profile) + for joint in profile.motion.observer_preparations: + actions = observer_actions(profile, joint) + if not 1 <= len(actions) <= 2 or any(not isinstance(a, ModelPreparation) for a in actions): + raise ValueError('observer_preparation_action_budget_invalid') + if len(actions) == 2 and _bounded_actions(profile, actions[0]).actions != actions: + raise ValueError('observer_preparation_escalation_changed') + for index, plan in enumerate(actions): + _validate_action(profile, joint, plan, channels, dependencies, index) + + +def _validate_action(profile, joint, plan, channels, dependencies, index): + from .observer_policy import is_rigid_observer + if joint not in dependencies or not is_rigid_observer( + profile.measurement.measurements[joint].observer_pose_policy): + raise ValueError('observer_preparation_dependency_invalid') + spec = profile.measurement.measurements[joint] + channel = channel_for_joint(profile, plan.joint) + if (channel not in channels[spec.parent_role] & channels[spec.child_role] + or plan.command != profile.motion.joint_zero_references[joint].command + or len(plan.approach_commands) != 2 or plan.approach_commands[0] != plan.command): + raise ValueError('observer_preparation_not_common_rigid_motion') + for pose in (*plan.approach_commands, plan.command): + if (len(pose) != profile.command.command_count + or any(not lo <= value <= hi for value, lo, hi in zip(pose, + profile.command.minimum_values, profile.command.maximum_values)) + or any(value != plan.command[i] for i, value in enumerate(pose) if i != channel)): + raise ValueError('observer_preparation_held_command_changed') + bound = (profile.command.maximum_values[channel]-profile.command.minimum_values[channel]) + if not 0 < abs(plan.approach_commands[1][channel]-plan.command[channel]) <= bound/(4 if index == 0 else 1): + raise ValueError('observer_preparation_excursion_outside_bound') diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/preparation.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/preparation.py new file mode 100644 index 0000000..a40b97d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/preparation.py @@ -0,0 +1,173 @@ +"""Explicit, bounded pose excitation at each task's existing clearance pose.""" +from dataclasses import asdict, replace +import json + +from ..core.domain.profile import ModelPreparation + + +def preparation_image_budget(profile, *, joint_count=1): + """Retain native command resolution for the O30 staged preparation plan. + + A parent hinge spends precision again when transferred to a child. Keep + more of the already acquired arc, with separate, bounded training and + validation halves. This is selected before fitting, never after a failure. + """ + from ..core.geometry.tag_pose.production_image_motion import ( + DENSE_PREPARATION_SAMPLING, image_parameters_for_sampling, + ) + from ..core.domain.capture_plan import PREPARATION_POLICIES + dense = (profile.key.model == 'O30' + and profile.quality.training_policy in PREPARATION_POLICIES + and bool(profile.motion.preparation_witnesses) and joint_count == 1) + return ((256, image_parameters_for_sampling(DENSE_PREPARATION_SAMPLING)) if dense + else (128, image_parameters_for_sampling())) + + +def preparation_contract(profile): + """Version the entire preparation graph independently of capture cycles. + + A strategy upgrade changes upstream geometry as well as downstream image + budgets. Old captures remain readable, but cannot supply frozen models to + a new preparation graph. Legacy strategies keep their existing contract. + """ + if not profile.motion.preparation_witnesses and not profile.motion.observer_preparations: + return None + tasks = {} + for task in profile.motion.tasks: + intervals, parameters = preparation_image_budget(profile, joint_count=len(task.joints)) + tasks[task.key] = dict(joints=list(task.joints), command_intervals=intervals, + image_parameters=asdict(parameters), + parent_reference=asdict(task.parent_reference) if task.parent_reference else None) + value = dict(version='dependency_bound_preparation_v1', tasks=tasks, + zero_references={name: asdict(spec) for name, spec in profile.motion.joint_zero_references.items()}, + witnesses={name: asdict(spec) for name, spec in profile.motion.preparation_witnesses.items()}) + conditioned = [name for name in profile.motion.preparation_witnesses + if uses_declared_witness_path(profile, name)] + if conditioned: + value['witness_pose_conditioning'] = dict(policy='shared_zero_pose_v2', joints=conditioned) + observers = {name: spec.observer_pose_policy for name, spec in profile.measurement.measurements.items() + if spec.observer_pose_policy != 'frozen_parent_v1'} + if observers: + value['observer_pose_policies'] = observers + if profile.motion.observer_preparations: + from ..core.domain.profile import ObserverPreparationPlan + from .observer_policy import TRAJECTORY_OBSERVER + sequence = any(isinstance(p, ObserverPreparationPlan) for p in profile.motion.observer_preparations.values()) + trajectory = any(spec.observer_pose_policy == TRAJECTORY_OBSERVER + for spec in profile.measurement.measurements.values()) + value['observer_preparations'] = dict(policy='occlusion_aware_trajectory_v3' if trajectory + else 'bounded_rigid_observation_v2' if sequence else 'bounded_rigid_observation_v1', + paths={name: asdict(spec) for name, spec in profile.motion.observer_preparations.items()}) + if trajectory: + value['observer_preparations']['trajectory_solver'] = { + 'policy': 'rigid_pair_full_trajectory_v3', + 'training_validation_split': 'chronological_even_odd', + 'maximum_actions_per_task': 2, + 'holdout_selects_model': False, + } + # The live header and decoded JSON must compare identically (including + # tuple-valued poses), without relying on incidental Python container types. + return json.loads(json.dumps(value, allow_nan=False)) + + +def validate_preparation_contract(profile, records): + """Audit a declared graph against both its profile and accepted models. + + Older captures remain evaluable under their original per-model policies. + A new header must not advertise the new graph while importing old budgets. + """ + from ..core.geometry.tag_pose.production_image_motion import image_parameters_for_sampling + declared = [row['preparation_contract'] for row in records + if row.get('kind') == 'session_start' and 'preparation_contract' in row] + if not declared: + return + if len(declared) != 1 or declared[0] != preparation_contract(profile): + raise ValueError('preparation_contract_profile_changed') + tasks = {task.key: set(task.joints) for task in profile.motion.tasks} + refreshed_parents = {(row.get('task_name'), row.get('pose_joint'), + row.get('image_model_sha256')) for row in records + if row.get('kind') == 'parent_reference_model_refreshed' + and row.get('passed_zero_preserved') is True} + for row in records: + if row.get('kind') != 'motion_branch_initialization' or row.get('status') != 'resolved': + continue + joints = row.get('zero_joints', ()) + ordinary = bool(joints) and set(joints) <= tasks.get(row.get('task_name'), set()) + refreshed = (len(joints) == 1 and (row.get('task_name'), joints[0], + row.get('image_model_sha256')) in refreshed_parents) + if not ordinary and not refreshed: + raise ValueError('preparation_contract_model_dependency_changed') + _, expected = preparation_image_budget(profile, joint_count=len(joints)) + if image_parameters_for_sampling(row.get('image_sampling_policy')) != expected: + raise ValueError('preparation_contract_model_budget_changed') + + +def configure_preparation(profile, policy='occlusion_aware_witness_v2'): + if policy not in {'occlusion_aware_witness_v1', 'occlusion_aware_witness_v2', + 'occlusion_aware_trajectory_v3'}: + raise ValueError('unknown_preparation_policy') + from ..core.domain.capture_plan import PREPARATION_POLICIES + if (profile.key.profile_id != 'O30/right/o30_right_18/v1' + or profile.quality.training_policy not in PREPARATION_POLICIES): + raise ValueError('preparation_witness_requires_o30_staged_session') + from ..core.fitting.motion_fit import channel_for_joint + witnesses = {} + for finger in ('pinky', 'ring', 'middle', 'index'): + target, donor = f'{finger}_mcp_pitch', f'{finger}_mcp_roll' + command = profile.motion.joint_zero_references[target].command + channel = channel_for_joint(profile, donor) + lower, upper = profile.command.minimum_values[channel], profile.command.maximum_values[channel] + excursion = list(command) + # At most one quarter of the declared range, within native limits. + # Keep the other fingers in this task's already declared avoidance pose. + step = int((upper-lower)/4) # SDK u8 commands must survive rounding unchanged. + excursion[channel] = command[channel]-step if command[channel]-step >= lower else command[channel]+step + witnesses[target] = ModelPreparation(donor, command, (command, tuple(excursion))) + prepared = replace(profile, motion=replace(profile.motion, preparation_witnesses=witnesses)) + if policy in {'occlusion_aware_witness_v2', 'occlusion_aware_trajectory_v3'}: + from .observer_policy import configure_observer_policy, RIGID_OBSERVER, TRAJECTORY_OBSERVER + strategy = TRAJECTORY_OBSERVER if policy == 'occlusion_aware_trajectory_v3' else RIGID_OBSERVER + prepared = configure_observer_policy(prepared, policy=strategy) + return prepared + + +def uses_declared_witness_path(profile, target): + """An exact existing zero approach also supplies a shared-pose anchor.""" + witness = profile.motion.preparation_witnesses[target] + reference = profile.motion.joint_zero_references.get(witness.joint) + return (reference is not None and reference.command == witness.command + and len(reference.approach_commands) == 1 + and witness.approach_commands == (reference.command, reference.approach_commands[0])) + + +def validate_preparation_witnesses(profile, source_model): + from .observations import compile_tag_feedback_channels + from ..core.fitting.motion_fit import channel_for_joint + channels = compile_tag_feedback_channels(profile, source_model) + tasks = {joint: task for task in profile.motion.tasks for joint in task.joints} + for target, witness in profile.motion.preparation_witnesses.items(): + donor = witness.joint + if target not in tasks or donor not in tasks or len(tasks[target].joints) != 1: + raise ValueError('preparation_witness_dependency_invalid') + spec = profile.measurement.measurements[target] + donor_channel = channel_for_joint(profile, donor) + moving = channels[spec.child_role]-channels[spec.parent_role] + if (donor_channel not in moving or donor_channel == channel_for_joint(profile, target) + or witness.command != profile.motion.joint_zero_references[target].command + or len(witness.approach_commands) != 2 or witness.approach_commands[0] != witness.command + or not any(tag.role == spec.parent_role and tag.fixed_reference + for view in profile.vision.views if view.name == spec.view for tag in view.tags)): + raise ValueError('preparation_witness_posture_not_shared') + for pose in (*witness.approach_commands, witness.command): + if (len(pose) != profile.command.command_count + or any(not lower <= value <= upper for value, lower, upper in zip(pose, + profile.command.minimum_values, profile.command.maximum_values)) + or any(value != witness.command[i] for i, value in enumerate(pose) if i != donor_channel)): + raise ValueError('preparation_witness_held_command_changed') + excursion = abs(witness.approach_commands[1][donor_channel]-witness.command[donor_channel]) + bounded = 0 < excursion <= (profile.command.maximum_values[donor_channel]-profile.command.minimum_values[donor_channel])/4 + # A larger excitation may only reuse an existing single-joint zero + # approach at the exact same clearance posture. This does not grant + # arbitrary full-range motion to a newly declared witness. + if not bounded and not (excursion > 0 and uses_declared_witness_path(profile, target)): + raise ValueError('preparation_witness_excursion_outside_bound') diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/scope.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/scope.py new file mode 100644 index 0000000..7027605 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/scope.py @@ -0,0 +1,67 @@ +"""Compile a declared partial scope once, before scheduling or fitting. + +The SDK layout and avoidance paths remain complete. Excluded joints have no +motion table or measured zero; their CAD geometry is an explicit prerequisite +for the held-pose partial geometry checks, never an independently measured fact. +""" + +from dataclasses import replace +from pathlib import PurePath +import re + + +def compile_capture_scope(profile): + name = profile.scope.default_scope + policy = profile.scope.retained_cad_scopes.get(name) + if policy is None: + return profile + if re.fullmatch(r"[a-z][a-z0-9_]*", name) is None: + raise ValueError("invalid partial scope name") + retained = profile.scope.frozen_joints[name] + selected = profile.scope.calibrate_joints[name] + if retained & selected or retained | selected != profile.zero.active_joints: + raise ValueError("partial scope must partition active joints") + tasks = [] + for task in profile.motion.tasks: + if set(task.joints) & retained: + if not set(task.joints) <= retained: + raise ValueError("partial scope cannot split a coupled motion task") + continue + if any(p.joint in retained for p in task.model_preparations): + raise ValueError("partial scope removes a required preparation measurement") + if task.parent_reference is not None and retained & { + task.parent_reference.pose_joint, task.parent_reference.geometry_joint}: + raise ValueError("partial scope removes a required parent reference source") + tasks.append(task) + def keep(mapping): + return {key: value for key, value in mapping.items() if key not in retained} + zero = profile.zero + spatial = dict(zero.spatial) + spatial.update(root_anchor_joints=list(policy.root_anchor_joints), + orientation_anchor_joint=policy.orientation_anchor_joint, parallel_root_pattern=False, + directed_base_axis_joints=list(policy.directed_base_axis_joints)) + spatial["axis_order"] = [j for j in spatial.get("axis_order", zero.axis_joints) if j not in retained] + for key in ("axis_parent_joint", "phase_parent_joint", "offset_observer_joint"): + spatial[key] = {j: parent for j, parent in spatial.get(key, {}).items() + if j not in retained and parent not in retained} + def filename(value): + path = PurePath(value) + suffix = "_" + name + return value if path.stem.endswith(suffix) else path.stem + suffix + path.suffix + return replace(profile, + motion=replace(profile.motion, tasks=tuple(tasks), + joint_zero_references=keep(profile.motion.joint_zero_references)), + measurement=replace(profile.measurement, measurements=keep(profile.measurement.measurements)), + zero=replace(zero, direct_zero_joints=tuple(j for j in zero.direct_zero_joints if j not in retained), + axis_joints=tuple(j for j in zero.axis_joints if j not in retained), + cad_zero_assumptions=keep(zero.cad_zero_assumptions), + known_baseline_geometry=keep(zero.known_baseline_geometry), + cad_frozen_joints=zero.cad_frozen_joints | retained, spatial=spatial), + artifacts=replace(profile.artifacts, + directional_command_joints=profile.artifacts.directional_command_joints - retained, + calibration_filename=filename(profile.artifacts.calibration_filename), + corrected_urdf_filename=filename(profile.artifacts.corrected_urdf_filename), + publication_pointer=f"latest_{name}_passed"), + urdf_authorized_fields=keep(profile.urdf_authorized_fields), + urdf_limit_policies=keep(profile.urdf_limit_policies), + joint_coverage={**profile.joint_coverage, **{j: "cad_nominal" for j in retained}}) diff --git a/src/linkerhand_calibration/linkerhand_calibration/profiles/validator.py b/src/linkerhand_calibration/linkerhand_calibration/profiles/validator.py new file mode 100644 index 0000000..1d57a92 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/profiles/validator.py @@ -0,0 +1,165 @@ +"""Validate executable mathematics and CAD bindings before opening hardware.""" + +from ..core.domain.profile import validate_profile +from ..core.fitting.session import compile_spatial_profile +from ..core.urdf.kinematics import UrdfKinematicModel +from .observations import compile_tag_links +from ..core.domain.motion_path import task_segments + + +def require_release_geometry(report): + """Reject structurally impossible releases before acquiring any images.""" + coverage = report["independent_measurement_coverage"] + missing_motion = coverage["unresolved_motion_joints"] + missing_zero = coverage["missing_baseline_geometry"] + if missing_motion or missing_zero: + raise ValueError(f"release_geometry_incomplete:motion={missing_motion}:baseline={missing_zero}") + + +def validate_executable_profile(profile, source_urdf): + if profile.artifacts.output_schema_version not in {2, 3}: + raise ValueError("production calibration requires unified output_schema_version: 2 or 3; legacy formats are read-only") + validate_profile(profile) + if not profile.command.sdk_to_joint_direction: + raise ValueError("executable Profile must declare fixed SDK-to-joint directions") + if any(sum(tag.fixed_reference for tag in view.tags) != 1 for view in profile.vision.views): + raise ValueError("each capture view must declare exactly one fixed reference Tag") + model = UrdfKinematicModel(source_urdf) + from .preparation import validate_preparation_witnesses + validate_preparation_witnesses(profile, model) + from .observer_preparation import validate_observer_preparations + validate_observer_preparations(profile, model) + spatial = compile_spatial_profile(profile) + links = compile_tag_links(profile, model) + _validate_parent_references(profile, model) + for joint, observer in spatial.offset_observer_joint.items(): + if joint == observer: + raise ValueError(f"absolute_zero_unobservable:{joint}:a free Tag on its own hinge is not a CAD datum") + measured = {joint for task in profile.motion.tasks for joint in task.joints} + from .observer_policy import rigid_observer_dependencies, is_rigid_observer + observer_dependencies = rigid_observer_dependencies(profile) + if not measured <= model.joints.keys() or not (profile.zero.active_joints | profile.zero.passive_joints) <= model.joints.keys(): + raise ValueError("Profile joint keys must name URDF joints; SDK names belong in command.names") + for name, spec in profile.measurement.measurements.items(): + if spec.observer_pose_policy not in {"frozen_parent_v1", "rigid_pair_v1", "rigid_pair_candidates_v2", + "rigid_pair_trajectory_v3"}: + raise ValueError(f"unknown_observer_pose_policy:{name}") + from ..core.domain.capture_plan import PREPARATION_POLICIES + if is_rigid_observer(spec.observer_pose_policy) and ( + spec.kind != "relative_rotation" or profile.vision_motion + or profile.quality.training_policy not in PREPARATION_POLICIES): + raise ValueError(f"rigid_pair_requires_staged_relative_measurement:{name}") + if is_rigid_observer(spec.observer_pose_policy) and name not in observer_dependencies: + raise ValueError(f"rigid_pair_requires_independent_parent_hinge:{name}") + if spec.kind not in {"relative_rotation", "urdf_axis_chain", "curve", "axis_cross_view_validation"}: + raise ValueError(f"unsupported measurement primitive:{name}:{spec.kind}") + if not set(profile.zero.axis_joints) <= measured: + raise ValueError("spatial observer axes require declared measured tasks") + if profile.artifacts.output_schema_version == 3: + required = {name for task in profile.motion.tasks for name in task.joints} + if required != set(profile.motion.joint_zero_references): + raise ValueError("v3 observing tasks require explicit per-joint baseline references") + _validate_separable_observations(profile, model, links) + for target, source in profile.zero.mimic_source_by_joint.items(): + if target not in model.joints or model.joints[target].mimic_joint != source: + raise ValueError(f"Profile mimic topology differs from CAD:{target}") + _validate_transfer_geometry(profile, model) + if not set(profile.urdf_authorized_fields) <= model.joints.keys(): + raise ValueError("URDF authorization references a missing joint") + for name in profile.urdf_limit_policies: + if name not in model.joints or model.joints[name].lower is None: + raise ValueError(f"calibrated motion envelope requires an existing bounded CAD joint:{name}") + conflicts = [] + for name, joint in model.joints.items(): + if joint.mimic_joint is None or joint.lower is None: + continue + parent = model.joints[joint.mimic_joint] + if parent.lower is None: + continue + lo, hi = sorted((parent.lower*joint.mimic_multiplier+joint.mimic_offset, + parent.upper*joint.mimic_multiplier+joint.mimic_offset)) + if lo < joint.lower-1e-9 or hi > joint.upper+1e-9: + conflicts.append({"joint": name, "source_joint": joint.mimic_joint, + "reachable_rad": [lo, hi], "cad_limits_rad": [joint.lower, joint.upper], + "measured_mimic_authorized": name in profile.zero.fitted_mimic_joints}) + transfers = profile.measurement.transferred_motion_sources + moving = {name for name, joint in model.joints.items() if joint.kind != "fixed"} + zero_transfers = {target for target, source in profile.zero.transferred_zero_sources.items() + if transfers.get(target) == source} + coverage = {"unmeasured_joints": sorted(moving-measured), + "unresolved_motion_joints": sorted(moving-measured-set(transfers)-profile.retained_joints), + "retained_uncalibrated_joints": sorted(profile.retained_joints), + "transferred_motion_sources": dict(transfers), + "missing_baseline_geometry": sorted((profile.zero.active_joints | profile.zero.passive_joints) + -set(profile.zero.direct_zero_joints)-set(profile.zero.known_baseline_geometry) + -set(profile.zero.cad_zero_assumptions)-zero_transfers-profile.retained_joints), + "transferred_joints": sorted(set(transfers)|set(profile.zero.transferred_zero_sources) + |set(profile.zero.transferred_mimic_sources))} + return {"profile_id": profile.key.profile_id, "tag_links": links, + "independent_measurement_coverage": coverage, + "zero_observers": dict(spatial.offset_observer_joint), + "cad_retained": sorted(profile.zero.cad_frozen_joints), + "cad_zero_assumptions": dict(profile.zero.cad_zero_assumptions), + "transferred": dict(profile.zero.transferred_zero_sources), + "cad_constraint_conflicts": conflicts, + "calibrated_motion_envelope_joints": sorted(profile.urdf_limit_policies), + "independent_angular_safety_limits_declared": sorted(name for name, policy + in profile.urdf_limit_policies.items() if policy.independent_safety_limits_cad_rad is not None), + "observability": "structural_checks_only; numerical_rank_and_holdout_required", + "arbitrary_multiaxis_validated": False} + + +def _validate_parent_references(profile, model): + from .observations import compile_parallel_axis_geometry, compile_tag_feedback_channels + from ..core.geometry.tag_pose.motion_evidence import MotionRelation + + channels = None + for task in profile.motion.tasks: + reference = task.parent_reference + if reference is None: + continue + if channels is None: + channels = compile_tag_feedback_channels(profile, model) + relations = tuple(MotionRelation(name, profile.measurement.measurements[name].parent_role, + profile.measurement.measurements[name].child_role) + for name in (reference.geometry_joint, *task.joints)) + constraints = compile_parallel_axis_geometry(profile, model, relations) + if len(constraints) != 1 or constraints[0].parent_joint != reference.geometry_joint: + raise ValueError(f"parent_reference_requires_adjacent_parallel_axes:{task.key}") + source = profile.motion.joint_zero_references[reference.pose_joint].command + target = profile.motion.joint_zero_references[task.joints[0]].command + role = profile.measurement.measurements[reference.pose_joint].child_role + if any(source[index] != target[index] for index in channels[role]): + raise ValueError(f"parent_reference_holding_pose_changed:{task.key}") + + +def _validate_transfer_geometry(profile, model): + """Check the declared strategy against CAD signs and actual joint types.""" + from ..core.fitting.motion_fit import joint_input_direction + + for target, source in profile.measurement.transferred_motion_sources.items(): + recipient, donor = model.joints[target], model.joints[source] + if recipient.kind == "fixed" or recipient.kind != donor.kind: + raise ValueError(f"motion transfer requires matching movable CAD joint types:{target}") + for name, joint in ((target, recipient), (source, donor)): + if (joint.mimic_joint is not None) != (name in profile.zero.passive_joints): + raise ValueError(f"motion transfer active/passive type differs from CAD:{name}") + if joint_input_direction(profile, model, target) != joint_input_direction(profile, model, source): + raise ValueError(f"motion transfer requires equal CAD output signs:{target}") + + +def _validate_separable_observations(profile, model, links): + from ..core.fitting.motion_fit import channel_for_joint + def chain(link): + return set() if link == model.root_link else {j.name for j in model._chain(model.parent_joint_by_child[link]) + if j.kind != "fixed"} + for task in profile.motion.tasks: + for name in task.joints: + spec = profile.measurement.measurements[name] + relative_chain = chain(links[spec.parent_role]) ^ chain(links[spec.child_role]) + for segment in task_segments(task): + if name not in segment.joints: + continue + moving = {j for j in relative_chain if channel_for_joint(profile, j) in segment.moving_channels} + if moving != {name}: + raise ValueError(f"joint_zero_motion_not_separable:{name}:coupled_between_tags={sorted(moving)}") diff --git a/src/linkerhand_calibration/linkerhand_calibration/publication.py b/src/linkerhand_calibration/linkerhand_calibration/publication.py new file mode 100644 index 0000000..dc5dcca --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/publication.py @@ -0,0 +1,7 @@ +"""One-release module alias for the relocated model publication policy.""" + +import sys + +from linkerhand_calibration.models.g20 import publication as _implementation + +sys.modules[__name__] = _implementation diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/__init__.py new file mode 100644 index 0000000..eaf337e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/__init__.py @@ -0,0 +1,39 @@ +"""Common calibration runtime, independent of model registries.""" + +from .engine import ( + ACQUISITION_POLICY_VERSION, + CalibrationEngine, + ScanUnit, + SweepQuality, +) +from .reference_lock import ReferenceLock, ReferenceMovement +from .resume import ( + ResumeDecision, + ResumeFingerprint, + ResumeVerifier, + TagPoseFingerprint, +) +from .safety import SafetyDecision, SafetyPolicy, SafetySample +from .session import CalibrationPhase, CalibrationSession, SessionAction +from .trajectory import ( + AvoidanceArrival, + avoidance_arrival, + build_calibration_motion_command, + build_calibration_preparation_waypoints, + build_calibration_return_waypoints, + cosine_position_trajectory_u8, + smoothstep_position, +) + +__all__ = [ + "ACQUISITION_POLICY_VERSION", "CalibrationEngine", + "CalibrationPhase", "CalibrationSession", + "ReferenceLock", "ReferenceMovement", "ResumeDecision", + "ResumeFingerprint", "ResumeVerifier", "SafetyDecision", "SafetyPolicy", + "SafetySample", "ScanUnit", "SessionAction", + "SweepQuality", "TagPoseFingerprint", + "AvoidanceArrival", "avoidance_arrival", "cosine_position_trajectory_u8", + "build_calibration_motion_command", "build_calibration_preparation_waypoints", + "build_calibration_return_waypoints", + "smoothstep_position", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/acquisition.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/acquisition.py new file mode 100644 index 0000000..56f256e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/acquisition.py @@ -0,0 +1,144 @@ +"""Retained image selection shared by online finalizers and offline replay.""" + +from __future__ import annotations + +import math +import json +from pathlib import Path +from typing import Any, Mapping, Sequence + +from ..core.domain.profile import CalibrationProfile +from ..core.fitting.observed_motion import image_identity +from ..core.domain.motion_path import record_scan_identity, task_segment +from ..core.fitting.motion_fit import channel_for_joint + + +def load_capture(path, *, verify_evidence=True): + from ..core.geometry.frozen_evidence import EvidenceDecoder + from ..core.artifacts.evidence_journal import REFERENCE_KEY, decode_envelope + decoder = EvidenceDecoder(verify_hashes=verify_evidence) + rows = [] + path = Path(path) + with path.open(encoding="utf-8") as stream: + for number, line in enumerate(stream, 1): + if not line.strip(): + continue + try: + row = decoder.loads(line) + except json.JSONDecodeError as error: + raise ValueError(f"invalid calibration JSONL at line {number}") from error + if not isinstance(row, dict): + raise ValueError(f"calibration JSONL record is not an object at line {number}") + if REFERENCE_KEY in row: + row = decode_envelope(path, row, decoder) + rows.append(row) + return rows + + +def accepted_joint_records(profile: CalibrationProfile, records: Sequence[Mapping[str, Any]], + *, directions_are_task_relative: bool = False, sample_phase="sweep"): + """Select newest attempt by scan unit, preserve complete native evidence. + + Never synthesize identities from row number, SDK value or a fitted curve. + The same camera frame can observe several joints, but only once per joint. + """ + expected = {name for name, spec in profile.measurement.measurements.items() + if spec.view is not None and spec.kind != "axis_cross_view_validation"} + samples = [row for row in records if row.get("joint") in expected and "relative_quaternion_xyzw" in row + and row.get("sample_phase", "sweep") == sample_phase] + def unit(row): + return record_scan_identity(row) + latest = {} + for row in records: + if not all(key in row for key in ("task_name", "cycle", "direction")): + continue + key = unit(row) + latest[key] = max(latest.get(key, 0), int(row.get("attempt", 1))) + selected = {name: [] for name in expected} + seen = set() + tasks = {task.key: task for task in profile.motion.tasks} + for raw in samples: + if int(raw.get("attempt", 1)) != latest[unit(raw)]: + continue + row = dict(raw) + task = tasks.get(str(row["task_name"])) + if task is None or row["joint"] not in task.joints: + raise ValueError("retained observation is not authorized by its task") + if task.segments: + segment = task_segment(task, row.get("segment_key", "")) + channel = channel_for_joint(profile, row["joint"]) + if row["joint"] not in segment.joints or row.get("motor_index") != channel or row["direction"] != segment.direction: + raise ValueError("retained segment observation differs from its motor or direction") + vector = row[f"command_vector_{profile.command.unit}"] + expected = segment.commands_at(vector[segment.command_index], quantize=profile.command.unit == "u8") + if any(abs(vector[i]-value) > 1 for i, value in expected.items()): + raise ValueError("retained command differs from declared multi-channel path") + if directions_are_task_relative and task.end_value > task.start_value: + row["direction"] = {"increasing": "decreasing", "decreasing": "increasing"}[row["direction"]] + row["sample_id"] = image_identity(row) + identity = (row["joint"], row["sample_id"]) + if identity in seen: + raise ValueError(f"duplicate retained image:{identity}") + seen.add(identity) + if profile.vision_motion: + value = row[f"command_{profile.command.unit}"] + if not math.isfinite(float(value)) or not profile.command.minimum_values[channel_for_joint(profile, row["joint"])] <= value <= profile.command.maximum_values[channel_for_joint(profile, row["joint"])]: + raise ValueError("retained command outside declared domain") + elif profile.command.unit == "u8": + value = float(row[profile.curve_input_domain]) + if not math.isfinite(value) or not 0 <= value <= 255: + raise ValueError("retained feedback outside byte domain") + # Raw command and feedback are immutable, distinct observations. + # Quantization belongs to the numerical primitive, not capture. + else: + value = float(row["feedback_rad"]) + index = task.command_index + if not math.isfinite(value) or not profile.command.minimum_feedback_values[index] <= value <= profile.command.maximum_feedback_values[index]: + raise ValueError("retained feedback outside physical SDK domain") + if profile.curve_input_domain.startswith("command_"): + command = float(row["command_rad"]) + if not math.isfinite(command) or not profile.command.minimum_values[index] <= command <= profile.command.maximum_values[index]: + raise ValueError("retained command outside SDK domain") + row["state_rad"] = list(row["command_vector_rad"]) + selected[str(row["joint"])].append(row) + return selected + + +def accepted_secondary_records(profile, records, *, directions_are_task_relative=False, sample_phase="sweep"): + """Select secondary observations without dropping their image/pose evidence. + + Secondary rows use ``observation_joint`` to identify the scanned joint; + they must never be mixed into its primary-view curve. + """ + tasks = {task.key: task for task in profile.motion.tasks} + samples = [dict(row) for row in records if row.get("observation_joint") in profile.measurement.cross_view_sources + and row.get("sample_phase", "sweep") == sample_phase] + latest = {} + for row in records: + if not all(key in row for key in ("task_name", "cycle", "direction")): + continue + key = record_scan_identity(row) + latest[key] = max(latest.get(key, 0), int(row.get("attempt", 1))) + output, seen = {}, set() + for row in samples: + key = record_scan_identity(row) + if int(row.get("attempt", 1)) != latest[key]: + continue + name = row["observation_joint"] + task = tasks.get(str(row["task_name"])) + if task is None or name not in task.joints: + raise ValueError("secondary observation is not authorized by its task") + spec = profile.measurement.measurements[profile.measurement.cross_view_sources[name]] + if row.get("view") != spec.view: + raise ValueError("secondary observation has a different camera view") + row["sample_id"] = image_identity(row) + identity = (name, row["sample_id"]) + if identity in seen: + raise ValueError("duplicate secondary observation image") + seen.add(identity) + if directions_are_task_relative and task.end_value > task.start_value: + row["direction"] = {"increasing": "decreasing", "decreasing": "increasing"}[row["direction"]] + if profile.curve_input_domain.startswith("command_"): + row[f"state_{profile.command.unit}"] = list(row[f"command_vector_{profile.command.unit}"]) + output.setdefault(name, []).append(row) + return output diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/__init__.py new file mode 100644 index 0000000..cdff85b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/__init__.py @@ -0,0 +1,13 @@ +"""Camera, detector, and hand-SDK runtime adapters.""" + +from .base import HardwareHealth, ProfileSdkAdapter, SdkAdapter +from .legacy_byte_sdk import LegacyByteSdkAdapter +from .o12_hcan_sdk import O12HcanSdkAdapter + +__all__ = [ + "HardwareHealth", + "LegacyByteSdkAdapter", + "O12HcanSdkAdapter", + "ProfileSdkAdapter", + "SdkAdapter", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/base.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/base.py new file mode 100644 index 0000000..8a8ece7 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/base.py @@ -0,0 +1,132 @@ +"""Hardware-facing contract used by the model-independent calibration engine. + +Adapters deliberately stop at the SDK boundary. Tag geometry, task ordering, +fitting, and URDF edits belong to :class:`CalibrationProfile`, so adding a hand +does not add another acquisition state machine. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Protocol, Sequence, runtime_checkable + +from ...core import CommandLayout + + +def ordered_feedback_values(layout, names, values): + """Apply the same channel order to positions and their measurement times.""" + if len(values) != layout.command_count: + return None + if not names or layout.feedback_by_index: + return tuple(values) + if len(names) != len(values) or len(set(names)) != len(names): + return None + by_name = dict(zip((str(name) for name in names), values)) + for alias, canonical in layout.feedback_name_aliases.items(): + if alias in by_name and canonical not in by_name: + by_name[canonical] = by_name[alias] + if any(name not in by_name for name in layout.names): + return None + return tuple(by_name[name] for name in layout.names) + + +@dataclass(frozen=True) +class HardwareHealth: + connected: bool + position_mode: bool + active_faults: tuple[str, ...] = () + feedback_fresh: bool = True + diagnostic: str = "" + + @property + def safe(self) -> bool: + return ( + self.connected + and self.position_mode + and self.feedback_fresh + and not self.active_faults + ) + + +@runtime_checkable +class SdkAdapter(Protocol): + """Minimum SDK surface required by ``CalibrationEngine``. + + ROS publishers/subscribers or vendor API objects can implement this + protocol. The engine never assumes byte commands, radians, CAN names, or + a particular ``JointState.name`` ordering. + """ + + @property + def command_layout(self) -> CommandLayout: ... + + def parse_feedback( + self, names: Sequence[str], values: Sequence[float] + ) -> tuple[float, ...] | None: ... + + def validate_command(self, values: Sequence[float]) -> tuple[float, ...]: ... + + def health(self) -> HardwareHealth: ... + + def publish_position(self, values: Sequence[float]) -> None: ... + + def set_speed(self, command_index: int, speed: float) -> None: ... + + def initial_command(self, feedback: Sequence[float]) -> tuple[float, ...]: ... + + +class ProfileSdkAdapter: + """Shared profile-driven parsing and physical-domain validation. + + Live model adapters subclass this object only to implement SDK I/O and + health. The parsing rules are shared by legacy-byte and physical-angle + model nodes. + """ + + def __init__(self, command_layout: CommandLayout) -> None: + self.command_layout = command_layout + + def initial_command(self, feedback: Sequence[float]) -> tuple[float, ...]: + """Protocols must explicitly declare how to start from observed pose.""" + raise NotImplementedError("SDK adapter has no safe initial-command conversion") + + def parse_feedback( + self, names: Sequence[str], values: Sequence[float] + ) -> tuple[float, ...] | None: + ordered = ordered_feedback_values(self.command_layout, names, values) + if ordered is None: + return None + try: + parsed = tuple(float(value) for value in ordered) + except (ValueError, TypeError, OverflowError): + return None + return parsed if all(math.isfinite(value) for value in parsed) else None + + def validate_command(self, values: Sequence[float]) -> tuple[float, ...]: + layout = self.command_layout + command = tuple(float(value) for value in values) + if len(command) != layout.command_count: + raise ValueError("command channel count differs from profile") + for index, value in enumerate(command): + if ( + not math.isfinite(value) + or value < layout.minimum_values[index] + or value > layout.maximum_values[index] + ): + raise ValueError( + f"command outside physical range: channel={index}:value={value}" + ) + return command + + def health(self) -> HardwareHealth: # pragma: no cover - live subclass hook + raise NotImplementedError + + def publish_position(self, values: Sequence[float]) -> None: # pragma: no cover + raise NotImplementedError + + def set_speed(self, command_index: int, speed: float) -> None: # pragma: no cover + raise NotImplementedError + + +__all__ = ["HardwareHealth", "ProfileSdkAdapter", "SdkAdapter"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/command_seed.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/command_seed.py new file mode 100644 index 0000000..58fb411 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/command_seed.py @@ -0,0 +1,61 @@ +"""Read the native command register before the runner starts its SDK owner. + +Never initialize posture, change a setting, or infer commands from positions. +The live health identity must match this read-only startup observation. +""" + +import argparse +import json +import math +from pathlib import Path +import time + +from ...storage import atomic_write_json + + +def read_o30_command(*, side, controller_factory=None): + if controller_factory is None: + from linker_hand_o30_ros2_sdk.core.canfd.linker_hand_o30_control import LinkerHandO30Controller + controller_factory = LinkerHandO30Controller + controller = controller_factory(hand_type=side, canfd_device=0, + comm_type="libcanbus", probe_sensor=False) + try: + identity = controller.hand_info + target = controller.get_target_position() + if (not isinstance(identity, dict) or "O30" not in str(identity.get("产品型号", "")) + or identity.get("左右手") != side.upper() or not identity.get("设备唯一标识")): + raise ValueError("initial_command_device_identity_invalid") + if (target is None or len(target) != 20 + or any(not math.isfinite(v) or not 0 <= v <= 255 for v in target)): + raise ValueError("initial_command_register_unavailable") + return dict(schema_version=1, source="sdk_target_position_register", + commands_sent=False, created_unix=time.time(), model="O30", side=side, + device_uid=identity["设备唯一标识"], values=list(target)) + finally: + controller.close() + + +def load_command_seed(path, profile): + if not path: + return (), "" + row = json.loads(Path(path).read_text()) + values = tuple(float(v) for v in row["values"]) + if (row.get("source") != "sdk_target_position_register" or row.get("commands_sent") is not False + or row.get("model") != profile.key.model or row.get("side") != profile.key.side + or not row.get("device_uid") or len(values) != profile.command.command_count + or any(not math.isfinite(v) or not low <= v <= high + for v, low, high in zip(values, profile.command.minimum_values, profile.command.maximum_values))): + raise ValueError("initial_command_seed_invalid") + return values, str(row["device_uid"]) + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--side", choices=("left", "right"), required=True) + parser.add_argument("--output", required=True) + args = parser.parse_args() + atomic_write_json(args.output, read_o30_command(side=args.side)) + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/legacy_byte_sdk.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/legacy_byte_sdk.py new file mode 100644 index 0000000..7ae71ff --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/legacy_byte_sdk.py @@ -0,0 +1,51 @@ +"""Common adapter for existing byte-command SDK transports.""" + +from __future__ import annotations + +from typing import Callable, Sequence +import math + +from ...core import CommandLayout +from .base import HardwareHealth, ProfileSdkAdapter + + +class LegacyByteSdkAdapter(ProfileSdkAdapter): + """Bind profile validation to arbitrary ROS/vendor transport callbacks.""" + + def __init__( + self, + command_layout: CommandLayout, + *, + publish: Callable[[tuple[float, ...]], None], + set_speed_callback: Callable[[int, float], None], + health_callback: Callable[[], HardwareHealth], + ) -> None: + if command_layout.unit != "u8": + raise ValueError("legacy byte adapter requires a u8 command layout") + super().__init__(command_layout) + self._publish = publish + self._set_speed = set_speed_callback + self._health = health_callback + + def publish_position(self, values: Sequence[float]) -> None: + validated = self.validate_command(values) + self._publish(tuple(float(round(value)) for value in validated)) + + def set_speed(self, command_index: int, speed: float) -> None: + index = int(command_index) + if not 0 <= index < self.command_layout.command_count: + raise ValueError("speed command index is out of range") + numeric = float(speed) + if not math.isfinite(numeric) or not 0 < numeric <= 255: + raise ValueError("byte SDK speed must be in (0, 255]") + slot = self.command_layout.speed_slot_by_command_index.get(index, index) + self._set_speed(int(slot), float(round(numeric))) + + def health(self) -> HardwareHealth: + return self._health() + + def initial_command(self, feedback): + return self.validate_command(tuple(float(round(v)) for v in feedback)) + + +__all__ = ["LegacyByteSdkAdapter"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o12_bridge.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o12_bridge.py new file mode 100644 index 0000000..9f5394b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o12_bridge.py @@ -0,0 +1,4 @@ +"""Compatibility import for the O12 adapter.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.o12_bridge") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o12_hcan_sdk.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o12_hcan_sdk.py new file mode 100644 index 0000000..4982687 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o12_hcan_sdk.py @@ -0,0 +1,4 @@ +"""Compatibility import for the O12 adapter.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o12.o12_hcan_sdk") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o30_ros.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o30_ros.py new file mode 100644 index 0000000..ebd0c9d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/o30_ros.py @@ -0,0 +1,4 @@ +"""Compatibility import for the O30 adapter.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.o30.o30_ros") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/ros_binding.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/ros_binding.py new file mode 100644 index 0000000..30fa15f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/ros_binding.py @@ -0,0 +1,70 @@ +"""SDK binding with explicit feedback freshness, clock and health input ports.""" + +from dataclasses import dataclass +import json +from typing import Callable + +from .base import HardwareHealth +from .legacy_byte_sdk import LegacyByteSdkAdapter +from .o12_hcan_sdk import O12HcanSdkAdapter +from .o30_ros import O30RosAdapter + + +@dataclass(frozen=True) +class SdkBindingPorts: + feedback_fresh: Callable[[], bool] + monotonic: Callable[[], float] + subscribe_health: Callable[[Callable[[str], None]], None] + + +def _byte(profile, ports, publish, set_speed): + return LegacyByteSdkAdapter(profile.command, publish=publish, set_speed_callback=set_speed, + health_callback=lambda: HardwareHealth(True, True, feedback_fresh=ports.feedback_fresh(), + diagnostic="position_protocol;no_separate_fault_telemetry")) + + +@dataclass +class HealthReport: + payload: dict | None = None + received_at: float = 0.0 + invalid: bool = False + + +def _hcan(profile, ports, publish, set_speed): + latest = HealthReport() + + def receive(payload: str): + try: + value = json.loads(payload) + if not isinstance(value.get("position_mode"), bool) or not isinstance(value.get("active_faults"), list): + raise ValueError("malformed SDK health") + latest.payload, latest.received_at, latest.invalid = value, ports.monotonic(), False + except (ValueError, TypeError, AttributeError): + latest.invalid = True + + ports.subscribe_health(receive) + + def health(): + value = latest.payload + if value is None: + return HardwareHealth(True, False, feedback_fresh=ports.feedback_fresh(), diagnostic="waiting_for_sdk_health") + if latest.invalid or ports.monotonic()-latest.received_at > 1.0: + raise ValueError("SDK health report is stale or unparseable") + return HardwareHealth(True, value["position_mode"], tuple(map(str, value["active_faults"])), + ports.feedback_fresh(), json.dumps(value, ensure_ascii=False)) + + return O12HcanSdkAdapter(profile.command, publish=publish, set_speed_callback=set_speed, + health_callback=health, clock=ports.monotonic) + + +FACTORIES = {"legacy_byte_sdk": _byte, "o12_hcan_sdk": _hcan, + "o30_ros": lambda profile, ports, publish, set_speed: O30RosAdapter( + profile, ports, publish=publish, set_speed=set_speed)} + + +def bind_ros_sdk(profile, ports: SdkBindingPorts, *, publish, set_speed): + try: + factory = FACTORIES[profile.sdk_adapter] + except KeyError as error: + raise ValueError(f"unregistered SDK protocol:{profile.sdk_adapter}") from error + return factory(profile, ports, publish, set_speed) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/ros_topics.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/ros_topics.py new file mode 100644 index 0000000..7357b12 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/ros_topics.py @@ -0,0 +1,25 @@ +"""Topic spelling belongs to SDK protocols, not calibration scheduling.""" + +from dataclasses import dataclass + +from ...core.domain.profile import CalibrationProfile + + +@dataclass(frozen=True) +class SdkTopics: + command: str + feedback: str + setting: str = "" + health: str = "" + + +def sdk_topics(profile: CalibrationProfile) -> SdkTopics: + prefix, side = f"/{profile.key.model.lower()}", profile.key.side + if profile.sdk_adapter == "o30_ros": + return SdkTopics(f"/cb_{side}_hand_control_cmd", f"/cb_{side}_hand_state", + f"/cb_{side}_hand_setting_cmd", f"/cb_{side}_hand_info") + if profile.sdk_adapter == "legacy_byte_sdk": + return SdkTopics(f"{prefix}/cb_{side}_hand_control_cmd", f"{prefix}/cb_{side}_hand_state") + if profile.sdk_adapter == "o12_hcan_sdk": + return SdkTopics(f"{prefix}/{side}/joint_cmd", f"{prefix}/{side}/joint_states") + raise ValueError(f"SDK adapter has no ROS topic binding: {profile.sdk_adapter}") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/vendor_package.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/vendor_package.py new file mode 100644 index 0000000..41fe9dd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/adapters/vendor_package.py @@ -0,0 +1,36 @@ +"""Load the pinned, bundled vendor wheel without installing globally.""" + +import hashlib +import importlib +from pathlib import Path +import sys +import tempfile +import zipfile + + +def load_vendor_sdk(wheel, expected_sha256): + path = Path(wheel).resolve() + if hashlib.sha256(path.read_bytes()).hexdigest() != expected_sha256: + raise ValueError("vendor SDK wheel changed before loading") + abi = f"cp{sys.version_info.major}{sys.version_info.minor}" + if f"-{abi}-{abi}-" not in path.name: + raise ValueError(f"vendor SDK wheel is not built for {abi}") + # Private per-process directory: never trust another run's writable cache + # of native libraries. The original wheel/SDK are never modified. + directory = tempfile.TemporaryDirectory(prefix="calibration-vendor-") + with zipfile.ZipFile(path) as archive: + for member in archive.infolist(): + target = (Path(directory.name)/member.filename).resolve() + if not target.is_relative_to(Path(directory.name)): + raise ValueError("unsafe path in vendor SDK wheel") + archive.extractall(directory.name) + if hashlib.sha256(path.read_bytes()).hexdigest() != expected_sha256: + directory.cleanup() + raise ValueError("vendor SDK wheel changed during loading") + sys.path.insert(0, directory.name) + module = importlib.import_module("omnihand") + if not Path(module.__file__).resolve().is_relative_to(Path(directory.name)): + raise ValueError("an unpinned vendor SDK was already imported") + # Keep libraries mapped from this directory until the process exits. + module._calibration_package_directory = directory + return module diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/__init__.py new file mode 100644 index 0000000..d6d6484 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/__init__.py @@ -0,0 +1,5 @@ +"""Common artifact serialization and atomic publication.""" + +from .publisher import ArtifactRelease, ArtifactPublisher + +__all__ = ["ArtifactPublisher", "ArtifactRelease"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/capture_validation.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/capture_validation.py new file mode 100644 index 0000000..f99095a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/capture_validation.py @@ -0,0 +1,117 @@ +"""Capture integrity shared by live completion and offline publication. + +This gate runs at finalization, never on the fast passed-unit resume path. +It reads retained evidence; it does not command the hand or refit old images. +""" + +from collections import defaultdict +import hashlib +import json + +from ...core.domain.motion_path import record_scan_identity +from ..diagnostic_capture import reject_diagnostic_capture +from ..engine import CalibrationEngine +from ..resume import ResumeVerifier, fingerprint_from_mapping +from ..scan_quality import evaluate_capture_unit + + +def validate_capture_provenance(profile, serial_number, hashes, records, *, allow_installation_draft=False): + """A journal cannot substitute today's hashes for old evidence.""" + reject_diagnostic_capture(records) + if not allow_installation_draft and any(row.get('kind') == 'raw_tag_remount_checkpoint' for row in records): + raise ValueError('capture_provenance:remounted_capture_requires_separate_installation_certification') + for row in records: + if row.get('kind') == 'raw_resume_verified': + check = row.get('installation_verification', {}) + if (not allow_installation_draft and (check.get('requires_offline_review') + or check.get('changed_roles') or check.get('unavailable_roles') + or check.get('installation_verified') is False)): + raise ValueError('capture_provenance:resume_installation_requires_offline_review') + headers = [row for row in records if row.get("kind") == "session_start"] + references = [row for row in records if row.get("kind") == "fixed_base_reference_locked"] + if len(headers) != 1 or len(references) != 1: + raise ValueError("capture_provenance:requires_unique_session_and_locked_reference") + header, reference = headers[0], references[0] + engine = CalibrationEngine(profile) + if (not engine.capture_compatible(header) or header.get("serial_number") != serial_number + or header.get("curve_input_domain") != profile.curve_input_domain): + raise ValueError("capture_provenance:obsolete_policy_or_coordinate_identity; fresh capture required") + for key, value in hashes.items(): + if header.get(key) != value or reference.get("protected_hashes", {}).get(key) != value: + raise ValueError(f"capture_provenance:protected_input_changed:{key}") + fingerprint = fingerprint_from_mapping(reference) + checker = ResumeVerifier(required_fixed_views=profile.vision.view_names, + required_fixed_poses=profile.vision.view_names, required_hashes=(*hashes, "intrinsics_sha256")) + evidence = checker.compare(fingerprint, fingerprint) + if not evidence.reuse or fingerprint.profile_id != profile.key.profile_id: + raise ValueError(f"capture_provenance:invalid_locked_reference:{evidence.incompatible_fields}") + models = {} + # Only preview models preceding the formal reference are relevant. Later + # camera changes are rejected online and cannot authorize a mixed replay. + for row in records: + if row.get("kind") == "fixed_base_reference_locked": + break + if row.get("kind") == "rectified_camera_model": + if row.get("matrix_source") != "CameraInfo.P[:3,:3]" or row.get("input_is_rectified") is not True: + raise ValueError("capture_provenance:unverified_rectified_projection") + models[row["view"]] = row["camera_matrix"] + intrinsic_hash = hashlib.sha256(json.dumps(dict(sorted(models.items())), sort_keys=True).encode()).hexdigest() + if set(models) != set(profile.vision.view_names) or intrinsic_hash != fingerprint.protected_hashes["intrinsics_sha256"]: + raise ValueError("capture_provenance:intrinsics_evidence_changed_or_missing") + + +def validate_capture_units(profile, records): + """Offline and resumed data must satisfy the actual post-sweep policy.""" + from ..task_deferral import unresolved_observation_records + blocked = unresolved_observation_records(profile, records) + if blocked: + raise ValueError("capture_unobservable_tasks:" + ",".join(sorted( + f"{row.get('task_name')}:{row.get('cycle')}:{row.get('state')}" for row in blocked))) + from ...core.fitting.command_sampling import validate_sampling_plans + from ..training import resolve_capture_plan + profile = resolve_capture_plan(profile, records, require_complete=True) + plans = validate_sampling_plans(profile, records) + by_unit, by_task = defaultdict(list), defaultdict(list) + for row in records: + by_unit[record_scan_identity(row)].append(row) + by_task[row.get("task_name")].append(row) + first_spans = {} + for unit in CalibrationEngine(profile).scan_units(): + key = unit.identity + rows = by_unit[key] + attempt = max((int(row.get("attempt", 1)) for row in rows), default=1) + completions = [row for row in rows if row.get("kind") == "scan_unit_complete" + and int(row.get("attempt", 1)) == attempt] + complete = bool(completions) and all(row.get("passed") is True for row in completions) + quality = evaluate_capture_unit(profile, unit, attempt, rows, first_cycle_spans=first_spans) + if not complete or not quality.passed: + failures = list(quality.failures) + if not complete: + failures.insert(0, "latest_attempt_not_completed" if not completions + else "latest_attempt_failed_or_conflicting") + raise ValueError(f"capture_incomplete:{key}:attempt={attempt}:{tuple(failures)}") + if profile.artifacts.output_schema_version >= 3: + from ..task_quality import evaluate_task_input_support + for task in profile.motion.tasks: + quality = evaluate_task_input_support(profile, task, by_task[task.key]) + if not quality.passed: + raise ValueError(f"task_input_support_failed:{task.key}:{quality.failures}") + return plans + + +def validate_capture_for_release(profile, serial_number, protected_inputs, records): + """Check the same immutable inputs and complete capture at either entry.""" + missing = profile.artifacts.protected_input_fields - protected_inputs.keys() + if missing: + raise ValueError(f"capture_provenance:protected_inputs_missing:{sorted(missing)}") + # Intrinsics are locked after the header; raw-journal hashes are produced + # after recording. Neither is a startup protected-file hash. + hashes = {key: value for key, value in protected_inputs.items() + if key not in {"intrinsics_sha256", "raw_samples_sha256"}} + validate_capture_provenance(profile, serial_number, hashes, records) + reference = next(row for row in records if row.get("kind") == "fixed_base_reference_locked") + expected_intrinsics = protected_inputs.get("intrinsics_sha256") + if (expected_intrinsics is not None + and expected_intrinsics != reference["protected_hashes"]["intrinsics_sha256"]): + raise ValueError("capture_provenance:protected_input_changed:intrinsics_sha256") + return validate_capture_units(profile, records) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/completion.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/completion.py new file mode 100644 index 0000000..0ad61b8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/completion.py @@ -0,0 +1,47 @@ +"""Read back the committed release; never re-fit or re-publish in the runner.""" + +from __future__ import annotations + +import json +import hashlib +from pathlib import Path +from typing import Any, Mapping + +from ...product import ProductConfig + + +def finish_online_artifacts( + config: ProductConfig, session: Path, status: Mapping[str, Any], +) -> dict[str, str]: + profile = config.calibration_contract.typed_profile + outputs = status.get("outputs", {}) + json_path = Path(outputs.get("json") or status.get("final_json") or "") + urdf_path = Path(outputs.get("urdf") or status.get("final_urdf") or "") + for path in (json_path, urdf_path): + if not path.is_file() or not path.resolve().is_relative_to(session.resolve()): + raise ValueError(f"node completion refers to a missing/external artifact: {path}") + payload = json.loads(json_path.read_text(encoding="utf-8")) + version = profile.artifacts.output_schema_version + unified = version in {2, 3} + if unified and (payload.get("format") != f"unified_calibration_v{version}" or payload.get("schema_version") != version): + raise ValueError("completed JSON format differs from selected Profile") + if not unified and payload.get("schema_version") != profile.artifacts.output_schema_version: + raise ValueError("completed JSON schema differs from selected Profile") + if not unified and payload.get("quality", {}).get("passed") is not True: + raise ValueError("completed JSON has no passing quality evidence") + manifest = json.loads((session/"release_manifest.json").read_text(encoding="utf-8")) + if unified and (manifest.get("validation", {}).get("final_file_spatial_replay") != "passed" + or not manifest.get("validation", {}).get("steady_command_tag_holdout")): + raise ValueError("completed release lacks independent command and feedback spatial evidence") + for path, name in ((json_path, "calibration_json"), (urdf_path, "corrected_urdf")): + if manifest.get(name) != path.name or manifest.get(name+"_sha256") != hashlib.sha256(path.read_bytes()).hexdigest(): + raise ValueError("completed artifact differs from the validated release manifest") + if unified: + from .reader import load_unified_mapper + load_unified_mapper(json_path, expected_side=profile.key.side) + if manifest.get("validation", {}).get("profile_id") != profile.key.profile_id: + raise ValueError("release evidence belongs to a different Profile") + pointer = config.session_root / profile.artifacts.publication_pointer + if not pointer.is_symlink() or pointer.resolve() != session.resolve(): + raise ValueError("node completion has no verified publication pointer to this session") + return {"JSON": str(json_path), "URDF": str(urdf_path), "发布指针": str(pointer)} diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/controller.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/controller.py new file mode 100644 index 0000000..0f825f0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/controller.py @@ -0,0 +1,100 @@ +"""Background preparation and one-time publication, without session ownership. + +The coordinator holds its state lock before entering this component. The worker +never takes the state lock: it reports stage events through a queue. This keeps +feedback live during fitting and orders cancellation against publication. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from functools import partial +from pathlib import Path +from queue import Empty, SimpleQueue +from typing import Any, Callable, Mapping + +from .finalization import finalize_profile_session +from .publisher import ArtifactPublisher +from .worker import FinalizationWorker + + +@dataclass(frozen=True) +class FinalizationInputs: + session_dir: Path + serial_number: str + source_urdf: Path + protected_inputs: Mapping[str, str] + records: tuple[dict[str, Any], ...] + require_motion_evidence: bool = False + journal_path: Path | None = None + journal_size: int | None = None + camera_extrinsics_file: Path | None = None + frozen_training_sha256: str | None = None + + +class FinalizationProtocolError(RuntimeError): + """The worker's event order does not match the session's acceptance stages.""" + + +class FinalizationController: + def __init__(self, profile, session_dir: Path, *, finalizer=finalize_profile_session, isolated=False): + self.worker = FinalizationWorker() + self._events: SimpleQueue[str] = SimpleQueue() + self._isolated = isolated + if isolated: + from .process_finalizer import isolated_finalize_profile_session + finalizer = partial(isolated_finalize_profile_session, finalizer=finalizer) + self._finalizer = partial(finalizer, profile=profile, phase_changed=self._events.put) + self._publisher = ArtifactPublisher(session_dir.parent, profile.artifacts.publication_pointer) + self.started = False + + @property + def uses_journal(self): + """Whether complete evidence is read from the durable journal.""" + return self._isolated + + def start(self, inputs: FinalizationInputs) -> None: + transport = {} + if inputs.camera_extrinsics_file is not None: + transport["camera_extrinsics_file"] = inputs.camera_extrinsics_file + if inputs.frozen_training_sha256 is not None: + transport["frozen_training_sha256"] = inputs.frozen_training_sha256 + if self._isolated: + if inputs.journal_path is None or inputs.journal_size is None: + raise ValueError("isolated_finalization_requires_synced_journal") + transport.update(journal_path=inputs.journal_path, journal_size=inputs.journal_size) + self.worker.start(self._finalizer, session_dir=inputs.session_dir, + serial_number=inputs.serial_number, source_urdf=inputs.source_urdf, + protected_inputs=dict(inputs.protected_inputs), records=inputs.records, + require_motion_evidence=inputs.require_motion_evidence, **transport) + self.started = True + + def drain_events(self, on_event: Callable[[str], None]) -> None: + while True: + try: + event = self._events.get_nowait() + except Empty: + return + on_event(event) + + def poll(self, on_event: Callable[[str], None], authorize: Callable[[], None]): + with self.worker.lock: + try: + self.drain_events(on_event) + except (ValueError, RuntimeError) as error: + raise FinalizationProtocolError(str(error)) from error + + def commit(result): + # The final event may arrive between the first drain and + # Future.done(). Consume it before authorizing the pointer swap. + self.drain_events(on_event) + authorize() + self._publisher.commit(result[2].staged_release) + + return self.worker.finish_if_ready(commit) + + def cancel(self) -> None: + self.worker.cancel() + + def close(self) -> None: + self.worker.close() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/direction.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/direction.py new file mode 100644 index 0000000..ed3d31b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/direction.py @@ -0,0 +1,42 @@ +"""Direction state for tables measured on complete endpoint-to-endpoint sweeps.""" + +from math import floor + + +def next_input_directions(values, previous, directions, *, resolution, channels, byte_input=False): + """Pure transition: callers commit it only after every mapping check passes. + + A hold keeps its arrival direction. Initial state requires the recorded + baseline; an interior reversal needs unmeasured minor-loop hysteresis and + is rejected. An endpoint reset is the scope actually covered by calibration. + """ + result = list(directions) + for index, (baseline, lower, upper) in channels.items(): + if previous is None: + if values[index] != baseline: + raise ValueError(f"directional_mapping_requires_baseline_initialization:channel={index}") + if not lower <= baseline <= upper: + raise ValueError("directional_mapping_baseline_outside_support") + # Both measured branches are anchored to zero at the recorded + # baseline. An interior baseline has no inferred arrival direction; + # the first actual change establishes it, and holds retain it. + result[index] = ("increasing" if baseline == upper else + "decreasing" if baseline == lower else "") + if previous is not None: + for index, (old, new) in enumerate(zip(previous, values)): + tolerance = resolution + if byte_input and index in channels: + # The serialized byte table uses floor(v + .5). Compare the + # same effective inputs so small float steps cannot accumulate + # into a changed table index with a stale travel direction. + old, new = floor(old+.5), floor(new+.5) + tolerance = 0 + if abs(new-old) <= tolerance: + continue + direction = "increasing" if new > old else "decreasing" + if index in channels and result[index] and direction != result[index]: + _, lower, upper = channels[index] + if min(abs(old-lower), abs(old-upper)) > tolerance: + raise ValueError(f"directional_mapping_interior_reversal_unvalidated:channel={index}") + result[index] = direction + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/evidence.py new file mode 100644 index 0000000..655215c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/evidence.py @@ -0,0 +1,189 @@ +"""Compile retained capture records into immutable, model-neutral evidence.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Any, Mapping, Sequence + + +from ...core.domain.profile import CalibrationProfile +from ...core.domain.capture_plan import training_cycles +from ...core.domain.result import JointMapping, evaluate_mappings +from ...core.fitting.tag_installation import ( + FrozenTagInstallation, TagTrainingPose, fit_tag_installations, matrix_tuple, register_base_translation, +) +from ...core.geometry.extrinsics import transform_matrix +from ...core.urdf.kinematics import UrdfKinematicModel +from ...core.urdf.plan import StandardUrdfPlan +from ...core.urdf.tag_acceptance import TagHoldout +from ...profiles.observations import compile_tag_links + + +@dataclass(frozen=True) +class TagReplayEvidence: + common_from_base: tuple[tuple[float, ...], ...] + installations: Mapping[str, FrozenTagInstallation] + holdout: tuple[TagHoldout, ...] + required_roles: tuple[str, ...] + + +def _pose(value): + if isinstance(value, Mapping): + return matrix_tuple(transform_matrix(value["translation_xyz_m"], value["quaternion_xyzw"])) + return matrix_tuple(value) + + +def _replay_directions(mappings, row, task, *, directions_are_task_relative=False): + """A held ancestor retains its arrival branch in both replay paths.""" + direction = row["direction"] + if directions_are_task_relative and task.end_value > task.start_value: + direction = {"increasing": "decreasing", "decreasing": "increasing"}[direction] + if direction not in {"increasing", "decreasing"}: + raise ValueError("Tag replay requires an explicit scan direction") + # Older CaptureFrame records encode unavailable history as an empty + # vector. Preserve that explicit unknown state; a nonempty partial vector + # is damaged evidence and must not silently change only some branches. + history = row.get("command_direction_by_index") + if history is not None and not isinstance(history, (list, tuple)): + raise ValueError("Tag replay has an invalid SDK direction history") + if history: + covered = len(history) > max(m.motor_index for m in mappings.values()) + valid = all(value in {"", "increasing", "decreasing"} for value in history) + if not covered or not valid: + raise ValueError("Tag replay has an invalid SDK direction history") + from ...core.domain.motion_path import task_segment + moving_channels = (task_segment(task, row["segment_key"]).moving_channels + if row.get("segment_key") else (task.command_index,)) + directions = {} + for joint, mapping in mappings.items(): + if mapping.motor_index in moving_channels: + directions[joint] = direction + else: + directions[joint] = history[mapping.motor_index] if history else "" + return directions + + +def prepare_command_holdout(profile, mappings, records): + """Raw independent command-validation poses; no registration or fit here.""" + from ...core.domain.sampling import command_holdout_cycle + holdout_cycle = command_holdout_cycle(profile) + specs = profile.measurement.measurements + tasks = {task.key: task for task in profile.motion.tasks} + seen, result = set(), [] + for row in records: + if row["cycle"] != holdout_cycle: + continue + if row.get("sample_phase") != "steady": + raise ValueError("command holdout requires stable command observations") + spec = specs[row["joint"]] + task = tasks[row["task_name"]] + identity = (spec.child_role, row["sample_id"]) + if identity in seen: + continue + seen.add(identity) + directions = _replay_directions(mappings, row, task) + result.append(TagHoldout(row["sample_id"], spec.child_role, holdout_cycle, + tuple(row[f"command_vector_{profile.command.unit}"]), directions, _pose(row["child_pose_common"]))) + return tuple(result) + + +def prepare_tag_replay( + *, profile: CalibrationProfile, source_model: UrdfKinematicModel, + plan: StandardUrdfPlan, output_mappings: Mapping[str, JointMapping], + common_from_base, records: Sequence[Mapping[str, Any]], + directions_are_task_relative: bool = False, + frozen_training=None, +) -> TagReplayEvidence: + """Use fit results for training poses; final validation reads files anew. + + Capture records must already have passed direction selection/quality. + A legacy-label conversion is explicit at this ingestion boundary, never + guessed from model identity. No unknown/missing image becomes evidence. + """ + links = compile_tag_links(profile, source_model) + tasks = {task.key: task for task in profile.motion.tasks} + specs = profile.measurement.measurements + required = {spec.child_role for spec in specs.values() if spec.view is not None} + # Include fixed references when observed, but do not demand they remain + # visible after an avoidance pose occludes them. Their locked-frame + # fingerprint is independently protected by the session reference policy. + required.discard(None) + training, holdout = [], [] + unique = {} + for row in records: + name = str(row.get("joint", "")) + if name not in specs or specs[name].view is None: + continue + if int(row.get("cycle", -1)) not in (*training_cycles(profile, joint=name), profile.quality.holdout_cycle): + continue + spec = specs[name] + if row.get("task_name") not in tasks: + raise ValueError("Tag replay record has no declared task") + task = tasks[str(row["task_name"])] + role = str(spec.child_role) + if profile.retained_joints: + from ...core.urdf.partial_scope import require_profile_held_pose + require_profile_held_pose(profile, source_model, row[f"command_vector_{profile.command.unit}"], links[role]) + if row.get("view") != spec.view: + raise ValueError("Tag replay record has a different view") + identity = str(row.get("sample_id", "")) + if not identity and row.get("image_stamp_ns") is not None: + identity = f"{spec.view}:{int(row['image_stamp_ns'])}" + if not identity or "child_pose_common" not in row: + raise ValueError("Tag replay requires identified common-frame poses") + domain = {value.input_domain for value in output_mappings.values()} + if len(domain) != 1: + raise ValueError("Tag replay requires one declared SDK input domain") + input_domain = next(iter(domain)) + field = f"state_{profile.command.unit}" if input_domain.startswith("feedback_") else f"command_vector_{profile.command.unit}" + sdk = tuple(float(value) for value in row[field]) + directions = _replay_directions(output_mappings, row, task, + directions_are_task_relative=directions_are_task_relative) + pose = _pose(row["child_pose_common"]) + cycle = int(row["cycle"]) + key = (role, identity) + previous = unique.get(key) + signature = (cycle, sdk, tuple(sorted(directions.items())), pose) + if previous is not None: + if previous != signature: + raise ValueError(f"conflicting duplicate capture:{role}:{identity}") + continue + unique[key] = signature + if cycle == profile.quality.holdout_cycle: + holdout.append(TagHoldout(identity, role, cycle, sdk, directions, pose)) + continue + if frozen_training is not None: + continue + angles = evaluate_mappings(output_mappings, sdk, directions) + # Resolve the FITTED linear relation in output coordinates, then + # transform every joint back to CAD exactly once. Using source-CAD + # mimic on output parent angles would miss a*delta_parent. + visiting = set() + def resolve(joint): + if joint in angles: + return angles[joint] + if joint in visiting: + raise ValueError("cyclic fitted mimic relation") + visiting.add(joint) + parent, multiplier, offset = plan.mimic_output[joint] + angles[joint] = multiplier * resolve(parent) + offset + visiting.remove(joint) + return angles[joint] + for joint in plan.mimic_output: + resolve(joint) + cad = {joint: angle + plan.zero_offsets_rad.get(joint, 0.0) for joint, angle in angles.items()} + training.append(TagTrainingPose(identity, role, cycle, pose, cad)) + selected_links = {role: links[role] for role in required} + if frozen_training is not None: + mounts = frozen_training["tag_installations"] + if set(mounts) != required: + raise ValueError("frozen_tag_roles_changed") + return TagReplayEvidence(frozen_training["common_from_base"], mounts, tuple(holdout), tuple(sorted(required))) + registered_base = register_base_translation(source_model=source_model, common_from_base=common_from_base, + link_by_role=selected_links, observations=training) + mounts = fit_tag_installations(source_model=source_model, common_from_base=registered_base, + link_by_role=selected_links, observations=training, + training_cycles_by_role={role: tuple(sorted({cycle for name, spec in specs.items() + if spec.child_role == role and spec.view is not None for cycle in training_cycles(profile, joint=name)})) + for role in required}) + return TagReplayEvidence(registered_base, mounts, tuple(holdout), tuple(sorted(required))) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/feedback_raw_finalization.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/feedback_raw_finalization.py new file mode 100644 index 0000000..3484ae9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/feedback_raw_finalization.py @@ -0,0 +1,151 @@ +"""Fit sealed feedback images before applying the ordinary final-file gates.""" +from dataclasses import asdict +from pathlib import Path + +from ...core.domain.profile import observation_streams +from ...core.fitting.command_sampling import validate_sampling_plans +from ...core.domain.reference import build_joint_zero_reference +from ...core.geometry.extrinsics import load_camera_extrinsics +from ...storage import atomic_write_json +from ..feedback_image_fit import (fit_feedback_image_motion, + fit_feedback_command_images, fit_feedback_spatial_images, + prepare_feedback_image_result) +from ..feedback_image_graph import feedback_task_image_graph +from ..feedback_image_observations import (reconstruct_feedback_image_observations, + reconstruct_feedback_image_zero_rows) +from ..feedback_image_zero import measure_feedback_zero_angle +from ..feedback_raw_evidence import partition_feedback_raw_capture +from .capture_validation import validate_capture_provenance + + +def fit_raw_feedback_session(*, profile, records, source_urdf, camera_extrinsics_file, + serial_number, protected_inputs, session_dir, publish=False): + directory = Path(session_dir) + status = dict(protocol='raw_feedback_images_v1', capture_verified=False, + feedback_motion_fit_complete=False, command_mapping_fit_complete=False, + spatial_zero_authorized=False, publication_allowed=False, + tasks={}, feedback_zeros=[]) + path = directory/'feedback_raw_fit.json' + + def save(): + atomic_write_json(path, status) + + try: + hashes = {key: value for key, value in protected_inputs.items() + if key not in {'intrinsics_sha256', 'raw_samples_sha256'}} + validate_capture_provenance(profile, serial_number, hashes, records) + evidence = partition_feedback_raw_capture(profile, records) + plans = validate_sampling_plans(profile, records) + expected_tasks = {task.key for task in profile.motion.tasks} + if set(plans) != expected_tasks: + raise ValueError('feedback_raw_command_sampling_plans_missing:' + + ','.join(sorted(expected_tasks-set(plans)))) + from ...profiles.validator import validate_executable_profile, require_release_geometry + from ..motion_provenance import validate_source_geometry + require_release_geometry(validate_executable_profile(profile, source_urdf)) + validate_source_geometry(profile, source_urdf, records) + extrinsics = load_camera_extrinsics(camera_extrinsics_file, + required_views=profile.vision.view_names, + reference_view=profile.vision.extrinsic_reference_view, + quality_limits=profile.vision.extrinsics_quality_limits, + minimum_capture_counts=profile.vision.minimum_capture_counts) + status.update(capture_verified=True, evidence_sha256=evidence.sha256, + completed_units=len(evidence.completed_units), + command_sampling_plan_sha256={key: item['plan_sha256'] + for key, item in sorted(plans.items())}) + save() + observations, zeros, zero_rows = [], [], {} + for task in profile.motion.tasks: + views = sorted({spec.view for _, _, spec in observation_streams(profile, task)}) + for view in views: + key = f'{task.key}:{view}' + graph = feedback_task_image_graph(profile, records, evidence.images, task.key, view) + resolution = graph.solve() + status['tasks'][key] = dict(source_frames=len(graph.frames), + discarded_frames=graph.discarded_frames, + source_images_sha256=graph.source_images_sha256, + geometry_resolved=resolution.resolved, reason=resolution.reason, + selected_hypothesis=resolution.selected_hypothesis, + hypotheses=[asdict(item) for item in resolution.hypotheses]) + save() + if not resolution.resolved or resolution.model is None: + raise ValueError('raw_feedback_image_geometry_unresolved:' + key + ':' + resolution.reason) + for relation in graph.relations: + zero = measure_feedback_zero_angle(profile, graph, resolution.model, + evidence.images, relation.joint) + zeros.append(zero) + zero_rows.setdefault(relation.joint, []).extend( + reconstruct_feedback_image_zero_rows(profile, graph, + resolution.model, evidence.images, extrinsics, zero)) + status['feedback_zeros'].append(zero.report()) + selected = reconstruct_feedback_image_observations(profile, graph, + resolution.model, evidence.images, extrinsics) + observations.append(selected) + status['tasks'][key].update(selected_motion_training=len(selected.motion_training), + selected_motion_holdout=len(selected.motion_holdout), + selected_command_training=len(selected.command_training), + selected_command_holdout=len(selected.command_holdout), + rejected_images=len(selected.rejected_images)) + save() + references = {joint: build_joint_zero_reference(profile, joint, rows, + session_epoch=1, motion_version=1) for joint, rows in zero_rows.items()} + status['zero_reference_image_counts'] = {joint: len(ref.samples) + for joint, ref in sorted(references.items())} + save() + motion = fit_feedback_image_motion(profile, source_urdf, observations, zeros) + status.update(feedback_motion_fit_complete=True, + feedback_motion=motion.report()) + save() + command = fit_feedback_command_images(profile, motion, observations, zeros) + status.update(command_mapping_fit_complete=True, + command_mapping=command.report()) + save() + spatial = fit_feedback_spatial_images(profile, source_urdf, motion, zeros) + status.update(spatial_zero_fit_complete=True, spatial_zero=spatial.report()) + save() + candidate = prepare_feedback_image_result(profile, spatial, command, references) + from ...core.urdf.result_plan import prepare_standard_result + from .finalization import _write_artifact_pair + draft = directory/'offline_draft' + draft.mkdir(exist_ok=False) + prepared = prepare_standard_result(profile, Path(source_urdf), + protected_inputs['source_urdf_sha256'], candidate) + payload, json_path, urdf_path = _write_artifact_pair(profile, candidate, + prepared, draft, Path(source_urdf), serial_number, protected_inputs) + from ...core.urdf.acceptance import validate_artifact_structure + from .standard_loader import validate_with_robot_state_publisher + changes = validate_artifact_structure(source_urdf=Path(source_urdf), + corrected_urdf=urdf_path, + source_sha256=protected_inputs['source_urdf_sha256'], + authorized_fields=profile.urdf_authorized_fields, payload=payload, + zero_offsets_rad=candidate.zero_offsets_rad, + range_evidence=prepared.plan.range_evidence) + validate_with_robot_state_publisher(urdf_path) + status.update(draft_structure_passed=True, draft_ros_load_passed=True, + draft_authorized_changes=list(changes)) + status.update(candidate_built=True, + draft_json=str(json_path), draft_urdf=str(urdf_path), + candidate_schema_version=payload['schema_version']) + save() + status['stage'] = 'final_file_validation' + save() + from .feedback_raw_release import validate_feedback_raw_draft + acceptance = validate_feedback_raw_draft(profile=profile, + session_dir=directory, source_urdf=source_urdf, + camera_extrinsics_file=camera_extrinsics_file, + protected_inputs=protected_inputs, records=records, + fit=candidate, prepared=prepared, observations=observations, + draft_json=json_path, draft_urdf=urdf_path, publish=publish) + status.update(accuracy_passed=True, spatial_zero_authorized=True, + publication_allowed=True, published=bool(publish), + stage='complete', acceptance=acceptance) + save() + return status + except Exception as error: + from ...core.urdf.image_acceptance import ImageHoldoutFailure + if isinstance(error, ImageHoldoutFailure): + status['final_image_failure'] = dict(input_kind=error.input_kind, + holdout_cycle=error.holdout_cycle, roles=error.report) + status.update(reason=str(error), publication_allowed=False) + save() + raise diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/feedback_raw_release.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/feedback_raw_release.py new file mode 100644 index 0000000..6ee1426 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/feedback_raw_release.py @@ -0,0 +1,99 @@ +"""Final-file validation for a sealed feedback-image capture. + +All image geometry and curve fitting has finished before this module runs. +The same frozen Tag replay and independent image gates used by the ordinary +v3 finalizer decide whether the draft files can become a release. +""" +from __future__ import annotations + +import json +import shutil +from pathlib import Path + +from ...core.artifacts.storage import atomic_write_json +from ...core.domain.capture_plan import CapturePlan +from ...core.fitting.motion_fit import channel_for_joint +from ...core.geometry.extrinsics import transform_matrix +from ...core.urdf.kinematics import UrdfKinematicModel +from ...core.urdf.partial_scope import profile_scope +from .evidence import prepare_command_holdout, prepare_tag_replay +from .image_evidence import ImageEvidence +from .publisher import ArtifactPublisher, FrozenTagArtifactValidator +from .serializers.compact_v2 import REPORT_FILENAME +from .standard_loader import validate_with_robot_state_publisher + + +def _replay_rows(profile, rows): + """Bind secondary view rows to their declared measurement alias.""" + aliases = profile.measurement.cross_view_sources + return tuple(dict(row, joint=aliases[row['observation_joint']]) + if 'observation_joint' in row else row for row in rows) + + +def validate_feedback_raw_draft(*, profile, session_dir, source_urdf, + camera_extrinsics_file, protected_inputs, records, fit, prepared, + observations, draft_json, draft_urdf, publish): + directory = Path(session_dir).resolve() + source = Path(source_urdf).resolve() + model = UrdfKinematicModel(source) + motion = tuple(row for group in observations + for row in (*group.motion_training, *group.motion_holdout)) + steady = tuple(row for group in observations + for row in (*group.command_training, *group.command_holdout)) + zero = fit.spatial_zero + replay = prepare_tag_replay(profile=profile, source_model=model, + plan=prepared.plan, output_mappings=fit.output_mappings, + common_from_base=transform_matrix(zero.base_translation_xyz_m, + zero.base_quaternion_xyzw), records=_replay_rows(profile, motion)) + command_holdout = prepare_command_holdout(profile, fit.command_mappings, + _replay_rows(profile, steady)) + image_evidence = ImageEvidence(profile, records, + camera_extrinsics_file=camera_extrinsics_file, + protected_inputs=protected_inputs, source_model=model) + from ...core.domain.sampling import command_holdout_cycle + command_cycle = command_holdout_cycle(profile) + image_inputs = dict( + image_observations=image_evidence.all_view_holdout(replay.holdout, + mappings=fit.output_mappings, input_kind='feedback', + holdout_cycle=profile.quality.holdout_cycle), + command_image_observations=image_evidence.all_view_holdout(command_holdout, + mappings=fit.command_mappings, input_kind='command', + holdout_cycle=command_cycle), + require_image_holdout=True, + out_of_scope_images=tuple(image_evidence.out_of_scope_images)) + validator = FrozenTagArtifactValidator(profile.key.profile_id, source, + protected_inputs['source_urdf_sha256'], profile.urdf_authorized_fields, + fit.zero_offsets_rad, replay.common_from_base, replay.installations, + replay.holdout, replay.required_roles, validate_with_robot_state_publisher, + protected_inputs=dict(protected_inputs), command_observations=command_holdout, + release_basis=profile.measurement.release_basis, + calibration_scope=profile_scope(profile), + capture_plan=CapturePlan.from_profile(profile).as_dict(), + joint_observations=tuple(row for row in steady + if 'joint' in row and row['cycle'] == command_cycle), + command_holdout_cycle=command_cycle, joint_curves=fit.curves, + joint_channels={name: channel_for_joint(profile, name) + for name in fit.output_mappings}, + transferred_motion_sources=profile.measurement.transferred_motion_sources, + cad_zero_assumptions=profile.zero.cad_zero_assumptions, + transferred_zero_sources=profile.zero.transferred_zero_sources, + joint_zero_methods=fit.zero_method_by_joint, + range_evidence=prepared.plan.range_evidence, + directional_command_joints=profile.artifacts.directional_command_joints, + **image_inputs) + # Keep the draft intact for review. The release files live directly in the + # session so ArtifactPublisher can enforce its normal immutable-file rules. + release_json = directory/Path(draft_json).name + release_urdf = directory/Path(draft_urdf).name + for original, target in ((draft_json, release_json), (draft_urdf, release_urdf), + (Path(draft_json).parent/REPORT_FILENAME, directory/REPORT_FILENAME)): + shutil.copyfile(original, target) + publisher = ArtifactPublisher(directory.parent, profile.artifacts.publication_pointer) + staged = publisher.prepare(session_directory=directory, + calibration_json=release_json, corrected_urdf=release_urdf, + validate=validator) + acceptance = json.loads(staged.validation_json) + atomic_write_json(directory/'standard_urdf_acceptance.json', acceptance) + if publish: + publisher.commit(staged) + return acceptance diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/finalization.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/finalization.py new file mode 100644 index 0000000..83c5559 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/finalization.py @@ -0,0 +1,287 @@ +"""Shared retained-data -> fit -> standard URDF -> read-back -> publication.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Callable + +from ...core.artifacts.storage import atomic_write_json +from ...core.domain.capture_plan import CapturePlan, STAGED, evidence_digest, training_cycles +from ...core.fitting.session import fit_profile_calibration +from ...core.fitting.command_mapping import fit_command_mappings +from ...core.fitting.motion_fit import channel_for_joint +from ...core.fitting.rotation_diagnostics import RotationHoldoutFailure +from ...core.geometry.candidate_selection import resolve_chain_observations +from ...core.geometry.extrinsics import transform_matrix +from ...core.urdf.kinematics import UrdfKinematicModel +from ...core.urdf.result_plan import prepare_standard_result +from ..acquisition import accepted_joint_records, accepted_secondary_records +from ..diagnostic_capture import reject_diagnostic_capture +from .evidence import prepare_tag_replay +from .publisher import ArtifactPublisher, FrozenTagArtifactValidator, StagedRelease +from .serializers.compact_v2 import from_report, REPORT_FILENAME +from .serializers.unified_v1 import serialize as serialize_report +from .standard_loader import validate_with_robot_state_publisher + + +@dataclass(frozen=True) +class CorrectedArtifact: + path: Path + staged_release: StagedRelease + + +def _write_artifact_pair(profile, fit, prepared, directory, source, serial_number, protected_inputs): + """Save the calibration first, then rebuild its URDF from those bytes. + + These are reviewable candidate files. Only independent final-file + acceptance and the publication controller can create a valid release. + """ + from .urdf_from_json import serialize_urdf_correction, rebuild_urdf_from_json + report_writer, command_writer = serialize_report, from_report + if profile.artifacts.output_schema_version >= 3: + from .serializers.measured_v3 import serialize_report as report_writer, from_report as command_writer + report = report_writer(profile, fit, prepared, serial_number=serial_number, protected_inputs=protected_inputs) + report["capture_plan"] = CapturePlan.from_profile(profile).as_dict() + report["urdf_correction"] = serialize_urdf_correction(prepared.plan) + if prepared.plan.range_evidence: + report["motion_range_evidence"] = {name: asdict(item) for name, item in prepared.plan.range_evidence.items()} + payload = command_writer(report) + naming = {"serial_number": serial_number, "side": profile.key.side, "model": profile.key.model.lower()} + json_path = directory / profile.artifacts.calibration_filename.format(**naming) + urdf_path = directory / profile.artifacts.corrected_urdf_filename.format(**naming) + atomic_write_json(json_path, payload) + atomic_write_json(directory / REPORT_FILENAME, report) + rebuild_urdf_from_json(json_path, source, urdf_path, + authorized_fields=profile.urdf_authorized_fields, expected_profile_id=profile.key.profile_id) + return payload, json_path, urdf_path + + +def finalize_profile_session(*, profile, session_dir, serial_number, source_urdf, + protected_inputs, records, publish=True, timestamp=None, + standard_loader: Callable = validate_with_robot_state_publisher, + cancelled: Callable[[], bool] = lambda: False, + directions_are_task_relative: bool = False, + require_motion_evidence: bool = False, + camera_extrinsics_file=None, + frozen_training_sha256=None, + phase_changed: Callable[[str], None] = lambda _phase: None): + """No worker may publish after an operator abort. + + The runtime owns cancellation synchronization. This function also checks + immediately before publication and never returns the hand to a pose. + """ + reject_diagnostic_capture(records) + del timestamp + if profile.artifacts.output_schema_version not in {2, 3}: + raise ValueError("production calibration requires unified output_schema_version: 2 or 3; legacy formats are read-only") + if profile.artifacts.output_schema_version >= 3: + from ...profiles.validator import validate_executable_profile, require_release_geometry + require_release_geometry(validate_executable_profile(profile, source_urdf)) + directory, source = Path(session_dir).resolve(), Path(source_urdf).resolve() + directory.mkdir(parents=True, exist_ok=True) + def check_cancelled(): + if cancelled(): + raise ValueError("operator_abort:no_artifact_publication") + check_cancelled() + from ...core.domain.capture_plan import raw_joint_capture + if raw_joint_capture(profile): + from .raw_joint_finalization import finalize_raw_joint_session + return finalize_raw_joint_session(profile=profile, session_dir=directory, + serial_number=serial_number, source_urdf=source, protected_inputs=protected_inputs, + records=records, camera_extrinsics_file=camera_extrinsics_file, + standard_loader=standard_loader, cancelled=cancelled, + phase_changed=phase_changed, publish=publish) + from ..training import resolve_capture_plan + profile = resolve_capture_plan(profile, records, source_urdf=source, + verify_decisions=frozen_training_sha256 is None, require_complete=True) + from ..motion_provenance import uses_motion_evidence + capture_evidence_required = (require_motion_evidence or uses_motion_evidence(records) + or any(row.get("kind") == "session_start" for row in records)) + try: + if capture_evidence_required: + from .capture_validation import validate_capture_for_release + sampling_plans = validate_capture_for_release(profile, serial_number, protected_inputs, records) + else: + # Legacy pose-only callers retain their numerical contract. + # Both product entry points explicitly require capture evidence. + from ...core.fitting.command_sampling import validate_sampling_plans + sampling_plans = validate_sampling_plans(profile, records) + except ValueError as error: + atomic_write_json(directory / "capture_validation.json", { + "passed": False, "reason": str(error), "publication_allowed": False}) + raise + if capture_evidence_required: + atomic_write_json(directory / "capture_validation.json", { + "passed": True, "scope": "provenance_and_complete_latest_attempts"}) + if sampling_plans: + atomic_write_json(directory / "command_sampling_plans.json", sampling_plans) + from ..motion_provenance import validate_source_geometry + validate_source_geometry(profile, source, records) + if any(row.get("projection_reprocessing_scope") for row in records): + raise ValueError("partial external projection is diagnostic-only; cannot certify a whole session") + pose_reports = {} + for task in profile.motion.tasks: + if task.key not in profile.measurement.candidate_selection_tasks: + continue + try: + records, report = resolve_chain_observations(records, task_key=task.key, + require_frozen_branches=True, + training_cycles=training_cycles(profile, task), holdout_cycle=profile.quality.holdout_cycle, + fixed_roles={tag.role for view in profile.vision.views for tag in view.tags if tag.fixed_reference}, + role_pairs={name: (profile.measurement.measurements[name].parent_role, + profile.measurement.measurements[name].child_role) for name in task.joints}) + except ValueError as error: + pose_reports[task.key] = {'status': 'failed', 'reason': str(error), 'publication_allowed': False} + atomic_write_json(directory / "pose_selection_diagnostics.json", pose_reports) + raise + pose_reports[task.key] = report + atomic_write_json(directory / "pose_selection_diagnostics.json", pose_reports) + if report["status"] == "legacy_projection_unverified": + raise ValueError("camera_projection_unverified:no_artifact_publication") + from ..motion_provenance import validate_motion_provenance + try: + motion_provenance = validate_motion_provenance(profile, records, + required=require_motion_evidence, require_complete=True) + except ValueError as error: + atomic_write_json(directory / "motion_branch_provenance.json", { + "status": "failed", "reason": str(error), "publication_allowed": False}) + raise + atomic_write_json(directory / "motion_branch_provenance.json", motion_provenance) + accepted = accepted_joint_records(profile, records, directions_are_task_relative=directions_are_task_relative) + secondary = accepted_secondary_records(profile, records, directions_are_task_relative=directions_are_task_relative) + try: + from ...core.domain.reference import read_joint_zero_references + references = read_joint_zero_references(profile, records) if profile.artifacts.output_schema_version >= 3 else None + frozen_training = None + if profile.quality.training_policy == STAGED: + import json + from ..staged_training import read_frozen_training, staged_snapshot + payload = json.loads((directory / "frozen_training.json").read_text()) + decisions = [r for r in records if r.get("kind") == "staged_training_decision" and r.get("decision") == "freeze"] + if (len(decisions) != 1 or evidence_digest(payload) != decisions[0]["frozen_training_sha256"] + or (frozen_training_sha256 is not None and evidence_digest(payload) != frozen_training_sha256)): + raise ValueError("frozen_hand_training_digest_changed") + frozen_training = read_frozen_training(profile, staged_snapshot(profile, records), references, source, payload) + def save_relative_motion(motion): + if profile.artifacts.output_schema_version >= 3: + atomic_write_json(directory / "relative_motion_diagnostics.json", { + "geometry_alignment_certified": False, "publication_allowed": False, + "curves": {name: asdict(curve) for name, curve in motion.observed_curves.items()}, + "holdout_errors_rad": motion.holdout_errors_rad}) + steady = accepted_joint_records(profile, records, sample_phase="steady", + directions_are_task_relative=directions_are_task_relative) + fit = fit_profile_calibration(profile, source, accepted, cross_view_records=secondary, + zero_references=references, steady_records=steady, motion_fitted=save_relative_motion, + frozen_training=frozen_training) + if not profile.command_based_release: + fit = fit_command_mappings(profile, fit, steady) + if fit.feedback_diagnostics: + atomic_write_json(directory / "feedback_mapping_diagnostics.json", fit.feedback_diagnostics) + if profile.artifacts.output_schema_version >= 3: + from ...core.fitting.motion_transfer import expand_profile_transfers + fit = expand_profile_transfers(profile, fit) + except ValueError as error: + diagnostic = {"passed": False, "reason": str(error), "publication_allowed": False} + if isinstance(error, RotationHoldoutFailure): + diagnostic.update(stage="relative_rotation_holdout", + rotation_holdout=asdict(error.diagnostics)) + atomic_write_json(directory / "fit_diagnostics.json", diagnostic) + raise + check_cancelled() + phase_changed("fit_complete") + try: + prepared = prepare_standard_result(profile, source, protected_inputs["source_urdf_sha256"], fit) + except ValueError as error: + atomic_write_json(directory / "fit_diagnostics.json", {"passed": False, "reason": str(error), + "publication_allowed": False, "relative_motion": {name: asdict(curve) for name, curve in fit.curves.items()}}) + raise + check_cancelled() + phase_changed("holdout_complete") + payload, json_path, urdf_path = _write_artifact_pair( + profile, fit, prepared, directory, source, serial_number, protected_inputs) + phase_changed("artifacts_built") + zero = fit.spatial_zero + replay_records = [row for rows in (steady if profile.command_based_release else accepted).values() for row in rows] + replay_records.extend(dict(row, joint=profile.measurement.cross_view_sources[name]) + for name, rows in secondary.items() for row in rows) + from ...core.fitting.tag_installation import TagInstallationFailure + try: + replay = prepare_tag_replay(profile=profile, source_model=UrdfKinematicModel(source), + plan=prepared.plan, output_mappings=fit.output_mappings, + common_from_base=transform_matrix(zero.base_translation_xyz_m, zero.base_quaternion_xyzw), + records=replay_records, frozen_training=frozen_training) + except TagInstallationFailure as error: + atomic_write_json(directory / "tag_installation_diagnostics.json", { + "passed": False, "publication_allowed": False, + "stage": "training_rigid_tag_installation", + "rotation_p95_limit_deg": 2.0, "translation_p95_limit_m": 0.003, + "roles": error.diagnostics}) + raise + from .evidence import prepare_command_holdout + from ...core.domain.sampling import command_holdout_cycle + command_validation_cycle = command_holdout_cycle(profile) + steady_secondary = accepted_secondary_records(profile, records, sample_phase="steady", + directions_are_task_relative=directions_are_task_relative) + steady_rows = [r for rows in steady.values() for r in rows] + steady_rows.extend(dict(r, joint=profile.measurement.cross_view_sources[name]) + for name, rows in steady_secondary.items() for r in rows) + command_holdout = prepare_command_holdout(profile, fit.command_mappings, steady_rows) + image_inputs = {} + if capture_evidence_required: + if camera_extrinsics_file is None: + raise ValueError("final_image_holdout_requires_protected_camera_file") + from .image_evidence import ImageEvidence + image_evidence = ImageEvidence(profile, records, camera_extrinsics_file=camera_extrinsics_file, + protected_inputs=protected_inputs, source_model=UrdfKinematicModel(source)) + image_inputs = { + "image_observations": (() if profile.command_based_release else image_evidence.all_view_holdout(replay.holdout, + mappings=fit.output_mappings, input_kind="feedback", holdout_cycle=profile.quality.holdout_cycle)), + "command_image_observations": image_evidence.all_view_holdout(command_holdout, + mappings=fit.command_mappings, input_kind="command", holdout_cycle=command_validation_cycle), + "require_image_holdout": True, + } + image_inputs["out_of_scope_images"] = tuple(image_evidence.out_of_scope_images) + from ...core.urdf.partial_scope import profile_scope + validator = FrozenTagArtifactValidator(profile.key.profile_id, source, + protected_inputs["source_urdf_sha256"], profile.urdf_authorized_fields, + fit.zero_offsets_rad, replay.common_from_base, replay.installations, + replay.holdout, replay.required_roles, standard_loader, protected_inputs=dict(protected_inputs), + command_observations=command_holdout, release_basis=profile.measurement.release_basis, + calibration_scope=profile_scope(profile), + capture_plan=CapturePlan.from_profile(profile).as_dict(), + joint_observations=tuple(r for rows in steady.values() for r in rows if r["cycle"] == command_validation_cycle), + command_holdout_cycle=command_validation_cycle, + joint_curves=fit.curves, + joint_channels={name: channel_for_joint(profile, name) for name in fit.output_mappings}, + transferred_motion_sources=profile.measurement.transferred_motion_sources, + cad_zero_assumptions=profile.zero.cad_zero_assumptions, + transferred_zero_sources=profile.zero.transferred_zero_sources, + joint_zero_methods=fit.zero_method_by_joint, range_evidence=prepared.plan.range_evidence, + directional_command_joints=profile.artifacts.directional_command_joints, **image_inputs) + check_cancelled() + atomic_write_json(directory / "frozen_tag_installations.json", { + "common_from_base": replay.common_from_base, + "installations": {name: asdict(mount) for name, mount in replay.installations.items()}}) + publisher = ArtifactPublisher(directory.parent, profile.artifacts.publication_pointer) + from ...core.urdf.image_acceptance import ImageHoldoutFailure + try: + staged = publisher.prepare(session_directory=directory, calibration_json=json_path, + corrected_urdf=urdf_path, validate=validator, cancelled=cancelled) + except ImageHoldoutFailure as error: + atomic_write_json(directory / "final_image_diagnostics.json", { + "passed": False, "publication_allowed": False, "reason": str(error), + "input_kind": error.input_kind, "holdout_cycle": error.holdout_cycle, "roles": error.report}) + raise + import json + acceptance = json.loads(staged.validation_json) + atomic_write_json(directory / "standard_urdf_acceptance.json", acceptance) + check_cancelled() + phase_changed("urdf_validated") + if publish: + publisher.commit(staged, cancelled=cancelled) + atomic_write_json(directory / "calibration_summary_zh.json", { + "profile_id": profile.key.profile_id, "result": "PASS", + "publication_evidence": "release_manifest.json and the product publication pointer", + "artifacts": {"json": json_path.name, "urdf": urdf_path.name}, "acceptance": acceptance}) + return payload, fit, CorrectedArtifact(urdf_path, staged) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/image_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/image_evidence.py new file mode 100644 index 0000000..ba29d09 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/image_evidence.py @@ -0,0 +1,174 @@ +"""Bind final-file image checks to raw pixels and protected camera identities.""" + +import hashlib +import json +from numbers import Real +from pathlib import Path + +import numpy as np + +from ...core.domain.motion_path import record_scan_identity +from ...core.domain.capture_plan import raw_feedback_capture +from ...core.geometry.extrinsics import camera_info_fingerprint, load_camera_extrinsics +from ...core.urdf.image_acceptance import TagImageObservation +from ..image_capture import IMAGE_OBSERVATION_POLICY +from .evidence import _replay_directions + + +class ImageEvidence: + """Validate source identities once, then prepare disjoint input holdouts. + + Primary observations retain their existing provenance checks. Additional + views contribute original pixels and synchronized SDK values directly, + without manufacturing a PnP pose or fitting against a holdout image. + """ + + def __init__(self, profile, records, *, camera_extrinsics_file, protected_inputs, source_model=None): + path = Path(camera_extrinsics_file) + if hashlib.sha256(path.read_bytes()).hexdigest() != protected_inputs["camera_extrinsics_sha256"]: + raise ValueError("final_image_camera_extrinsics_changed") + self.profile = profile + if profile.retained_joints and source_model is None: + raise ValueError("partial_image_scope_requires_source_topology") + self.source_model = source_model + self.out_of_scope_images = [] + self.extrinsics = load_camera_extrinsics(path, required_views=profile.vision.view_names, + reference_view=profile.vision.extrinsic_reference_view, + quality_limits=profile.vision.extrinsics_quality_limits, + minimum_capture_counts=profile.vision.minimum_capture_counts) + self.models, self.frames, self.raw_frames, self.completed = {}, {}, {}, {} + self.tags = {tag.role: (view.name, tag) for view in profile.vision.views for tag in view.tags} + self.tasks = {task.key: task for task in profile.motion.tasks} + for row in records: + kind = row.get("kind") + if kind == "rectified_camera_model": + self._bind(self.models, row["view"], row) + elif kind in {"pnp_candidate_frame", "image_observation_frame"}: + target = self.frames if kind == "pnp_candidate_frame" else self.raw_frames + self._bind(target, f"{row['view']}:{row['image_stamp_ns']}", row) + elif kind == "scan_unit_complete": + key = record_scan_identity(row) + self.completed[key] = row + for view, model in self.models.items(): + identity = self.extrinsics.cameras[view] + fingerprint = camera_info_fingerprint(width=model["width"], height=model["height"], + camera_matrix=model["raw_k"], distortion=model["raw_d"], + rectification=model["rectification_r"], projection=model["projection_p"]) + if (fingerprint != identity.intrinsics_sha256 + or model.get("matrix_source") != "CameraInfo.P[:3,:3]" + or model.get("input_is_rectified") is not True): + raise ValueError("final_image_camera_intrinsics_changed") + if not np.array_equal(np.asarray(model["projection_p"]).reshape(3, 4)[:, :3], model["camera_matrix"]): + raise ValueError("final_image_camera_projection_changed") + + @staticmethod + def _bind(mapping, key, row): + if key in mapping and json.dumps(mapping[key], sort_keys=True) != json.dumps(row, sort_keys=True): + raise ValueError("final_image_source_identity_reused") + mapping[key] = row + + def _image(self, frame, *, sample_id, role, cycle, sdk_values, directions): + view, tag = self.tags[role] + model = self.models.get(view) + if (model is None or frame["view"] != view or frame["cycle"] != cycle + or frame.get("input_is_rectified") is not True + or frame.get("camera_matrix_source") != "CameraInfo.P[:3,:3]" + or not np.array_equal(frame["camera_matrix"], model["camera_matrix"])): + raise ValueError("final_image_holdout_source_missing_or_changed") + field = "tags" if frame["kind"] == "image_observation_frame" else "roles" + pixel = frame[field].get(role, {}) + if pixel.get("tag_size_m") != tag.size_m or pixel.get("tag_id") != tag.tag_id: + raise ValueError("final_image_holdout_tag_changed") + corners = np.asarray(pixel.get("corners_xy", ())) + if corners.shape != (4, 2) or not np.all(np.isfinite(corners)): + raise ValueError("final_image_holdout_corners_missing") + return TagImageObservation(sample_id, role, cycle, tuple(sdk_values), tuple(sorted(directions.items())), + view, tag.size_m, tuple(map(tuple, corners)), tuple(map(tuple, frame["camera_matrix"])), + tuple(map(tuple, np.linalg.inv(self.extrinsics.transform(view)))), + task_name=frame.get("task_name", "")) + + def primary_holdout(self, observations): + result = [] + source = self.raw_frames if raw_feedback_capture(self.profile) else self.frames + for observation in observations: + frame = source.get(observation.sample_id) + if frame is None: + raise ValueError("final_image_holdout_source_missing_or_changed") + result.append(self._image(frame, sample_id=observation.sample_id, role=observation.role, + cycle=observation.cycle, sdk_values=observation.sdk_values, + directions=observation.sdk_directions_by_joint)) + return tuple(result) + + def all_view_holdout(self, observations, *, mappings, input_kind, holdout_cycle): + """Use every synchronized image in the accepted independent scan units. + + Duplicate primary/raw identities must agree in both pixels and SDK + conditions. Missing feedback is explicit unavailable evidence; it is + never replaced with a command value or a fitted angle. + """ + if input_kind not in {"feedback", "command"}: + raise ValueError("final_image_input_kind_invalid") + primary = self.primary_holdout(observations) + expected = {(row.role, row.sample_id): row for row in primary} + roles = {row.role for row in primary} + phase = "sweep" if input_kind == "feedback" else "steady" + result = {} + count = self.profile.command.command_count + for sample_id, frame in self.raw_frames.items(): + if frame.get("cycle") != holdout_cycle or frame.get("sample_phase") != phase: + continue + unit = self.completed.get(record_scan_identity(frame)) + if unit is None or not unit["passed"] or unit["attempt"] != frame["attempt"]: + continue + if frame.get("policy") != IMAGE_OBSERVATION_POLICY or frame.get("command_unit") != self.profile.command.unit: + raise ValueError("final_image_raw_policy_or_unit_changed") + vectors = [frame.get("command_vector"), frame.get("feedback_vector")] + skew = frame.get("state_image_sync_error_ns") + if self.profile.vision_motion and input_kind == "command": + vectors = [frame.get("command_vector")] + skew = frame.get("command_image_skew_ns") + if any(values is None for values in vectors) or skew is None: + continue + if (not isinstance(skew, Real) or isinstance(skew, bool) + or not np.isfinite(skew) or skew < 0): + raise ValueError("final_image_raw_sync_error_invalid") + arrays = [np.asarray(values) for values in vectors] + if any(values.shape != (count,) or values.dtype.kind not in "fiu" + or not np.all(np.isfinite(values)) for values in arrays): + raise ValueError("final_image_raw_sdk_vector_invalid") + history = frame.get("command_direction_by_index") + if (not isinstance(history, (list, tuple)) or len(history) != count + or any(value not in {"", "increasing", "decreasing"} for value in history)): + raise ValueError("final_image_raw_direction_history_invalid") + task = self.tasks.get(frame["task_name"]) + if task is None: + raise ValueError("final_image_raw_task_unknown") + directions = _replay_directions(mappings, frame, task) + values = frame["feedback_vector" if input_kind == "feedback" else "command_vector"] + for role in sorted(roles.intersection(frame["tags"])): + if self.profile.retained_joints: + from ...core.urdf.partial_scope import profile_scope, out_of_scope_ancestors + outside = out_of_scope_ancestors(profile_scope(self.profile)["retained_joints"], + values, model=self.source_model, link=self.tags[role][1].link) + if outside: + if (role, sample_id) in expected: + raise ValueError("primary_image_has_uncalibrated_moving_ancestor") + self.out_of_scope_images.append({"sample_id": sample_id, "role": role, + "task_name": frame["task_name"], "retained_ancestors": list(outside), + "reason": "unmeasured_ancestor_outside_declared_hold"}) + continue + image = self._image(frame, sample_id=sample_id, role=role, cycle=holdout_cycle, + sdk_values=values, directions=directions) + identity = (role, sample_id) + if identity in expected and image != expected[identity]: + raise ValueError("final_image_primary_raw_disagree") + result[identity] = image + if not expected or not expected.keys() <= result.keys(): + raise ValueError("final_image_all_view_source_missing") + return tuple(result.values()) + + +def prepare_image_holdout(profile, records, observations, *, camera_extrinsics_file, protected_inputs): + """Historical primary-image binding; no new evidence is imputed to old files.""" + return ImageEvidence(profile, records, camera_extrinsics_file=camera_extrinsics_file, + protected_inputs=protected_inputs).primary_holdout(observations) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/process_finalizer.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/process_finalizer.py new file mode 100644 index 0000000..573c79a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/process_finalizer.py @@ -0,0 +1,108 @@ +"""Isolate CPU-heavy finalization from live ROS callbacks. + +The parent thread transports events/results and owns cancellation. Only the +controller may publish. A bounded, synced journal prefix avoids pickling the +entire capture while holding the control lock. +""" + +import json +import multiprocessing +from pathlib import Path +import time +import traceback + +from .finalization import finalize_profile_session + + +def read_journal_prefix(path, size): + """Decode the frozen prefix without retaining copies of the raw journal. + + Captures can contain hundreds of megabytes of JSONL. Reading the whole + prefix and then splitting it keeps two additional copies alive while the + decoded records accumulate, alongside the live camera processes. + """ + if not isinstance(size, int) or isinstance(size, bool) or size <= 0: + raise ValueError("invalid_finalization_journal_size") + from ...core.geometry.frozen_evidence import EvidenceDecoder + from ...core.artifacts.evidence_journal import REFERENCE_KEY, decode_envelope + decoder = EvidenceDecoder() + rows = [] + remaining = size + path = Path(path) + with path.open("rb") as stream: + while remaining: + line = stream.readline(remaining) + if not line or not line.endswith(b"\n"): + raise ValueError("incomplete_finalization_journal_prefix") + remaining -= len(line) + row = decoder.loads(line) + if not isinstance(row, dict): + raise ValueError("invalid_finalization_journal_rows") + if REFERENCE_KEY in row: + row = decode_envelope(path, row, decoder) + rows.append(row) + return tuple(rows) + + +def _prepare(connection, finalizer, journal_path, journal_size, kwargs): + started = time.monotonic() + try: + records = read_journal_prefix(journal_path, journal_size) + result = finalizer(**kwargs, records=records, publish=False, + phase_changed=lambda phase: connection.send(("phase", phase))) + connection.send(("result", result)) + except Exception: + connection.send(("error", traceback.format_exc())) + finally: + from ...core.artifacts.storage import atomic_write_json + atomic_write_json(Path(kwargs["session_dir"]) / "finalization_timing.json", { + "backend": "isolated_process", "elapsed_seconds": time.monotonic()-started, + "journal_prefix_bytes": journal_size}) + connection.close() + + +def isolated_finalize_profile_session(*, journal_path, journal_size, records, + phase_changed, cancelled, publish=False, finalizer=finalize_profile_session, + timeout_seconds=600., **kwargs): + """Same production finalizer, with bounded cancellation and no publication.""" + del records # The synced journal is the immutable capture transport. + if publish: + raise ValueError("isolated_worker_cannot_publish") + if cancelled(): + raise ValueError("operator_abort:no_artifact_publication") + context = multiprocessing.get_context("spawn") + receive, send = context.Pipe(duplex=False) + process = context.Process(target=_prepare, + args=(send, finalizer, journal_path, journal_size, kwargs), daemon=True) + started = time.monotonic() + try: + process.start() + send.close() + while not cancelled(): + if receive.poll(.05): + kind, value = receive.recv() + if kind == "phase": + phase_changed(value) + elif kind == "result": + return value + elif kind == "error": + raise RuntimeError(f"finalization_process_failed:\n{value}") + else: + raise RuntimeError(f"invalid_finalization_process_event:{kind}") + elif not process.is_alive(): + raise RuntimeError(f"finalization_process_exited:{process.exitcode}") + if time.monotonic()-started >= timeout_seconds: + raise TimeoutError("finalization_process_timeout:no_artifact_publication") + raise ValueError("operator_abort:no_artifact_publication") + finally: + receive.close() + send.close() + if process.pid is not None: + process.join(timeout=.2) + if process.is_alive(): + process.terminate() + process.join(timeout=1.) + if process.is_alive(): + process.kill() + process.join(timeout=1.) + process.close() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/publisher.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/publisher.py new file mode 100644 index 0000000..ced0157 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/publisher.py @@ -0,0 +1,445 @@ +"""Atomic JSON/URDF release shared by all output-schema serializers.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, field +import hashlib +import json +import os +from pathlib import Path +from typing import Any, Callable, Mapping, Sequence +import uuid +import xml.etree.ElementTree as ET + +from ...core.artifacts.storage import atomic_write_json +from ...core.urdf.acceptance import ( + JointHoldout, validate_artifact_structure, validate_standard_urdf_holdout, +) +from ...core.fitting.tag_installation import FrozenTagInstallation +from ...core.urdf.tag_acceptance import TagHoldout, validate_serialized_tag_holdout +from ...core.domain.profile import ProfileKey +from .serializers.compact_v2 import FORMAT as COMPACT_FORMAT, REPORT_FILENAME, from_report +from .serializers.measured_v3 import FORMAT as MEASURED_FORMAT, from_report as measured_from_report + + +def _validate_identity(payload, profile_id): + if payload.get("schema_version") == 4 and "profile_id" not in payload: + # The exact deployed v4 shape has no layout/profile/hash fields. + # The protected caller fixes layout, source geometry and authorization; + # source/JSON/URDF hashes and full identity are kept in the manifest. + key = ProfileKey.parse(profile_id) + if (payload.get("model"), payload.get("side")) == (key.model, key.side): + return + elif payload.get("profile_id") == profile_id: + return + raise ValueError("serialized artifact belongs to another profile") + + +@dataclass(frozen=True) +class StandardArtifactValidator: + """Release evidence independent of the serializer and its fitted payload. + + Construct this from the locked profile and training-frozen measurement + model. A serializer cannot choose its own authorized fields, truth angles, + required joints or protected source hash. + """ + + profile_id: str + source_urdf: Path + source_sha256: str + authorized_fields: Mapping[str, Sequence[str]] + zero_offsets_rad: Mapping[str, float] + observations: tuple[JointHoldout, ...] + required_joints: tuple[str, ...] + required_pose_joints: tuple[str, ...] + standard_loader: Callable[[Path], None] + minimum_samples: int = 40 + + def __call__(self, json_path: Path, urdf_path: Path) -> Mapping[str, Any]: + payload = json.loads(json_path.read_text(encoding="utf-8")) + _validate_identity(payload, self.profile_id) + if not self.required_pose_joints: + raise ValueError("final URDF acceptance requires independent spatial observations") + changes = validate_artifact_structure(source_urdf=self.source_urdf, + corrected_urdf=urdf_path, source_sha256=self.source_sha256, + authorized_fields=self.authorized_fields, payload=payload, + zero_offsets_rad=self.zero_offsets_rad) + metrics = validate_standard_urdf_holdout(corrected_urdf=urdf_path, + payload=payload, observations=self.observations, + required_joints=self.required_joints, required_pose_joints=self.required_pose_joints, + minimum_samples=self.minimum_samples) + # Production injects the standard parser/robot_state_publisher check; + # offline tests inject an independent parser, never a hardware node. + self.standard_loader(urdf_path) + evidence = json.dumps([asdict(row) for row in self.observations], + sort_keys=True, separators=(",", ":"), allow_nan=False).encode() + return { + "acceptance": "serialized_standard_urdf_v1", + "profile_id": self.profile_id, + "source_urdf_sha256": self.source_sha256, + "holdout_evidence_sha256": hashlib.sha256(evidence).hexdigest(), + "holdout_cycle": 3, + "holdout_by_joint": {name: asdict(value) for name, value in metrics.items()}, + "spatial_holdout_joints": list(self.required_pose_joints), + "structured_changes": list(changes), + } + + +@dataclass(frozen=True) +class FrozenTagArtifactValidator: + """Final-file gate for raw Tag observations with training-frozen mounts.""" + + profile_id: str + source_urdf: Path + source_sha256: str + authorized_fields: Mapping[str, Sequence[str]] + zero_offsets_rad: Mapping[str, float] + common_from_base: tuple[tuple[float, ...], ...] + installations: Mapping[str, FrozenTagInstallation] + observations: tuple[TagHoldout, ...] + required_roles: tuple[str, ...] + standard_loader: Callable[[Path], None] + minimum_samples: int = 40 + protected_inputs: Mapping[str, str] = field(default_factory=dict) + command_observations: tuple[TagHoldout, ...] = () + joint_observations: tuple[Mapping, ...] = () + joint_curves: Mapping = field(default_factory=dict) + joint_channels: Mapping[str, int] = field(default_factory=dict) + transferred_motion_sources: Mapping[str, str] = field(default_factory=dict) + cad_zero_assumptions: Mapping[str, str] = field(default_factory=dict) + transferred_zero_sources: Mapping[str, str] = field(default_factory=dict) + joint_zero_methods: Mapping[str, str] = field(default_factory=dict) + range_evidence: Mapping = field(default_factory=dict) + directional_command_joints: frozenset[str] = frozenset() + command_holdout_cycle: int = 3 + image_observations: tuple = () + command_image_observations: tuple = () + require_image_holdout: bool = False + release_basis: str = "feedback_and_command" + calibration_scope: Mapping | None = None + out_of_scope_images: tuple = () + capture_plan: Mapping | None = None + + def __call__(self, json_path: Path, urdf_path: Path) -> Mapping[str, Any]: + payload = json.loads(json_path.read_text(encoding="utf-8")) + _validate_identity(payload, self.profile_id) + feedback_payload = payload + measured = payload.get("format") == MEASURED_FORMAT + if payload.get("format") in {COMPACT_FORMAT, MEASURED_FORMAT}: + feedback_payload = json.loads((json_path.parent / REPORT_FILENAME).read_text(encoding="utf-8")) + _validate_identity(feedback_payload, self.profile_id) + if self.capture_plan is not None and feedback_payload.get("capture_plan") != self.capture_plan: + raise ValueError("capture plan differs from frozen session decisions") + if (measured_from_report if measured else from_report)(feedback_payload) != payload: + raise ValueError("compact JSON differs from the frozen calibration report") + if measured: + if payload.get("directional_command_joints", []) != sorted(self.directional_command_joints): + raise ValueError("directional command declaration differs from the Profile") + if feedback_payload.get("protected_inputs") != dict(self.protected_inputs): + raise ValueError("v3 report protected inputs differ from the session") + if {name: row["sdk_channel"] for name, row in payload["joints"].items()} != dict(self.joint_channels): + raise ValueError("v3 SDK channel bindings differ from measured Profile bindings") + self._validate_report_provenance(feedback_payload) + validate_artifact_structure(source_urdf=self.source_urdf, + corrected_urdf=urdf_path, source_sha256=self.source_sha256, + authorized_fields=self.authorized_fields, payload=feedback_payload, + zero_offsets_rad=self.zero_offsets_rad, range_evidence=self.range_evidence) + changes = validate_artifact_structure(source_urdf=self.source_urdf, + corrected_urdf=urdf_path, source_sha256=self.source_sha256, + authorized_fields=self.authorized_fields, payload=payload, + zero_offsets_rad=self.zero_offsets_rad, range_evidence=self.range_evidence) + rebuilt_from_json = "urdf_correction" in payload + if rebuilt_from_json: + from .urdf_from_json import validate_json_urdf_correspondence + validate_json_urdf_correspondence(payload, self.source_urdf, urdf_path, + expected_profile_id=self.profile_id) + metrics = {} + if self.release_basis == "feedback_and_command": + metrics = validate_serialized_tag_holdout(corrected_urdf=urdf_path, + payload=feedback_payload, common_from_base=self.common_from_base, + installations=self.installations, observations=self.observations, + required_roles=self.required_roles, minimum_samples=self.minimum_samples) + command_metrics = {} + if payload.get("format") in {"unified_calibration_v1", COMPACT_FORMAT, MEASURED_FORMAT}: + try: + command_metrics = validate_serialized_tag_holdout(corrected_urdf=urdf_path, + payload=payload, common_from_base=self.common_from_base, + installations=self.installations, observations=self.command_observations, + required_roles=self.required_roles, minimum_samples=3, input_kind="command", + holdout_cycle=self.command_holdout_cycle) + except ValueError as error: + if payload.get("format") == COMPACT_FORMAT: + raise ValueError(f"compact_command_table_holdout_failed:{error}") from error + raise + image_metrics = {} + image_policy = None + if self.require_image_holdout: + from ...core.urdf.image_acceptance import FINAL_IMAGE_ACCEPTANCE_POLICY, validate_serialized_image_holdout + image_policy = FINAL_IMAGE_ACCEPTANCE_POLICY + common = dict(corrected_urdf=urdf_path, common_from_base=self.common_from_base, + installations=self.installations, required_roles=self.required_roles) + if self.release_basis == "feedback_and_command": + image_metrics["feedback"] = validate_serialized_image_holdout(**common, + payload=feedback_payload, observations=self.image_observations, + independent_observations=self.observations, + input_kind="feedback", holdout_cycle=3, minimum_samples=self.minimum_samples) + image_metrics["command"] = validate_serialized_image_holdout(**common, + payload=payload, observations=self.command_image_observations, + independent_observations=self.command_observations, + input_kind="command", holdout_cycle=self.command_holdout_cycle, minimum_samples=3) + self.standard_loader(urdf_path) + evidence = {"base": self.common_from_base, + "installations": {k: asdict(v) for k, v in self.installations.items()}, + "observations": [asdict(row) for row in self.observations]} + evidence["steady_command_observations"] = [asdict(row) for row in self.command_observations] + evidence["image_observations"] = [asdict(row) for row in self.image_observations] + evidence["command_image_observations"] = [asdict(row) for row in self.command_image_observations] + evidence["motion_range_evidence"] = {name: asdict(item) for name, item in self.range_evidence.items()} + extra = {} + if measured: + from ...core.urdf.joint_control import ( + JSON_JOINT_ANGLES, independent_joint_sources, uses_affine_mimic_approximation, + uses_source_mimic, + ) + from ...core.urdf.measured_acceptance import validate_measured_joint_holdout + extra = {"independent_mapping_holdout": validate_measured_joint_holdout(payload, + self.joint_curves, self.joint_observations, + transferred_motion_sources=self.transferred_motion_sources, + holdout_cycle=self.command_holdout_cycle), + "full_json_urdf_holdout": command_metrics, + "independently_measured_joints": sorted(self.joint_curves), + "transferred_joints": sorted(self.transferred_motion_sources), + "transferred_motion_sources": dict(self.transferred_motion_sources), + "cad_zero_assumptions": dict(self.cad_zero_assumptions), + "directional_command_joints": sorted(self.directional_command_joints), + "precision_scope": "observed_joints_travel_directions_and_held_poses"} + if independent_joint_sources(payload) is not None: + extra["urdf_joint_angle_source"] = JSON_JOINT_ANGLES + else: + extra["urdf_mimic_approximation"] = validate_serialized_tag_holdout(corrected_urdf=urdf_path, + payload=payload, common_from_base=self.common_from_base, installations=self.installations, + observations=self.command_observations, required_roles=self.required_roles, minimum_samples=3, + input_kind="command", mimic_approximation=True, enforce_precision=False, + holdout_cycle=self.command_holdout_cycle) + if uses_affine_mimic_approximation(payload) or uses_source_mimic(payload): + extra["urdf_joint_angle_source"] = JSON_JOINT_ANGLES + extra["urdf_mimic_policy"] = payload["urdf_correction"]["mimic_policy"] + evidence["joint_observations"] = self.joint_observations + evidence["frozen_joint_curves"] = {key: asdict(value) for key, value in self.joint_curves.items()} + evidence["transferred_motion_sources"] = dict(self.transferred_motion_sources) + evidence["cad_zero_assumptions"] = dict(self.cad_zero_assumptions) + acceptance_kind = ("measured_and_transferred_json_urdf_v3" if self.transferred_motion_sources + else "independently_measured_json_urdf_v3") if measured else "serialized_standard_urdf_tag_replay_v1" + if self.calibration_scope is not None: + evidence["calibration_scope"] = self.calibration_scope + evidence["out_of_scope_images"] = self.out_of_scope_images + extra.update(calibration_scope=self.calibration_scope, + out_of_scope_images=self.out_of_scope_images) + acceptance_kind = "partial_measured_json_urdf_v3" + elif self.out_of_scope_images: + raise ValueError("full_calibration_cannot_exclude_ancestor_image_evidence") + return {"acceptance": acceptance_kind, "release_basis": self.release_basis, + "feedback_mapping_required": self.release_basis == "feedback_and_command", + "final_file_image_holdout": image_metrics, + "final_file_image_holdout_policy": image_policy, + "final_file_image_holdout_verified": self.require_image_holdout, + **extra, + "urdf_rebuilt_from_json": rebuilt_from_json, + "profile_id": self.profile_id, "source_urdf_sha256": self.source_sha256, + "protected_inputs": dict(self.protected_inputs), + "motion_range_evidence": evidence["motion_range_evidence"], + "holdout_cycle": 3, "tag_holdout": metrics, + "command_holdout_cycle": self.command_holdout_cycle, + "steady_command_tag_holdout": command_metrics, + "final_file_spatial_replay": "passed", + "holdout_evidence_sha256": hashlib.sha256(json.dumps(evidence, + sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest(), + "structured_changes": list(changes)} + + def _validate_report_provenance(self, report): + """The report cannot grant itself new transfer or CAD authorizations.""" + if report.get("calibration_scope") != self.calibration_scope: + raise ValueError("v3 partial scope differs from the protected Profile") + if report.get("quality", {}).get("release_basis", "feedback_and_command") != self.release_basis: + raise ValueError("v3 release basis differs from the protected Profile") + if report.get("quality", {}).get("command_holdout_cycle", 3) != self.command_holdout_cycle: + raise ValueError("v3 command validation partition differs from the Profile") + ranges = json.loads(json.dumps({name: asdict(item) for name, item in self.range_evidence.items()})) + if report.get("motion_range_evidence", {}) != ranges: + raise ValueError("v3 motion range evidence differs from the frozen training fit") + if report.get("transferred_motion_sources", {}) != dict(self.transferred_motion_sources): + raise ValueError("v3 transfer sources differ from the measured Profile") + rows = report["joints"] + observed = {name for name, row in rows.items() if row.get("independently_measured") is True} + if (observed != set(self.joint_curves) + or set(rows) != observed | self.transferred_motion_sources.keys()): + raise ValueError("v3 reported measurement coverage differs from frozen observations") + assumptions = {name: row["cad_zero_assumption"] for name, row in rows.items() if "cad_zero_assumption" in row} + if assumptions != dict(self.cad_zero_assumptions): + raise ValueError("v3 CAD zero assumptions differ from the Profile") + zero_sources = {name: row["zero_transferred_from_joint"] for name, row in rows.items() + if "zero_transferred_from_joint" in row} + if zero_sources != dict(self.transferred_zero_sources): + raise ValueError("v3 static zero transfer sources differ from the Profile") + if self.joint_zero_methods and {name: row["zero_method"] for name, row in rows.items()} != dict(self.joint_zero_methods): + raise ValueError("v3 zero provenance differs from the frozen fit") + for name in assumptions: + if rows[name]["zero_method"] != "assumed_source_cad_zero" or rows[name]["zero_offset_rad"] != 0: + raise ValueError(f"v3 assumed CAD zero is mislabeled:{name}") + + +@dataclass(frozen=True) +class ArtifactRelease: + calibration_json: Path + corrected_urdf: Path + manifest: Path + pointer: Path + sha256: Mapping[str, str] + + +@dataclass(frozen=True) +class StagedRelease: + session: Path + calibration_json: Path + corrected_urdf: Path + calibration_json_sha256: str + corrected_urdf_sha256: str + # Canonical immutable evidence; no mutable callback object crosses the + # worker/control-thread boundary. + validation_json: str + calibration_report: Path | None = None + calibration_report_sha256: str | None = None + + +class ArtifactPublisher: + """Validate both staged products before changing the public pointer.""" + + def __init__(self, release_root: str | Path, pointer_name: str) -> None: + self.release_root = Path(release_root).expanduser().resolve() + if not pointer_name or Path(pointer_name).name != pointer_name: + raise ValueError("publication pointer must be one filename") + self.pointer_name = str(pointer_name) + + def prepare( + self, + *, + session_directory: str | Path, + calibration_json: str | Path, + corrected_urdf: str | Path, + validate: Callable[[Path, Path], Mapping[str, Any] | None], + cancelled: Callable[[], bool] = lambda: False, + ) -> StagedRelease: + session = Path(session_directory).expanduser().resolve() + if cancelled(): + raise ValueError("operator_abort:no_artifact_publication") + json_path = Path(calibration_json).expanduser().resolve() + urdf_path = Path(corrected_urdf).expanduser().resolve() + if session.parent != self.release_root: + raise ValueError("published session must be a direct child of the release root") + if json_path.parent != session or urdf_path.parent != session: + raise ValueError("artifacts must be staged inside the session directory") + if not json_path.is_file() or not urdf_path.is_file(): + raise ValueError("both JSON and URDF must exist before publication") + if json_path == urdf_path or "release_manifest.json" in {json_path.name, urdf_path.name}: + raise ValueError("artifact names conflict with the release manifest") + hashes = { + "calibration_json_sha256": _sha256(json_path), + "corrected_urdf_sha256": _sha256(urdf_path), + } + value = json.loads(json_path.read_text(encoding="utf-8")) + if not isinstance(value, dict): + raise ValueError("calibration JSON root must be an object") + report_path = session / REPORT_FILENAME if value.get("format") in {COMPACT_FORMAT, MEASURED_FORMAT} else None + report_hash = None + if report_path is not None: + if report_path in {json_path, urdf_path} or not report_path.is_file() or report_path.resolve().parent != session: + raise ValueError("compact release requires a separate calibration report") + report_hash = _sha256(report_path) + ET.parse(urdf_path) + validation = validate(json_path, urdf_path) + if cancelled(): + raise ValueError("operator_abort:no_artifact_publication") + if hashes["calibration_json_sha256"] != _sha256(json_path) or hashes["corrected_urdf_sha256"] != _sha256(urdf_path): + raise ValueError("artifacts changed during validation") + if report_path is not None and report_hash != _sha256(report_path): + raise ValueError("calibration report changed during validation") + return StagedRelease(session, json_path, urdf_path, + hashes["calibration_json_sha256"], hashes["corrected_urdf_sha256"], + json.dumps(dict(validation or {}), sort_keys=True, allow_nan=False), report_path, report_hash) + + def commit(self, staged: StagedRelease, *, cancelled: Callable[[], bool] = lambda: False) -> ArtifactRelease: + """Fast pointer commit; call under the runtime's abort/commit lock.""" + session, json_path, urdf_path = staged.session, staged.calibration_json, staged.corrected_urdf + if session.parent != self.release_root or json_path.parent != session or urdf_path.parent != session: + raise ValueError("staged artifacts belong to another release root") + if cancelled(): + raise ValueError("operator_abort:no_artifact_publication") + hashes = {"calibration_json_sha256": staged.calibration_json_sha256, + "corrected_urdf_sha256": staged.corrected_urdf_sha256} + if hashes["calibration_json_sha256"] != _sha256(json_path) or hashes["corrected_urdf_sha256"] != _sha256(urdf_path): + raise ValueError("artifacts changed after validation") + if staged.calibration_report is not None: + if (staged.calibration_report != session / REPORT_FILENAME + or staged.calibration_report_sha256 != _sha256(staged.calibration_report)): + raise ValueError("calibration report changed after validation") + hashes["calibration_report_sha256"] = staged.calibration_report_sha256 + manifest = session / "release_manifest.json" + manifest_payload = { + "schema_version": 1, + "session": session.name, + "calibration_json": json_path.name, + "corrected_urdf": urdf_path.name, + **hashes, + "validation": json.loads(staged.validation_json), + } + if staged.calibration_report is not None: + manifest_payload["calibration_report"] = staged.calibration_report.name + # Refuse to mutate an already materialized release. A retry using the + # same frozen files/evidence is idempotent; a new fit needs a new session. + if manifest.exists(): + if json.loads(manifest.read_text(encoding="utf-8")) != manifest_payload: + raise ValueError("refusing to overwrite a different release manifest") + else: + json.dumps(manifest_payload, allow_nan=False) + atomic_write_json(manifest, manifest_payload) + # Verify after durable re-read, then atomically replace only the + # pointer. A crash cannot expose one artifact without the other. + persisted = json.loads(manifest.read_text(encoding="utf-8")) + if ( + persisted.get("calibration_json_sha256") != _sha256(json_path) + or persisted.get("corrected_urdf_sha256") != _sha256(urdf_path) + ): + raise ValueError("artifact hashes changed after staging") + if staged.calibration_report is not None and persisted.get("calibration_report_sha256") != _sha256(staged.calibration_report): + raise ValueError("calibration report changed after staging") + self.release_root.mkdir(parents=True, exist_ok=True) + pointer = self.release_root / self.pointer_name + temporary = self.release_root / f".{self.pointer_name}.{uuid.uuid4().hex}.tmp" + relative = os.path.relpath(session, self.release_root) + try: + os.symlink(relative, temporary, target_is_directory=True) + if cancelled(): + raise ValueError("operator_abort:no_artifact_publication") + os.replace(temporary, pointer) + descriptor = os.open(self.release_root, os.O_RDONLY | os.O_DIRECTORY) + try: + os.fsync(descriptor) + finally: + os.close(descriptor) + finally: + temporary.unlink(missing_ok=True) + return ArtifactRelease(json_path, urdf_path, manifest, pointer, hashes) + + def publish(self, *, cancelled: Callable[[], bool] = lambda: False, **kwargs) -> ArtifactRelease: + return self.commit(self.prepare(cancelled=cancelled, **kwargs), cancelled=cancelled) + + +def _sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(chunk) + return digest.hexdigest() + + +__all__ = ["ArtifactPublisher", "ArtifactRelease", "StandardArtifactValidator", "FrozenTagArtifactValidator", "StagedRelease"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_draft.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_draft.py new file mode 100644 index 0000000..0f4dd21 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_draft.py @@ -0,0 +1,348 @@ +"""Offline approximate URDF export, separate from precision certification.""" +from dataclasses import asdict, replace +import json +from pathlib import Path +from types import SimpleNamespace +import traceback + +import numpy as np + +from ...core.domain.result import JointMapping +from ...core.fitting.command_support import validate_turnaround_mapping +from ...core.fitting.raw_joint_draft import ( + DraftCommandImages, draft_profile, draft_targets, draft_training_coverage, fit_draft, + define_upright_splay_zero, UPRIGHT_SPLAY_JOINTS, UPRIGHT_SPLAY_REFERENCE, +) +from ...core.fitting.raw_joint_validation import validate_raw_joint_candidate +from ...core.geometry.extrinsics import load_camera_extrinsics +from ...core.urdf.kinematics import UrdfKinematicModel +from ...core.urdf.limits import MotionRangeEvidence +from ...core.urdf.plan import build_standard_correction_plan +from ...profiles import load_hand_profile +from ...profiles.observations import compile_tag_links +from ...storage import atomic_write_json +from ..acquisition import load_capture +from ..engine import CalibrationEngine +from ..raw_completion import file_digest, implementation_digest, verify_capture_manifest +from ..raw_evidence import partition_raw_capture, fitting_frames +from .capture_validation import validate_capture_provenance +from .raw_joint_report import prepare_raw_motion_ranges +from .serializers.unified_v1 import _mapping +from .standard_loader import validate_with_robot_state_publisher +from .urdf_from_json import serialize_urdf_correction + +DRAFT_FORMAT = 'raw_joint_urdf_draft_v1' + + +def evaluate_draft_holdout(bundle, parameters, holdout): + """Preserve evaluator failures without certifying or refitting a draft.""" + try: + return validate_raw_joint_candidate(bundle, SimpleNamespace(parameters=parameters), holdout) + except Exception as error: + # An evaluator failure is not a measured accuracy result. Retain its + # diagnostics; only the uncertified training draft remains exportable. + return dict(passed=False, status='evaluation_failed', reason=str(error), + exception_type=type(error).__name__, traceback=traceback.format_exc()) + + +def capture_profile_for_draft(profile, header, path): + """Replay may correct model bindings/signs, never the captured SDK route.""" + if path is None: + return profile + path = Path(path) + if file_digest(path) != header.get('profile_config_sha256'): + raise ValueError('draft_capture_profile_hash_mismatch') + captured = load_hand_profile(path) + current = {tag.role: tag.link for view in profile.vision.views for tag in view.tags} + corrected = replace(captured, + command=replace(captured.command, sdk_to_joint_direction=profile.command.sdk_to_joint_direction), + vision=replace(captured.vision, views=tuple( + replace(view, tags=tuple(replace(tag, link=current.get(tag.role, tag.link)) for tag in view.tags)) + for view in captured.vision.views))) + if corrected != profile: + raise ValueError('draft_profile_change_must_only_correct_model_bindings_or_directions') + return captured + + +def read_draft_plan(payload, source, profile): + """Rebuild the plan from saved numeric evidence, with the original writer.""" + if (payload.get('format') != DRAFT_FORMAT or payload.get('profile_id') != profile.key.profile_id + or payload.get('accuracy_passed') is not False or payload.get('publication_allowed') is not False): + raise ValueError('draft_identity_or_status_invalid') + joints = payload['joints'] + if not joints or not set(joints) <= profile.zero.active_joints: + raise ValueError('draft_joint_scope_invalid') + if set(payload['motion_range_evidence']) != set(joints): + raise ValueError('draft_range_scope_mismatch') + ranges, mappings, offsets = {}, {}, {} + for name, row in joints.items(): + table = row['command_to_rad'] + mappings[name] = JointMapping(name, table['channel_index'], table['input_domain'], + *(tuple(table[key]) for key in ('knots', 'angle_rad', 'increasing_rad', 'decreasing_rad'))) + offsets[name] = float(row['zero_offset_rad']) + if (not np.isfinite(offsets[name]) or abs(offsets[name]) > np.radians(20)+1e-10 + or (row['zero_status'] in ('retained_cad', 'operator_defined') and offsets[name] != 0.)): + raise ValueError('draft_zero_outside_authorized_model:' + name) + if row['zero_status'] == 'operator_defined' and (name not in UPRIGHT_SPLAY_JOINTS + or row.get('zero_assumption') != UPRIGHT_SPLAY_REFERENCE + or payload.get('baseline_command') != list(profile.command.baseline_values)): + raise ValueError('draft_operator_zero_reference_invalid:' + name) + evidence = payload['motion_range_evidence'][name] + ranges[name] = MotionRangeEvidence(**{key: tuple(value) if isinstance(value, list) else value + for key, value in evidence.items()}) + validate_turnaround_mapping(mappings[name], ranges[name].command_support) + if (mappings[name].motor_index != profile.command.command_index_by_joint[name] + or mappings[name].input_domain != 'command_u8' + or mappings[name].bounds_rad != ranges[name].command_bounds_rad + or abs(mappings[name].evaluate(ranges[name].baseline_command)) > 1e-10): + raise ValueError('draft_mapping_differs_from_urdf_evidence:' + name) + plan = build_standard_correction_plan(source_urdf=source, + source_sha256=payload['urdf_correction']['source_urdf_sha256'], zero_offsets_rad=offsets, + measured_ranges_output_rad={name: value.output_limits_rad for name, value in ranges.items()}, + authorized_fields=profile.urdf_authorized_fields, range_evidence=ranges, preserve_source_mimic=True, + allow_single_training_cycle=True) + if serialize_urdf_correction(plan) != payload['urdf_correction']: + raise ValueError('draft_saved_correction_differs_from_evidence') + return plan, mappings + + +def load_training_initialization(directory, config, input_sha256): + """A prior same-data training result supplies a guess, never a fixed zero.""" + directory = Path(directory).resolve() + paths = [directory/name for name in ('draft_result.json', 'draft_calibration.json', + 'draft_training.json', 'draft_candidates.npz')] + digests = {str(path): file_digest(path) for path in paths} + state, payload, training = (json.loads(path.read_text()) for path in paths[:3]) + from ..runner_support import protected_inputs + if (state.get('format') != DRAFT_FORMAT or not state.get('generated') + or state.get('input_sha256') != input_sha256 + or state.get('solver_protected_inputs') != protected_inputs(config) + or training.get('validation_used_for_selection') is not False + or training.get('selection') != 'minimum_training_coordinate_rms' + or payload.get('training') != training): + raise ValueError('draft_initialization_must_match_source_and_training_only_selection') + _, mappings = read_draft_plan(payload, config.source_urdf, config.calibration_contract.typed_profile) + with np.load(paths[3], allow_pickle=False) as arrays: + matches = np.flatnonzero(np.all(arrays['seeds'] == training['selected_seed'], axis=1)) + if len(matches) != 1: + raise ValueError('draft_initialization_selected_seed_missing') + parameters = arrays['parameters'][matches[0]] + if not np.all(np.isfinite(parameters)) or len(parameters) < 6: + raise ValueError('draft_initialization_parameters_invalid') + hint = dict(palm=parameters[:6], mappings=mappings, + offsets={name: float(row['zero_offset_rad']) for name, row in payload['joints'].items()}) + return hint, dict(source_directory=str(directory), input_sha256=digests, + policy='same_capture_training_initial_guess_v1', shared_parameters_frozen=False, + validation_used=False) + + +def export_draft_artifacts(payload, source, profile, directory, probes, *, + standard_loader=validate_with_robot_state_publisher): + """One writer for single/multiple-batch drafts; JSON owns every edit.""" + directory = Path(directory) + json_path, urdf_path = directory/'draft_calibration.json', directory/'o30_right_draft.urdf' + if json_path.exists() or urdf_path.exists(): + raise ValueError('draft_artifacts_already_exist') + # Check before saving so invalid evidence cannot look like a finished pair. + read_draft_plan(payload, source, profile) + atomic_write_json(json_path, payload) + saved = json.loads(json_path.read_text()) + plan, mappings = read_draft_plan(saved, source, profile) + plan.write(source, urdf_path) + original, corrected = UrdfKinematicModel(source), UrdfKinematicModel(urdf_path) + offsets = {name: row['zero_offset_rad'] for name, row in saved['joints'].items()} + commands = {(tuple(row['command_vector']), tuple(row['command_direction_by_index'])) for row in probes} + if not commands: + raise ValueError('draft_final_file_probes_missing') + maximum = 0. + for values, directions in sorted(commands): + angles = {name: mapping.evaluate(values[mapping.motor_index], directions[mapping.motor_index]) + for name, mapping in mappings.items()} + for name in mappings: + cad = profile.command.urdf_joint_by_joint.get(name, name) + before = original.link_transform(cad, zero_offsets=offsets, joint_angles=angles, + independent_mimic_angles=True) + after = corrected.link_transform(cad, zero_offsets={}, joint_angles=angles, + independent_mimic_angles=True) + maximum = max(maximum, float(np.max(np.abs(before-after)))) + if maximum > 1e-8: + raise ValueError('draft_json_urdf_fk_mismatch') + standard_loader(urdf_path) + return json_path, urdf_path, corrected, maximum + + +def replay_draft(config, raw_path, *, output, capture_profile=None, initialization_from=None, + upright_splay_zero=False, + standard_loader=validate_with_robot_state_publisher): + """No SDK, resume, publisher or automatic recapture can be reached here.""" + from ..runner_support import protected_inputs, create_session_directory + raw_path = Path(raw_path).resolve() + installation_note = raw_path.parent/'operator_installation_clarification.json' + files = sorted({raw_path, *raw_path.parent.glob(raw_path.stem + '.*'), + *raw_path.parent.glob('imported_evidence_*.zlib'), installation_note}) + files = [path for path in files if path.exists()] + digests = {str(path): file_digest(path) for path in files} + records = load_capture(raw_path) + header = next(row for row in records if row.get('kind') == 'session_start') + profile = config.calibration_contract.typed_profile + if profile.key.model != 'O30': + raise ValueError('draft_currently_requires_o30_raw_capture') + snapshot = raw_path.parent/'capture_profile.yaml' + if (capture_profile is None and snapshot.is_file() + and header.get('profile_config_sha256') != config.profile_config_sha256): + capture_profile = snapshot + captured = capture_profile_for_draft(profile, header, capture_profile) + hashes = protected_inputs(config) + captured_hashes = dict(hashes) + if capture_profile is not None: + captured_hashes['profile_config_sha256'] = file_digest(Path(capture_profile)) + validate_capture_provenance(captured, config.serial_number, captured_hashes, records, + allow_installation_draft=True) + from ..motion_provenance import validate_source_geometry + validate_source_geometry(captured, config.source_urdf, records) + sealed = (raw_path.parent/'raw_capture_manifest.json').exists() + if sealed: + manifest = verify_capture_manifest(raw_path) + if manifest['capture_plan'] != header['capture_plan'] or manifest['serial_number'] != config.serial_number: + raise ValueError('draft_manifest_identity_changed') + evidence = partition_raw_capture(captured, records, require_complete=False, reassess_quality=True) + training = fitting_frames(captured, evidence.training) + model = UrdfKinematicModel(config.source_urdf) + captured_links = compile_tag_links(captured, model) + corrected_links = compile_tag_links(profile, model) + units = CalibrationEngine(captured).scan_units() + coverage = draft_training_coverage(evidence.completed_units, units) + selected = draft_profile(profile, model, evidence.completed_units, units, training) + if upright_splay_zero: + selected = define_upright_splay_zero(selected, model) + tasks = {task.key for task in selected.motion.tasks} + roles = {tag.role for view in selected.vision.views for tag in view.tags if not tag.fixed_reference} + def scoped(rows): + return tuple(row for row in rows if row['task_name'] in tasks and roles.intersection(row['tags'])) + training, holdout = scoped(training), scoped(fitting_frames(captured, evidence.validation)) + # Every accepted image must use the locked rectified camera projection. + matrices = {row['view']: row['camera_matrix'] for row in records if row.get('kind') == 'rectified_camera_model'} + if any(not np.array_equal(row['camera_matrix'], matrices[row['view']]) for row in (*training, *holdout)): + raise ValueError('draft_camera_projection_changed') + extrinsics = load_camera_extrinsics(config.camera_extrinsics, required_views=profile.vision.view_names, + reference_view=profile.vision.extrinsic_reference_view, quality_limits=profile.vision.extrinsics_quality_limits, + minimum_capture_counts=profile.vision.minimum_capture_counts) + hint, hint_audit = (load_training_initialization(initialization_from, config, digests) + if initialization_from is not None else (None, None)) + bundle = DraftCommandImages(selected, model, extrinsics, training, compile_tag_links(selected, model), + initialization_cycles={task: coverage[task]['initialization_cycle'] for task in tasks}, + training_initialization=hint) + if output is None: + directory = create_session_directory(config.session_root/'drafts') + else: + directory = Path(output).expanduser().resolve() + directory.mkdir(parents=True, exist_ok=False) + state = dict(format=DRAFT_FORMAT, commands_enabled=False, accuracy_passed=False, + publication_allowed=False, generated=False, input_sha256=digests, sealed_capture=sealed, + missing_units=evidence.missing_units, raw_capture_complete=not evidence.missing_units, + acquisition_reassessment=evidence.reassessed_units, implementation_sha256=implementation_digest(), + training_selection=dict(policy='at_least_one_complete_training_cycle_v1', + tasks=coverage, included_tasks=sorted(tasks), training_frames=len(training), + validation_frames=len(holdout), validation_used_for_training=False), + training_initialization=hint_audit, + operator_zero_reference=(dict(policy=UPRIGHT_SPLAY_REFERENCE, + joints=sorted(UPRIGHT_SPLAY_JOINTS), baseline_command=list(profile.command.baseline_values), + independently_measured=False) if upright_splay_zero else None), + solver_observations=dict(policy='exact_repeated_pose_least_squares_v1', + original_tag_observations=bundle.original_residual_count//8, + grouped_tag_observations=len(bundle.residual_weights)//8, + within_group_squared_error=bundle.within_group_error), + captured_protected_inputs=captured_hashes, solver_protected_inputs=hashes, + remount_history=[row for row in records if row.get('kind') == 'raw_tag_remount_checkpoint'], + resume_installation_checks=[row.get('installation_verification', {}) for row in records + if row.get('kind') == 'raw_resume_verified'], + operator_installation_clarification=(json.loads(installation_note.read_text()) + if installation_note.is_file() else None), + model_direction_corrections={name: dict(captured=captured.command.joint_directions[channel], + offline=profile.command.joint_directions[channel]) + for name, channel in profile.command.command_index_by_joint.items() + if captured.command.joint_directions[channel] != profile.command.joint_directions[channel]}, + model_tag_link_corrections={role: dict(captured=captured_links[role], offline=link) + for role, link in corrected_links.items() if captured_links.get(role) != link}, + correction_scope=draft_targets(profile, selected), full_target_generated=False) + atomic_write_json(directory/'draft_result.json', state) + print(f'离线草稿:{len(tasks)} 个任务,{len(bundle.joints)} 个关节;' + f'训练 {len(training)} 帧,独立验证 {len(holdout)} 帧;' + f'保留 {len(evidence.missing_units)} 个采集缺项。', flush=True) + # Keep every usable steady frame, but release the much larger sweep and + # rejected-frame journals before allocating the optimizer's Jacobian. + range_frames = fitting_frames(selected, evidence.training) + del records, evidence + audit_rows = [] + def progress(row): + audit_rows.append(row) + atomic_write_json(directory/'draft_training.json', dict(candidates=audit_rows, validation_used=False)) + try: + direction_audit = bundle.audit_root_directions() + atomic_write_json(directory/'draft_direction_audit.json', direction_audit) + if not direction_audit['passed']: + raise ValueError('draft_sdk_to_urdf_direction_conflict') + parameters, audit, candidates = fit_draft(bundle, progress) + atomic_write_json(directory/'draft_training.json', audit) + np.savez_compressed(directory/'draft_candidates.npz', + parameters=np.asarray([values for _, values in candidates]), + seeds=np.asarray([row['seed'] for row, _ in candidates])) + # Freeze the training choice before any validation. Precision cannot + # block a draft; structural and source-integrity checks still do. + atomic_write_json(directory/'draft_selection.json', audit) + validation = evaluate_draft_holdout(bundle, parameters, holdout) + atomic_write_json(directory/'draft_holdout.json', validation) + mappings, offsets = bundle.output_mappings(parameters), bundle.zero_offsets(parameters) + ranges = prepare_raw_motion_ranges(bundle, parameters, range_frames) + plan = build_standard_correction_plan(source_urdf=config.source_urdf, + source_sha256=config.source_urdf_sha256, zero_offsets_rad=offsets, + measured_ranges_output_rad={name: value.output_limits_rad for name, value in ranges.items()}, + authorized_fields=profile.urdf_authorized_fields, range_evidence=ranges, preserve_source_mimic=True, + allow_single_training_cycle=True) + payload = dict(format=DRAFT_FORMAT, profile_id=profile.key.profile_id, serial_number=config.serial_number, + accuracy_passed=False, publication_allowed=False, baseline_command=list(profile.command.baseline_values), + coordinate_convention='q_CAD=q_output+zero_offset; mapping emits q_output', + scope='observed_training_travel_and_held_poses; arbitrary_multiaxis_not_validated', + correction_scope=state['correction_scope'], + retained_joints=sorted(profile.zero.active_joints-set(mappings)), + joints={name: dict(zero_offset_rad=offsets[name], + zero_status=('operator_defined' if selected.zero.cad_zero_assumptions.get(name) + == UPRIGHT_SPLAY_REFERENCE else 'retained_cad' + if name in selected.zero.cad_zero_assumptions else 'estimated_draft'), + zero_assumption=selected.zero.cad_zero_assumptions.get(name), command_to_rad=_mapping(mapping)) + for name, mapping in mappings.items()}, + urdf_correction=serialize_urdf_correction(plan), + motion_range_evidence={name: asdict(value) for name, value in ranges.items()}, + training=audit, holdout=validation, provenance=state) + json_path, urdf_path, corrected, maximum = export_draft_artifacts(payload, + config.source_urdf, profile, directory, training, standard_loader=standard_loader) + from ...core.urdf.linear_drive import UrdfLinearImages + linear_validation = evaluate_draft_holdout(UrdfLinearImages(bundle, corrected), parameters, holdout) + linear_validation.update(drive='urdf_limits_linear_sdk_u8', parameters_refitted=False) + atomic_write_json(directory/'draft_urdf_linear_holdout.json', linear_validation) + if digests != {str(path): file_digest(path) for path in files}: + raise ValueError('draft_source_capture_changed_during_fit') + if hint_audit is not None and hint_audit['input_sha256'] != { + path: file_digest(Path(path)) for path in hint_audit['input_sha256']}: + raise ValueError('draft_initialization_changed_during_fit') + state.update(generated=True, source_unchanged=True, urdf=str(urdf_path), + full_target_generated=state['correction_scope']['full_target_covered'], + urdf_sha256=file_digest(urdf_path), calibration_json=str(json_path), + corrected_joints=sorted(plan.patches.joints), zero_offsets_rad=offsets, + retained_zero_assumptions=dict(selected.zero.cad_zero_assumptions), + final_file_fk_maximum_difference=maximum, standard_loader_passed=True, + independent_holdout_passed=validation.get('passed', False)) + state['urdf_linear_holdout_passed'] = linear_validation.get('passed', False) + atomic_write_json(directory/'draft_result.json', state) + print(f'已生成修正草稿:{urdf_path};零位及行程见 draft_calibration.json。精度尚未认证。', flush=True) + scope = state['correction_scope'] + print(f"零位 {len(scope['estimated_zero_joints'])}/{len(scope['zero_target_joints'])}、" + f"另有用户定义竖直零位 {len(scope['defined_zero_joints'])} 个;" + f"运动范围 {len(scope['estimated_range_joints'])}/{len(scope['range_target_joints'])};" + f"五指末端零位保留 CAD。全手参数已生成:{state['full_target_generated']};" + f"独立验证通过:{state['independent_holdout_passed']};草稿不允许正式发布。", flush=True) + return state + except Exception as error: + state['reason'] = str(error) + atomic_write_json(directory/'draft_result.json', state) + raise diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_finalization.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_finalization.py new file mode 100644 index 0000000..1eb2b97 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_finalization.py @@ -0,0 +1,166 @@ +"""One raw capture -> bounded joint solve -> frozen holdout -> atomic release.""" +import hashlib +import json +from pathlib import Path + +import numpy as np + +from ...core.artifacts.storage import atomic_write_json +from ...core.fitting.raw_joint_fit import fit_raw_joint_candidates +from ...core.fitting.raw_joint_validation import validate_raw_joint_candidate +from ...core.geometry.extrinsics import load_camera_extrinsics +from ...core.geometry.tag_pose.urdf_command_images import UrdfCommandImages +from ...core.urdf.kinematics import UrdfKinematicModel +from ...profiles.observations import compile_tag_links +from ..optical_verification import verify_optical_observations +from ..raw_evidence import partition_raw_capture, fitting_frames +from .capture_validation import validate_capture_provenance +from .publisher import ArtifactPublisher +from .raw_joint_report import prepare_raw_report +from .raw_joint_validator import RawJointArtifactValidator +from .serializers.measured_v3 import from_report +from .serializers.compact_v2 import REPORT_FILENAME +from .urdf_from_json import rebuild_urdf_from_json + + +def finalize_raw_joint_session(*, profile, session_dir, serial_number, source_urdf, + protected_inputs, records, camera_extrinsics_file, standard_loader, + cancelled=lambda: False, phase_changed=lambda _phase: None, publish=True): + from .finalization import CorrectedArtifact + directory, source = Path(session_dir).resolve(), Path(source_urdf).resolve() + directory.mkdir(parents=True, exist_ok=True) + state = dict(protocol=next((r['capture_plan']['observation_protocol']['version'] + for r in records if r.get('kind') == 'session_start'), 'unknown'), raw_capture_complete=False, + fit_complete=False, accuracy_passed=False, publication_allowed=False) + def save(): + atomic_write_json(directory/'raw_joint_result.json', state) + def check(): + if cancelled(): + raise ValueError('operator_abort:no_artifact_publication') + try: + check() + missing = profile.artifacts.protected_input_fields-protected_inputs.keys() + if missing: + raise ValueError('raw_joint_protected_inputs_missing:' + str(sorted(missing))) + hashes = {k: v for k, v in protected_inputs.items() + if k not in {'intrinsics_sha256', 'raw_samples_sha256'}} + validate_capture_provenance(profile, serial_number, hashes, records) + if hashlib.sha256(source.read_bytes()).hexdigest() != protected_inputs['source_urdf_sha256']: + raise ValueError('raw_joint_source_urdf_changed') + from ..motion_provenance import validate_source_geometry + validate_source_geometry(profile, source, records) + evidence = partition_raw_capture(profile, records, require_complete=False, reassess_quality=True) + state['missing_units'] = evidence.missing_units + state['acquisition_reassessment'] = evidence.reassessed_units + if evidence.missing_units: + raise ValueError('raw_joint_capture_incomplete:see_missing_units') + state.update(raw_capture_complete=True, capture_sha256=evidence.sha256) + save() + training, holdout = fitting_frames(profile, evidence.training), fitting_frames(profile, evidence.validation) + matrices = {} + for row in (*training, *holdout): + matrix = np.asarray(row['camera_matrix']) + if row['view'] in matrices and not np.array_equal(matrix, matrices[row['view']]): + raise ValueError('raw_joint_camera_projection_changed') + matrices[row['view']] = matrix + reference = next(r for r in records if r.get('kind') == 'fixed_base_reference_locked') + from ..raw_resume import RawCheckpoint + for resumed in (r for r in records if r.get('kind') == 'raw_resume_verified'): + header = resumed['source_header'] + if (header.get('capture_plan') != evidence.capture_plan + or header.get('serial_number') != serial_number + or any(header.get(key) != value for key, value in hashes.items())): + raise ValueError('raw_joint_imported_provenance_changed') + RawCheckpoint(header, resumed['source_reference'], records, frozenset()).verify_reference(profile, reference) + digest = hashlib.sha256(json.dumps({k: v.tolist() for k,v in sorted(matrices.items())}, sort_keys=True).encode()).hexdigest() + if digest != reference['protected_hashes']['intrinsics_sha256']: + raise ValueError('raw_joint_projection_differs_from_locked_reference') + extrinsics_path = Path(camera_extrinsics_file) + if hashlib.sha256(extrinsics_path.read_bytes()).hexdigest() != protected_inputs['camera_extrinsics_sha256']: + raise ValueError('raw_joint_camera_extrinsics_changed') + extrinsics = load_camera_extrinsics(extrinsics_path, required_views=profile.vision.view_names, + reference_view=profile.vision.extrinsic_reference_view, + quality_limits=profile.vision.extrinsics_quality_limits, + minimum_capture_counts=profile.vision.minimum_capture_counts) + checks = [r for r in records if r.get('kind') == 'measured_optical_verification'] + reuse = [r for r in records if r.get('kind') == 'existing_camera_calibration_reused'] + if checks: + optical = verify_optical_observations(checks[-1]['observations'], extrinsics, matrices, + extrinsics_sha256=protected_inputs['camera_extrinsics_sha256']) + elif len(reuse) == 1: + from ..optical_verification import accept_existing_camera_calibration + optical = accept_existing_camera_calibration(profile, extrinsics_path, + protected_inputs['camera_extrinsics_sha256']) + if reuse[0]['acceptance'] != optical: + raise ValueError('raw_joint_camera_reuse_evidence_changed') + else: + raise ValueError('raw_joint_measured_optical_verification_missing') + model = UrdfKinematicModel(source) + bundle = UrdfCommandImages(profile, model, extrinsics, training, compile_tag_links(profile, model)) + audit = [] + def progress(row): + audit.append(row) + atomic_write_json(directory/'raw_joint_training.json', dict(completed=len(audit), + maximum_initializations=64, maximum_evaluations_per_initialization=200, candidates=audit)) + check() + fit = fit_raw_joint_candidates(bundle, cancelled=cancelled, candidate_completed=progress, workers=1) + atomic_write_json(directory/'raw_joint_training_selection.json', fit.training_selection) + atomic_write_json(directory/'raw_joint_training.json', dict(completed=len(fit.training_audit), + maximum_initializations=64, maximum_evaluations_per_initialization=200, + candidates=fit.training_audit)) + np.savez_compressed(directory/'raw_joint_candidates.npz', + parameters=np.asarray([c.parameters for c in fit.candidates]), + covariance=np.asarray([c.covariance for c in fit.candidates]), + seeds=np.asarray([c.seed for c in fit.candidates])) + state.update(fit_complete=True, candidate_uncertainty=fit.uncertainty) + save(); phase_changed('fit_complete'); check() + if not fit.uncertainty['passed']: + state['required_observations'] = [item for value in fit.uncertainty.values() + if isinstance(value,dict) for item in value.get('required_observations',())] + raise ValueError('raw_joint_candidate_union_exceeds_original_precision') + validations = [] + for candidate in fit.candidates: + validation = validate_raw_joint_candidate(bundle, candidate, holdout, cancelled=cancelled) + validations.append(validation) + atomic_write_json(directory/'raw_joint_holdout.json', dict(candidates=validations, + all_candidates_passed=all(r['passed'] for r in validations), parameters_updated=False)) + if not validation['passed']: + raise ValueError('raw_joint_independent_holdout_failed') + selected = validations[fit.representative] + validation = dict(selected, candidate_count=len(validations), + all_candidates_passed=True, candidates=validations) + phase_changed('holdout_complete'); check() + report, plan = prepare_raw_report(bundle, fit, evidence, validation, + serial_number=serial_number, protected_inputs=protected_inputs) + from ...core.domain.capture_plan import evidence_digest + report['raw_joint_audit'].update(installation_reference_sha256=evidence_digest(reference), + camera_acceptance=optical) + if 'observations_sha256' in optical: + report['raw_joint_audit']['optical_observations_sha256'] = optical['observations_sha256'] + naming = dict(serial_number=serial_number, side=profile.key.side, model=profile.key.model.lower()) + json_path = directory/profile.artifacts.calibration_filename.format(**naming) + urdf_path = directory/profile.artifacts.corrected_urdf_filename.format(**naming) + payload = from_report(report) + atomic_write_json(json_path, payload) + atomic_write_json(directory/REPORT_FILENAME, report) + rebuild_urdf_from_json(json_path, source, urdf_path, + authorized_fields=profile.urdf_authorized_fields, expected_profile_id=profile.key.profile_id) + phase_changed('artifacts_built'); check() + validator = RawJointArtifactValidator(bundle, fit.candidates[fit.representative], report, + plan, holdout, validation, optical, standard_loader) + publisher = ArtifactPublisher(directory.parent, profile.artifacts.publication_pointer) + staged = publisher.prepare(session_directory=directory, calibration_json=json_path, + corrected_urdf=urdf_path, validate=validator, cancelled=cancelled) + atomic_write_json(directory/'standard_urdf_acceptance.json', json.loads(staged.validation_json)) + state.update(accuracy_passed=True, publication_allowed=True) + save(); phase_changed('urdf_validated'); check() + if publish: + publisher.commit(staged, cancelled=cancelled) + return payload, fit, CorrectedArtifact(urdf_path, staged) + except Exception as error: + state.update(reason=str(error), publication_allowed=False, + automatic_geometry_recapture=False, + next_action=('inspect_saved_missing_units_without_automatic_motion' if state.get('missing_units') else + 'inspect_training_candidate_and_holdout_reports_before_selecting_new_observations')) + save() + raise diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_report.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_report.py new file mode 100644 index 0000000..6bca261 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_report.py @@ -0,0 +1,133 @@ +"""Raw-protocol provenance with the existing JSON command-table interface.""" +from dataclasses import asdict + +from ...core.domain.capture_plan import CapturePlan, task_for_joint, evidence_digest +from ...core.domain.motion_path import task_segment +from ...core.urdf.limits import MotionRangeEvidence +from ...core.urdf.plan import build_standard_correction_plan +from .serializers.measured_v3 import REPORT_FORMAT, ZERO_CONVENTION +from .serializers.unified_v1 import _mapping +from .urdf_from_json import serialize_urdf_correction +from ..raw_evidence import fitting_frames +from ...core.fitting.command_support import TURNAROUND_POLICY, validate_turnaround_mapping + + +def joint_training_rows(profile, training, name): + """Only visible, active training observations support a joint's range.""" + task = task_for_joint(profile, name) + spec = profile.measurement.measurements[name] + return [row for row in training if row['task_name'] == task.key + and row.get('cycle') in (0, 1) and row['view'] == spec.view + and spec.child_role in row.get('tags', {}) + and (not task.segments or name in task_segment(task, row.get('segment_key', '')).joints)] + + +def prepare_raw_motion_ranges(bundle, parameters, training): + """Training-supported travel, shared by drafts and precision releases.""" + profile = bundle.profile + training = fitting_frames(profile, training) + mappings, offsets = bundle.output_mappings(parameters), bundle.zero_offsets(parameters) + ranges = {} + for name, mapping in mappings.items(): + rows = joint_training_rows(profile, training, name) + baseline = profile.command.baseline_values[mapping.motor_index] + baseline_rows = [row for row in rows if row['command_vector'][mapping.motor_index] == baseline] + if not baseline_rows: + raise ValueError('raw_joint_baseline_support_missing:' + name) + policy = profile.urdf_limit_policies[name] + original = bundle.model.joints[bundle.cad_names[name]] + ids = tuple(sorted(f"{row['view']}:{row['image_stamp_ns']}" for row in rows)) + baseline_ids = tuple(sorted(f"{r['view']}:{r['image_stamp_ns']}" for r in baseline_rows)) + bounds = min(0., mapping.bounds_rad[0]), max(0., mapping.bounds_rad[1]) + cycles = tuple(sorted({row['cycle'] for row in rows})) + support = None + if hasattr(bundle, 'turnaround_constraints'): + constraints = [{key: value for key, value in row.items() if key != 'column'} + for row in bundle.turnaround_constraints.get(name, ())] + endpoints = [] + for command in (mapping.knots[0], mapping.knots[-1]): + observed = [r for r in rows if r['command_vector'][mapping.motor_index] == command] + if not observed: + raise ValueError('raw_joint_endpoint_support_missing:' + name + ':' + str(command)) + for direction, label in enumerate(('increasing', 'decreasing')): + if (command != baseline and not any(r['command_direction_by_index'][mapping.motor_index] == label + for r in observed) and not any(c['command'] == command and c['recipient'] == direction + for c in constraints)): + raise ValueError('raw_joint_directional_endpoint_support_missing:' + name + ':' + label) + endpoints.append(dict(command=command, samples=[dict( + id=f"{r['view']}:{r['image_stamp_ns']}", cycle=r['cycle'], + direction=r['command_direction_by_index'][mapping.motor_index]) for r in observed])) + support = dict(policy=TURNAROUND_POLICY, constraints=constraints, + endpoints=endpoints, independently_measured_outgoing_endpoint=False if constraints else None) + validate_turnaround_mapping(mapping, support) + ranges[name] = MotionRangeEvidence(name, name, True, (original.lower, original.upper), + bounds, None, mapping.bounds_rad, offsets[name], baseline, cycles, ids, baseline_ids, + policy.source_limits, policy.evidence_source, policy.independent_safety_limits_cad_rad, + policy.safety_evidence_source, cycles, ids, 'steady_command', support) + return ranges + + +def prepare_raw_report(bundle, fit, evidence, validation, *, serial_number, protected_inputs): + profile = bundle.profile + candidate = fit.candidates[fit.representative] + mappings, offsets = bundle.output_mappings(candidate.parameters), bundle.zero_offsets(candidate.parameters) + ranges = prepare_raw_motion_ranges(bundle, candidate.parameters, evidence.training) + references = {} + training_rows = fitting_frames(profile, evidence.training) + training_digest = evidence_digest(evidence.training) + candidate_digest = evidence_digest([dict(seed=list(c.seed), parameters=c.parameters.tolist(), + covariance=c.covariance.tolist()) for c in fit.candidates]) + for name, mapping in mappings.items(): + rows = joint_training_rows(profile, training_rows, name) + baseline = profile.command.baseline_values[mapping.motor_index] + baseline_rows = [row for row in rows if row['command_vector'][mapping.motor_index] == baseline] + if not baseline_rows: + raise ValueError('raw_joint_baseline_support_missing:' + name) + references[name] = dict(kind='raw_joint_training_baseline', joint=name, channel=mapping.motor_index, + baseline_command=baseline, training_sha256=training_digest, candidate_set_sha256=candidate_digest, + physical_zero_source='joint_urdf_image_graph', + samples=[dict(view=r['view'], image_stamp_ns=r['image_stamp_ns']) for r in baseline_rows]) + plan = build_standard_correction_plan(source_urdf=bundle.model.source, + source_sha256=protected_inputs['source_urdf_sha256'], zero_offsets_rad=offsets, + measured_ranges_output_rad={name: value.output_limits_rad for name, value in ranges.items()}, + authorized_fields=profile.urdf_authorized_fields, range_evidence=ranges, preserve_source_mimic=True) + joints = {} + for name, mapping in mappings.items(): + frozen = name in profile.zero.cad_zero_assumptions + row = dict(urdf_joint=name, independently_measured=True, zero_offset_rad=offsets[name], + zero_method='assumed_source_cad_zero' if frozen else 'urdf_joint_image_geometry', + zero_reference=references[name], command_to_rad=_mapping(mapping), + feedback_diagnostic=dict(required_for_release=False, input_domain='feedback_u8', status='not_fitted'), + applicability=dict(scope='observed_training_travel_and_held_poses', arbitrary_multiaxis_validated=False), + command_holdout=validation['joints'][name], passive=name in plan.mimic_output) + if frozen: + row['cad_zero_assumption'] = profile.zero.cad_zero_assumptions[name] + if name in plan.mimic_output: + parent, multiplier, offset = plan.mimic_output[name] + row['mimic_approximation'] = dict(joint=parent, multiplier=multiplier, offset_rad=offset, + usage='source_urdf_linear_fallback', physical_zero_correction=False) + joints[name] = row + report = dict(format=REPORT_FORMAT, schema_version=3, profile_id=profile.key.profile_id, + model=profile.key.model, side=profile.key.side, serial_number=serial_number, + command_unit=profile.command.unit, command_names=list(profile.command.names), + baseline_command=list(profile.command.baseline_values), coordinate_convention=ZERO_CONVENTION, + directional_command_joints=sorted(profile.artifacts.directional_command_joints), + feedback_by_index=profile.command.feedback_by_index, + feedback_name_aliases=dict(profile.command.feedback_name_aliases), + protected_inputs=dict(protected_inputs), joints=joints, + capture_plan=evidence.capture_plan, + urdf_correction=serialize_urdf_correction(plan), + motion_range_evidence={name: asdict(value) for name, value in ranges.items()}, + raw_joint_audit=dict(protocol=evidence.capture_plan['observation_protocol']['version'], capture_sha256=evidence.sha256, + command_support={name: value.command_support for name, value in ranges.items()}, + acquisition_reassessment=evidence.reassessed_units, + training_sha256=training_digest, candidate_set_sha256=candidate_digest, + candidate_uncertainty=fit.uncertainty, candidate_count=len(fit.candidates), + training_selection=fit.training_selection, + representative=fit.representative, validation_parameters_updated=False), + quality=dict(release_basis='steady_command', feedback_mapping_required=False, + training_cycles=[0, 1], holdout_cycle=3, command_training_cycles=[0, 1], command_holdout_cycle=3, + training_policy=profile.quality.training_policy, independently_measured_joints=sorted(joints), + transferred_joints=[], arbitrary_multiaxis_validated=False, + final_file_acceptance='release_manifest.json')) + return report, plan diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_validator.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_validator.py new file mode 100644 index 0000000..66e17df --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/raw_joint_validator.py @@ -0,0 +1,71 @@ +"""Bind final files to the independently validated, training-frozen image graph.""" +import json +from dataclasses import dataclass + +import numpy as np + +from ...core.domain.capture_plan import evidence_digest +from ...core.urdf.acceptance import SerializedJointMapping, validate_artifact_structure +from ...core.urdf.kinematics import UrdfKinematicModel +from .serializers.measured_v3 import from_report +from .serializers.compact_v2 import REPORT_FILENAME +from .urdf_from_json import validate_json_urdf_correspondence + + +@dataclass(frozen=True) +class RawJointArtifactValidator: + bundle: object + candidate: object + report: dict + plan: object + holdout: tuple + validation: dict + optical: dict + standard_loader: object + + def __call__(self, json_path, urdf_path): + payload = json.loads(json_path.read_text(encoding='utf-8')) + report = json.loads((json_path.parent / REPORT_FILENAME).read_text(encoding='utf-8')) + if evidence_digest(report) != evidence_digest(self.report) or payload != from_report(self.report): + raise ValueError('raw_joint_serialized_report_changed') + camera_accepted = self.optical.get('passed') is True or ( + self.optical.get('policy') == 'reuse_validated_camera_calibration_v1' + and self.optical.get('accepted') is True + and self.optical.get('camera_extrinsics_sha256') == self.report['protected_inputs']['camera_extrinsics_sha256']) + if not self.validation['passed'] or not camera_accepted: + raise ValueError('raw_joint_independent_acceptance_failed') + bundle, profile = self.bundle, self.bundle.profile + offsets = bundle.zero_offsets(self.candidate.parameters) + changes = validate_artifact_structure(source_urdf=bundle.model.source, + corrected_urdf=urdf_path, source_sha256=self.report['protected_inputs']['source_urdf_sha256'], + authorized_fields=profile.urdf_authorized_fields, payload=payload, + zero_offsets_rad=offsets, range_evidence=self.plan.range_evidence) + validate_json_urdf_correspondence(payload, bundle.model.source, urdf_path, + expected_profile_id=profile.key.profile_id) + reader, corrected = SerializedJointMapping(payload), UrdfKinematicModel(urdf_path) + mappings = bundle.output_mappings(self.candidate.parameters) + probes = {(tuple(row['command_vector']), tuple(row['command_direction_by_index'])) for row in self.holdout} + if not probes: + raise ValueError('raw_joint_final_file_replay_empty') + maximum = 0. + for commands, directions in sorted(probes): + per_joint = {name: directions[channel] for name, channel in bundle.channels.items()} + angles = reader.evaluate(commands, '', active_joints=bundle.joints, directions_by_joint=per_joint) + expected = {name: mappings[name].evaluate(commands[bundle.channels[name]], per_joint[name]) + for name in bundle.joints} + for name in bundle.joints: + before = bundle.model.link_transform(bundle.cad_names[name], zero_offsets=offsets, + joint_angles=expected, independent_mimic_angles=True) + after = corrected.link_transform(bundle.cad_names[name], zero_offsets={}, + joint_angles=angles, independent_mimic_angles=True) + maximum = max(maximum, float(np.max(np.abs(before-after)))) + if maximum > 1e-8: + raise ValueError('raw_joint_json_urdf_frozen_forward_mismatch') + self.standard_loader(urdf_path) + return dict(acceptance='raw_joint_frozen_image_and_final_file_v1', + profile_id=profile.key.profile_id, final_file_spatial_replay='passed', + steady_command_tag_holdout=self.validation, + final_file_fk_maximum_difference=maximum, final_file_command_poses=len(probes), + optical_verification=self.optical, structured_changes=list(changes), + raw_joint_audit=self.report['raw_joint_audit'], + holdout_evidence_sha256=evidence_digest(self.holdout)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/reader.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/reader.py new file mode 100644 index 0000000..a69fc6f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/reader.py @@ -0,0 +1,149 @@ +"""Model-neutral reader for a certified JSON/URDF pair; no ROS dependency.""" + +import hashlib +import json +import math +from pathlib import Path + +from ...core.urdf.acceptance import SerializedJointMapping, validate_compact_urdf_tables +from ...core.urdf.kinematics import UrdfKinematicModel +from ...core.urdf.joint_control import ( + JSON_JOINT_ANGLES, independent_joint_sources, uses_affine_mimic_approximation, + uses_source_mimic, +) +from .serializers.compact_v2 import FORMAT as COMPACT_FORMAT, from_report +from .serializers.measured_v3 import FORMAT as MEASURED_FORMAT, from_report as measured_from_report +from .direction import next_input_directions + + +class UnifiedCommandMapper: + def __init__(self, payload, corrected_urdf, *, input_kind="command", expected_side=None, report=None): + self.measured = payload.get("format") == MEASURED_FORMAT + self.json_mimic_override = self.measured and independent_joint_sources(payload) is None + compact = payload.get("format") in {COMPACT_FORMAT, MEASURED_FORMAT} + if payload.get("format") not in {"unified_calibration_v1", COMPACT_FORMAT, MEASURED_FORMAT}: + raise ValueError("requires a unified calibration artifact") + if expected_side and payload["side"] != expected_side: + raise ValueError("calibration side does not match requested side") + if compact and (report is None or (measured_from_report if self.measured else from_report)(report) != payload): + raise ValueError("compact JSON requires its matching calibration report") + metadata = report if compact else payload + self.transferred_motion_sources = dict(metadata.get("transferred_motion_sources", {})) if self.measured else {} + self.independently_measured_joints = tuple(sorted(name for name, row in metadata["joints"].items() + if row.get("independently_measured") is True)) if self.measured else () + self.mapping = SerializedJointMapping(metadata if compact and input_kind == "feedback" else payload, input_kind=input_kind) + self.urdf = UrdfKinematicModel(corrected_urdf) + self.active = tuple(name for name, j in self.urdf.joints.items() if j.kind != "fixed" and j.mimic_joint is None) + if self.measured: + self.active = tuple(name for name, j in self.urdf.joints.items() if j.kind != "fixed") + self.active = tuple(name for name in self.active if name not in self.mapping.retained_joints) + if compact: + validate_compact_urdf_tables(payload, self.urdf) + if not self.mapping.compact and set(self.mapping.joints) != set(self.active): + raise ValueError("JSON active joints differ from the exported URDF") + self.urdf_joint_names = tuple(sorted(name for name, j in self.urdf.joints.items() + if j.kind != "fixed" and name not in self.mapping.retained_joints)) + self.retained_joints = tuple(sorted(self.mapping.retained_joints)) + self.command_names = tuple(metadata["command_names"]) + if any(row["motor_index"] >= len(self.command_names) for row in self.mapping.joints.values()): + raise ValueError("JSON SDK channel exceeds the recorded SDK layout") + self.input_domain = self.mapping.domain + self.model, self.side = payload["model"], payload["side"] + self.profile_id, self.serial_number = payload["profile_id"], payload["serial_number"] + self.feedback_by_index = bool(metadata.get("feedback_by_index", False)) if input_kind == "feedback" else True + self.feedback_name_aliases = dict(metadata.get("feedback_name_aliases", {})) + self.previous = None + self.directions = [""]*len(self.command_names) + self.directional_channels = {} + for name in self.mapping.directional_joints: + row = self.mapping.joints[name] + knots = row["curve_input_knots_rad"] + lower, upper = (knots[0], knots[-1]) if knots else (0., 255.) + index = row["motor_index"] + self.directional_channels[index] = (metadata["baseline_command"][index], lower, upper) + + def map_positions(self, positions, names=()): + values = tuple(float(v) for v in positions) + if len(values) != len(self.command_names) or not all(math.isfinite(v) for v in values): + raise ValueError("SDK input requires a complete finite channel vector") + if self.mapping.retained_joints: + from ...core.urdf.partial_scope import require_retained_pose + require_retained_pose(self.mapping.retained_joints, values) + if names and not self.feedback_by_index and self.input_domain.startswith("feedback_"): + names = tuple(self.feedback_name_aliases.get(n, n) for n in names) + if len(names) != len(values) or set(names) != set(self.command_names): + raise ValueError("feedback names differ from the serialized SDK layout") + named = dict(zip(names, values)) + values = tuple(named[n] for n in self.command_names) + directions = next_input_directions(values, self.previous, self.directions, + resolution=0.5 if self.input_domain.endswith("u8") else 1e-9, + channels=self.directional_channels, byte_input=self.input_domain.endswith("u8")) + active = self.mapping.evaluate(values, "", active_joints=self.active, + directions_by_joint={name: directions[row["motor_index"]] for name, row in self.mapping.joints.items()}) + result = self.urdf.resolve_angles(active, independent_mimic_angles=self.json_mimic_override) + for name, angle in result.items(): + joint = self.urdf.joints[name] + if joint.lower is not None and not joint.lower-1e-9 <= angle <= joint.upper+1e-9: + raise ValueError(f"mapped value exceeds exported URDF range:{name}") + self.previous, self.directions = values, directions + return tuple(result[name] for name in self.urdf_joint_names) + + +def load_unified_mapper(calibration_file, *, expected_side=None, input_kind="command"): + path = Path(calibration_file).expanduser().resolve() + manifest_path = path if path.name == "release_manifest.json" else path.parent/"release_manifest.json" + manifest = json.loads(manifest_path.read_text()) + def artifact(field): + name = manifest[field] + if Path(name).name != name: + raise ValueError("release artifact must be a sibling filename") + result = manifest_path.parent/name + if hashlib.sha256(result.read_bytes()).hexdigest() != manifest[field+"_sha256"]: + raise ValueError(f"released artifact SHA256 changed:{field}") + return result + json_path, urdf_path = artifact("calibration_json"), artifact("corrected_urdf") + if path not in {manifest_path, json_path.resolve()}: + raise ValueError("JSON is not the artifact certified by this manifest") + validation = manifest["validation"] + if validation.get("final_file_spatial_replay") != "passed" or not validation.get("steady_command_tag_holdout"): + raise ValueError("release lacks independent command and feedback URDF evidence") + payload = json.loads(json_path.read_text()) + if "urdf_correction" in payload and validation.get("urdf_rebuilt_from_json") is not True: + raise ValueError("release lacks JSON-to-URDF correspondence validation") + report = json.loads(artifact("calibration_report").read_text()) if payload.get("format") in {COMPACT_FORMAT, MEASURED_FORMAT} else None + if payload.get("format") == MEASURED_FORMAT: + if (independent_joint_sources(payload) is not None + and validation.get("urdf_joint_angle_source") != JSON_JOINT_ANGLES): + raise ValueError("release lacks explicit JSON joint angle acceptance") + if (uses_affine_mimic_approximation(payload) or uses_source_mimic(payload)) and ( + validation.get("urdf_mimic_policy") != payload["urdf_correction"]["mimic_policy"] + or validation.get("urdf_joint_angle_source") != JSON_JOINT_ANGLES + or not validation.get("urdf_mimic_approximation")): + raise ValueError("release lacks separate mimic approximation acceptance") + if validation.get("directional_command_joints", []) != payload.get("directional_command_joints", []): + raise ValueError("v3 release directional mapping differs from its acceptance") + transfers = report.get("transferred_motion_sources", {}) + expected_kind = "measured_and_transferred_json_urdf_v3" if transfers else "independently_measured_json_urdf_v3" + scope = payload.get("calibration_scope") + if scope != report.get("calibration_scope") or scope != validation.get("calibration_scope"): + raise ValueError("v3 release partial scope differs from its report or acceptance") + if scope is not None: + expected_kind = "partial_measured_json_urdf_v3" + observed = {name for name, row in report["joints"].items() if row.get("independently_measured") is True} + if (validation.get("acceptance") != expected_kind or not observed + or set(validation.get("independent_mapping_holdout", {})) != observed + or not validation.get("full_json_urdf_holdout") + or validation.get("transferred_motion_sources", {}) != transfers): + raise ValueError("v3 release lacks independent measured acceptance") + if transfers or "independently_measured_joints" in validation: + if (validation.get("independently_measured_joints") != sorted(observed) + or validation.get("transferred_joints") != sorted(transfers)): + raise ValueError("v3 release measurement coverage differs from its report") + assumptions = {name: row["cad_zero_assumption"] for name, row in report["joints"].items() + if "cad_zero_assumption" in row} + if validation.get("cad_zero_assumptions", {}) != assumptions: + raise ValueError("v3 release CAD assumptions differ from its report") + if validation.get("motion_range_evidence", {}) != report.get("motion_range_evidence", {}): + raise ValueError("v3 release motion range evidence differs from its report") + return UnifiedCommandMapper(payload, urdf_path, + input_kind=input_kind, expected_side=expected_side, report=report) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/replay.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/replay.py new file mode 100644 index 0000000..1e4a22b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/replay.py @@ -0,0 +1,64 @@ +"""Offline use of exactly the online finalizer, for any declared Profile.""" + +from pathlib import Path + +from ..acquisition import load_capture +from ...core.domain.capture_plan import CapturePlan, raw_feedback_capture +from .capture_validation import validate_capture_provenance, validate_capture_units +from .finalization import finalize_profile_session + + +def replay_capture(config, raw_path: Path, *, output: Path | None, publish: bool): + from ...product import sha256_file + from ..runner_support import create_session_directory, protected_inputs + profile = config.calibration_contract.typed_profile + from ..raw_completion import verify_capture_manifest + sealed = (raw_path.parent / 'raw_capture_manifest.json').exists() + manifest = verify_capture_manifest(raw_path) if sealed else None + records = load_capture(raw_path) + header = next((r for r in records if r.get('kind') == 'session_start'), {}) + if sealed or header.get('capture_plan', {}).get('observation_protocol', {}).get('version') == 'raw_joint_images_v2': + if manifest is None: + manifest = verify_capture_manifest(raw_path) + if manifest['capture_plan'] != header['capture_plan'] or manifest['serial_number'] != config.serial_number: + raise ValueError('raw_capture_manifest_identity_changed') + if manifest['capture_plan'] != CapturePlan.from_profile(profile).as_dict(): + raise ValueError('capture_profile_differs_from_sealed_plan') + hashes = protected_inputs(config) + reference = next((row for row in records if row.get("kind") == "fixed_base_reference_locked"), {}) + if "intrinsics_sha256" in reference.get("protected_hashes", {}): + hashes["intrinsics_sha256"] = reference["protected_hashes"]["intrinsics_sha256"] + hashes["raw_samples_sha256"] = sha256_file(raw_path) + if output is None: + output = create_session_directory(config.session_root) + else: + output = output.expanduser().resolve() + output.mkdir(parents=True, exist_ok=False) + from ..raw_completion import implementation_digest + from ...storage import atomic_write_json + atomic_write_json(output / 'offline_run.json', dict( + input_raw=str(raw_path.resolve()), input_sha256=hashes['raw_samples_sha256'], + capture_plan=header.get('capture_plan'), implementation_sha256=implementation_digest(), + protected_inputs=hashes, commands_enabled=False, publish_requested=publish)) + if manifest is not None and manifest['raw_capture_complete'] is not True: + raise ValueError(('raw_joint_capture_incomplete' if manifest['protocol'] == 'raw_joint_images_v2' + else 'capture_incomplete') + ':see_raw_capture_manifest') + if raw_feedback_capture(profile): + from .feedback_raw_finalization import fit_raw_feedback_session + fit_raw_feedback_session(profile=profile, records=records, + source_urdf=config.source_urdf, + camera_extrinsics_file=config.camera_extrinsics, + serial_number=config.serial_number, protected_inputs=hashes, + session_dir=output, publish=publish) + print(f"离线反馈标定完成:验收报告 {output / 'standard_urdf_acceptance.json'}") + return + from ...core.domain.capture_plan import STAGED + if profile.quality.training_policy == STAGED: + import shutil + shutil.copyfile(raw_path.parent / "frozen_training.json", output / "frozen_training.json") + payload, _fit, correction = finalize_profile_session( + profile=profile, + session_dir=output, serial_number=config.serial_number, source_urdf=config.source_urdf, + protected_inputs=hashes, records=records, publish=publish, + camera_extrinsics_file=config.camera_extrinsics, require_motion_evidence=True) + print(f"离线回放完成:schema {payload['schema_version']},URDF {correction.path}") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/__init__.py new file mode 100644 index 0000000..871b95b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/__init__.py @@ -0,0 +1 @@ +"""Format compatibility only. Mathematical choices precede serialization.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/compact_v2.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/compact_v2.py new file mode 100644 index 0000000..399add9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/compact_v2.py @@ -0,0 +1,62 @@ +"""Small command lookup; the complete training result stays in the report. + +No extrapolation, new fit, zero shift or independent passive curve is allowed. +The exported single curve must subsequently pass final-file visual holdout. +""" + +import numpy as np + +from ....core.urdf.acceptance import SerializedJointMapping +from .unified_v1 import serialize as serialize_report + +FORMAT = "unified_calibration_v2" +REPORT_FILENAME = "calibration_report.json" + + +def from_report(report): + mapping = SerializedJointMapping(report, input_kind="command") + unit = report["command_unit"] + rows, visiting = {}, set() + + def resolve(name): + if name in rows: + return rows[name] + if name in visiting or name not in report["joints"]: + raise ValueError("invalid report mimic graph") + visiting.add(name) + source = report["joints"][name] + if source.get("passive"): + mimic = source["mimic"] + parent = resolve(mimic["joint"]) + row = {**parent, "angle_rad": [mimic["multiplier"]*v + mimic["offset_rad"] + for v in parent["angle_rad"]]} + else: + data = mapping.joints[name] + knots = np.asarray(data["curve_input_knots_rad"], dtype=float) + # Averaging is a declared training-only reduction. Never choose a + # better branch using holdout, or retain hidden direction fallback. + angles = (np.asarray(data["increasing_rad"]) + np.asarray(data["decreasing_rad"]))/2 + row = {"sdk_channel": data["motor_index"]} + if unit == "u8": + if knots[0] != 0 or knots[-1] != 255: + raise ValueError(f"compact_byte_requires_measured_full_command_domain:{name}") + angles = np.interp(np.arange(256), knots, angles) + else: + row["input_values"] = knots.tolist() + row["angle_rad"] = angles.tolist() + if not np.all(np.isfinite(row["angle_rad"])): + raise ValueError(f"nonfinite compact curve:{name}") + visiting.remove(name) + rows[name] = row + return row + + for name in sorted(report["joints"]): + resolve(name) + return {"format": FORMAT, "schema_version": 2, + **({"urdf_correction": report["urdf_correction"]} if "urdf_correction" in report else {}), + **{key: report[key] for key in ("profile_id", "model", "side", "serial_number")}, + "input_unit": unit, "joints": {name: rows[name] for name in sorted(rows)}} + + +def serialize(profile, fit, prepared, **metadata): + return from_report(serialize_report(profile, fit, prepared, **metadata)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/measured_v3.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/measured_v3.py new file mode 100644 index 0000000..1acb950 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/measured_v3.py @@ -0,0 +1,252 @@ +"""Measured command tables and explicit copies; no fitting or rebasing here.""" + +from dataclasses import asdict +import numpy as np + +from .unified_v1 import _mapping +from ....core.urdf.joint_control import PRESERVE_SOURCE_MIMIC, uses_source_mimic +from ....core.urdf.partial_scope import profile_scope, retained_from_payload + +FORMAT = "unified_calibration_v3" +REPORT_FORMAT = "unified_calibration_report_v3" +ZERO_CONVENTION = "q_CAD=q_output+delta; joint_baseline:q_output=0" + + +def serialize_report(profile, fit, prepared, *, serial_number, protected_inputs): + from ....core.domain.sampling import command_training_cycles, command_holdout_cycle + expected = set(prepared.mappings) + transfers = dict(profile.measurement.transferred_motion_sources) + observed = expected - transfers.keys() + if not expected or any(set(values) != expected for values in + (fit.command_mappings, fit.output_mappings, fit.zero_offsets_rad)): + raise ValueError("independent_measurement_or_geometry_incomplete") + if set(fit.joint_zero_references) != observed or set(fit.curves) != observed: + raise ValueError("independent_measurement_or_reference_coverage_differs") + rows = {} + independent_sources = getattr(prepared.plan, "independent_joint_sources", None) + preserved = getattr(prepared.plan, "mimic_policy", None) == PRESERVE_SOURCE_MIMIC + passive_sources = prepared.plan.mimic_output if independent_sources is None else independent_sources + for name in sorted(expected): + donor = transfers.get(name) + if any(mapping.transferred_from != donor for mapping in + (fit.command_mappings[name], fit.output_mappings[name])): + raise ValueError(f"mapping_transfer_differs_from_profile:{name}") + row = {"urdf_joint": name, "independently_measured": donor is None, + "zero_offset_rad": fit.zero_offsets_rad[name], "zero_method": fit.zero_method_by_joint[name], + "command_to_rad": _mapping(fit.command_mappings[name]), + "passive": name in passive_sources} + if profile.command_based_release: + row["feedback_diagnostic"] = fit.feedback_diagnostics[name] + else: + row["feedback_to_rad"] = _mapping(fit.output_mappings[name]) + if donor is None: + row.update(zero_reference=fit.joint_zero_references[name].as_record(), + applicability=fit.command_applicability[name], + command_holdout=fit.command_holdout_metrics[name]) + else: + row.update(transferred_from_joint=donor, zero_reference_source_joint=donor, + command_holdout_source_joint=donor, + baseline_command=profile.command.baseline_values[fit.command_mappings[name].motor_index], + applicability={"scope": "transferred_from_declared_joint", "source_joint": donor, + "recipient_independently_validated": False, "arbitrary_multiaxis_validated": False}) + if row["passive"] and preserved: + parent, multiplier, offset = prepared.plan.mimic_output[name] + row["mimic_approximation"] = {"joint": parent, "multiplier": multiplier, "offset_rad": offset, + "usage": "source_urdf_linear_fallback", "physical_zero_correction": False} + elif row["passive"]: + approximation = fit.mimic_approximations[name] + if approximation.transferred_from_joint != donor: + raise ValueError(f"mimic_transfer_differs_from_profile:{name}") + if independent_sources is None: + parent, multiplier, offset = prepared.plan.mimic_output[name] + else: + parent = independent_sources[name] + multiplier, offset = approximation.output_fit.multiplier, approximation.output_fit.offset_rad + row["mimic_approximation"] = {"joint": parent, "multiplier": multiplier, "offset_rad": offset, + "evidence": asdict(approximation)} + if independent_sources is not None: + row["mimic_approximation"]["usage"] = "diagnostic_only_not_exported" + elif getattr(prepared.plan, "mimic_policy", None) is not None: + row["mimic_approximation"].update(usage="urdf_linear_approximation", + baseline_error_rad=offset, physical_zero_correction=False) + if name in profile.zero.known_baseline_geometry: + row["known_baseline_geometry"] = asdict(profile.zero.known_baseline_geometry[name]) + if name in profile.zero.cad_zero_assumptions: + row["cad_zero_assumption"] = profile.zero.cad_zero_assumptions[name] + if name in profile.zero.transferred_zero_sources: + row["zero_transferred_from_joint"] = profile.zero.transferred_zero_sources[name] + rows[name] = row + return {"format": REPORT_FORMAT, "schema_version": 3, + **({"calibration_scope": profile_scope(profile)} if profile.retained_joints else {}), + **({"directional_command_joints": sorted(profile.artifacts.directional_command_joints)} + if profile.artifacts.directional_command_joints else {}), + "profile_id": profile.key.profile_id, "model": profile.key.model, "side": profile.key.side, + "serial_number": serial_number, "command_unit": profile.command.unit, + "command_names": list(profile.command.names), "baseline_command": list(profile.command.baseline_values), + "feedback_by_index": profile.command.feedback_by_index, + "feedback_name_aliases": dict(profile.command.feedback_name_aliases), + "coordinate_convention": ZERO_CONVENTION, "protected_inputs": dict(protected_inputs), + "joints": rows, **({"transferred_motion_sources": transfers} if transfers else {}), + "quality": {"release_basis": profile.measurement.release_basis, + "motion_observation": profile.acquisition.motion_observation, + "fixed_reference_mode": profile.acquisition.fixed_reference_mode, + "position_feedback_required": not profile.vision_motion, + "feedback_mapping_required": not profile.command_based_release, + "training_cycles": sorted({c for task in profile.motion.tasks + for c in profile.quality.task_training_cycles.get(task.key, profile.quality.training_cycles)}), + "holdout_cycle": profile.quality.holdout_cycle, + "task_training_cycles": {task.key: list(profile.quality.task_training_cycles.get(task.key, + profile.quality.training_cycles)) for task in profile.motion.tasks}, + "training_policy": profile.quality.training_policy, + "command_capture_mode": profile.acquisition.command_capture_mode, + "command_training_cycles": sorted({c for task in profile.motion.tasks + for c in command_training_cycles(profile, task)}), + "command_holdout_cycle": command_holdout_cycle(profile), + "precision_scope": "observed_travel_directions_and_held_poses", + "independently_measured_joints": sorted(observed), "transferred_joints": sorted(transfers), + "final_file_acceptance": "release_manifest.json", "arbitrary_multiaxis_validated": False}} + + +def from_report(report): + from ....core.urdf.acceptance import SerializedJointMapping + if report.get("format") != REPORT_FORMAT or report.get("coordinate_convention") != ZERO_CONVENTION: + raise ValueError("v3 requires its original measured report; legacy promotion is forbidden") + raw_audit = report.get('raw_joint_audit') + if report.get('capture_plan', {}).get('policy') == 'raw_joint_2_plus_1' and raw_audit is None: + raise ValueError('raw_joint_report_audit_missing') + if raw_audit is not None: + from ....core.domain.capture_plan import RAW_JOINT + if (report.get('capture_plan', {}).get('policy') != RAW_JOINT + or raw_audit.get('protocol') not in {'raw_joint_images_v1', 'raw_joint_images_v2'} + or raw_audit.get('protocol') != report['capture_plan'].get('observation_protocol', {}).get('version') + or raw_audit.get('candidate_uncertainty', {}).get('passed') is not True + or raw_audit.get('validation_parameters_updated') is not False): + raise ValueError('raw_joint_report_not_certified') + if any(not isinstance(raw_audit.get(key), str) or len(raw_audit[key]) != 64 + or any(c not in '0123456789abcdef' for c in raw_audit[key]) + for key in ('capture_sha256', 'training_sha256', 'candidate_set_sha256')): + raise ValueError('raw_joint_report_digest_invalid') + for name, row in report['joints'].items(): + if 'command_support' in raw_audit: + from ....core.domain.result import JointMapping + from ....core.fitting.command_support import validate_turnaround_mapping + table = row['command_to_rad'] + command = JointMapping(name, table['channel_index'], table['input_domain'], + *(tuple(table[key]) for key in ('knots', 'angle_rad', 'increasing_rad', 'decreasing_rad'))) + if name not in raw_audit['command_support']: + raise ValueError('raw_joint_command_support_missing:' + name) + validate_turnaround_mapping(command, raw_audit['command_support'][name]) + reference = row.get('zero_reference', {}) + if (reference.get('kind') != 'raw_joint_training_baseline' + or reference.get('training_sha256') != raw_audit.get('training_sha256') + or reference.get('candidate_set_sha256') != raw_audit.get('candidate_set_sha256')): + raise ValueError('raw_joint_report_reference_changed:' + name) + mapping = SerializedJointMapping(report, input_kind="command") + retained_from_payload(report) + basis = report.get("quality", {}).get("release_basis", "feedback_and_command") + if basis not in {"feedback_and_command", "steady_command"}: + raise ValueError("invalid_report_release_basis") + feedback = SerializedJointMapping(report, input_kind="feedback") if basis == "feedback_and_command" else None + if basis == "steady_command": + if report.get("transferred_motion_sources") or report['quality'].get('feedback_mapping_required') is not False: + raise ValueError('invalid_command_release_contract') + for name, row in report['joints'].items(): + diagnostic = row.get('feedback_diagnostic', {}) + if ('feedback_to_rad' in row or diagnostic.get('required_for_release') is not False + or diagnostic.get('input_domain') != f"feedback_{report['command_unit']}"): + raise ValueError(f'invalid_feedback_diagnostic:{name}') + unit, baseline, rows = report["command_unit"], report["baseline_command"], {} + directional = set(report.get("directional_command_joints", ())) + if not directional <= mapping.joints.keys(): + raise ValueError("directional_command_joint_missing") + if len(baseline) != len(report["command_names"]) or not np.all(np.isfinite(baseline)): + raise ValueError("joint_baseline_vector_differs_from_sdk_layout") + transfers = report.get("transferred_motion_sources", {}) + if (not isinstance(transfers, dict) or not set(transfers) <= mapping.joints.keys() + or any(not isinstance(source, str) or source not in mapping.joints or source in transfers + for source in transfers.values())): + raise ValueError("invalid_direct_motion_transfer_contract") + quality = report.get("quality", {}) + if transfers or "independently_measured_joints" in quality: + if (quality.get("independently_measured_joints") != sorted(mapping.joints.keys() - transfers.keys()) + or quality.get("transferred_joints") != sorted(transfers)): + raise ValueError("reported_motion_coverage_differs_from_provenance") + for name, data in mapping.joints.items(): + evidence = report["joints"][name] + if "cad_zero_assumption" in evidence and ( + not isinstance(evidence["cad_zero_assumption"], str) or not evidence["cad_zero_assumption"].strip() + or evidence.get("zero_method") != "assumed_source_cad_zero" or evidence.get("zero_offset_rad") != 0 + or "known_baseline_geometry" in evidence or "zero_transferred_from_joint" in evidence): + raise ValueError(f"assumed_cad_zero_provenance_differs:{name}") + if "zero_transferred_from_joint" in evidence: + zero_donor = report["joints"].get(evidence["zero_transferred_from_joint"], {}) + if (not zero_donor or "zero_transferred_from_joint" in zero_donor + or evidence.get("zero_method") != "transferred_static_zero_on_own_cad" + or evidence.get("zero_offset_rad") != zero_donor.get("zero_offset_rad")): + raise ValueError(f"transferred_zero_provenance_differs:{name}") + index = data["motor_index"] + if index >= len(baseline) or (feedback is not None and feedback.joints[name]["motor_index"] != index): + raise ValueError(f"joint_input_channel_differs:{name}") + donor = transfers.get(name) + if donor is None: + if evidence.get("independently_measured") is not True or evidence.get("transferred_from_joint"): + raise ValueError(f"joint_is_not_independently_measured:{name}") + reference = evidence.get("zero_reference", {}) + if (reference.get("joint") != name or reference.get("channel") != index + or reference.get("baseline_command") != baseline[index] or not reference.get("samples")): + raise ValueError(f"joint_zero_evidence_differs:{name}") + else: + source = report["joints"][donor] + if (evidence.get("independently_measured") is not False + or evidence.get("transferred_from_joint") != donor + or evidence.get("zero_reference_source_joint") != donor + or evidence.get("command_holdout_source_joint") != donor + or "zero_reference" in evidence or "command_holdout" in evidence + or evidence.get("baseline_command") != baseline[index] + or source.get("independently_measured") is not True + or baseline[index] != baseline[mapping.joints[donor]["motor_index"]]): + raise ValueError(f"transferred_joint_evidence_differs:{name}") + for kind in ("command_to_rad", "feedback_to_rad"): + # Copies preserve all knots, branches and coordinate metadata. + # Only the recipient's real SDK channel is allowed to differ. + left = {key: value for key, value in evidence[kind].items() if key != "channel_index"} + right = {key: value for key, value in source[kind].items() if key != "channel_index"} + if left != right: + raise ValueError(f"transferred_curve_differs_from_source:{name}:{kind}") + if evidence.get("passive") and not uses_source_mimic(report): + approximation = evidence.get("mimic_approximation", {}) + source_approximation = source.get("mimic_approximation", {}).get("evidence", {}) + expected_approximation = {**source_approximation, + "output_fit": {**source_approximation.get("output_fit", {}), + "target_joint": name, "source_joint": approximation.get("joint")}, + "transferred_from_joint": donor} + if not source_approximation or approximation.get("evidence") != expected_approximation: + raise ValueError(f"transferred_mimic_evidence_differs_from_source:{name}") + knots = np.asarray(data["curve_input_knots_rad"]) + angles = np.asarray(data["angle_rad"]) + if not knots[0] <= baseline[index] <= knots[-1] or abs(np.interp(baseline[index], knots, angles)) > 1e-10: + raise ValueError(f"joint_baseline_is_not_zero:{name}") + row = {"sdk_channel": index} + if unit == "u8": + if knots[0] != 0 or knots[-1] != 255: + raise ValueError(f"compact_byte_requires_measured_full_command_domain:{name}") + row["angle_rad"] = np.interp(np.arange(256), knots, angles).tolist() + else: + row.update(input_values=knots.tolist(), angle_rad=angles.tolist()) + if name in directional: + for direction in ("increasing", "decreasing"): + values = np.asarray(data[direction + "_rad"]) + if abs(np.interp(baseline[index], knots, values)) > 1e-10: + raise ValueError(f"directional_joint_baseline_is_not_zero:{name}:{direction}") + row[direction + "_rad"] = (np.interp(np.arange(256), knots, values).tolist() + if unit == "u8" else values.tolist()) + rows[name] = row + return {"format": FORMAT, "schema_version": 3, + **({'raw_joint_audit': raw_audit} if raw_audit is not None else {}), + **({"capture_plan": report["capture_plan"]} if "capture_plan" in report else {}), + **({"calibration_scope": report["calibration_scope"]} if "calibration_scope" in report else {}), + **({"urdf_correction": report["urdf_correction"]} if "urdf_correction" in report else {}), + **({"directional_command_joints": sorted(directional)} if directional else {}), + **{key: report[key] for key in ("profile_id", "model", "side", "serial_number")}, + "input_unit": unit, "baseline_command": baseline, + "coordinate_convention": ZERO_CONVENTION, "joints": rows} diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/unified_v1.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/unified_v1.py new file mode 100644 index 0000000..b0a4c85 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/serializers/unified_v1.py @@ -0,0 +1,47 @@ +"""Lossless dual-input format. No fitting, rebasing or passive curve bypass.""" + +FORMAT = "unified_calibration_v1" + + +def _mapping(mapping): + return {"input_domain": mapping.input_domain, "channel_index": mapping.motor_index, + "input_unit": mapping.input_domain.rsplit("_", 1)[1], "output_unit": "rad", + "knots": list(mapping.knots), "valid_input_range": [mapping.knots[0], mapping.knots[-1]], + "interpolation": "piecewise_linear", "extrapolation": "reject", + **{field: list(getattr(mapping, field)) for field in ("angle_rad", "increasing_rad", "decreasing_rad")}} + + +def serialize(profile, fit, prepared, *, serial_number, protected_inputs): + if set(fit.command_mappings) != set(fit.output_mappings): + raise ValueError("unified artifacts require independently measured command AND feedback mappings") + if any(not m.input_domain.startswith("feedback_") for m in fit.output_mappings.values()): + raise ValueError("unified geometry must use feedback, not a relabelled command curve") + rows = {} + for name in sorted(prepared.mappings): + row = {"urdf_joint": name, "calibration_status": profile.joint_coverage[name], + "zero_offset_rad": fit.zero_offsets_rad.get(name, 0.0), + "zero_method": fit.zero_method_by_joint.get(name, "source_cad_passive_zero")} + if name in prepared.plan.mimic_output: + parent, multiplier, offset = prepared.plan.mimic_output[name] + row.update(passive=True, runtime_source="exported_standard_urdf_mimic", + mimic={"joint": parent, "multiplier": multiplier, "offset_rad": offset}) + else: + row.update(passive=False, command_to_rad=_mapping(fit.command_mappings[name]), + feedback_to_rad=_mapping(fit.output_mappings[name]), + applicability=fit.command_applicability[name], + command_holdout=fit.command_holdout_metrics[name]) + donor = profile.zero.transferred_zero_sources.get(name) + if donor: + row.update(transferred_from_joint=donor, independently_measured=False) + rows[name] = row + return {"format": FORMAT, "schema_version": 1, "profile_id": profile.key.profile_id, + "serial_number": serial_number, "model": profile.key.model, "side": profile.key.side, + "angle_unit": "rad", "command_unit": profile.command.unit, + "command_names": list(profile.command.names), "baseline_command": list(profile.command.baseline_values), + "feedback_by_index": profile.command.feedback_by_index, + "feedback_name_aliases": dict(profile.command.feedback_name_aliases), + "protected_inputs": dict(protected_inputs), "joints": rows, + "coordinate_convention": "q_CAD=q_output+delta; JSON already emits q_output", + "quality": {"training_cycles": list(profile.quality.training_cycles), "holdout_cycle": profile.quality.holdout_cycle, + "command_and_feedback_fits_passed": True, + "final_file_acceptance": "release_manifest.json", "arbitrary_multiaxis_validated": False}} diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/standard_loader.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/standard_loader.py new file mode 100644 index 0000000..72f3b44 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/standard_loader.py @@ -0,0 +1,62 @@ +"""Bounded, isolated standard ROS URDF loader check. Never starts an SDK.""" + +from __future__ import annotations + +import os +from pathlib import Path +import selectors +import subprocess +import tempfile +import time +import uuid + +import yaml + + +def validate_with_robot_state_publisher(path: Path, *, timeout_seconds: float = 8.0) -> None: + """Require urdfdom/KDL/RSP to load the generated file successfully. + + All subscriptions and TF outputs use a fresh private namespace. The + process has no motor-command publisher or SDK connection. It is terminated + after initialization, not left running as another hand model publisher. + """ + from ament_index_python.packages import get_package_prefix + executable = Path(get_package_prefix("robot_state_publisher")) / "lib/robot_state_publisher/robot_state_publisher" + if not executable.is_file(): + raise ValueError("standard_urdf_loader_unavailable:robot_state_publisher") + namespace = "/calibration_verify_" + uuid.uuid4().hex + with tempfile.TemporaryDirectory(prefix="calibration_urdf_verify_") as directory: + parameters = Path(directory) / "parameters.yaml" + parameters.write_text(yaml.safe_dump({"/**": {"ros__parameters": { + "robot_description": path.read_text(encoding="utf-8"), + "publish_frequency": 1.0}}}), encoding="utf-8") + environment = dict(os.environ, ROS_LOG_DIR=directory, ROS_LOCALHOST_ONLY="1") + process = subprocess.Popen([str(executable), "--ros-args", "--params-file", str(parameters), + "-r", f"__ns:={namespace}", "-r", f"/tf:={namespace}/tf", + "-r", f"/tf_static:={namespace}/tf_static", "-r", f"joint_states:={namespace}/joint_states", + "--log-level", "info", "--disable-rosout-logs"], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=environment) + output = bytearray() + try: + assert process.stdout is not None + with selectors.DefaultSelector() as selector: + selector.register(process.stdout, selectors.EVENT_READ) + deadline = time.monotonic() + timeout_seconds + while time.monotonic() < deadline: + for key, _ in selector.select(timeout=0.1): + output.extend(os.read(key.fileobj.fileno(), 65536)) + if b"Robot initialized" in output and process.poll() is None: + return + if process.poll() is not None: + break + raise ValueError("standard_urdf_loader_failed:" + output.decode(errors="replace")[-4000:]) + finally: + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=2) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=2) + if process.stdout is not None: + process.stdout.close() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/urdf_from_json.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/urdf_from_json.py new file mode 100644 index 0000000..4fbc727 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/urdf_from_json.py @@ -0,0 +1,150 @@ +"""Persisted calibration JSON -> immutable-source URDF, without fitting.""" + +from dataclasses import asdict, fields +import hashlib +import json +import math +from pathlib import Path +import xml.etree.ElementTree as ET + +from ...core.urdf.acceptance import SerializedJointMapping, validate_compact_urdf_tables +from ...core.urdf.joint_control import ( + JSON_JOINT_ANGLES, independent_joint_sources, independent_export_authorization, + AFFINE_MIMIC_APPROXIMATION, uses_affine_mimic_approximation, + PRESERVE_SOURCE_MIMIC, uses_source_mimic, +) +from ...core.urdf.source_mimic import validate_source_mimic_elements +from ...core.urdf.kinematics import UrdfKinematicModel +from ...core.urdf.patch import ( + UrdfJointPatch, UrdfPatchSet, apply_urdf_patch_text, + write_urdf_patches, validate_urdf_mimic_ranges, +) + + +def serialize_urdf_correction(plan): + """Persist numeric edits and the explicit JSON angle-provider contract.""" + if plan.patches.mujoco_equalities: + raise ValueError("standard_calibration_cannot_rebuild_mujoco_extensions") + sources = plan.independent_joint_sources + affine = plan.mimic_policy == AFFINE_MIMIC_APPROXIMATION + preserved = plan.mimic_policy == PRESERVE_SOURCE_MIMIC + return {"schema_version": 4 if preserved else (3 if affine else (1 if sources is None else 2)), + "source_urdf_sha256": plan.source_sha256, + **({"joint_angle_source": JSON_JOINT_ANGLES, "mimic_policy": plan.mimic_policy} if affine or preserved else {}), + **({"mimic_envelopes": {name: {key: list(value) for key, value in asdict(item).items()} + for name, item in plan.mimic_envelopes.items()}} if preserved else {}), + **({"joint_angle_source": JSON_JOINT_ANGLES, "passive_joint_sources": dict(sources)} + if sources is not None else {}), + "joint_patches": {name: {key: value for key, value in asdict(patch).items() + if value is not None and not (key == "remove_mimic" and value is False)} + for name, patch in sorted(plan.patches.joints.items())}} + + +def _read_correction(payload, expected_profile_id): + if (not isinstance(payload, dict) + or payload.get("format") not in {"unified_calibration_v2", "unified_calibration_v3"} + or payload.get("profile_id") != expected_profile_id): + raise ValueError("calibration_json_profile_or_format_mismatch") + correction = payload.get("urdf_correction") + if not isinstance(correction, dict): + raise ValueError("calibration_json_missing_supported_urdf_correction") + sources = independent_joint_sources(payload) + keys = {"schema_version", "source_urdf_sha256", "joint_patches"} + if sources is not None: + keys.update({"joint_angle_source", "passive_joint_sources"}) + preserved = uses_source_mimic(payload) + if uses_affine_mimic_approximation(payload) or preserved: + keys.update({"joint_angle_source", "mimic_policy"}) + if preserved: + keys.add("mimic_envelopes") + if set(correction) != keys: + raise ValueError("calibration_json_missing_supported_urdf_correction") + digest = correction["source_urdf_sha256"] + if not isinstance(digest, str) or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest): + raise ValueError("invalid_calibration_source_sha256") + declared = correction["joint_patches"] + allowed = {field.name for field in fields(UrdfJointPatch)} + if sources is None: + allowed.remove("remove_mimic") + if preserved: + allowed -= {"mimic_multiplier", "mimic_offset"} + if not isinstance(declared, dict): + raise ValueError("invalid_calibration_joint_edits") + patches = {} + for name, values in declared.items(): + if not isinstance(values, dict) or not values or not set(values) <= allowed: + raise ValueError(f"invalid_calibration_joint_edits:{name}") + for key, value in values.items(): + if key == "remove_mimic": + if value is not True: + raise ValueError(f"invalid_calibration_mimic_removal:{name}") + continue + if not isinstance(value, str): + raise ValueError(f"calibration_edit_requires_numeric_text:{name}:{key}") + numbers = [float(item) for item in value.split()] + if len(numbers) != (3 if key == "origin_rpy" else 1) or not all(math.isfinite(v) for v in numbers): + raise ValueError(f"invalid_calibration_numeric_edit:{name}:{key}") + patches[name] = UrdfJointPatch(**values) + if sources is not None and {name for name, patch in patches.items() if patch.remove_mimic} != set(sources): + raise ValueError("calibration_mimic_removals_differ_from_joint_control") + return digest, UrdfPatchSet(patches) + + +def _export_authorization(payload, source_urdf, authorized_fields): + sources = independent_joint_sources(payload) + if sources is None: + return authorized_fields + mapping = SerializedJointMapping(payload, input_kind="command") + channels = {name: row["motor_index"] for name, row in mapping.joints.items()} + return independent_export_authorization(UrdfKinematicModel(source_urdf), channels, sources, authorized_fields) + + +def validate_json_urdf_correspondence(payload, source_urdf, corrected_urdf, *, expected_profile_id): + """Prove that the saved correction describes the exact final URDF bytes.""" + digest, patches = _read_correction(payload, expected_profile_id) + source_bytes = Path(source_urdf).read_bytes() + if hashlib.sha256(source_bytes).hexdigest() != digest: + raise ValueError("calibration_json_source_sha256_mismatch") + _export_authorization(payload, source_urdf, {}) + rebuilt = apply_urdf_patch_text(source_bytes.decode("utf-8"), ET.fromstring(source_bytes), patches) + if rebuilt.encode("utf-8") != Path(corrected_urdf).read_bytes(): + raise ValueError("calibration_json_correction_differs_from_urdf") + if uses_source_mimic(payload): + validate_source_mimic_elements(source_urdf, corrected_urdf) + validate_compact_urdf_tables(payload, UrdfKinematicModel(corrected_urdf)) + + +def rebuild_urdf_from_json(calibration_json, source_urdf, destination_urdf, *, + authorized_fields, expected_profile_id): + """Validate and atomically write only edits read from the saved JSON. + + Rebuilding checks source identity, declared field rights, topology, full + mimic ranges and JSON tables. It does not certify measurement precision or + publish a release; the normal final-file validator still owns those checks. + """ + payload = json.loads(Path(calibration_json).read_text(encoding="utf-8")) + digest, patches = _read_correction(payload, expected_profile_id) + authorization = _export_authorization(payload, source_urdf, authorized_fields) + def validate(path): + if uses_source_mimic(payload): + validate_source_mimic_elements(source_urdf, path) + validate_urdf_mimic_ranges(path) + validate_compact_urdf_tables(payload, UrdfKinematicModel(path)) + return write_urdf_patches(source_urdf=source_urdf, destination_urdf=destination_urdf, + patches=patches, authorized_fields=authorization, + expected_source_sha256=digest, validate_output=validate) + + +def main(args=None): + import argparse + from ...product import load_product_config + parser = argparse.ArgumentParser(description="读取标定 JSON,从受保护的原始 URDF 重建修正文件") + parser.add_argument("--config", required=True) + parser.add_argument("--calibration-json", required=True) + parser.add_argument("--output", required=True) + selected = parser.parse_args(args) + config = load_product_config(selected.config, check_can=False) + profile = config.calibration_contract.typed_profile + output = rebuild_urdf_from_json(selected.calibration_json, config.source_urdf, selected.output, + authorized_fields=profile.urdf_authorized_fields, expected_profile_id=profile.key.profile_id) + print(f"已按标定 JSON 重建:{output}。精度结论以原会话验收为准。") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/worker.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/worker.py new file mode 100644 index 0000000..08a2b60 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/artifacts/worker.py @@ -0,0 +1,49 @@ +"""CPU-bound finalization without blocking the SDK or status callbacks. + +The worker only prepares artifacts. The controller commits them, under the +same lock as abort/pause, after observing successful completion. +""" + +from concurrent.futures import ThreadPoolExecutor +from threading import Event, RLock + + +class FinalizationWorker: + def __init__(self): + self.lock = RLock() + self._cancelled = Event() + self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="calibration-fit") + self._future = None + self._consumed = False + + def start(self, finalizer, **kwargs): + with self.lock: + if self._future is not None or self._cancelled.is_set(): + raise RuntimeError("finalization_already_started_or_cancelled") + self._future = self._executor.submit( + finalizer, **kwargs, publish=False, cancelled=self._cancelled.is_set) + + def finish_if_ready(self, commit): + """Invoke commit at most once; an abort cannot race the pointer swap. + + The controller holds ``lock`` while also updating its terminal state. + A failed job is consumed too, so a failed publication is never retried. + """ + with self.lock: + if (self._cancelled.is_set() or self._consumed or + self._future is None or not self._future.done()): + return None + self._consumed = True + result = self._future.result() + commit(result) + return result + + def cancel(self): + with self.lock: + self._cancelled.set() + if self._future is not None: + self._future.cancel() + + def close(self): + self.cancel() + self._executor.shutdown(wait=False, cancel_futures=True) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_diagnostics.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_diagnostics.py new file mode 100644 index 0000000..59f6368 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_diagnostics.py @@ -0,0 +1,32 @@ +"""Small solver lifecycle records, separate from immutable measurement evidence.""" + +import hashlib +import json +import logging + +from ..core.artifacts.storage import append_jsonl_many + + +def record_solver_event(path, request, event, *, stamp_ns, monotonic_time, **details): + """Record even a discarded result without changing a finalized raw journal. + + These events diagnose wall time and commit gates. They never authorize a + branch, a zero or publication, and cannot substitute for source images. + """ + sources = json.dumps(dict(request.source_frame_hashes), sort_keys=True, + separators=(",", ":")).encode() + record = { + "event": event, "stamp_ns": stamp_ns, "monotonic_time": monotonic_time, + "task_name": request.task_name, "view": request.view, + "zero_joints": list(request.zero_joints), "session_epoch": request.session_epoch, + "motion_version": request.motion_version, "generation": request.generation, + "source_frames": len(request.frames), "image_geometry": request.image_geometry, + "source_hashes_sha256": hashlib.sha256(sources).hexdigest(), + "source_first_stamp_ns": request.frames[0].stamp_ns if request.frames else None, + "source_last_stamp_ns": request.frames[-1].stamp_ns if request.frames else None, + **details, + } + try: + append_jsonl_many(path, (record,), durable=False) + except OSError: + logging.getLogger(__name__).exception("Could not record motion solver lifecycle") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_initialization.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_initialization.py new file mode 100644 index 0000000..ba64e99 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_initialization.py @@ -0,0 +1,621 @@ +"""Bounded evidence from declared zero-arrival motion, owned by the coordinator. + +Mutation is performed under the session lock after its observation-version +gate. A request is an immutable snapshot; the expensive geometry solver runs +outside that lock. Nothing here moves hardware, fits a control curve, or uses +training/holdout observations to revise an existing reference. +""" + +from dataclasses import asdict, dataclass, replace +from collections import deque +from collections.abc import Mapping +import hashlib +import json +import math + +from ..core.geometry.tag_pose.motion_evidence import ( + FrozenMotionConstraint, MotionBranchResolution, MotionEvidenceFrame, + MotionRelation, RoleCandidates, resolve_motion_branches, +) +from ..core.geometry.tag_pose.types import SquareTagPose +from ..core.geometry.tag_pose.motion_image_types import ImageMotionFrame, ImageRoleObservation +from ..core.geometry.tag_pose.cad_hinge import ParallelAxisGeometry +from ..core.geometry.tag_pose.source_hinge import SourceHinge +from ..core.geometry.tag_pose.pose_bridge import ( + SharedTagPoseBridge, shared_pose_selection_policy, +) +from ..core.geometry.tag_pose.production_image_motion import ( + ImageMotionModel, ImageMotionResolution, ImageMotionParameters, resolve_image_motion, +) +from .scan_quality import observation_streams +from .motion_provenance import source_frame_sha256 +from ..core.geometry.tag_pose.image_model_selection import IMAGE_MODEL_SELECTION_POLICY + + +@dataclass(frozen=True) +class MotionBranchModel: + task_name: str + view: str + constraints: tuple[FrozenMotionConstraint, ...] + evidence_ids: tuple[tuple[str, str], ...] + image_model: ImageMotionModel | None = None + + +@dataclass(frozen=True) +class BranchInitializationRequest: + task_name: str + view: str + zero_joints: tuple[str, ...] + session_epoch: int + motion_version: int + generation: int + frames: tuple[MotionEvidenceFrame, ...] + relations: tuple[MotionRelation, ...] + existing_evidence_ids: tuple[tuple[str, str], ...] + moving_roles: tuple[str, ...] + source_frame_hashes: tuple[tuple[str, str], ...] = () + invalid_reason: str = "" + image_frames: tuple[ImageMotionFrame, ...] = () + image_geometry: bool = False + geometry_constraints: tuple[ParallelAxisGeometry, ...] = () + source_urdf_sha256: str = "" + source_motion_versions: tuple[tuple[str, int], ...] = () + source_hinges: tuple[SourceHinge, ...] = () + parent_reference_sha256: str = "" + pose_bridges: tuple[SharedTagPoseBridge, ...] = () + pose_bridge_records: tuple[dict, ...] = () + rejected_observations: tuple[tuple[str, int], ...] = () + observer_sources: tuple = () + observer_profile: object = None + transition_source: object = None + transition_profile: object = None + current_source_rows: tuple = () + witness_sources: tuple = () + witness_profile: object = None + image_parameters: ImageMotionParameters | None = None + + +def _pose(payload): + return SquareTagPose(tuple(payload["quaternion_xyzw"]), + tuple(payload["translation_xyz_m"]), float(payload["reprojection_error_px"])) + + +def _image_references(record, roles): + from ..core.geometry.tag_pose.image_reference import IMAGE_REFERENCE_SOURCE, reference_from_evidence + return tuple(reference_from_evidence(item, stamp_ns=record["image_stamp_ns"], + camera_matrix=record["camera_matrix"]) for item in record["tags"].values() + if item.get("pose_source") == IMAGE_REFERENCE_SOURCE and item.get("tag_role") in roles) + + +def _finite_report(value): + if isinstance(value, float) and not math.isfinite(value): + return None + # Resume keeps large evidence rows as lazy Mapping objects. Solver reports + # are durable journal records, so materialize any nested mapping at this + # single ownership boundary instead of leaking storage-layer objects into + # the JSON encoder. + if isinstance(value, Mapping): + return {key: _finite_report(item) for key, item in value.items()} + if isinstance(value, (list, tuple)): + return [_finite_report(item) for item in value] + return value + + +def solve_initialization(request: BranchInitializationRequest): + """Pure expensive operation; the caller must check request identity again.""" + from .chain_reference import ChainReferenceRequest, solve_chain_reference + if isinstance(request, ChainReferenceRequest): + return solve_chain_reference(request) + if request.invalid_reason: + return MotionBranchResolution(False, request.invalid_reason) + if request.image_geometry: + if request.witness_sources and request.transition_source is not None: + return ImageMotionResolution(False, 'preparation_witness_composition_unsupported') + transition_rejections = () + if request.transition_source is not None: + from .preparation_transition import build_preparation_transition, PreparationTransitionUnavailable + from ..core.geometry.tag_pose.transition_image_solver import resolve_transition_motion + if request.pose_bridges or request.geometry_constraints or request.source_hinges or request.observer_sources: + return ImageMotionResolution(False, 'preparation_transition_constraints_unsupported') + try: + transition, record = build_preparation_transition(request.transition_profile, + request.transition_source, request.current_source_rows) + except PreparationTransitionUnavailable as error: + # Decline missing optional data before training. A completed + # transition fit or holdout failure never falls back to another + # model-selection attempt. + transition_rejections = (str(error),) + except (ValueError, KeyError, TypeError, IndexError) as error: + return ImageMotionResolution(False, str(error)) + else: + result = resolve_transition_motion(request.image_frames, request.relations, transition, + parameters=request.image_parameters) + return replace(result, preparation_transitions=(record,)) + bridges, records, rejections = [], [], [] + if request.observer_profile is not None: + from ..profiles.observer_policy import is_rigid_observer + required = {joint for joint, spec in request.observer_profile.measurement.measurements.items() + if joint in request.zero_joints and is_rigid_observer(spec.observer_pose_policy)} + if not required <= {source.joint for source in request.observer_sources}: + return ImageMotionResolution(False, 'rigid_pair_source_missing') + if request.observer_sources: + from .observer_reference import build_observer_bridge + for source in request.observer_sources: + try: + bridge, record = build_observer_bridge(request.observer_profile, source) + bridges.append(bridge) + records.append(record) + except (ValueError, KeyError, TypeError, IndexError) as error: + if is_rigid_observer(request.observer_profile.measurement.measurements[source.joint].observer_pose_policy): + return ImageMotionResolution(False, str(error)) + rejections.append(str(error)) + witness_bridges, witness_records = [], [] + if request.witness_sources: + from .preparation_witness import build_preparation_witness + if request.pose_bridges or request.observer_sources or request.geometry_constraints or request.source_hinges: + return ImageMotionResolution(False, 'preparation_witness_composition_unsupported') + for source in request.witness_sources: + try: + bridge, record = build_preparation_witness(request.witness_profile, source) + if bridge is not None: + witness_bridges.append(bridge) + witness_records.append(record) + except (ValueError, KeyError, TypeError, IndexError) as error: + return ImageMotionResolution(False, str(error)) + result = resolve_image_motion(request.image_frames, request.relations, + parameters=request.image_parameters, + geometry_constraints=request.geometry_constraints, source_urdf_sha256=request.source_urdf_sha256, + source_hinges=request.source_hinges, pose_bridges=request.pose_bridges+tuple(bridges)+tuple(witness_bridges)) + return replace(result, observer_pose_bridges=tuple(records), observer_rejections=tuple(rejections), + preparation_transition_rejections=transition_rejections, preparation_witnesses=tuple(witness_records)) + return resolve_motion_branches(request.frames, request.relations) + + +def initialization_artifacts(request, resolution): + """Bind each newly established physical-Tag branch to its actual evidence.""" + image_model = resolution.model if isinstance(resolution, ImageMotionResolution) else None + constraints = () if isinstance(resolution, ImageMotionResolution) else resolution.constraints + record = { + "kind": "motion_branch_initialization", "schema_version": 1, + "status": "resolved" if resolution.resolved else "unresolved", + "task_name": request.task_name, "view": request.view, + "zero_joints": list(request.zero_joints), + "session_epoch": request.session_epoch, "motion_version": request.motion_version, + "source_image_stamps": [frame.stamp_ns for frame in request.frames], + "source_frame_hashes": dict(request.source_frame_hashes), + "reason": resolution.reason, + "constraints": [asdict(model) for model in constraints], + "hypotheses": _finite_report([asdict(item) for item in resolution.hypotheses]), + "evidence_ids": {}, "evidence_payloads": {}, + "preparation_observation_rejections": dict(request.rejected_observations), + } + if request.source_motion_versions: + record.update(schema_version=2, approach_evidence_scope="path", + source_motion_versions=dict(request.source_motion_versions)) + if image_model is not None: + from ..core.geometry.tag_pose.image_motion_model import image_model_payload + payload = image_model_payload(image_model) + record["frozen_image_model"] = payload + record["image_model_sha256"] = hashlib.sha256(json.dumps( + payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest() + winner = (resolution.hypotheses[resolution.selected_hypothesis] + if resolution.selected_hypothesis is not None else + next(item for item in resolution.hypotheses if item.branches == image_model.branches)) + record["geometry_uncertainty"] = [list(item) for item in winner.child_frame_uncertainty] + if request.parent_reference_sha256: + record["parent_reference_sha256"] = request.parent_reference_sha256 + if request.pose_bridge_records: + record["shared_tag_pose_bridges"] = list(request.pose_bridge_records) + if isinstance(resolution, ImageMotionResolution) and resolution.observer_pose_bridges: + record["observer_pose_bridges"] = list(resolution.observer_pose_bridges) + if isinstance(resolution, ImageMotionResolution) and resolution.observer_rejections: + record["observer_rejections"] = list(resolution.observer_rejections) + if isinstance(resolution, ImageMotionResolution) and resolution.preparation_transitions: + record["preparation_transitions"] = list(resolution.preparation_transitions) + record["selected_hypothesis"] = resolution.selected_hypothesis + if isinstance(resolution, ImageMotionResolution) and resolution.preparation_transition_rejections: + record["preparation_transition_rejections"] = list(resolution.preparation_transition_rejections) + if isinstance(resolution, ImageMotionResolution) and resolution.preparation_witnesses: + record["preparation_witnesses"] = list(resolution.preparation_witnesses) + record["selected_hypothesis"] = resolution.selected_hypothesis + if request.image_geometry: + from ..core.geometry.tag_pose.production_image_motion import ( + DENSE_PREPARATION_SAMPLING, image_parameters_for_sampling, + ) + if request.image_parameters == image_parameters_for_sampling(DENSE_PREPARATION_SAMPLING): + record["image_sampling_policy"] = DENSE_PREPARATION_SAMPLING + if any(len(getattr(h, "training_solver_attempts", ())) > 1 for h in resolution.hypotheses): + from ..core.geometry.tag_pose.image_bundle_optimizer import IMAGE_BUNDLE_SOLVER_POLICY + record["image_solver_policy"] = IMAGE_BUNDLE_SOLVER_POLICY + record["image_solver_attempts"] = [ + {key: hypothesis[key] for key in ("branches", "training_solver_attempts", + "training_solver_status", "training_solver_evaluations")} + for hypothesis in record["hypotheses"]] + record["image_model_selection_policy"] = IMAGE_MODEL_SELECTION_POLICY + if request.pose_bridges: + record["image_model_selection_policy"] = shared_pose_selection_policy(request.pose_bridges) + if record.get("observer_pose_bridges"): + from ..core.geometry.tag_pose.pose_bridge import observer_pose_selection_policy, RIGID_OBSERVER_SELECTION_POLICY + record["image_model_selection_policy"] = (RIGID_OBSERVER_SELECTION_POLICY + if any(r.get('version') in {'observer_pose_bridge_v2', 'observer_pose_bridge_v3', + 'observer_pose_bridge_v4'} for r in record['observer_pose_bridges']) + else observer_pose_selection_policy(request.pose_bridges)) + if record.get("preparation_transitions"): + from ..core.geometry.tag_pose.transition_image_solver import TRANSITION_SELECTION_POLICY + record["image_model_selection_policy"] = TRANSITION_SELECTION_POLICY + if record.get("preparation_witnesses"): + from .preparation_witness import WITNESS_POLICY, INDEPENDENT_WITNESS_POLICY, CONDITIONED_WITNESS_POLICY + record["image_model_selection_policy"] = (INDEPENDENT_WITNESS_POLICY + if all(r.get('decision') == 'independent_before_fit' for r in record['preparation_witnesses']) + else CONDITIONED_WITNESS_POLICY + if any(r.get('conditioning') for r in record['preparation_witnesses']) else WITNESS_POLICY) + record["image_geometry_constraints"] = [asdict(item) for item in request.geometry_constraints] + record["source_urdf_sha256"] = request.source_urdf_sha256 + if request.image_geometry: + from ..core.geometry.tag_pose.image_solve_diagnosis import diagnose_image_solve_record + record["image_solve_diagnosis"] = diagnose_image_solve_record(record) + record = _finite_report(record) + if not resolution.resolved: + return None, record + existing = dict(request.existing_evidence_ids) + for role in request.moving_roles: + if role in existing: + record["evidence_ids"][role] = existing[role] + continue + payload = {key: record[key] for key in ( + "task_name", "view", "zero_joints", "session_epoch", "motion_version", + "source_image_stamps", "source_frame_hashes", "constraints", + )} + if request.source_motion_versions: + payload.update(approach_evidence_scope="path", + source_motion_versions=record["source_motion_versions"]) + if image_model is not None: + payload.update(frozen_image_model=record["frozen_image_model"], + image_model_sha256=record["image_model_sha256"], geometry_uncertainty=record["geometry_uncertainty"]) + if "image_solver_policy" in record: + payload.update(image_solver_policy=record["image_solver_policy"], + image_solver_attempts=record["image_solver_attempts"]) + if "image_sampling_policy" in record: + payload["image_sampling_policy"] = record["image_sampling_policy"] + if request.parent_reference_sha256: + payload["parent_reference_sha256"] = request.parent_reference_sha256 + if request.pose_bridge_records: + payload["shared_tag_pose_bridges"] = record["shared_tag_pose_bridges"] + from ..core.geometry.tag_pose.pose_bridge import is_handoff_policy + if is_handoff_policy(record['image_model_selection_policy']): + payload['image_model_selection_policy'] = record['image_model_selection_policy'] + if record.get("observer_pose_bridges"): + payload["observer_pose_bridges"] = record["observer_pose_bridges"] + if any(r.get('version') in {'observer_pose_bridge_v2', 'observer_pose_bridge_v3', + 'observer_pose_bridge_v4'} for r in record['observer_pose_bridges']): + payload['image_model_selection_policy'] = record['image_model_selection_policy'] + if record.get("preparation_transitions"): + payload["preparation_transitions"] = record["preparation_transitions"] + if record.get("preparation_witnesses"): + payload["preparation_witnesses"] = record["preparation_witnesses"] + payload["tag_role"] = role + encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False) + record["evidence_ids"][role] = hashlib.sha256(encoded.encode()).hexdigest() + record["evidence_payloads"][role] = payload + model = MotionBranchModel(request.task_name, request.view, constraints, + tuple(sorted(record["evidence_ids"].items())), image_model) + return model, record + + +class BranchInitialization: + """Bounded pre-zero evidence from an arrival or an explicitly declared path. + + Path capture begins only after reaching its first declared pose. Holding + channels, task, joint group and session epoch remain fixed across its legs. + Each selected frame keeps its original motion version and content hash. + """ + + def __init__(self, profile, *, image_geometry=True, source_urdf=None): + self.profile = profile + self.image_geometry = image_geometry + from ..profiles.preparation import preparation_image_budget + self.command_intervals, self.image_parameters = preparation_image_budget(profile) + self.source_model = None + self.source_urdf_sha256 = "" + self.tag_feedback_channels = None + if source_urdf is not None: + from ..core.urdf.kinematics import UrdfKinematicModel + from ..profiles.observations import compile_tag_feedback_channels + self.source_model = UrdfKinematicModel(source_urdf) + self.source_urdf_sha256 = hashlib.sha256(self.source_model.source.read_bytes()).hexdigest() + self.tag_feedback_channels = compile_tag_feedback_channels(profile, self.source_model) + self.generation = 0 + from .parent_reference import ParentReferenceRegistry + self.parent_references = ParentReferenceRegistry(profile, self.tag_feedback_channels) + self.observer_records = {} + from .observer_preparation import ObserverPreparation + self.observer_preparation = ObserverPreparation(self) + from .preparation_transition import PreparationTransitionCapture + self.transition_capture = PreparationTransitionCapture(self) + from .preparation_witness import PreparationWitnessCapture + self.witness_capture = PreparationWitnessCapture(self) + self.clear() + + def clear(self): + self.transition_capture.clear() + self._clear_motion() + + def _clear_motion(self): + self.generation += 1 + self.task_name = None + self.zero_joints = () + self.motion_version = None + self.session_epoch = None + self._frames = {} + self._source_records = {} + self._endpoint_records = {} + self._rejected_observations = {} + self._existing_ids = {} + self._held_feedback = None + self._invalid_reason = "" + self._requested = set() + self.reference_spec = None + self.parent_model_refresh_for = "" + self.reports = {} + self.path_index = None + + def begin(self, motion, *, session_epoch, motion_version): + if motion.preparation_witness_joint: + self.clear() + return + self.transition_capture.begin(motion, session_epoch) + if motion.reference_reuse or motion.reference_check: + self.clear() + return + if motion.phase == "zero_approach": + from ..profiles.preparation import preparation_image_budget + self.command_intervals, self.image_parameters = preparation_image_budget( + self.profile, joint_count=len(motion.reference_joints)) + index = motion.reference_path_index + identity = (motion.task_key, motion.reference_joints, session_epoch) + previous = (self.task_name, self.zero_joints, self.session_epoch) + continuing = (index is not None and index > 0 and identity == previous + and self.path_index is not None and index in {self.path_index, self.path_index + 1} + and self.motion_version is not None and motion_version > self.motion_version) + if not continuing: + self._clear_motion() + if index is not None and index != 0: + self._invalid_reason = "motion_approach_path_discontinuous" + self.path_index = index + self.reference_spec = (motion.reference_command, motion.reference_approach) if motion.reference_only else None + self.parent_model_refresh_for = motion.parent_model_refresh_for + self.task_name = motion.task_key + self.zero_joints = motion.reference_joints + self.motion_version = motion_version + self.session_epoch = session_epoch + elif motion.phase == "joint_zero": + if (self.task_name, self.zero_joints, self.session_epoch) != ( + motion.task_key, motion.zero_joints, session_epoch): + self._clear_motion() + self.task_name, self.zero_joints = motion.task_key, motion.zero_joints + self.session_epoch = session_epoch + self._invalid_reason = "motion_approach_evidence_missing" + self.parent_model_refresh_for = motion.parent_model_refresh_for + elif self.path_index is not None: + spec = self.profile.motion.joint_zero_references[motion.zero_joints[0]] + if spec.evidence_scope != "path" or self.path_index != len(spec.approach_commands): + self._invalid_reason = "motion_approach_path_incomplete" + + def _relations(self, view): + relations = [] + for name in self.zero_joints: + measurements = [self.profile.measurement.measurements[name]] + secondary = self.profile.measurement.cross_view_sources.get(name) + if secondary is not None: + measurements.append(self.profile.measurement.measurements[secondary]) + relations.extend(MotionRelation(name, spec.parent_role, spec.child_role) + for spec in measurements if spec.view == view) + return tuple(relations) + + def observe(self, record): + self.witness_capture.observe(record) + if record.get('preparation_witness_joint'): + return + self.transition_capture.observe(record) + if (record["task_name"], tuple(record["zero_joints"]), record["motion_version"], + record["session_epoch"]) != ( + self.task_name, self.zero_joints, self.motion_version, self.session_epoch): + return + if self.path_index is not None and (self.path_index == 0 + or record.get("reference_path_index") != self.path_index): + return + command, feedback = record["command_vector"], record["feedback_vector"] + if command is None or (feedback is None and not self.profile.vision_motion) or not self.zero_joints: + return + from ..core.domain.profile import JointZeroSpec + spec = (JointZeroSpec(self.task_name, *self.reference_spec) if self.reference_spec else + self.profile.motion.joint_zero_references[self.zero_joints[0]]) + if (spec.evidence_scope == "path") != (self.path_index is not None): + self._invalid_reason = "motion_approach_scope_mismatch" + return + from ..core.fitting.motion_fit import channel_for_joint + index = channel_for_joint(self.profile, self.zero_joints[0]) + moving_channels = {i for i, v in enumerate(spec.approach_commands[-1]) if v != spec.command[i]} + # The current measured channel moves; every other declared command + # must already be in this reference's actual clearance/holding pose. + if any(abs(value - spec.command[i]) > 1e-9 + for i, value in enumerate(command) if i not in moving_channels): + return + relations = self._relations(record["view"]) + if not relations: + return + # Full commands above retain the declared avoidance posture. Only + # ancestors of the observed Tags can invalidate their hinge geometry. + # Historical callers without source topology retain the full check. + relevant_channels = (set(range(self.profile.command.command_count)) + if self.tag_feedback_channels is None else set().union(*( + self.tag_feedback_channels[role] for relation in relations + for role in (relation.parent_role, relation.child_role)))) + held_channels = relevant_channels - moving_channels + if feedback is not None and self._held_feedback is None: + self._held_feedback = tuple(feedback) + layout = self.profile.command + for i, value in enumerate(() if self.profile.vision_motion else feedback): + tolerance = max(1.0 if layout.unit == "u8" else 0.002, + 0.005 * (layout.maximum_feedback_values[i] - layout.minimum_feedback_values[i])) + if i in held_channels and abs(value - self._held_feedback[i]) > tolerance: + self._invalid_reason = "motion_held_feedback_changed" + return + roles = tuple(dict.fromkeys(role for relation in relations + for role in (relation.parent_role, relation.child_role))) + items, existing = [], self._existing_ids.setdefault(record["view"], {}) + frame_evidence_ids = {} + for role in roles: + item = record["tags"].get(role) + if item is None: + return + diagnostics = item["candidate_diagnostics"] + if diagnostics.get("observation_stamp_ns") != record["image_stamp_ns"]: + return + frozen = diagnostics.get("branch_frozen") is True + if frozen: + if item["selected_pose"] is None: + return + candidates = (_pose(item["selected_pose"]),) + evidence_id = diagnostics.get("motion_evidence_id") + if evidence_id: + if existing.get(role, evidence_id) != evidence_id: + self._invalid_reason = "motion_frozen_evidence_changed" + return + frame_evidence_ids[role] = evidence_id + else: + candidates = tuple(_pose(p) for p in item["reprojection_valid_candidates"]) + items.append(RoleCandidates(role, candidates, frozen)) + frame = MotionEvidenceFrame(record["image_stamp_ns"], tuple(items)) + from ..core.geometry.tag_pose.motion_evidence import motion_frame_rejection + rejection = motion_frame_rejection(frame, relations, require_frozen_roots=self.image_geometry) + if rejection: + counts = self._rejected_observations.setdefault(record["view"], {}) + counts[rejection] = counts.get(rejection, 0)+1 + return + existing.update(frame_evidence_ids) + lower, upper = layout.minimum_values[index], layout.maximum_values[index] + # Preserve native u8 command positions instead of discarding roughly + # half of an already recorded approach. There is still only one image + # per interval; stationary repeats cannot inflate the sample count. + bin_index = round(self.command_intervals * (command[index] - lower) / (upper - lower)) + # A dropout must not erase an earlier eligible image of this same + # motion interval. Every retained image still needs full model and + # held-out validation; admission itself does not authorize a branch. + self._frames.setdefault(record["view"], {})[bin_index] = frame + self._source_records.setdefault(record["view"], {})[bin_index] = record + self.observer_records[(self.session_epoch, self.task_name, record['view'])] = { + row['image_stamp_ns']: row for row in self._source_records[record['view']].values()} + # Keep a separate bounded stationary tail. Repeated endpoint images + # must not inflate the arc's motion bins or enter its holdout split. + tail = self._endpoint_records.setdefault(record['view'], deque( + maxlen=max(10, self.profile.acquisition.fixed_reference_minimum_frames)+1)) + if tuple(command) == tuple(spec.command): + if not tail or record['image_stamp_ns'] > tail[-1]['image_stamp_ns']: + tail.append(record) + else: + tail.clear() + + def request(self, view, motion, *, session_epoch, motion_version, zero_references=None): + if motion is None or motion.reference_reuse or motion.reference_check or motion.phase != "joint_zero" or view in self._requested: + return None + if (self.task_name, self.zero_joints, self.session_epoch) != ( + motion.task_key, motion.zero_joints, session_epoch): + return None + relations = self._relations(view) + if not relations: + return None + self._requested.add(view) + roles = {role for relation in relations for role in (relation.parent_role, relation.child_role)} + moving = tuple(sorted(tag.role for v in self.profile.vision.views if v.name == view + for tag in v.tags if tag.role in roles and not tag.fixed_reference)) + frames = tuple(sorted(self._frames.get(view, {}).values(), key=lambda frame: frame.stamp_ns)) + sources = tuple(self._source_records.get(view, {}).values()) + by_stamp = {row["image_stamp_ns"]: row for row in sources} + image_frames, reason = (), self._invalid_reason + if self.image_geometry: + try: + image_frames = tuple(ImageMotionFrame(frame, + tuple(tuple(float(v) for v in values) for values in by_stamp[frame.stamp_ns]["camera_matrix"]), + tuple(ImageRoleObservation(item.role, + float(by_stamp[frame.stamp_ns]["tags"][item.role]["tag_size_m"]), + tuple(tuple(float(v) for v in point) for point in + by_stamp[frame.stamp_ns]["tags"][item.role]["corners_xy"])) + for item in frame.roles), + _image_references(by_stamp[frame.stamp_ns], {item.role for item in frame.roles})) + for frame in frames) + except (KeyError, TypeError, ValueError): + reason = reason or "image_motion_preparation_pixels_missing" + geometry_constraints = () + pose_bridges, pose_bridge_records = (), () + if self.image_geometry and zero_references and not motion.reference_only: + from .shared_tag_reference import prepare_pose_bridges + try: + pose_bridges, pose_bridge_records = prepare_pose_bridges(self, view, zero_references, + self._endpoint_records.get(view, ()), {f.stamp_ns for f in frames}, session_epoch) + except (ValueError, KeyError, TypeError, IndexError) as error: + reason = reason or 'shared_pose_bridge_invalid:' + str(error) + source_hinges, parent_reference_sha256 = (), "" + task = next(task for task in self.profile.motion.tasks if task.key == self.task_name) + if task.parent_reference is not None and not self.parent_model_refresh_for: + try: + source_hinges, parent_reference_sha256 = self.parent_references.geometry(task, session_epoch) + except ValueError as error: + reason = reason or str(error) + if self.image_geometry and self.source_model is not None: + from ..profiles.observations import compile_parallel_axis_geometry + geometry_constraints = compile_parallel_axis_geometry(self.profile, self.source_model, + tuple(item.geometry.relation for item in source_hinges) + relations) + from .observer_reference import observer_inputs + observer_sources = observer_inputs(self, view, self._endpoint_records.get(view, ()), + {f.stamp_ns for f in frames}, session_epoch) if ( + self.image_geometry and not self.parent_model_refresh_for) else () + transition_source = None + if self.image_geometry and not self.parent_model_refresh_for: + try: + transition_source = self.transition_capture.snapshot(view) + except ValueError as error: + reason = reason or str(error) + witness_sources = self.witness_capture.inputs(view, self.zero_joints, + self._endpoint_records.get(view, ()), {f.stamp_ns for f in frames}, session_epoch) if ( + self.image_geometry and not self.parent_model_refresh_for) else () + return BranchInitializationRequest(self.task_name, view, self.zero_joints, + session_epoch, self.motion_version if self.motion_version is not None else motion_version, self.generation, + frames, + relations, tuple(sorted(self._existing_ids.get(view, {}).items())), moving, + tuple(sorted((str(row["image_stamp_ns"]), source_frame_sha256(row)) + for row in sources)), reason, image_frames, self.image_geometry, + geometry_constraints, self.source_urdf_sha256 if geometry_constraints else "", + tuple(sorted((str(row["image_stamp_ns"]), row["motion_version"]) + for row in sources)) if self.path_index is not None else (), source_hinges, parent_reference_sha256, + pose_bridges, pose_bridge_records, + tuple(sorted(self._rejected_observations.get(view, {}).items())), observer_sources, + self.profile, transition_source, + self.profile if transition_source is not None else None, + tuple(sorted(sources, key=lambda row: row['image_stamp_ns'])) if transition_source is not None else (), + witness_sources, self.profile if witness_sources else None, self.image_parameters) + + def pending(self): + """A bounded preparation solve is running outside the state lock.""" + return bool(self._requested - self.reports.keys()) + + def accept(self, request, resolution): + if request.generation != self.generation: + return None + model, report = initialization_artifacts(request, resolution) + if model is not None: + self.parent_references.remember(model, report) + self.reports[request.view] = report + return model, report + + def error(self): + for view, report in sorted(self.reports.items()): + if report["status"] != "resolved": + return f"view={view}:joints={','.join(self.zero_joints)}:{report['reason']}" + return "" + + def ready(self, motion): + if (motion.task_key, motion.zero_joints) != (self.task_name, self.zero_joints): + return False + views = [view.name for view in self.profile.vision.views if self._relations(view.name)] + return bool(views) and all(self.reports.get(view, {}).get("status") == "resolved" for view in views) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_tracking.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_tracking.py new file mode 100644 index 0000000..fbc7efc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_tracking.py @@ -0,0 +1,107 @@ +"""Apply an immutable task-local model to actual same-image Tag candidates.""" + +from ..core.geometry.tag_pose.motion_evidence import MotionEvidenceFrame, RoleCandidates, select_motion_frame +from ..core.geometry.tag_pose.motion_image_types import ImageMotionFrame, ImageRoleObservation +from ..core.geometry.tag_pose.tracking import MotionPoseSelection, SquareTagPoseTracker + + +class CommittedPoseEvidence: + """Read the metadata copied atomically with this frame's joint decision.""" + + def __init__(self, tracker, managed_roles, snapshots): + self.tracker = tracker + self.managed_roles = frozenset(managed_roles) + self.snapshots = {item.role: item for item in snapshots} + + def observation_snapshot(self, role, stamp_ns): + if role not in self.managed_roles: + return self.tracker.observation_snapshot(role, stamp_ns) + item = self.snapshots.get(role) + if item is None or item.stamp_ns != stamp_ns: + return None + return item.candidates, dict(item.diagnostics), item.corrections + + +def select_motion_poses(frame, model, tracker, selected, *, base, cached, + projection_worker=None, reference_tracker=None): + """Called outside the session lock; tracker commits check image versions.""" + if model.image_model is not None: + return _select_image_poses(frame, model, tracker, selected, + projection_worker=projection_worker, reference_tracker=reference_tracker) + ids = dict(model.evidence_ids) + roles = tuple(dict.fromkeys(role for constraint in model.constraints + for role in (constraint.relation.parent_role, constraint.relation.child_role))) + snapshots, candidates = {}, [] + for role in roles: + if role in ids: + snapshot = tracker.motion_snapshot(role, frame.stamp_ns) + if snapshot is not None and snapshot.motion_managed: + snapshots[role] = snapshot + poses = () if snapshot is None else snapshot.candidates + candidates.append(RoleCandidates(role, poses)) + else: + pose = selected.get(role) + if (pose is None and role == base.role and cached is not None + and role not in frame.corners and role not in frame.observed_roles): + pose = cached[0] # Same verified stationary-cache contract as capture. + candidates.append(RoleCandidates(role, () if pose is None else (pose,), frozen=True)) + decision = select_motion_frame(model.constraints, candidates) + if not decision.resolved or set(snapshots) != set(ids): + reason = "pose_branch_" + (decision.reason if not decision.resolved else "motion_candidates_missing") + rejected = SquareTagPoseTracker.reject_motion_frame(tuple(snapshots.values()), reason) + evidence = CommittedPoseEvidence(tracker, ids, rejected.observation_snapshots) + return {}, {role: rejected.reason for role in ids}, evidence + proposals = tuple(MotionPoseSelection(snapshots[item.role], item.pose, ids[item.role]) + for item in decision.selections if item.role in ids) + result = SquareTagPoseTracker.commit_motion_frame(proposals, + establish=any(snapshot.evidence_id is None for snapshot in snapshots.values())) + evidence = CommittedPoseEvidence(tracker, ids, result.observation_snapshots) + if not result.accepted: + return {}, {role: result.reason for role in ids}, evidence + return {item.snapshot.role: item.pose for item in result.selections}, {}, evidence + + +def _select_image_poses(frame, model, tracker, selected, *, projection_worker=None, reference_tracker=None): + """The model owns its children; already frozen parents keep their identity.""" + image_model = model.image_model + children = {item.relation.child_role for item in image_model.geometry} + ids = {role: identity for role, identity in model.evidence_ids if role in children} + snapshots, candidates, observations = {}, [], [] + for role, size in image_model.tag_sizes: + if role not in frame.corners: + continue + observations.append(ImageRoleObservation(role, size, + tuple(tuple(float(v) for v in point) for point in frame.corners[role]))) + if role in children: + snapshot = tracker.motion_snapshot(role, frame.stamp_ns) + if snapshot is not None and snapshot.motion_managed: + snapshots[role] = snapshot + candidates.append(RoleCandidates(role, snapshot.candidates)) + elif role in selected: + candidates.append(RoleCandidates(role, (selected[role],), frozen=True)) + image_frame = ImageMotionFrame(MotionEvidenceFrame(frame.stamp_ns, tuple(candidates)), + tuple(tuple(float(v) for v in row) for row in frame.camera_matrix), tuple(observations), + image_model.reference_frames) + roots = () + if image_model.reference_frames: + reference_roles = {ref.role for ref in image_model.reference_frames} + root_snapshots = [] + for role in sorted(set(dict(image_model.tag_sizes)) - children): + provider = reference_tracker if role in reference_roles else tracker + snapshot = None if provider is None else provider.motion_snapshot(role, frame.stamp_ns) + if snapshot is not None: + root_snapshots.append(snapshot) + roots = tuple(root_snapshots) + decision = SquareTagPoseTracker.verify_image_motion_frame(tuple(snapshots.values()), + image_model, image_frame, ids, projection_worker=projection_worker, root_snapshots=roots) + if not decision.accepted: + reason = "pose_branch_" + decision.reason + rejected = SquareTagPoseTracker.reject_motion_frame(tuple(snapshots.values()), reason) + evidence = CommittedPoseEvidence(tracker, children, rejected.observation_snapshots) + return {}, {role: rejected.reason for role in children}, evidence + result = SquareTagPoseTracker.commit_image_motion_frame(decision, + establish=any(snapshot.evidence_id is None for snapshot in snapshots.values())) + evidence = CommittedPoseEvidence(tracker, children, result.observation_snapshots) + if not result.accepted: + return {}, {role: result.reason for role in children}, evidence + return {item.snapshot.role: item.pose for item in result.selections}, {}, evidence diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_worker.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_worker.py new file mode 100644 index 0000000..6c1a137 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/branch_worker.py @@ -0,0 +1,73 @@ +"""Run immutable geometry requests outside the ROS interpreter and its GIL.""" + +import multiprocessing +import threading +import time +import traceback + +from .branch_initialization import solve_initialization +from .branch_diagnostics import record_solver_event +from ..core.geometry.tag_pose.motion_evidence import MotionBranchResolution + + +def _solve(connection, request, diagnostic_path): + started, cpu = time.monotonic(), time.thread_time() + try: + result = solve_initialization(request) + if diagnostic_path is not None: + record_solver_event(diagnostic_path, request, "worker_solve_finished", + stamp_ns=time.time_ns(), monotonic_time=time.monotonic(), + elapsed_seconds=time.monotonic()-started, + thread_cpu_seconds=time.thread_time()-cpu, + resolved=result.resolved, reason=result.reason) + connection.send((result, None)) + except Exception: + connection.send((None, traceback.format_exc())) + finally: + connection.close() + + +class IsolatedBranchSolver: + """One bounded child per request; children have no SDK or ROS interfaces. + + Cancellation only stops computation. The coordinator's epoch and motion + checks remain the sole authority for accepting a returned resolution. + """ + + def __init__(self, diagnostic_path=None, *, timeout_seconds=120.): + self.diagnostic_path = diagnostic_path + self.timeout_seconds = timeout_seconds + self._closed = threading.Event() + + def __call__(self, request): + if self._closed.is_set(): + return MotionBranchResolution(False, "image_motion_solver_cancelled") + context = multiprocessing.get_context("spawn") + receive, send = context.Pipe(duplex=False) + process = context.Process(target=_solve, args=(send, request, self.diagnostic_path), daemon=True) + started = time.monotonic() + try: + process.start() + send.close() + while not self._closed.is_set(): + if receive.poll(.05): + result, error = receive.recv() + if error is not None: + raise RuntimeError(f"geometry worker failed:\n{error}") + return result + if time.monotonic()-started >= self.timeout_seconds: + return MotionBranchResolution(False, "image_motion_solver_timeout") + if not process.is_alive(): + raise RuntimeError(f"geometry worker exited without result: {process.exitcode}") + return MotionBranchResolution(False, "image_motion_solver_cancelled") + finally: + receive.close() + send.close() + if process.pid is not None: + if process.is_alive(): + process.terminate() + process.join() + process.close() + + def close(self): + self._closed.set() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/camera_preflight.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/camera_preflight.py new file mode 100644 index 0000000..74315b5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/camera_preflight.py @@ -0,0 +1,48 @@ +"""Describe the evidence available before motion without claiming optical validation.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from typing import TYPE_CHECKING, Literal, Mapping + +if TYPE_CHECKING: + from .snapshot import CameraReadiness + + +@dataclass(frozen=True) +class CameraCheck: + status: Literal["passed", "failed", "unverified"] + reason: str + suggestion: str = "" + + +@dataclass(frozen=True) +class CameraPreflight: + configuration: Mapping[str, CameraCheck] + intrinsics: CameraCheck + extrinsics: CameraCheck + + @classmethod + def from_readiness(cls, cameras: Mapping[str, CameraReadiness]) -> CameraPreflight: + configuration = {} + for view, camera in cameras.items(): + if camera.error: + check = CameraCheck("failed", camera.error, + "检查相机绑定、分辨率和内参文件;参数不匹配时不能开始,不能只更新哈希绕过检查。") + elif camera.camera_info_ready: + check = CameraCheck("passed", "实时 CameraInfo 参数与受保护外参记录一致") + else: + check = CameraCheck("unverified", "未收到有效、新鲜的 CameraInfo", + "检查相机出图和 CameraInfo 发布;收到匹配参数后重新检查。") + configuration[view] = check + # Hand/Tag placement is allowed to change before Start. Neither old + # palm pixels nor the CameraInfo hash establishes physical validity. + # No live geometric verification is implemented in this path yet. + return cls(configuration, + CameraCheck("unverified", "仅核对加载参数,未实测验证当前焦距、畸变等光学内参", + "镜头或成像设置变化后需重新核验内参;现有手上 Tag 的单次姿态不足以证明内参有效。"), + CameraCheck("unverified", "缺少已验证的跨机位共同观测,无法确认当前相机相对外参", + "相机相对位置变化后需重新核验外参;重新锁定手掌 Tag 不能替代外参检查。")) + + def as_dict(self) -> dict: + return asdict(self) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/cameras.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/cameras.py new file mode 100644 index 0000000..e6832e1 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/cameras.py @@ -0,0 +1,71 @@ +"""Protected rectified camera identity and live pipeline readiness.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Callable + +import numpy as np + +from ..core.geometry.extrinsics import CameraExtrinsics, camera_info_fingerprint +from ..storage import append_jsonl +from .inputs import CameraModelInput + + +class CameraObservations: + def __init__(self, extrinsics: CameraExtrinsics, raw_path: Path, monotonic: Callable[[], float]): + self.extrinsics = extrinsics + self.raw_path = raw_path + self.monotonic = monotonic + self.matrices: dict[str, np.ndarray] = {} + self.image_sizes: dict[str, tuple[int, int]] = {} + self.info_received_at: dict[str, float] = {} + self.detections_received_at: dict[str, float] = {} + self.errors: dict[str, str] = {} + self.models: dict[str, dict] = {} + + def accept(self, view: str, message: CameraModelInput, *, started: bool, pause, trackers) -> None: + from ..core.geometry.camera import rectified_camera_matrix + try: + matrix = rectified_camera_matrix(message.p) + if message.width <= 0 or message.height <= 0: + raise ValueError('invalid rectified image dimensions') + identity = self.extrinsics.cameras[view] + fingerprint = camera_info_fingerprint( + width=message.width, height=message.height, camera_matrix=message.k, + distortion=message.d, rectification=message.r, projection=message.p) + if (message.width != identity.width or message.height != identity.height + or fingerprint != identity.intrinsics_sha256): + raise ValueError('camera_info_does_not_match_extrinsics') + except ValueError as error: + self.errors[view] = str(error) + self.info_received_at.pop(view, None) + if started: + pause(f"protected_camera_model_changed:{view}:{error}") + self.matrices.pop(view, None) + self.image_sizes.pop(view, None) + return + previous = self.matrices.get(view) + dimensions = (int(message.width), int(message.height)) + if started and previous is not None and ( + not np.array_equal(previous, matrix) or self.image_sizes.get(view) != dimensions + ): + pause(f"protected_camera_model_changed:{view}:intrinsics_or_dimensions") + return + self.matrices[view] = matrix + self.image_sizes[view] = (int(message.width), int(message.height)) + self.info_received_at[view] = self.monotonic() + self.errors.pop(view, None) + model = { + 'kind': 'rectified_camera_model', 'view': view, + 'matrix_source': 'CameraInfo.P[:3,:3]', + 'width': int(message.width), 'height': int(message.height), + 'raw_k': list(message.k), 'raw_d': list(message.d), + 'rectification_r': list(message.r), 'projection_p': list(message.p), + 'camera_matrix': matrix.tolist(), 'input_is_rectified': True, + } + if self.models.get(view) != model: + self.models[view] = model + append_jsonl(self.raw_path, model) + if previous is not None and not np.allclose(previous, matrix): + trackers[view].reset() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/capture.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/capture.py new file mode 100644 index 0000000..5586c50 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/capture.py @@ -0,0 +1,767 @@ +"""Profile observation capture shared by every SDK and ROS camera host.""" + +from collections import deque +from contextlib import ExitStack +from dataclasses import asdict, dataclass, replace +from threading import RLock + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.domain.motion_path import segment_metadata +from ..core.fitting.motion_fit import channel_for_joint +from ..core.geometry.extrinsics import matrix_payload, transform_matrix +from ..core.geometry.pnp import SquareTagPose, SquareTagPoseTracker +from ..core.geometry.tag_pose.fixed_reference import FixedTagReference +from ..core.geometry.image_motion_replay import has_image_model +from .pose_evidence import snapshot_pose_evidence +from .scan_quality import observation_streams +from .branch_initialization import MotionBranchModel +from .branch_tracking import select_motion_poses + + +@dataclass(frozen=True) +class CaptureTiming: + received_stamp_ns: int + history_snapshot_stamp_ns: int + latest_feedback_stamp_ns: int | None + latest_command_stamp_ns: int | None + + +@dataclass(frozen=True) +class CaptureFrame: + view: str + stamp_ns: int + camera_matrix: np.ndarray + corners: dict + feedback: tuple[float, ...] | None + command: tuple[float, ...] | None + skew_ns: int = 0 + command_directions: tuple[str, ...] = () + observed_roles: frozenset[str] = frozenset() + timing: CaptureTiming | None = None + command_skew_ns: int | None = None + detection_quality: dict | None = None + + +class _FramePoseEvidence: + """Keep each model's atomic current-frame metadata after parent-chain solves.""" + + def __init__(self, tracker): + self.tracker = tracker + self.by_role = {} + + def register(self, roles, snapshot): + self.by_role.update((role, snapshot) for role in roles) + + def observation_snapshot(self, role, stamp_ns): + return self.by_role.get(role, self.tracker).observation_snapshot(role, stamp_ns) + + +class ObservationCapture: + def __init__(self, profile, *, reference_lock, extrinsics, tag_size_m=0.016, trackers=None, + projection_worker=None): + self.profile, self.reference_lock, self.extrinsics = profile, reference_lock, extrinsics + self.projection_worker = projection_worker + self.tag_size_m = float(tag_size_m) + self.trackers = trackers or {view.name: SquareTagPoseTracker() + for view in profile.vision.views} + self._metadata_lock = RLock() + self._metadata_generation = 0 + self._latest_stamp_by_view = {} + self._poses = {} + self._pose_revisions = {} + self.locked_poses = {} + self.locked_revisions = {} + self.installations = {} + self._installation_revisions = {} + self.last_missing = {} + self.last_filtered = {} + self._branch_events_active = set() + self._motion_models = {} + self._preparation_identity = None + from .image_reference import ImageReferenceTracker + from ..core.domain.capture_plan import raw_feedback_capture + # Raw feedback sessions must retain the pre-motion stationary image + # source. The root's camera-aligned frame is a coordinate convention, + # never a selected planar Tag normal or an online joint zero. + self._image_references = ({view.name: ImageReferenceTracker( + profile.acquisition.fixed_reference_minimum_frames) for view in profile.vision.views} + if profile.acquisition.fixed_reference_mode == "stationary_image" + or raw_feedback_capture(profile) else {}) + self._model_image_references = {} + self._active_image_references = dict(self._image_references) + + def reset(self): + with self._metadata_lock: + self._metadata_generation += 1 + self._latest_stamp_by_view.clear() + self._poses.clear() + self._pose_revisions.clear() + self.locked_poses.clear() + self.locked_revisions.clear() + self.installations.clear() + self._installation_revisions.clear() + self.last_missing.clear() + self.last_filtered.clear() + self._branch_events_active.clear() + self._motion_models.clear() + for tracker in self._model_image_references.values(): + tracker.reset() + self._model_image_references.clear() + self._active_image_references = dict(self._image_references) + self._preparation_identity = None + for tracker in self.trackers.values(): + tracker.reset() + for tracker in self._image_references.values(): + tracker.reset() + + def begin_motion(self, motion): + """Reauthorize reused Tags when their driven hinge or holding pose changes. + + Only the declared task scope permits replacement. Recorded evidence and + frozen joint zeros remain immutable; dependent image models are dropped + together, so an old child can never use a newly interpreted parent. + """ + if self.profile.acquisition.motion_model_scope != "task" or motion.phase != "zero_approach" or motion.reference_check: + return + identity = (motion.task_key, motion.reference_joints) + with self._metadata_lock: + if identity == self._preparation_identity: + return + self._preparation_identity = identity + requested = {self.profile.measurement.measurements[name].child_role + for name in motion.reference_joints} + self._release_model_roles(requested) + + def _release_model_roles(self, requested): + """Caller owns metadata lock; invalidate all downstream interpretations.""" + removed, roles = set(), set(requested) + while True: + affected = {key for key, model in self._motion_models.items() + if self._model_children(model) & roles or any( + g.relation.parent_role in roles for g in ( + model.constraints if model.image_model is None else model.image_model.geometry))} + if affected <= removed: + break + removed.update(affected) + roles.update(role for key in affected for role in self._model_children(self._motion_models[key])) + for key in removed: + del self._motion_models[key] + self._metadata_generation += 1 + for view in self.profile.vision.views: + reset = roles & {tag.role for tag in view.tags if not tag.fixed_reference} + if reset: + self.trackers[view.name].reset_roles(reset) + + def activate_reference_model(self, model): + """Reinstall immutable evidence for a declared stationary pose check.""" + if self.profile.acquisition.motion_model_scope != "task": + raise ValueError("parent_reference_requires_task_model_scope") + with self._metadata_lock: + self._release_model_roles(self._model_children(model)) + self._preparation_identity = None + self.install_motion_model(model) + + def current_image_reference_stable(self, view): + """Check the independent current-session anchor, not an active old model.""" + tracker = self._image_references.get(view) + return tracker is not None and tracker.tracking_current_image() + + def install_motion_model(self, model: MotionBranchModel): + """Add evidence before zero capture without replacing existing roles.""" + key = (model.task_name, model.view) + if self.profile.acquisition.motion_model_scope == "task": + key += (tuple(sorted(self._model_children(model))),) + with self._metadata_lock: + owned = self._model_children(model) + for installed in self._motion_models.values(): + if installed.view != model.view: + continue + shared = owned & self._model_children(installed) + if shared and any(dict(installed.evidence_ids).get(role) != dict(model.evidence_ids).get(role) + for role in shared): + raise ValueError("motion_branch_evidence_replacement_forbidden") + if shared and installed.image_model != model.image_model: + raise ValueError("image_motion_model_replacement_forbidden") + previous = self._motion_models.get(key) + if previous is not None: + ids, new_ids = dict(previous.evidence_ids), dict(model.evidence_ids) + if any(ids[role] != new_ids[role] for role in ids.keys() & new_ids.keys()): + raise ValueError("motion_branch_evidence_replacement_forbidden") + old = {item.relation.joint: item for item in previous.constraints} + for item in model.constraints: + if item.relation.joint in old and old[item.relation.joint] != item: + raise ValueError("motion_constraint_replacement_forbidden") + old[item.relation.joint] = item + if (previous.image_model is not None and model.image_model is not None + and previous.image_model != model.image_model): + raise ValueError("image_motion_model_replacement_forbidden") + model = MotionBranchModel(model.task_name, model.view, + tuple(old.values()), tuple(sorted({**ids, **new_ids}.items())), + image_model=model.image_model or previous.image_model) + if previous != model: + self._metadata_generation += 1 + self._motion_models[key] = model + if model.image_model is not None and model.view in self._image_references: + from .image_reference import ImageReferenceTracker + for reference in model.image_model.reference_frames: + reference_key = (model.view, reference.identity) + if reference_key not in self._model_image_references: + self._model_image_references[reference_key] = ImageReferenceTracker( + self.profile.acquisition.fixed_reference_minimum_frames, + reference=reference) + + def _scheduled_image_reference(self, view, models): + """Choose one coordinate convention for this frame's complete ancestry. + + Inactive models may belong to different sessions. Active models must + agree on the fixed root; mixing coordinates in a persisted frame would + invalidate its geometry and replay evidence. The caller owns metadata. + """ + references = {ref.identity: ref for model in models if model.image_model is not None + for ref in model.image_model.reference_frames} + if len(references) > 1: + return None + current = self._image_references.get(view) + if not references or current is None: + return current + identity, reference = next(iter(references.items())) + if current.reference == reference: + return current + return self._model_image_references[(view, identity)] + + @staticmethod + def _model_children(model): + geometry = model.constraints if model.image_model is None else model.image_model.geometry + return {item.relation.child_role for item in geometry} + + def _observed_joint_names(self, motion): + if motion is None: + return () + task = next((task for task in self.profile.motion.tasks if task.key == motion.task_key), None) + return (motion.zero_joints or motion.reference_joints or motion.observed_joints + or (() if task is None else task.joints)) + + def _observed_roles(self, motion): + names = set(self._observed_joint_names(motion)) + names.update(self.profile.measurement.cross_view_sources[name] for name in tuple(names) + if name in self.profile.measurement.cross_view_sources) + return {role for name in names for role in ( + self.profile.measurement.measurements[name].parent_role, + self.profile.measurement.measurements[name].child_role)} + + def _motion_model_schedule(self, view, motion): + """Keep installed identities while any task, return or idle pose changes. + + A model-authorized Tag can never return to independent IPPE selection. + Session scope tracks the installed chain through clearance and return. + Task scope selects the current observations and their parent models; + inactive frozen roles are not passed to independent pose selection. + """ + + available = {key: model for key, model in self._motion_models.items() if model.view == view} + if not available: + return () + owners = {role: key for key, model in available.items() for role in self._model_children(model)} + ordered, visiting, visited = [], set(), set() + + def include(key): + if key in visited: + return + if key in visiting: + raise ValueError("image_motion_model_dependency_cycle") + visiting.add(key) + model = available[key] + geometry = model.constraints if model.image_model is None else model.image_model.geometry + roots = {item.relation.parent_role for item in geometry} - self._model_children(model) + for role in sorted(roots): + if role in owners and owners[role] != key: + include(owners[role]) + visiting.remove(key) + visited.add(key) + ordered.append(model) + + selected_keys = set(available) + if self.profile.acquisition.motion_model_scope == "task": + selected_keys = set() + if motion is not None and motion.task_key: + roles = self._observed_roles(motion) + selected_keys = {owners[role] for role in roles if role in owners} + for key in sorted(selected_keys): + include(key) + return tuple(ordered) + + @staticmethod + def _median_pose(poses): + return SquareTagPose( + quaternion_xyzw=tuple(Rotation.from_quat([p.quaternion_xyzw for p in poses]).mean().as_quat()), + translation_xyz_m=tuple(np.median([p.translation_xyz_m for p in poses], axis=0)), + reprojection_error_px=float(np.median([p.reprojection_error_px for p in poses]))) + + @staticmethod + def _image_model_roles(roles, evidence): + """Include frozen moving parents' complete ancestral image evidence.""" + required, pending = set(roles), list(roles) + while pending: + item = evidence.get(pending.pop(), {}) + model = item.get("frozen_image_model") + if model is None: + continue + ancestors = {role for role, _ in model["tag_sizes"]} - required + required.update(ancestors) + pending.extend(ancestors) + return required + + def _candidate_frame(self, frame, motion, task, roles, evidence, selected, locked): + """Persist the exact decision alongside unchanged original candidates.""" + observations = {} + for role in sorted(roles): + if role not in frame.corners and role not in locked: + continue + item = dict(evidence[role]) + pose = selected.get(role) + item.update(locked_reference=role in locked, + selected=None if pose is None else { + "quaternion_xyzw": list(pose.quaternion_xyzw), + "translation_xyz_m": list(pose.translation_xyz_m), + "reprojection_error_px": pose.reprojection_error_px}, + maximum_reprojection_error_px=self.trackers[frame.view].maximum_reprojection_error_px) + item.pop("selected_pose", None) + observations[role] = item + return {"kind": "pnp_candidate_frame", "task_name": task.key, + "cycle": motion.cycle, "direction": motion.direction, "attempt": motion.attempt, + **segment_metadata(motion.segment_key), + "view": frame.view, "image_stamp_ns": frame.stamp_ns, "tag_size_m": self.tag_size_m, + "sample_phase": motion.phase if motion.phase in {"steady", "joint_zero"} else "sweep", + "camera_matrix": frame.camera_matrix.tolist(), "camera_matrix_source": "CameraInfo.P[:3,:3]", + "input_is_rectified": True, "roles": observations} + + @staticmethod + def _observation_record(frame, motion, evidence, allow_recording, raw_joint, command_unit): + return {"kind": "raw_observation_frame" if raw_joint else "diagnostic_observation_frame", "view": frame.view, + "image_stamp_ns": frame.stamp_ns, "task_name": motion.task_key, + "cycle": motion.cycle, "direction": motion.direction, "attempt": motion.attempt, + **segment_metadata(motion.segment_key), + "sample_phase": motion.phase, "command_unit": command_unit, + **({"zero_joints": list(motion.zero_joints)} if motion.phase == "joint_zero" else {}), + **({"steady_index": motion.steady_index, + "steady_target": None if motion.command_index is None else motion.target[motion.command_index], + "minimum_hold_seconds": motion.minimum_hold_seconds, + "target_command_vector": list(motion.target), + "accepted_sample_window_open": bool(allow_recording)} if motion.phase == "steady" else {}), + "command_vector": None if frame.command is None else list(frame.command), + "feedback_vector": None if frame.feedback is None else list(frame.feedback), + "state_image_sync_error_ms": None if frame.feedback is None else abs(frame.skew_ns)/1e6, + "command_image_skew_ns": frame.command_skew_ns, + "command_direction_by_index": list(frame.command_directions), + **({"timing": asdict(frame.timing)} if frame.timing is not None else {}), + "camera_matrix": frame.camera_matrix.tolist(), "input_is_rectified": True, + "tags": evidence, + **({"observation_protocol": "raw_joint_images_v2"} if raw_joint else {}), "is_accepted_joint_sample": False} + + def _consume_raw(self, frame, motion, allow_recording): + # Only the fixed reference runs through pose tracking. Moving-tag + # evidence is independent of any PnP branch or online joint model. + with self._metadata_lock: + if frame.stamp_ns <= self._latest_stamp_by_view.get(frame.view, 0): + return (), None + events, movement = self.consume(frame, fixed_reference_only=True) + if motion is None or motion.phase not in {"sweep", "steady"}: + return events, movement + view = next(v for v in self.profile.vision.views if v.name == frame.view) + evidence = {tag.role: dict(tag_role=tag.role, tag_id=tag.tag_id, + tag_size_m=float(tag.size_m), corners_xy=np.asarray(frame.corners[tag.role]).tolist(), + image_stamp_ns=frame.stamp_ns, pose_source="raw_corners", + detection_quality=(frame.detection_quality or {}).get(tag.role, {})) + for tag in view.tags if tag.role in frame.corners} + record = self._observation_record(frame, motion, evidence, allow_recording, + raw_joint=True, command_unit=self.profile.command.unit) + return (*events, record), movement + + def consume(self, frame: CaptureFrame, motion=None, *, collect_installations=False, + diagnostic=False, allow_recording=True, accepted_joints: frozenset[str] | None = None, + fixed_reference_only=False, raw_joint=False): + if raw_joint: + return self._consume_raw(frame, motion, allow_recording) + if fixed_reference_only and (motion is not None or collect_installations): + raise ValueError("fixed reference monitoring cannot acquire motion or installations") + if frame.view not in self.reference_lock.fixed_tag_by_view: + return (), None + with self._metadata_lock: + if frame.stamp_ns <= self._latest_stamp_by_view.get(frame.view, 0): + return (), None + self._latest_stamp_by_view[frame.view] = frame.stamp_ns + generation = self._metadata_generation + models = () if fixed_reference_only else self._motion_model_schedule(frame.view, motion) + image_reference = self._scheduled_image_reference(frame.view, models) + view = next(v for v in self.profile.vision.views if v.name == frame.view) + tags = tuple(tag for tag in view.tags if not fixed_reference_only or tag.fixed_reference) + if self.profile.acquisition.motion_model_scope == "task" and (motion is not None or self._motion_models): + relevant = self._observed_roles(motion) + if motion is not None: + from .observer_reference import observer_roles + relevant.update(observer_roles(self.profile, motion)) + from .preparation_witness import witness_roles + relevant.update(witness_roles(self.profile, motion)) + relevant.update(role for model in models for role, _ in model.evidence_ids) + relevant.update(g.relation.parent_role for model in models for g in ( + model.constraints if model.image_model is None else model.image_model.geometry)) + tags = tuple(tag for tag in tags if tag.fixed_reference or tag.role in relevant) + base = next(tag for tag in view.tags if tag.fixed_reference) + cached = self.locked_reference(frame.view) + fixed_reference = None if cached is None else FixedTagReference(*cached) + selected, filtered, evidence, events, reasons = {}, [], {}, [], {} + evidence_tracker = _FramePoseEvidence(self.trackers[frame.view]) + managed_roles = {role for model in models for role in self._model_children(model)} + for tag in tags: + points = frame.corners.get(tag.role) + if points is None: + continue + if tag.fixed_reference and frame.view in self._image_references: + reference_tracker = self._image_references[frame.view] + pose, reason = reference_tracker.estimate(tag.role, points, + size=tag.size_m, matrix=frame.camera_matrix, stamp_ns=frame.stamp_ns, + locking=self.reference_lock.locking_enabled) + # Keep the session's independent drift witness live. A restored + # model additionally checks this same image against its own + # original root, preserving its geometry, hash and provenance. + if image_reference is None: + pose, reason = None, "image_reference_model_binding_conflict" + elif image_reference is not reference_tracker: + reference_tracker = image_reference + pose, reason = reference_tracker.estimate(tag.role, points, + size=tag.size_m, matrix=frame.camera_matrix, stamp_ns=frame.stamp_ns, + locking=False) + evidence_tracker.register((tag.role,), reference_tracker) + else: + pose, reason = self.trackers[frame.view].estimate(tag.role, points, + tag_size_m=tag.size_m, camera_matrix=frame.camera_matrix, stamp_ns=frame.stamp_ns, + fixed_reference=fixed_reference if tag.fixed_reference else None, + **({"motion_managed": True} if tag.role in managed_roles else {})) + reasons[tag.role] = reason + if pose is not None: + selected[tag.role] = pose + for model in models: + poses, rejected, model_evidence = select_motion_poses(frame, model, self.trackers[frame.view], selected, + base=base, cached=cached, + **({"reference_tracker": image_reference} + if frame.view in self._image_references else {}), + **({"projection_worker": self.projection_worker} if self.projection_worker is not None else {})) + evidence_tracker.register(self._model_children(model), model_evidence) + for role in rejected: + selected.pop(role, None) + selected.update(poses) + reasons.update({role: "" for role in poses}) + reasons.update(rejected) + for tag in tags: + points = frame.corners.get(tag.role) + if points is None: + continue + pose, reason = selected.get(tag.role), reasons[tag.role] + item = snapshot_pose_evidence({tag.role: tag}, {tag.role: points}, + {} if pose is None else {tag.role: pose}, evidence_tracker, (), + stamp_ns=frame.stamp_ns)[tag.role] + diagnostics = item["candidate_diagnostics"] + if diagnostics.get("observation_stamp_ns") != frame.stamp_ns: + # An early model-commit rejection may have no committed + # snapshot. Keep its actual cause; missing metadata alone + # does not prove that a newer camera frame superseded it. + pose, reason = None, reason or "pose_branch_observation_superseded" + elif pose is not None and diagnostics.get("branch_status") != "tracking": + pose, reason = None, "pose_branch_unconfirmed" + evidence[tag.role] = item + tracking_rejected = pose is None and ( + reason.startswith(("pose_", "image_reference")) or reason == "fixed_reference_pose_unverified") + if pose is None: + selected.pop(tag.role, None) + filtered.append(tag.tag_id) + if tracking_rejected: + events.append({"kind": "pnp_branch_event", "view": frame.view, + "image_stamp_ns": frame.stamp_ns, "tag_role": tag.role, + "tag_id": tag.tag_id, "reason": reason, + "task_name": None if motion is None else motion.task_key, + "motion_phase": None if motion is None else motion.phase, + "command_unit": self.profile.command.unit, + "command_vector": None if frame.command is None else list(frame.command), + "feedback_vector": None if frame.feedback is None else list(frame.feedback), + "state_image_sync_error_ms": None if frame.feedback is None else abs(frame.skew_ns)/1e6, + **({"timing": asdict(frame.timing)} if frame.timing is not None else {}), + "pnp_observation_evidence": item}) + else: + selected[tag.role] = pose + with self._metadata_lock: + if (generation != self._metadata_generation + or self._latest_stamp_by_view.get(frame.view) != frame.stamp_ns): + return (), None + if pose is not None and (frame.view, tag.role) in self._branch_events_active: + events.append({"kind": "pnp_branch_event", "view": frame.view, + "image_stamp_ns": frame.stamp_ns, "tag_role": tag.role, + "tag_id": tag.tag_id, "reason": "pose_branch_recovered", + "pnp_observation_evidence": item}) + self._branch_events_active.discard((frame.view, tag.role)) + if tracking_rejected: + self._branch_events_active.add((frame.view, tag.role)) + with self._metadata_lock: + if (generation != self._metadata_generation + or self._latest_stamp_by_view.get(frame.view) != frame.stamp_ns): + return (), None + self.last_missing[frame.view] = tuple(tag.tag_id for tag in view.tags if tag.role not in frame.corners) + self.last_filtered[frame.view] = tuple(filtered) + if frame.view in self._image_references and not fixed_reference_only: + self._active_image_references[frame.view] = image_reference + movement = self._observe_fixed_reference(frame, base, selected, evidence) + # Include the last locking frame exactly once; never update mounting + # fingerprints during task motion or while the worker is fitting. + if collect_installations and self.reference_lock.locking_enabled: + self._observe_installations(frame.view, base.role, selected, evidence, + prefix="" if collect_installations is True else str(collect_installations)+"/") + if motion is not None and motion.phase == "zero_approach" and motion.reference_joints: + events.append({"kind": "motion_branch_observation", "view": frame.view, + "image_stamp_ns": frame.stamp_ns, "task_name": motion.task_key, + "zero_joints": list(motion.reference_joints), "sample_phase": "zero_approach", + "reference_only": motion.reference_only, + **({"preparation_witness_joint": motion.preparation_witness_joint, "cycle": motion.cycle} + if motion.preparation_witness_joint else {}), + "command_unit": self.profile.command.unit, + "command_vector": None if frame.command is None else list(frame.command), + "feedback_vector": None if frame.feedback is None else list(frame.feedback), + "state_image_sync_error_ms": None if frame.feedback is None else abs(frame.skew_ns)/1e6, + "camera_matrix": frame.camera_matrix.tolist(), "input_is_rectified": True, + "tags": evidence, "is_accepted_joint_sample": False}) + diagnostic_raw = (diagnostic and motion is not None and ( + motion.phase == "steady" or (motion.phase in {"sweep", "joint_zero"} and allow_recording))) + if diagnostic_raw: + # Raw candidate capture has its own record type. It cannot be + # mistaken for an accepted joint angle or enter formal fitting. + events.append(self._observation_record(frame, motion, evidence, + allow_recording, raw_joint=False, command_unit=self.profile.command.unit)) + if movement is not None or motion is None or not motion.recording or not allow_recording: + return tuple(events), movement + task = next(t for t in self.profile.motion.tasks if t.key == motion.task_key) + streams = [item for item in observation_streams(self.profile, task) if item[2].view == frame.view] + if motion.phase == "joint_zero": + if motion.reference_only: + streams = [item for item in observation_streams(self.profile, replace(task, joints=motion.zero_joints)) + if item[2].view == frame.view] + else: + streams = [item for item in streams if item[1] in motion.zero_joints] + elif motion.observed_joints: + streams = [item for item in streams if item[1] in motion.observed_joints] + if diagnostic: + streams = [item for item in streams if item[1] in (accepted_joints or ())] + if not streams or (frame.feedback is None and not self.profile.vision_motion) or frame.command is None: + return tuple(events), movement + from ..core.geometry.tag_pose.image_reference import IMAGE_REFERENCE_SOURCE + locked = [role for role, item in evidence.items() + if role in selected and item["pose_source"] in {"verified_fixed_reference", IMAGE_REFERENCE_SOURCE}] + cached = self.locked_reference(frame.view) + if (frame.view not in self._image_references + and base.role not in frame.corners and base.role not in frame.observed_roles + and cached is not None + and self.trackers[frame.view].freeze_roles({base.role: cached[1]})): + selected[base.role] = cached[0] + locked.append(base.role) + evidence.update(snapshot_pose_evidence({base.role: base}, {}, + {base.role: selected[base.role]}, self.trackers[frame.view], locked, + stamp_ns=frame.stamp_ns, + reference_revisions={base.role: cached[1]})) + roles = {role for _, _, spec in streams for role in (spec.parent_role, spec.child_role)} + image_geometry = any(has_image_model(evidence.get(role, {})) for role in roles) + if image_geometry: + roles = self._image_model_roles(roles, evidence) + if (self.profile.acquisition.motion_model_scope == "session" + and any(role not in selected or role not in frame.corners for role in roles)): + # Every ancestor is verified in this image. A partial chain or + # cached root cannot become an accepted constrained observation. + return tuple(events), movement + if task.key in self.profile.measurement.candidate_selection_tasks and motion.phase != "joint_zero": + if any(role not in selected or (role not in frame.corners and role not in locked) for role in roles): + return tuple(events), movement # An incomplete articulated frame is a discarded sample. + rows = list(events) + common_from_view = self.extrinsics.transform(frame.view) + unit = self.profile.command.unit + for field, joint, spec in streams: + channel = channel_for_joint(self.profile, joint) + if image_geometry: + joint_roles = self._image_model_roles((spec.parent_role, spec.child_role), evidence) + if any(role not in selected or role not in frame.corners for role in joint_roles): + continue + if spec.parent_role not in selected or spec.child_role not in selected: + continue + parent, child = selected[spec.parent_role], selected[spec.child_role] + p = common_from_view @ transform_matrix(parent.translation_xyz_m, parent.quaternion_xyzw) + c = common_from_view @ transform_matrix(child.translation_xyz_m, child.quaternion_xyzw) + relative = np.linalg.inv(p) @ c + row = {"kind": "joint_sample" if field == "joint" else "secondary_joint_sample", + "profile_id": self.profile.key.profile_id, field: joint, "task_name": task.key, + "view": frame.view, "image_stamp_ns": frame.stamp_ns, + "cycle": motion.cycle, "direction": motion.direction, "attempt": motion.attempt, + **segment_metadata(motion.segment_key), + "sample_phase": motion.phase if motion.phase in {"steady", "joint_zero"} else "sweep", + "command_direction_by_index": list(frame.command_directions), + "motor_index": channel, + f"feedback_{unit}": None if frame.feedback is None else frame.feedback[channel], + f"command_{unit}": frame.command[channel], + f"state_{unit}": None if frame.feedback is None else list(frame.feedback), f"command_vector_{unit}": list(frame.command), + "command_image_skew_ns": frame.command_skew_ns, + "state_image_sync_error_ms": None if frame.feedback is None else abs(frame.skew_ns)/1e6, + "relative_quaternion_xyzw": Rotation.from_matrix(relative[:3, :3]).as_quat().tolist(), + "relative_translation_xyz_m": relative[:3, 3].tolist(), + "parent_pose_common": matrix_payload(p), "child_pose_common": matrix_payload(c), + "view_normal_common_xyz": common_from_view[:3, 2].tolist(), + "camera_center_common_xyz_m": common_from_view[:3, 3].tolist(), + "locked_reference_roles": locked, + "pnp_reprojection_error_px": max(parent.reprojection_error_px, child.reprojection_error_px), + "pnp_observation_evidence": {"parent": evidence[spec.parent_role], + "child": evidence[spec.child_role]}} + if motion.phase == "steady": + row.update(steady_index=motion.steady_index, + steady_target=motion.target[channel]) + if motion.sampling_plan_sha256: + row.update(steady_training_nodes=list(motion.steady_training_nodes), + sampling_plan_sha256=motion.sampling_plan_sha256) + if spec.parent_role in frame.corners and spec.child_role in frame.corners: + row["image_relative_xy_px"] = (np.mean(frame.corners[spec.child_role], axis=0) + - np.mean(frame.corners[spec.parent_role], axis=0)).tolist() + elif joint in self.profile.measurement.image_curve_joints: + continue # Image-circle observations cannot be synthesized from a cached pose. + rows.append(row) + if motion.phase == "joint_zero": + row["kind"] = "joint_zero_sample" + row["joint"] = joint + if ((task.key in self.profile.measurement.candidate_selection_tasks or image_geometry) + and len(rows) > len(events)): + rows.append(self._candidate_frame(frame, motion, task, roles, evidence, selected, locked)) + return tuple(rows), movement + + def _observe_fixed_reference(self, frame, base, selected, evidence): + movement = None + if frame.view not in self.reference_lock.missing_views and base.role in frame.corners: + # Pose rejection must not mask actual image-space movement. + movement = self.reference_lock.observe(frame.view, base.tag_id, frame.corners[base.role]) + if base.role not in selected: + return movement + if frame.view in self.reference_lock.missing_views: + movement = self.reference_lock.observe(frame.view, base.tag_id, frame.corners[base.role]) + if not self.reference_lock.locking_enabled: + return movement + revision = evidence[base.role]["candidate_diagnostics"]["branch_revision"] + if frame.view in self._image_references: + # This cache is a coordinate convention. No physical Tag normal or + # IPPE branch is selected/frozen by its image stationarity check. + with self._metadata_lock: + self.locked_poses.setdefault(frame.view, selected[base.role]) + self.locked_revisions.setdefault(frame.view, revision) + return movement + with self._metadata_lock: + if frame.view in self.locked_poses: + return movement + generation = self._metadata_generation + buffer = self._poses.setdefault(frame.view, deque(maxlen=30)) + if self._pose_revisions.get(frame.view) != revision: + buffer.clear() + self._pose_revisions[frame.view] = revision + buffer.append(selected[base.role]) + poses = tuple(buffer) + if frame.view in self.reference_lock.missing_views or len(poses) < self.reference_lock.minimum_frames: + return movement + median = self._median_pose(poses) + with self._metadata_lock: + if (generation == self._metadata_generation and frame.view not in self.locked_poses + and self._pose_revisions.get(frame.view) == revision + and self.trackers[frame.view].freeze_roles({base.role: revision})): + self.locked_poses[frame.view] = median + self.locked_revisions[frame.view] = revision + return movement + + def _observe_installations(self, view, base_role, poses, evidence, *, prefix=""): + if base_role not in poses: + return + with self._metadata_lock: + generation = self._metadata_generation + parent = poses[base_role] + p = transform_matrix(parent.translation_xyz_m, parent.quaternion_xyzw) + observations = [] + for role, pose in poses.items(): + if role == base_role: + continue + key = f"{prefix}{view}:{role}" + revisions = tuple(evidence[name]["candidate_diagnostics"]["branch_revision"] + for name in (base_role, role)) + relative = np.linalg.inv(p) @ transform_matrix(pose.translation_xyz_m, pose.quaternion_xyzw) + observations.append((key, revisions, SquareTagPose( + quaternion_xyzw=tuple(Rotation.from_matrix(relative[:3, :3]).as_quat()), + translation_xyz_m=tuple(relative[:3, 3]), reprojection_error_px=pose.reprojection_error_px))) + with self._metadata_lock: + if generation != self._metadata_generation: + return + for key, revisions, pose in observations: + buffer = self.installations.setdefault(key, deque(maxlen=30)) + if self._installation_revisions.get(key) != revisions: + buffer.clear() + self._installation_revisions[key] = revisions + buffer.append(pose) + + def locked_reference(self, view): + with self._metadata_lock: + if view not in self.locked_poses: + return None + return self.locked_poses[view], self.locked_revisions[view] + + def image_reference_payloads(self): + """Declared coordinate frames, kept separate from physical Tag poses.""" + result = {} + for view, tracker in self._image_references.items(): + with tracker._lock: + if tracker.reference is not None: + result[view] = asdict(tracker.reference) + return result + + def freeze_reference_branches(self, revisions): + """Freeze physical branches with the same atomic fixed-image check.""" + with self._metadata_lock: + return self._freeze_reference_branches(revisions) + + def _freeze_reference_branches(self, revisions): + """Hold the selected reference context until physical branches freeze.""" + fixed = {(view.name, tag.role) for view in self.profile.vision.views + for tag in view.tags if tag.fixed_reference} + image_refs, physical, moving = [], [], [] + for (view, role), revision in revisions.items(): + if (view, role) in fixed and view in self._image_references: + tracker = self._active_image_references[view] + if tracker is None: + return False + image_refs.append((tracker, role, revision)) + else: + physical.append((self.trackers[view], role, revision)) + if (view, role) not in fixed: + moving.append((self.trackers[view], role)) + with ExitStack() as stack: + for tracker in sorted({tracker for tracker, _, _ in (*image_refs, *physical)}, key=id): + stack.enter_context(tracker._lock) + if not all(tracker.reference_confirmed(role, revision) for tracker, role, revision in image_refs): + return False + return (SquareTagPoseTracker.freeze_references(physical, require_motion_evidence=moving) + if physical else bool(image_refs)) + + def locked_reference_views(self): + with self._metadata_lock: + return frozenset(self.locked_poses) + + def installation_count(self, key): + with self._metadata_lock: + return len(self.installations.get(key, ())) + + def fingerprint_poses(self): + # Copy both the dictionary and each deque while writers hold the same + # short lock. Rotation means and NumPy work use only immutable snapshots. + with self._metadata_lock: + fixed = tuple(self.locked_poses.items()) + moving = tuple((name, tuple(rows)) for name, rows in self.installations.items()) + def payload(pose): + return {"rotation_xyzw": list(pose.quaternion_xyzw), "translation_xyz_m": list(pose.translation_xyz_m)} + return ({view: payload(pose) for view, pose in fixed}, + {name: payload(self._median_pose(rows)) for name, rows in moving + if len(rows) >= self.reference_lock.minimum_frames}) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/capture_index.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/capture_index.py new file mode 100644 index 0000000..21ea029 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/capture_index.py @@ -0,0 +1,123 @@ +"""Live acquisition checks need an index, not a second copy of the journal. + +The complete image and pose evidence is written to JSONL by the coordinator. +Journal-backed finalization reads those bytes independently. Keep only fields +used by coverage, retry identity and training-knot selection in its live index. +In-process finalizers may request complete records. Diagnostics use the bounded +current-scan window for live checks and reread their journal after safe return. +""" + +from collections.abc import Sequence + + +class CaptureRecordIndex(Sequence): + def __init__(self, *, retain_complete, retain_training_geometry=False): + self.retain_complete = retain_complete + self.retain_training_geometry = retain_training_geometry + self._rows = [] + self._attempts = set() + self._by_task = {} + self._training_snapshots = {} + + def __len__(self): + return len(self._rows) + + def __getitem__(self, index): + return self._rows[index] + + def reset(self, rows=()): + self._rows.clear() + self._attempts.clear() + self._by_task.clear() + self._training_snapshots.clear() + self.extend(rows) + + def extend(self, rows): + for row in rows: + self.append(row) + + def task_records(self, task_key): + return tuple(self._by_task.get(task_key, ())) + + def training_task_snapshot(self, task_key, cycles): + rows = self._by_task.get(task_key, ()) + key = tuple(cycles), len(rows) + cached = self._training_snapshots.get(task_key) + if cached is None or cached[0] != key: + cached = key, task_training_snapshot(rows, cycles) + self._training_snapshots[task_key] = cached + return cached[1] + + def _store(self, row): + self._rows.append(row) + if row.get("task_name") is not None: + self._by_task.setdefault(row["task_name"], []).append(row) + + def append(self, row): + if self.retain_complete: + self._store(row) + return + kind = row.get('kind') + if kind in {'joint_sample', 'secondary_joint_sample'}: + # Scalars contain native command/feedback and all scan identities. + # These two short sequences are the only non-scalar inputs to the + # live training-grid selector. Pose provenance stays in the journal. + source = getattr(row, "metadata", row) + indexed = {key: value for key, value in source.items() + if value is None or isinstance(value, (str, int, float, bool))} + if self.retain_training_geometry: + from ..core.fitting.training_quality import TRAINING_FIELDS + from ..core.domain.capture_plan import evidence_digest + from .resume_storage import materialize_plain_record + # A deferred row decompresses and parses its evidence when a + # non-indexed field is accessed. Materialize it exactly once; + # probing every training field through Mapping.__contains__ + # used to decode the same sample dozens of times. + materialized = materialize_plain_record(row) + indexed.update({key: materialized[key] for key in TRAINING_FIELDS + if key in materialized}) + # DeferredCaptureRecord implements Mapping for indexed reads, + # but json.dumps intentionally accepts only concrete JSON + # containers. Hash the immutable materialized record exactly + # as an eager capture would. + indexed['source_record_sha256'] = evidence_digest(materialized) + else: + for key in ('relative_quaternion_xyzw', 'steady_training_nodes', + 'command_direction_by_index'): + if key in row: + indexed[key] = tuple(row[key]) + self._store(indexed) + elif kind in {'command_sampling_plan', 'training_decision', 'staged_training_decision'}: + self._store(row) + elif self.retain_training_geometry and kind in {'session_start', 'joint_zero_reference', 'scan_unit_complete'}: + self._store(row) + elif all(key in row for key in ('task_name', 'cycle', 'direction')): + # An unsuccessful later attempt can contain images but no valid + # joint sample. Preserve its identity so it cannot expose old data. + keys = ('task_name', 'cycle', 'direction', 'segment_key', 'attempt') + identity = tuple(row.get(key) for key in keys) + if identity not in self._attempts: + self._attempts.add(identity) + self._store({key: row[key] for key in keys if key in row}) + + +def task_training_snapshot(records, cycles): + from ..core.domain.capture_plan import evidence_digest + from ..core.domain.motion_path import record_scan_identity + from ..core.fitting.training_quality import TRAINING_FIELDS + latest = {} + for row in records: + if row.get('cycle') in cycles: + key = record_scan_identity(row) + latest[key] = max(latest.get(key, 0), int(row.get('attempt', 1))) + selected = [] + for row in records: + if (row.get('kind') != 'joint_sample' or row.get('cycle') not in cycles + or row.get('sample_phase', 'sweep') not in {'sweep', 'steady'} + or row.get('attempt', 1) != latest[record_scan_identity(row)]): + continue + snapshot = {key: row[key] for key in TRAINING_FIELDS if key in row} + snapshot['command_direction_by_index'] = row.get('command_direction_by_index', []) + snapshot['source_record_sha256'] = row.get('source_record_sha256') or evidence_digest(row) + selected.append(snapshot) + return tuple(selected) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/chain_capture.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/chain_capture.py new file mode 100644 index 0000000..728cd00 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/chain_capture.py @@ -0,0 +1,314 @@ +"""Raw, bounded reference visits for a deferred finger-chain fit. + +This proves a stable acquisition visit, never a parent installation or an +angle. References stay pending and diagnostic evidence remains non-publishable. +SDK arrival, watchdogs, fixed-base monitoring and timeouts belong to the common +coordinator and must pass before this gate is called. +""" +from dataclasses import asdict, dataclass +from copy import deepcopy + +import numpy as np + +from .diagnostic_reference import DiagnosticZeroAttempt +from .revisit import revisit_feedback_limits, REVISIT_POLICY + + +@dataclass(frozen=True) +class ChainReferenceVisit: + record: dict + attempt: DiagnosticZeroAttempt | None + + +class DeferredChainCapture: + def __init__(self, profile, plan): + if not plan.chain_joints: + raise ValueError('deferred_chain_requires_explicit_plan') + self.profile, self.plan = profile, plan + self.tasks = {task.key: task for task in profile.motion.tasks if task.key in plan.task_keys} + distal = profile.measurement.measurements[plan.chain_joints[-1]] + self.view = distal.view + self.roles = (distal.parent_role, distal.child_role) + self.tags = {tag.role: tag for view in profile.vision.views if view.name == self.view for tag in view.tags} + self.clear() + + def clear(self): + self.references = {} + self.training_returns = set() + self.generation = getattr(self, 'generation', 0)+1 + self.arcs, self.initial_frames, self.return_frames = {}, {}, {} + self.models = {} + self._pending = None + + def observe(self, row): + """Bounded command bins; validation and subsequent laps never enter.""" + if (row.get('kind') != 'diagnostic_observation_frame' or row.get('view') != self.view + or row.get('cycle') != 0 or row.get('direction') != 'decreasing' + or row.get('sample_phase') != 'sweep'): + return + task = self.tasks.get(row.get('task_name')) + if task is None or task.joints[0] not in self.plan.chain_joints[:2]: + return + if (row['session_epoch'], task.joints[0]) in self.training_returns: + return + command = row.get('command_vector') + if command is None or row.get('feedback_vector') is None: + return + target = self.profile.motion.joint_zero_references[task.joints[0]].command + if any(v != target[i] for i, v in enumerate(command) if i != task.command_index): + return + spec = self.profile.measurement.measurements[task.joints[0]] + if any(not row.get('tags', {}).get(role, {}).get('reprojection_valid_candidates') + for role in (spec.parent_role, spec.child_role)): + return + from ..profiles.preparation import preparation_image_budget + intervals, _ = preparation_image_budget(self.profile) + lo, hi = self.profile.command.minimum_values[task.command_index], self.profile.command.maximum_values[task.command_index] + key = round(intervals*(command[task.command_index]-lo)/(hi-lo)) + if 0 <= key <= intervals: + self.arcs.setdefault((row['session_epoch'], task.joints[0]), {})[key] = deepcopy(row) + + def _frames(self, records, raw_rows, joint): + from .shared_tag_reference import bridge_frames + from ..core.geometry.tag_pose.motion_evidence import MotionRelation + spec = self.profile.measurement.measurements[joint] + stamps = {r['image_stamp_ns'] for r in raw_rows} + selected = {r['image_stamp_ns']: r for r in records + if r.get('kind') == 'diagnostic_observation_frame' and r.get('view') == spec.view + and r.get('image_stamp_ns') in stamps} + if selected.keys() != stamps: + raise ValueError('deferred_chain_model_images_missing') + for raw in raw_rows: + diagnostic = selected[raw['image_stamp_ns']] + if any(diagnostic.get(field) != raw.get(field) for field in ( + 'task_name', 'sample_phase', 'session_epoch', 'motion_version', + 'cycle', 'direction', 'command_vector', 'feedback_vector')): + raise ValueError('deferred_chain_model_image_identity_changed') + return bridge_frames([selected[s] for s in sorted(stamps)], + MotionRelation(joint, spec.parent_role, spec.child_role)) + + def request(self, view, motion, *, session_epoch, motion_version, zero_references=None): + if (motion is None or view != self.view or motion.phase != 'steady' + or not self.is_training_return(motion)): + return None + task = self.tasks[motion.task_key] + joint = task.joints[0] + key = (session_epoch, joint) + if (joint not in self.plan.chain_joints[:2] or key not in self.training_returns + or key in self.models or self._pending is not None): + return None + from .chain_reference import ChainReferenceRequest + from .shared_tag_reference import bridge_frames + from ..core.geometry.tag_pose.motion_evidence import MotionRelation + from ..profiles.preparation import preparation_image_budget + from .motion_provenance import source_frame_sha256 + spec = self.profile.measurement.measurements[joint] + relation = MotionRelation(joint, spec.parent_role, spec.child_role) + rows = sorted(self.arcs.get(key, {}).values(), key=lambda r:r['image_stamp_ns']) + invalid = '' + frames = () + try: + if len(rows) < 24: + raise ValueError('training_reference_arc_missing') + feedback = np.asarray([r['feedback_vector'] for r in rows]) + held = [i for i in range(self.profile.command.command_count) if i != task.command_index] + tolerance = max(1., .005*255) + if (not np.all(np.isfinite(feedback)) or np.any(np.ptp(feedback[:, held], axis=0) > tolerance)): + raise ValueError('training_reference_held_feedback_changed') + frames = bridge_frames(rows, relation) + except (ValueError, KeyError, TypeError) as error: + invalid = str(error) + source = None if joint == self.plan.chain_joints[0] else self.models.get( + (session_epoch, self.plan.chain_joints[0])) + if joint != self.plan.chain_joints[0] and source is None: + invalid = 'training_reference_source_missing' + request = ChainReferenceRequest(task.key, view, (joint,), session_epoch, motion_version, + self.generation, tuple(f.evidence for f in frames), (relation,), (), (spec.child_role,), + source_frame_hashes=tuple((str(r['image_stamp_ns']), source_frame_sha256(r)) for r in rows), + invalid_reason=invalid, image_geometry=True, image_frames=frames, + image_parameters=preparation_image_budget(self.profile)[1], + endpoint_frames=self.return_frames.get(key, ()), + before_frames=self.initial_frames.get(key, ()), source=source) + self._pending = request + return request + + def accept(self, request, result): + if self._pending is not request or request.generation != self.generation: + return None + self._pending = None + key = (request.session_epoch, request.zero_joints[0]) + self.models[key] = result + self.arcs.pop(key, None) + from .branch_initialization import _finite_report + return None, dict(kind='deferred_chain_reference_model', policy='original_training_return_handoff_v1', + task_name=request.task_name, session_epoch=request.session_epoch, + motion_version=request.motion_version, source_frame_hashes=dict(request.source_frame_hashes), + endpoint_stamps=[f.evidence.stamp_ns for f in request.endpoint_frames], + before_stamps=[f.evidence.stamp_ns for f in request.before_frames], + result=_finite_report(asdict(result)), publication_allowed=False, physical_zero_validated=False) + + def pending(self): + return self._pending is not None + + def reference_ready(self, motion, epoch): + if not self.is_training_return(motion) or self.tasks[motion.task_key].joints[0] not in self.plan.chain_joints[:2]: + return True + result = self.models.get((epoch, self.tasks[motion.task_key].joints[0])) + if result is not None and not result.resolved: + raise ValueError('deferred_chain_reference_model_unresolved:'+result.reason) + return result is not None + + def is_training_return(self, motion): + """Canonical directed return, already part of the first training lap.""" + task = self.tasks[motion.task_key] + reference = self.profile.motion.joint_zero_references[task.joints[0]] + return (motion.phase == 'steady' and motion.cycle == 0 + and motion.direction == 'decreasing' + and tuple(motion.target) == reference.command) + + def steady_visit(self, motion, records, *, epoch, version): + """Check a hold and retain the directed training reference once. + + Initial held observations have no approach-direction claim. Replace + their *raw* reference only at the first training return. A validation + image can never change this source, and no visit authorizes a zero. + """ + returned = self.is_training_return(motion) + minimum = (self.profile.acquisition.fixed_reference_minimum_frames if returned + else self.profile.acquisition.steady_minimum_samples) + rows = self.current_window(motion, records, epoch, version, 'steady', minimum) + if not returned: + return None + task = self.tasks[motion.task_key] + keys = {(epoch, name) for name in task.joints} + if keys <= self.training_returns: + return None + if not keys <= self.references.keys(): + raise ValueError('deferred_chain_initial_visit_missing') + before = self.references[epoch, task.joints[0]] + if rows[0]['image_stamp_ns'] <= before[-1]['image_stamp_ns']: + raise ValueError('deferred_chain_training_return_not_current') + record = dict(kind='deferred_chain_training_return', schema_version=1, + task_name=task.key, cycle=motion.cycle, direction=motion.direction, + session_epoch=epoch, motion_version=version, + initial_images=[(self.view, row['image_stamp_ns']) for row in before], + source_images=[(self.view, row['image_stamp_ns']) for row in rows], + command_vector=list(motion.target), reference_policy='first_training_return_v1', + geometry_status='pending', is_accepted_joint_sample=False, publication_allowed=False) + if task.joints[0] in self.plan.chain_joints[:2]: + self.return_frames[epoch, task.joints[0]] = self._frames(records, rows, task.joints[0]) + for key in keys: + self.references[key] = deepcopy(rows) + self.training_returns.update(keys) + return record + + def current_window(self, motion, records, epoch, version, phase, minimum): + """Only synchronized current images in the already-open stable window.""" + selected = {} + for row in records: + if (row.get('kind') != 'image_observation_frame' or row.get('view') != self.view + or row.get('task_name') != motion.task_key or row.get('sample_phase') != phase + or row.get('session_epoch') != epoch or row.get('motion_version') != version): + continue + if phase == 'steady' and (row.get('cycle') != motion.cycle + or row.get('direction') != motion.direction): + continue + command = np.asarray(row.get('command_vector'), dtype=float) + feedback = np.asarray(row.get('feedback_vector'), dtype=float) + if (command.shape != (self.profile.command.command_count,) or feedback.shape != command.shape + or not np.all(np.isfinite(feedback)) or not np.array_equal(command, motion.target)): + continue + stamp = row.get('image_stamp_ns') + if type(stamp) is not int or stamp <= 0: + continue + valid = True + for role in self.roles: + tag = row.get('tags', {}).get(role, {}) + corners = np.asarray(tag.get('corners_xy'), dtype=float) + valid &= (tag.get('tag_id') == self.tags[role].tag_id + and tag.get('tag_size_m') == self.tags[role].size_m + and corners.shape == (4, 2) and np.all(np.isfinite(corners))) + if valid: + selected[stamp] = row + if len(selected) < minimum: + raise ValueError('deferred_chain_current_images_missing') + rows = [row for _, row in sorted(selected.items())[-minimum:]] + feedback = np.asarray([row['feedback_vector'] for row in rows]) + if np.any(np.ptp(feedback, axis=0) > revisit_feedback_limits(self.profile)['within_hold_range']): + raise ValueError('deferred_chain_feedback_unstable') + for role in self.roles: + corners = np.asarray([row['tags'][role]['corners_xy'] for row in rows]) + if np.max(np.linalg.norm(corners-np.median(corners, axis=0), axis=2)) > self.profile.acquisition.fixed_reference_maximum_drift_px: + raise ValueError('deferred_chain_reference_image_unstable') + return rows + + def reference_visit(self, motion, records, *, epoch, version): + task = self.tasks[motion.task_key] + target = self.profile.motion.joint_zero_references[task.joints[0]].command + if (motion.phase != 'joint_zero' or tuple(motion.target) != target or motion.reference_check + or motion.cycle not in (0, 1)): + raise ValueError('deferred_chain_reference_contract_changed') + rows = self.current_window(motion, records, epoch, version, 'joint_zero', + self.profile.acquisition.fixed_reference_minimum_frames) + latest = rows[-1] + source_images = () + if motion.reference_reuse: + reference = task.parent_reference + if reference is None or motion.zero_joints != (reference.pose_joint,): + raise ValueError('deferred_chain_parent_contract_changed') + from .chain_reference import check_chain_parent + checked = check_chain_parent(self.models.get((epoch, reference.geometry_joint)), + self._frames(records, rows, reference.geometry_joint)) + for joint in (reference.pose_joint, reference.geometry_joint): + before = self.references.get((epoch, joint)) + if before is None: + raise ValueError('deferred_chain_parent_visit_missing') + if (epoch, joint) not in self.training_returns: + raise ValueError('deferred_chain_parent_training_return_missing') + if rows[0]['image_stamp_ns'] <= before[-1]['image_stamp_ns']: + raise ValueError('deferred_chain_parent_visit_not_current') + if any(tuple(row['command_vector']) != target for row in before): + raise ValueError('deferred_chain_parent_command_changed') + limits = revisit_feedback_limits(self.profile) + old = np.median([row['feedback_vector'] for row in before], axis=0) + if np.any(np.abs(np.asarray([row['feedback_vector'] for row in rows])-old) + > limits['between_visit_difference']): + raise ValueError('deferred_chain_parent_feedback_changed') + # The original frozen source pose is checked geometrically + # through the handed-off PIP model above. Do not require its + # older MCP pixels to be identical after the PIP task. Keep + # the same raw drift gate against the PIP held-pair reference. + for role in (self.roles if joint == reference.geometry_joint else ()): + origin = np.median([row['tags'][role]['corners_xy'] for row in before], axis=0) + current = np.asarray([row['tags'][role]['corners_xy'] for row in rows]) + if np.max(np.linalg.norm(current-origin, axis=2)) > self.profile.acquisition.fixed_reference_maximum_drift_px: + raise ValueError('deferred_chain_parent_image_changed') + source_images += tuple((self.view, row['image_stamp_ns']) for row in before) + attempt = None + else: + if motion.reference_only or motion.zero_joints != task.joints: + raise ValueError('deferred_chain_zero_contract_changed') + if any((epoch, joint) in self.references for joint in task.joints): + raise ValueError('deferred_chain_reference_replacement_forbidden') + attempt = DiagnosticZeroAttempt(task.joints, task.key, 'deferred_joint_chain_geometry', + epoch, version, tuple(latest['command_vector']), tuple(latest['feedback_vector']), + tuple((self.view, row['image_stamp_ns']) for row in rows), + tuple((joint, self.view) for joint in task.joints)) + if task.joints[0] in self.plan.chain_joints[:2]: + self.initial_frames[epoch, task.joints[0]] = self._frames(records, rows, task.joints[0]) + record = dict(kind='deferred_chain_reference_visit', schema_version=1, + task_name=task.key, session_epoch=epoch, motion_version=version, + reference_reuse=motion.reference_reuse, source_images=source_images, + current_images=[(self.view, row['image_stamp_ns']) for row in rows], + verification=REVISIT_POLICY, feedback_limits=revisit_feedback_limits(self.profile), + reference_policy='first_training_return_v1', + geometry_status='pending', is_accepted_joint_sample=False, publication_allowed=False) + if motion.reference_reuse: + record.update(parent_pose_check=asdict(checked), + parent_model_joint=reference.geometry_joint, + parent_reference_policy='original_training_return_handoff_v1') + # Mutation is transactional: retain nothing until every check passes. + if attempt is not None: + for joint in task.joints: + self.references[epoch, joint] = deepcopy(rows) + return ChainReferenceVisit(record, attempt) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/chain_reference.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/chain_reference.py new file mode 100644 index 0000000..0542c50 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/chain_reference.py @@ -0,0 +1,84 @@ +"""Reuse original per-joint image solvers on an existing training return. + +This adapter grants only a bounded, current parent-pose check to raw capture. +It never creates a physical zero, joint sample, command map or publishable model. +The coordinator's isolated worker and epoch/version commit gates own execution. +""" +from dataclasses import dataclass, replace +import math + +import numpy as np +from scipy.spatial.transform import Rotation + +from .branch_initialization import BranchInitializationRequest +from ..core.geometry.tag_pose.production_image_motion import resolve_image_motion, select_image_motion_frame +from ..core.geometry.tag_pose.pose_bridge import SharedTagPoseBridge, check_pose_bridge +from ..core.geometry.tag_pose.relative import _relative_pose + + +@dataclass(frozen=True) +class ChainReferenceRequest(BranchInitializationRequest): + endpoint_frames: tuple = () + before_frames: tuple = () + source: object = None + + +@dataclass(frozen=True) +class ChainReferenceResult: + resolved: bool + reason: str + model: object = None + quaternion_xyzw: tuple = () + translation_xyz_m: tuple = () + reference_stamps: tuple = () + hypotheses: tuple = () + + +def solve_chain_reference(request): + """Same solvers and gates as the original MCP -> PIP handoff.""" + if request.invalid_reason: + return ChainReferenceResult(False, request.invalid_reason) + if len(request.endpoint_frames) < 10: + return ChainReferenceResult(False, 'training_reference_endpoint_missing') + bridges = () + source = request.source + if source is not None: + if not source.resolved or source.model is None or len(request.before_frames) < 10: + return ChainReferenceResult(False, 'training_reference_source_missing') + bridges = (SharedTagPoseBridge(request.relations[0], source.quaternion_xyzw, + source.translation_xyz_m, request.endpoint_frames, source_model=source.model, + source_frames=request.before_frames),) + resolved = resolve_image_motion(request.image_frames, request.relations, + parameters=request.image_parameters, pose_bridges=bridges) + if not resolved.resolved: + return ChainReferenceResult(False, resolved.reason, hypotheses=resolved.hypotheses) + if source is not None: + # Preserve the first source pose; a recipient cannot redefine its zero. + return replace(source, model=resolved.model, hypotheses=resolved.hypotheses) + relation = request.relations[0] + rotations, points = [], [] + for frame in request.endpoint_frames: + check = select_image_motion_frame(resolved.model, frame) + if not check.resolved: + return ChainReferenceResult(False, 'training_reference_endpoint:'+check.reason) + poses = {s.role: s.pose for s in check.selections} + rotation, point = _relative_pose(poses[relation.parent_role], poses[relation.child_role]) + rotations.append(rotation.as_quat()); points.append(point) + rotations = Rotation.from_quat(rotations) + point = np.median(points, axis=0) + if (np.max((rotations.mean().inv()*rotations).magnitude()) > math.radians(1) + or np.max(np.linalg.norm(np.asarray(points)-point, axis=1)) > .001): + return ChainReferenceResult(False, 'training_reference_endpoint_unstable') + return ChainReferenceResult(True, '', resolved.model, tuple(rotations.mean().as_quat()), + tuple(point), tuple(f.evidence.stamp_ns for f in request.endpoint_frames), resolved.hypotheses) + + +def check_chain_parent(result, frames): + if result is None or not result.resolved or result.model is None: + raise ValueError('deferred_chain_parent_model_unavailable') + bridge = SharedTagPoseBridge(result.model.relations[0], result.quaternion_xyzw, + result.translation_xyz_m, tuple(frames)) + checked = check_pose_bridge(result.model, bridge) + if checked.status != 'consistent': + raise ValueError('deferred_chain_parent_geometry_changed:'+checked.reason) + return checked diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_extension.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_extension.py new file mode 100644 index 0000000..87ee9e6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_extension.py @@ -0,0 +1,138 @@ +"""Explicit, audited extension of a partial checkpoint with new trailing tasks. + +Ordinary resume remains strict. This offline operation verifies both protected +profiles and both replay contracts before creating a separate derived journal. +It does not authorize reuse of any physical zero or publish a calibration. +""" + +from dataclasses import dataclass, replace +import hashlib +import json +from pathlib import Path + +from ..core.domain.profile import CalibrationProfile +from ..core.urdf.partial_scope import profile_scope +from ..profiles import load_hand_profile +from .engine import CalibrationEngine +from .joint_resume import JointResume, PreparedResume + + +@dataclass(frozen=True) +class ScopeExtension: + source: CalibrationProfile + target: CalibrationProfile + source_yaml: bytes + target_yaml: bytes + + @classmethod + def load(cls, source_path, target_path): + source, target = load_hand_profile(source_path), load_hand_profile(target_path) + expanded = load_hand_profile(source_path, scope=target.scope.default_scope) + if not source.retained_joints > target.retained_joints: + raise ValueError("checkpoint_extension_requires_larger_scope") + if source.motion.tasks != target.motion.tasks[:len(source.motion.tasks)]: + raise ValueError("checkpoint_extension_requires_unchanged_task_prefix") + # Expanding the original protected file must yield exactly the target + # contract, allowing only the placement of the previously omitted tasks. + reordered = replace(target, motion=replace(target.motion, tasks=expanded.motion.tasks)) + if expanded != reordered: + raise ValueError("checkpoint_extension_changes_measurement_contract") + if CalibrationEngine(source).capture_schedule_version != CalibrationEngine(target).capture_schedule_version: + raise ValueError("checkpoint_extension_changes_capture_schedule") + return cls(source, target, Path(source_path).read_bytes(), Path(target_path).read_bytes()) + + def metadata(self, checkpoint, protected_inputs, source_path, source_digest): + old_hash = hashlib.sha256(self.source_yaml).hexdigest() + new_hash = hashlib.sha256(self.target_yaml).hexdigest() + if protected_inputs.get("profile_config_sha256") != new_hash: + raise ValueError("checkpoint_extension_target_profile_hash_invalid") + expected = {**protected_inputs, "profile_config_sha256": old_hash} + for row in (checkpoint.header, checkpoint.fixed_reference): + actual = row.get("protected_hashes", row) + if any(actual.get(key) != value for key, value in expected.items()): + raise ValueError("checkpoint_extension_source_inputs_changed") + header = {**checkpoint.header, **protected_inputs, "calibration_scope": profile_scope(self.target), + "resume_checkpoint_requested": True} + if "protected_hashes" in header: + header["protected_hashes"] = {**header["protected_hashes"], **protected_inputs} + reference = {**checkpoint.fixed_reference, "protected_hashes": { + **checkpoint.fixed_reference["protected_hashes"], **protected_inputs}} + audit = {"kind": "capture_scope_extension", "policy": "unchanged_prefix_scope_extension_v1", + "source_raw_samples": str(Path(source_path).resolve()), "source_raw_sha256": source_digest, + "source_profile_sha256": old_hash, "target_profile_sha256": new_hash, + "original_header": checkpoint.header, "original_fixed_reference": checkpoint.fixed_reference, + "target_scope": profile_scope(self.target), + "reused_task_prefix": [task.key for task in self.source.motion.tasks], + "appended_tasks": [task.key for task in self.target.motion.tasks[len(self.source.motion.tasks):]], + "physical_reference_reverification_required": True} + return header, reference, audit + + +def _file_sha256(path): + with Path(path).open("rb") as stream: + return hashlib.file_digest(stream, "sha256").hexdigest() + + +def extend_checkpoint(extension, source_path, output_dir, *, serial_number, + protected_inputs, image_replay_workers=1): + """Preserve sample lines verbatim; only session metadata gains a new scope.""" + source_path, output_dir = Path(source_path), Path(output_dir) + if output_dir.exists(): + raise FileExistsError(output_dir) + source_digest = _file_sha256(source_path) + checkpoint = PreparedResume.load(extension.source, CalibrationEngine(extension.source), + source_path, serial_number, image_replay_workers=image_replay_workers) + header, reference, audit = extension.metadata(checkpoint, protected_inputs, source_path, source_digest) + replacement = {"session_start": header, "fixed_base_reference_locked": reference} + rows = tuple(replacement.get(row.get("kind"), row) for row in checkpoint.rows) + (audit,) + verified = JointResume(extension.target, image_replay_workers=image_replay_workers) + verified.stage(CalibrationEngine(extension.target), rows, checkpoint.completed_units) + if (verified.units != checkpoint.joints.units or verified.references != checkpoint.joints.references + or verified.first_cycle_spans != checkpoint.joints.first_cycle_spans): + raise ValueError("checkpoint_extension_changes_reusable_evidence") + output_dir.mkdir(parents=True, exist_ok=False) + temporary = output_dir / "raw_samples.jsonl.tmp" + digest = hashlib.sha256() + with source_path.open("rb") as source, temporary.open("xb") as target: + for line in source: + digest.update(line) + row = json.loads(line) if line.strip() else {} + if row.get("kind") in replacement: + target.write((json.dumps(replacement[row["kind"]], ensure_ascii=False) + "\n").encode()) + else: + target.write(line) + target.write(("\n" + json.dumps(audit, ensure_ascii=False) + "\n").encode()) + if digest.hexdigest() != source_digest: + temporary.unlink() + raise ValueError("checkpoint_extension_source_changed_during_replay") + (output_dir / "source_profile.yaml").write_bytes(extension.source_yaml) + (output_dir / "target_profile.yaml").write_bytes(extension.target_yaml) + (output_dir / "scope_extension.json").write_text(json.dumps({**audit, + "reusable_units": len(verified.units), "result": "STATIC_REPLAY_PASSED"}, + ensure_ascii=False, indent=2) + "\n") + temporary.rename(output_dir / "raw_samples.jsonl") + return output_dir + + +def main(): + import argparse + from ..product import load_product_config + from .image_replay import checkpoint_replay_workers + from .runner_support import protected_inputs + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-profile", required=True) + parser.add_argument("--target-product", required=True) + parser.add_argument("--source-checkpoint", required=True) + parser.add_argument("--output-dir", required=True) + args = parser.parse_args() + product = load_product_config(args.target_product, check_can=False) + extension = ScopeExtension.load(args.source_profile, product.profile_config) + result = extend_checkpoint(extension, args.source_checkpoint, args.output_dir, + serial_number=product.serial_number, protected_inputs=protected_inputs(product), + image_replay_workers=checkpoint_replay_workers()) + print(f"已创建扩展范围断点:{result};实机基准和逐关节零位仍须重新验证。", flush=True) + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_observer_upgrade.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_observer_upgrade.py new file mode 100644 index 0000000..ec12d48 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_observer_upgrade.py @@ -0,0 +1,204 @@ +"""Audited observer-policy migration for unfinished staged checkpoints. + +Only unmeasured dependencies may change. Accepted models, scan units, motion +plans and quality limits remain immutable; both profiles undergo normal replay. +The source journal is never edited and a target appears only after validation. +""" +from dataclasses import dataclass, replace +import hashlib +import json +from pathlib import Path +import shutil + +from ..core.domain.profile import CalibrationProfile +from ..profiles import load_hand_profile +from ..profiles.observer_policy import (configure_observer_policy, + RIGID_OBSERVER, TRAJECTORY_OBSERVER) +from ..profiles.preparation import preparation_contract +from ..profiles.validator import validate_executable_profile +from .engine import CalibrationEngine +from .joint_resume import PreparedResume, JointResume +from .staged_resume import stage_visits + + +def _copy_indexed_evidence(source_path, output_dir): + """Copy content-addressed evidence before exposing the migrated index.""" + from ..core.artifacts.evidence_journal import ( + is_indexed_journal, manifest_path, archive_path, + ) + if not is_indexed_journal(source_path): + return + for source_evidence in (manifest_path(source_path), archive_path(source_path)): + target_evidence = output_dir/source_evidence.name + shutil.copy2(source_evidence, target_evidence) + with source_evidence.open('rb') as source_stream, target_evidence.open('rb') as target_stream: + source_hash = hashlib.file_digest(source_stream, 'sha256').hexdigest() + target_hash = hashlib.file_digest(target_stream, 'sha256').hexdigest() + if source_hash != target_hash: + raise ValueError('observer_upgrade_evidence_archive_changed') + + +def preserved_observer_joints(checkpoint): + if any(r.get('kind') == 'staged_training_decision' for r in checkpoint.rows): + raise ValueError('observer_upgrade_training_already_decided') + # Include every accepted model, even if its first scan has not finished. + return frozenset(checkpoint.joints.references) | frozenset( + joint for row in checkpoint.rows + if row.get('kind') == 'motion_branch_initialization' and row.get('status') == 'resolved' + for joint in row['zero_joints']) + + +@dataclass(frozen=True) +class ObserverPolicyUpgrade: + source: CalibrationProfile + target: CalibrationProfile + source_yaml: bytes + target_yaml: bytes + source_urdf: Path | None = None + + @classmethod + def load(cls, source_path, target_path): + source, target = load_hand_profile(source_path), load_hand_profile(target_path) + if source.quality.training_policy != 'staged_2_to_3': + raise ValueError('observer_upgrade_requires_staged_checkpoint') + return cls(source, target, Path(source_path).read_bytes(), Path(target_path).read_bytes()) + + def metadata(self, checkpoint, protected_inputs, source_path, source_digest): + from .resume_storage import materialize_record + source_header = materialize_record(checkpoint.header) + source_reference = materialize_record(checkpoint.fixed_reference) + preserved = preserved_observer_joints(checkpoint) + target_strategies = {spec.observer_pose_policy + for spec in self.target.measurement.measurements.values() + if spec.observer_pose_policy in {RIGID_OBSERVER, TRAJECTORY_OBSERVER}} + strategy = (TRAJECTORY_OBSERVER if TRAJECTORY_OBSERVER in target_strategies + else RIGID_OBSERVER) + expected = configure_observer_policy(self.source, preserved_joints=preserved, + policy=strategy) + if self.target.motion.observer_preparations != self.source.motion.observer_preparations: + if self.source_urdf is None: + raise ValueError('observer_upgrade_source_geometry_missing') + from ..core.urdf.kinematics import UrdfKinematicModel + from ..profiles.observer_preparation import configure_observer_preparations + expected = configure_observer_preparations(expected, UrdfKinematicModel(self.source_urdf), + preserved_joints=preserved) + if self.target != expected: + raise ValueError('observer_upgrade_changes_existing_contract') + if self.target == self.source: + raise ValueError('observer_upgrade_has_no_changes') + old_hash, new_hash = (hashlib.sha256(data).hexdigest() + for data in (self.source_yaml, self.target_yaml)) + if protected_inputs.get('profile_config_sha256') != new_hash: + raise ValueError('observer_upgrade_target_hash_invalid') + old_inputs = {**protected_inputs, 'profile_config_sha256': old_hash} + for row in (source_header, source_reference): + actual = row.get('protected_hashes', row) + if any(actual.get(key) != value for key, value in old_inputs.items()): + raise ValueError('observer_upgrade_protected_inputs_changed') + if source_header.get('preparation_contract') != preparation_contract(self.source): + raise ValueError('observer_upgrade_source_preparation_changed') + header = {**source_header, **protected_inputs, + 'preparation_contract': preparation_contract(self.target), + 'resume_checkpoint_requested': True} + if 'protected_hashes' in header: + header['protected_hashes'] = {**header['protected_hashes'], **protected_inputs} + reference = {**source_reference, 'protected_hashes': { + **source_reference['protected_hashes'], **protected_inputs}} + changes = {joint: dict(previous=spec.observer_pose_policy, + current=self.target.measurement.measurements[joint].observer_pose_policy) + for joint, spec in self.source.measurement.measurements.items() + if spec != self.target.measurement.measurements[joint]} + audit = dict(kind='capture_observation_revision', policy='unmeasured_observer_upgrade_v1', + source_raw_samples=str(Path(source_path).resolve()), source_raw_sha256=source_digest, + source_profile_sha256=old_hash, target_profile_sha256=new_hash, + original_header=source_header, original_fixed_reference=source_reference, + preserved_joints=sorted(preserved), observer_policy_changes=changes, + completed_units=[list(unit) for unit in sorted(checkpoint.joints.units)], + physical_zero_reverification_performed=False) + if self.target.motion.observer_preparations != self.source.motion.observer_preparations: + from dataclasses import asdict + audit.update(policy='unmeasured_observer_upgrade_v2', observer_preparations={ + name: asdict(plan) for name, plan in self.target.motion.observer_preparations.items() + if self.source.motion.observer_preparations.get(name) != plan}) + if strategy == TRAJECTORY_OBSERVER: + audit.update(policy='unmeasured_observer_upgrade_v3', + target_observation_policy='occlusion_aware_trajectory_v3', + accepted_evidence_semantics='preserved_without_reinterpretation', + pending_evidence_semantics='full_trajectory_with_bounded_observation') + return header, reference, audit + + +def upgrade_checkpoint(upgrade, source_path, output_dir, *, serial_number, + protected_inputs, source_urdf, image_replay_workers=1): + source_path, output_dir = Path(source_path), Path(output_dir) + upgrade = replace(upgrade, source_urdf=Path(source_urdf)) + if output_dir.exists(): + raise FileExistsError(output_dir) + for profile in (upgrade.source, upgrade.target): + validate_executable_profile(profile, source_urdf) + with source_path.open('rb') as stream: + source_digest = hashlib.file_digest(stream, 'sha256').hexdigest() + checkpoint = PreparedResume.load(upgrade.source, CalibrationEngine(upgrade.source), + source_path, serial_number, image_replay_workers=image_replay_workers, + resume_mode='passed', source_urdf=source_urdf) + header, reference, audit = upgrade.metadata(checkpoint, protected_inputs, source_path, source_digest) + replacement = {'session_start': header, 'fixed_base_reference_locked': reference} + rows = tuple(replacement.get(row.get('kind'), row) for row in checkpoint.rows) + (audit,) + verified = JointResume(upgrade.target, image_replay_workers=image_replay_workers) + stage_visits(verified, CalibrationEngine(upgrade.target), rows) + if (verified.units != checkpoint.joints.units or verified.references != checkpoint.joints.references + or verified.first_cycle_spans != checkpoint.joints.first_cycle_spans): + raise ValueError('observer_upgrade_changes_reusable_evidence') + output_dir.mkdir(parents=True, exist_ok=False) + try: + _copy_indexed_evidence(source_path, output_dir) + temporary = output_dir/'raw_samples.jsonl.tmp' + digest = hashlib.sha256() + with source_path.open('rb') as source, temporary.open('xb') as target: + for line in source: + digest.update(line) + row = json.loads(line) if line.strip() else {} + if row.get('kind') in replacement: + target.write((json.dumps(replacement[row['kind']], ensure_ascii=False)+'\n').encode()) + else: + target.write(line) + target.write(('\n'+json.dumps(audit, ensure_ascii=False)+'\n').encode()) + if digest.hexdigest() != source_digest: + raise ValueError('observer_upgrade_source_changed_during_replay') + (output_dir/'source_profile.yaml').write_bytes(upgrade.source_yaml) + (output_dir/'target_profile.yaml').write_bytes(upgrade.target_yaml) + report = {**audit, 'reusable_units': len(verified.units), 'result': 'STATIC_REPLAY_PASSED'} + installed = output_dir/'raw_samples.jsonl' + temporary.rename(installed) + if (output_dir/'raw_samples.storage.json').is_file(): + from ..core.artifacts.evidence_journal import compact_existing_journal + report['storage_compaction'] = compact_existing_journal(installed, replace=True) + (output_dir/'observer_upgrade.json').write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n') + return report + except Exception: + shutil.rmtree(output_dir, ignore_errors=True) + raise + + +def main(): + import argparse + from ..product import load_product_config + from .runner_support import protected_inputs + from .image_replay import checkpoint_replay_workers + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--source-profile', required=True) + parser.add_argument('--target-product', required=True) + parser.add_argument('--source-checkpoint', required=True) + parser.add_argument('--output-dir', required=True) + args = parser.parse_args() + product = load_product_config(args.target_product, check_can=False) + upgrade = ObserverPolicyUpgrade.load(args.source_profile, product.profile_config) + report = upgrade_checkpoint(upgrade, args.source_checkpoint, args.output_dir, + serial_number=product.serial_number, protected_inputs=protected_inputs(product), + source_urdf=product.source_urdf, image_replay_workers=checkpoint_replay_workers()) + print(json.dumps({key: report[key] for key in ( + 'result', 'reusable_units', 'observer_policy_changes')}, ensure_ascii=False), flush=True) + + +if __name__ == '__main__': + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_training_upgrade.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_training_upgrade.py new file mode 100644 index 0000000..519944a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/checkpoint_training_upgrade.py @@ -0,0 +1,173 @@ +"""Audited migration from whole-hand staged training to taskwise staged training. + +The measurement contract, motion paths, accepted scan identities and raw image +evidence stay unchanged. Only the ordering of future training visits and the +time at which a task-local repeatability decision is made are revised. The +source journal is immutable and the target journal links its content-addressed +evidence blocks. +""" + +from dataclasses import dataclass +import hashlib +import json +from pathlib import Path +import shutil + +from ..core.domain.capture_plan import (CapturePlan, STAGED, TASKWISE_STAGED, + configure_training) +from ..profiles import load_hand_profile +from ..profiles.export import dump_hand_profile +from ..profiles.preparation import preparation_contract +from ..profiles.validator import validate_executable_profile +from .engine import CalibrationEngine, capture_schedule_version +from .joint_resume import PreparedResume, JointResume +from .resume_storage import materialize_record +from .staged_resume import stage_passed_visits + + +@dataclass(frozen=True) +class TaskwiseTrainingUpgrade: + source: object + target: object + source_yaml: bytes + target_yaml: bytes + + @classmethod + def load(cls, source_profile): + source = load_hand_profile(source_profile) + if source.quality.training_policy != STAGED: + raise ValueError("taskwise_upgrade_requires_staged_source") + target = configure_training(source, TASKWISE_STAGED) + return cls(source, target, Path(source_profile).read_bytes(), + dump_hand_profile(target).encode()) + + def replacement_records(self, checkpoint, *, source_path, source_digest): + if any(row.get("kind") in {"staged_training_decision", "training_decision"} + for row in checkpoint.rows): + raise ValueError("taskwise_upgrade_training_decision_already_recorded") + source_header = materialize_record(checkpoint.header) + source_reference = materialize_record(checkpoint.fixed_reference) + old_hash = hashlib.sha256(self.source_yaml).hexdigest() + new_hash = hashlib.sha256(self.target_yaml).hexdigest() + actual = source_header.get("protected_hashes", source_header) + if actual.get("profile_config_sha256") != old_hash: + raise ValueError("taskwise_upgrade_source_profile_hash_changed") + if source_header.get("preparation_contract") != preparation_contract(self.source): + raise ValueError("taskwise_upgrade_source_preparation_changed") + if preparation_contract(self.target) != preparation_contract(self.source): + raise ValueError("taskwise_upgrade_changes_preparation_contract") + + header = {**source_header, + "capture_schedule_version": capture_schedule_version(self.target), + "capture_plan": CapturePlan.from_profile(self.target).as_dict(), + "profile_config_sha256": new_hash, + "resume_checkpoint_requested": True} + if "protected_hashes" in header: + header["protected_hashes"] = {**header["protected_hashes"], + "profile_config_sha256": new_hash} + reference = {**source_reference, "protected_hashes": { + **source_reference["protected_hashes"], "profile_config_sha256": new_hash}} + audit = { + "kind": "capture_schedule_revision", + "version": "taskwise_staged_training_upgrade_v1", + "source_raw_samples": str(Path(source_path).resolve()), + "source_raw_sha256": source_digest, + "source_profile_sha256": old_hash, + "target_profile_sha256": new_hash, + "source_policy": STAGED, + "target_policy": TASKWISE_STAGED, + "accepted_evidence_semantics": "preserved_without_reinterpretation", + "future_schedule": ( + "first_whole_hand_pass_then_taskwise_second_pass_with_immediate_supplement_then_validation" + ), + "completed_units": [list(unit) for unit in sorted(checkpoint.joints.units)], + } + return header, reference, audit + + +def upgrade_checkpoint(upgrade, source_path, output_dir, *, serial_number, + source_urdf, image_replay_workers=1): + source_path, output_dir = Path(source_path).resolve(), Path(output_dir).resolve() + if output_dir.exists(): + raise FileExistsError(output_dir) + for profile in (upgrade.source, upgrade.target): + validate_executable_profile(profile, source_urdf) + with source_path.open("rb") as stream: + source_digest = hashlib.file_digest(stream, "sha256").hexdigest() + checkpoint = PreparedResume.load(upgrade.source, CalibrationEngine(upgrade.source), + source_path, serial_number, image_replay_workers=image_replay_workers, + resume_mode="passed", source_urdf=source_urdf) + header, reference, audit = upgrade.replacement_records(checkpoint, + source_path=source_path, source_digest=source_digest) + replacement = {"session_start": header, "fixed_base_reference_locked": reference} + rows = tuple(replacement.get(row.get("kind"), row) for row in checkpoint.rows) + (audit,) + + # The source is itself an unchanged-installation ``passed`` checkpoint. + # Its compact journal intentionally omits historical witness windows that + # strict replay would require. Preserve and compare the same durable pass + # decisions here; finalization still performs the complete evidence replay + # before it may publish JSON/URDF artifacts. + verified = JointResume(upgrade.target, image_replay_workers=image_replay_workers) + stage_passed_visits(verified, CalibrationEngine(upgrade.target), rows) + if (verified.units != checkpoint.joints.units + or verified.references != checkpoint.joints.references + or verified.first_cycle_spans != checkpoint.joints.first_cycle_spans): + raise ValueError("taskwise_upgrade_changes_reusable_evidence") + + output_dir.mkdir(parents=True, exist_ok=False) + try: + raw = output_dir / "raw_samples.jsonl" + from ..core.artifacts.evidence_journal import initialize_evidence_journal + from ..core.artifacts.storage import append_jsonl_many, sync_jsonl + initialize_evidence_journal(raw) + for offset in range(0, len(rows), 4096): + append_jsonl_many(raw, rows[offset:offset + 4096], durable=False) + sync_jsonl(raw) + (output_dir / "source_profile.yaml").write_bytes(upgrade.source_yaml) + target_profile = output_dir / "target_profile.yaml" + target_profile.write_bytes(upgrade.target_yaml) + prepared = PreparedResume.load(upgrade.target, CalibrationEngine(upgrade.target), + raw, serial_number, image_replay_workers=image_replay_workers, + resume_mode="passed", source_urdf=source_urdf) + if (prepared.completed_units != frozenset(verified.units) + or prepared.joints.references != verified.references + or prepared.joints.first_cycle_spans != verified.first_cycle_spans): + raise ValueError("taskwise_upgrade_written_checkpoint_changed") + report = {**audit, "reusable_units": len(verified.units), + "zero_references": len(verified.references), + "target_profile": str(target_profile), + "resume_validation": "passed_mode_loaded", + "historical_replay_performed": False, + "full_replay_required_before_publication": True, + "result": "PASSED_EVIDENCE_PRESERVATION_VERIFIED"} + (output_dir / "training_upgrade.json").write_text( + json.dumps(report, ensure_ascii=False, indent=2) + "\n") + return report + except Exception: + shutil.rmtree(output_dir, ignore_errors=True) + raise + + +def main(): + import argparse + from ..product import load_product_config + from .image_replay import checkpoint_replay_workers + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-profile", required=True) + parser.add_argument("--target-product", required=True) + parser.add_argument("--source-checkpoint", required=True) + parser.add_argument("--output-dir", required=True) + args = parser.parse_args() + product = load_product_config(args.target_product, check_can=False) + upgrade = TaskwiseTrainingUpgrade.load(args.source_profile) + report = upgrade_checkpoint(upgrade, args.source_checkpoint, args.output_dir, + serial_number=product.serial_number, source_urdf=product.source_urdf, + image_replay_workers=checkpoint_replay_workers()) + print(json.dumps({key: report[key] for key in ( + "result", "reusable_units", "zero_references", "target_profile" + )}, ensure_ascii=False), flush=True) + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/coordinator.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/coordinator.py new file mode 100644 index 0000000..5f910bd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/coordinator.py @@ -0,0 +1,2310 @@ +"""Transport-neutral owner of the live calibration session. + +State transitions, capture submission and artifact commit share one RLock. +The lock order is always coordinator state, then finalization worker; fitting +and pose estimation never hold the state lock while doing expensive work. +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import asdict, replace +from ..core.domain.motion_path import record_scan_identity +import hashlib +import json +import threading +import traceback + +import numpy as np + +from ..acquisition import StateSample, interpolate_state_u8 +from ..core.domain.profile import CalibrationProfile +from ..core.domain.reference import build_joint_zero_reference +from ..core.geometry.pnp import POSE_TRACKING_POLICY_VERSION, SquareTagPoseTracker +from ..core.urdf.partial_scope import profile_scope +from ..storage import append_jsonl, append_jsonl_many, atomic_write_json, sync_jsonl +from .engine import ACQUISITION_POLICY_VERSION, CAPTURE_SCHEDULE_VERSION +from .reference_lock import ReferenceLock +from .artifacts.controller import FinalizationController, FinalizationInputs, FinalizationProtocolError +from .cameras import CameraObservations +from .camera_preflight import CameraPreflight +from .capture import CaptureFrame, CaptureTiming, ObservationCapture +from .branch_initialization import BranchInitialization, solve_initialization +from .branch_diagnostics import record_solver_event +from .execution import SessionExecution +from .diagnostic_capture import diagnostic_hold_timing, resolve_diagnostic_capture, reject_diagnostic_capture +from .diagnostic_reference import build_diagnostic_zero_attempt +from .inputs import AdapterFactory, CameraModelInput, DetectionInput, RuntimePorts, ServiceResult +from .pose_evidence import reference_branch_revisions +from .motion_execution import MotionExecution +from .parameters import RuntimeParameters +from .resume import ResumeDecision, ResumeVerifier, fingerprint_from_mapping +from .safety import SafetyPolicy, SafetySample +from .session import CalibrationPhase as Phase +from .snapshot import DeviceReadiness, CameraReadiness, RuntimeSnapshot, build_snapshot, legacy_state +from ..core.domain.capture_plan import (CapturePlan, ADAPTIVE, STAGED, + TASKWISE_STAGED, STAGED_POLICIES, raw_joint_capture, raw_feedback_capture) + + +_TERMINAL_STATES = frozenset({"PASSED", "CAPTURE_COMPLETE", "DIAGNOSTIC_COMPLETE", "PAUSED", "ABORTED", "FAILED"}) + + +class CalibrationCoordinator: + def __init__(self, profile: CalibrationProfile, parameters: RuntimeParameters, + ports: RuntimePorts, adapter_factory: AdapterFactory, *, finalization=None, + initialization_solver=None, projection_worker=None): + self.profile, self.parameters, self.ports = profile, parameters, ports + self.raw_joint = raw_joint_capture(profile) + from .timing_diagnostics import StageTiming + self.stage_timing = StageTiming(ports.monotonic()) + self._timing_saved = False + self.initialization_solver = initialization_solver + self.projection_worker = projection_worker + self.step_data_lock = threading.RLock() + self.model_name = profile.key.model + self.command_names = tuple(profile.command.names) + self.command_count = profile.command.command_count + self.command_unit = profile.command.unit + self.feedback_lower = tuple(profile.command.minimum_feedback_values) + self.feedback_upper = tuple(profile.command.maximum_feedback_values) + self.diagnostic_capture = resolve_diagnostic_capture(profile, parameters.diagnostic_capture) + self.raw_joint = self.raw_joint and self.diagnostic_capture is None + self.raw_feedback = raw_feedback_capture(profile) and self.diagnostic_capture is None + if self.raw_feedback and parameters.resume_raw_samples_path is not None: + raise ValueError("raw_feedback_resume_requires_offline_verification_not_implemented") + if self.diagnostic_capture is not None and ( + not parameters.commands_enabled or parameters.resume_raw_samples_path is not None): + raise ValueError("diagnostic_capture_requires_fresh_command_enabled_session") + self.execution = SessionExecution(profile, diagnostic_capture=self.diagnostic_capture) + from .chain_capture import DeferredChainCapture + self.chain_capture = (DeferredChainCapture(profile, self.diagnostic_capture) + if self.diagnostic_capture is not None and self.diagnostic_capture.chain_joints else None) + self.training_worker = None + self._training_request = None + self._frozen_training_sha256 = None + if profile.quality.training_policy in {ADAPTIVE, STAGED, TASKWISE_STAGED}: + if self.diagnostic_capture is not None: + raise ValueError("adaptive_training_cannot_run_as_diagnostic") + from .training import TrainingWorker + self.training_worker = TrainingWorker() + self.safety = SafetyPolicy(profile) + from .stall_retry import StallRetry + self.stall_retry = StallRetry(maximum_failures=2 if self.raw_joint else 3) if profile.key.model.upper() == 'O30' else None + self.reference_lock = self._new_reference_lock() + self.trackers = parameters.new_trackers(self.required_observation_views) + self.capture = ObservationCapture(profile, reference_lock=self.reference_lock, + extrinsics=parameters.extrinsics, tag_size_m=parameters.tag_size_m, trackers=self.trackers, + projection_worker=projection_worker) + self.latest_feedback: tuple[float, ...] = () + self.state_history: deque[StateSample] = deque(maxlen=2000) + self.state_receive_times: deque[float] = deque(maxlen=300) + self.command_history: deque[StateSample] = deque(maxlen=2000) + self.command_direction_history = deque(maxlen=2000) + self._command_directions = [""]*self.command_count + self._actual_command_count = 0 + self._actual_direction_changes = [0]*self.command_count + self.finalization = finalization or FinalizationController(profile, parameters.session_dir, + isolated=self.raw_joint) + from .journal_durability import JournalDurabilityWorker + self.journal_durability = JournalDurabilityWorker() + from .capture_index import CaptureRecordIndex + self.capture_index = CaptureRecordIndex(retain_complete=( + self.diagnostic_capture is None and not getattr(self.finalization, "uses_journal", False)), + retain_training_geometry=(self.diagnostic_capture is None + and profile.quality.training_policy in {ADAPTIVE, STAGED, TASKWISE_STAGED})) + self._image_record_stamps = {} + self.last_command = None + self.commanded_speed = None + self.step_speed_ready_at = 0.0 + self.reason = "waiting_for_feedback_and_camera_info" + self._started_at: float | None = None + self._camera_preflight: CameraPreflight | None = None + self._observation_epoch = 0 + self._pause_effects_applied = False + self.segment = None + self._direction_progress = None + self._raw_capture_closed = False + self._settled_pose = None + self._segment_number = 0 + self._motion = None + self._motion_started_ns = 0 + self._steady_capture_after_ns = None + self._zero_geometry_started_at = None + self._zero_geometry_completed_at = None + self._zero_capture_started_at = None + self._resume_message = ("diagnostic_capture_no_resume" if self.diagnostic_capture else + "已请求按通过任务续采,不复核已完成关节零位" if parameters.resume_raw_samples_path is not None + and parameters.resume_mode == "passed" else + "waiting_for_reference_verification" if parameters.resume_raw_samples_path is not None else + "not_requested") + self._resumed_count = 0 + self._resume_import = None + self._raw_resume_import = None + from .raw_resume import InstallationReference + self._raw_installation = InstallationReference(profile) if self.raw_joint else None + self._reference_import = None + self._passed_reference_import = None + from .visual_motion import VisualMotionObserver + self.visual_motion = VisualMotionObserver(profile) if profile.vision_motion else None + self._visual_wait_started_at = None + from .joint_resume import JointResume, PreparedResume + self.joint_resume = JointResume(profile) + self._resume_checkpoint, self._resume_checkpoint_error = None, "" + if parameters.resume_raw_samples_path is not None: + self.stage_timing.enter("resume_loading", ports.monotonic()) + from .image_replay import checkpoint_replay_workers + try: + from .raw_resume import RawCheckpoint + checkpoint_type = RawCheckpoint if self.raw_joint else PreparedResume + self._resume_checkpoint = checkpoint_type.load(profile, self.execution.session.engine, + parameters.resume_raw_samples_path, parameters.serial_number, + image_replay_workers=checkpoint_replay_workers(), resume_mode=parameters.resume_mode, + source_urdf=parameters.source_urdf) + except (OSError, ValueError, KeyError, TypeError) as error: + self._resume_checkpoint_error = str(error) + self.stage_timing.enter("startup", ports.monotonic()) + self._unit_rows = [] + self._capture_unit_key = None + self._steady_rows = [] + self._zero_reference_error = "" + self._branch_observation_reasons = {} + self.branch_initialization = BranchInitialization(profile, source_urdf=parameters.source_urdf) + from .zero_recovery import ZeroRecovery + self.zero_recovery = ZeroRecovery() + self._reference_capture_key = None + self._reference_observation_started = None + self._current_fingerprint = {} + self.final_json = "" + self.final_urdf = "" + for path, key in ((parameters.source_urdf, "source_urdf_sha256"), + (parameters.camera_extrinsics_file, "camera_extrinsics_sha256")): + if hashlib.sha256(path.read_bytes()).hexdigest() != parameters.protected_inputs[key]: + raise ValueError(f"protected input changed:{key}") + from ..profiles.validator import validate_executable_profile + validate_executable_profile(profile, parameters.source_urdf) + parameters.session_dir.mkdir(parents=True, exist_ok=True) + self.raw_path = parameters.session_dir / "raw_samples.jsonl" + from ..core.artifacts.evidence_journal import initialize_evidence_journal + initialize_evidence_journal(self.raw_path) + self._session_header = { + "kind": "session_start", "sample_schema_version": profile.artifacts.output_schema_version, + "calibration_scope": profile_scope(profile), + "profile_id": profile.key.profile_id, "serial_number": parameters.serial_number, + "curve_input_domain": profile.curve_input_domain, + "acquisition_policy_version": ACQUISITION_POLICY_VERSION, + "capture_schedule_version": self.execution.session.engine.capture_schedule_version, + "capture_plan": CapturePlan.from_profile(profile).as_dict(), + "pose_tracking_policy_version": POSE_TRACKING_POLICY_VERSION, + "required_observation_views": list(self.required_observation_views), + **parameters.protected_inputs, + "resume_checkpoint_requested": parameters.resume_raw_samples_path is not None, + "resume_mode": parameters.resume_mode, + "motion_observation": profile.acquisition.motion_observation, + "fixed_reference_mode": profile.acquisition.fixed_reference_mode, + "initial_command_observation": {"values": list(parameters.initial_command), + "device_uid": parameters.initial_device_uid, + "source": "sdk_target_position_register" if parameters.initial_command else "adapter_feedback"}, + **({"diagnostic_capture": self.diagnostic_capture.as_dict()} if self.diagnostic_capture else {}), + } + from ..profiles.preparation import preparation_contract + preparation = preparation_contract(profile) + if preparation is not None: + self._session_header["preparation_contract"] = preparation + if profile.acquisition.command_capture_mode == "separate" and self.diagnostic_capture is None: + from ..core.fitting.command_sampling import SAMPLING_POLICY + self._session_header["command_sampling_policy"] = SAMPLING_POLICY + append_jsonl(self.raw_path, self._session_header) + self.capture_index.append(self._session_header) + self.cameras = CameraObservations(parameters.extrinsics, self.raw_path, ports.monotonic) + self.sdk_adapter = adapter_factory(self._write_position, self._write_speed, self.feedback_fresh) + + @property + def raw_records(self): + """Explicit full-evidence access; live checks use capture_index instead.""" + if self.capture_index.retain_complete: + return list(self.capture_index) + from .acquisition import load_capture + return load_capture(self.raw_path) + + @property + def state(self) -> str: + return legacy_state(self.execution.session.phase) + + @property + def started(self) -> bool: + return self._started_at is not None + + @property + def required_observation_views(self) -> tuple[str, ...]: + return self.execution.session.required_observation_views + + def start(self) -> ServiceResult: + with self.step_data_lock: + if self.execution.session.phase != Phase.READY or not self.parameters.commands_enabled: + return ServiceResult(False, self.reason) + if self.raw_joint and self._resume_checkpoint_error: + self.reason = 'raw_resume_rejected:' + self._resume_checkpoint_error + return ServiceResult(False, self.reason) + devices = self._device_status(self.ports.monotonic()) + self._record_camera_preflight(devices, at_start=devices.ready) + if not devices.ready: + self.execution.session.devices_unavailable() + self.reason = "; ".join(devices.waiting_for) + return ServiceResult(False, self.reason) + if self.raw_joint: + try: + self._verify_optical_preflight() + except (ValueError, OSError, KeyError, TypeError) as error: + self.reason = 'raw_optical_preflight_failed:' + str(error) + return ServiceResult(False, self.reason) + # Swap complete capture objects: an in-flight preview PnP callback + # may finish later, but cannot populate the new formal reference. + self.reference_lock = self._new_reference_lock() + self.reference_lock.begin_session() + self.trackers = self.parameters.new_trackers(self.required_observation_views) + self.capture = ObservationCapture(self.profile, reference_lock=self.reference_lock, + extrinsics=self.parameters.extrinsics, tag_size_m=self.parameters.tag_size_m, trackers=self.trackers, + projection_worker=self.projection_worker) + if self.profile.vision_motion: + from .visual_motion import VisualMotionObserver + self.visual_motion = VisualMotionObserver(self.profile) + self._visual_wait_started_at = None + self.state_history.clear() + self.command_history.clear() + self.command_direction_history.clear() + self._command_directions = [""]*self.command_count + # Both the in-memory and process finalizers consume a self-contained + # capture, including the source identity used by CAD constraints. + self.capture_index.reset((self._session_header,)) + self._image_record_stamps.clear() + self._branch_observation_reasons.clear() + self.branch_initialization.clear() + self.branch_initialization.parent_references.clear() + if self.chain_capture is not None: + self.chain_capture.clear() + self.branch_initialization.witness_capture.clear() + self.branch_initialization.observer_preparation.clear() + self.execution.session.start(resume_requested=self.parameters.resume_raw_samples_path is not None) + self._started_at = self.ports.monotonic() + self.stage_timing.mark_start(self._started_at) + self._observation_epoch += 1 + self.reason = "moving_to_safe_baseline" + self._publish_torque() + return ServiceResult(True, "标定已开始;安全基准后锁定参考") + + def abort(self) -> ServiceResult: + with self.step_data_lock: + if self.state in {"FAILED", "ABORTED"}: + return ServiceResult(False, self.reason) + if self.state == "CAPTURE_COMPLETE": + return ServiceResult(False, "raw_capture_already_complete") + if self.state == "DIAGNOSTIC_COMPLETE": + return ServiceResult(False, "diagnostic_capture_already_complete") + if self.state == "PASSED": + return ServiceResult(False, "calibration_already_published") + self._pause("operator_abort_holding_current_position") + self.execution.session.abort() + self.reason = "operator_abort_holding_current_position" + return ServiceResult(True, self.reason) + + def receive_feedback(self, names, positions, stamp_ns: int, *, channel_stamps_ns=()) -> StateSample | None: + with self.step_data_lock: + if self._raw_capture_closed: + return None + return self._accept_feedback(names, positions, stamp_ns, channel_stamps_ns=channel_stamps_ns) + + def receive_camera_info(self, view: str, message: CameraModelInput) -> None: + with self.step_data_lock: + if (view not in self.required_observation_views or self.finalization.started + or self.state in _TERMINAL_STATES): + return + self.cameras.accept(view, message, started=self.started, pause=self._pause, trackers=self.trackers) + + def _record_solver_event(self, request, event, **details): + record_solver_event(self.parameters.session_dir / "motion_solver_diagnostic.jsonl", + request, event, stamp_ns=self.ports.clock_ns(), + monotonic_time=self.ports.monotonic(), **details) + + def receive_motion_observation(self, observation: DetectionInput) -> None: + """Observe raw pixels before any potentially slow geometry worker. + + The ROS callback and offline host use the same idempotent boundary. + A branch solve cannot make current camera evidence appear stale. + """ + if self.visual_motion is None: + return + from .detection_filter import filter_detections + view, stamp = observation.view, observation.stamp_ns + with self.step_data_lock: + if (view not in self.cameras.image_sizes or self.finalization.started + or self.state in _TERMINAL_STATES + or not 0 <= self.ports.clock_ns()-stamp <= self.profile.acquisition.visual_stale_seconds*1e9 + or (self._motion is not None and stamp < self._motion_started_ns)): + return + width, height = self.cameras.image_sizes[view] + corners, _, _ = filter_detections(self._view(view), self.parameters.detection, + observation, width, height, self._motion) + command = next((row.position_u8 for row in reversed(self.command_history) + if 0 <= stamp-row.stamp_ns <= self.parameters.maximum_state_image_skew_ns), None) + self.visual_motion.observe(view, stamp, corners, now=self.ports.monotonic(), + epoch=self._observation_epoch, version=self._segment_number, command=command) + self._flush_visual_evidence() + + def receive_detections(self, observation: DetectionInput) -> None: + self.receive_motion_observation(observation) + view, stamp = observation.view, observation.stamp_ns + received_stamp = self.ports.clock_ns() + with self.step_data_lock: + if (view not in self.required_observation_views or self.finalization.started + or self.state in _TERMINAL_STATES): + return + self.cameras.detections_received_at[view] = self.ports.monotonic() + if view not in self.cameras.matrices or self.state in _TERMINAL_STATES: + return + capture, motion = self.capture, self._motion + if motion is not None and stamp < self._motion_started_ns: + return + epoch = self._observation_epoch + motion_version = self._segment_number + initialization_owner = self.chain_capture or self.branch_initialization + initialization = None if self.raw_joint or self.raw_feedback else initialization_owner.request(view, motion, + session_epoch=epoch, motion_version=motion_version, + zero_references=self.execution.zero_references) + if initialization is not None and self._zero_geometry_started_at is None: + self._zero_geometry_started_at = self.ports.monotonic() + accepted_joints = self._diagnostic_accepted_joints(motion) + steady_after = self._steady_capture_after_ns + locking = self._reference_capture_key or self.execution.session.phase == Phase.REFERENCE_LOCKING + matrix = self.cameras.matrices[view].copy() + width, height = self.cameras.image_sizes[view] + feedback_history = tuple(self.state_history) + command_history = tuple(self.command_history) + direction_history = tuple(self.command_direction_history) + timing = CaptureTiming(received_stamp, self.ports.clock_ns(), + feedback_history[-1].stamp_ns if feedback_history else None, + command_history[-1].stamp_ns if command_history else None) + if initialization is not None: + solver_started = self.ports.monotonic() + self._record_solver_event(initialization, "request_created", + current_motion_version=motion_version) + try: + resolution = (self.initialization_solver or solve_initialization)(initialization) + except Exception: + self._record_solver_event(initialization, "solve_exception", + elapsed_seconds=self.ports.monotonic()-solver_started, + traceback=traceback.format_exc()) + raise + self._record_solver_event(initialization, "solve_finished", + elapsed_seconds=self.ports.monotonic()-solver_started, + resolved=resolution.resolved, reason=resolution.reason) + with self.step_data_lock: + if (epoch != self._observation_epoch or capture is not self.capture + or motion is not self._motion or motion_version != self._segment_number): + self._record_solver_event(initialization, "commit_rejected", + current_session_epoch=self._observation_epoch, + expected_current_motion_version=motion_version, + current_motion_version=self._segment_number, + capture_changed=capture is not self.capture, + motion_changed=motion is not self._motion) + return + accepted = initialization_owner.accept(initialization, resolution) + if accepted is None: + self._record_solver_event(initialization, "commit_rejected", + current_generation=initialization_owner.generation) + return + model, report = accepted + append_jsonl(self.raw_path, report) + self.capture_index.append(report) + if not initialization_owner.pending(): + self._zero_geometry_completed_at = self.ports.monotonic() + if model is not None: + capture.install_motion_model(model) + # Keep feedback readiness independent of geometry. If a + # stable window already exists, only post-confirmation + # images may establish zero; older callbacks are invalid. + self._steady_rows.clear() + self._zero_capture_started_at = None + if self._steady_capture_after_ns is not None: + self._steady_capture_after_ns = self.ports.clock_ns() + steady_after = self._steady_capture_after_ns + accepted_joints = self._diagnostic_accepted_joints(motion) + self._record_solver_event(initialization, "commit_accepted", + resolved=resolution.resolved) + from .detection_filter import filter_detections + corners, quality_events, observed_roles = filter_detections(self._view(view), + self.parameters.detection, observation, width, height, motion) + matched = interpolate_state_u8(feedback_history, stamp, maximum_skew_ns=self.parameters.maximum_state_image_skew_ns) + # Commands are sample-and-held by the transport, NOT interpolated + # from a future setpoint or read from the current motion timer. + command_sample = next((row for row in reversed(command_history) + if row.stamp_ns <= stamp and stamp-row.stamp_ns <= self.parameters.maximum_state_image_skew_ns), None) + command = None if command_sample is None else command_sample.position_u8 + frame = CaptureFrame(view, stamp, matrix, corners, + None if matched is None else matched[0], command, 0 if matched is None else matched[1], + next((d for t, d in reversed(direction_history) if t <= stamp), ()), observed_roles, timing, + None if command_sample is None else stamp-command_sample.stamp_ns, + {tag.role: dict(hamming=d.hamming, decision_margin=d.decision_margin, + border_quality=d.border_quality) for tag in self._view(view).tags + for d in observation.detections if d.tag_id == tag.tag_id}) + record_motion = motion + if motion is not None and motion.phase in {"steady", "joint_zero"} and (steady_after is None or stamp < steady_after): + record_motion = None + from .image_capture import image_observation_record + raw_image = None if self.raw_joint else image_observation_record(self.profile, frame, record_motion) + # Pose estimation is deliberately outside the state lock. Start swaps + # capture objects; pause/abort invalidates the epoch; movement changes + # the motion identity. None of their late results may enter the session. + from .observer_preparation import PHASES as OBSERVER_PHASES + if motion is not None and motion.phase in OBSERVER_PHASES: + # The probe intentionally changes a common ancestor. Its raw + # corners must not be interpreted by the held-parent hinge model. + # Fixed-reference movement is still checked on every exposure. + rows, movement = capture.consume(frame, fixed_reference_only=True) + elif self.raw_feedback: + # Keep the fixed-fixture safety check, but do not run online PnP + # for moving tags. The separately recorded corners are the data. + rows, movement = capture.consume(frame, fixed_reference_only=True) + else: + rows, movement = capture.consume(frame, motion, collect_installations=locking, + diagnostic=self.diagnostic_capture is not None, allow_recording=record_motion is not None, + accepted_joints=accepted_joints, raw_joint=self.raw_joint) + rows = (*(() if raw_image is None else (raw_image,)), *quality_events, *rows) + with self.step_data_lock: + if (epoch != self._observation_epoch or capture is not self.capture + or motion is not self._motion or motion_version != self._segment_number + or stamp <= self._image_record_stamps.get(view, 0)): + return + if motion is not None and motion.phase in {"steady", "joint_zero"} and steady_after != self._steady_capture_after_ns: + if self.diagnostic_capture is None or motion.phase != "steady" or motion.minimum_hold_seconds <= 0: + return + # The diagnostic needs the actual approach and recovery, too. + # Its unaccepted raw images are retained while ordinary joint + # samples still require an unchanged stable-feedback window. + rows = tuple(row for row in rows if row.get("kind") in { + "diagnostic_observation_frame", "pnp_branch_event"}) + record_motion = None + if movement is not None: + self._pause(f"fixed_reference_moved:{view}:{movement.drift_px}") + return + if self._raw_installation is not None and locking: + self._raw_installation.observe(frame) + if self.visual_motion is not None: + if self.segment is not None and motion is not None and motion.phase in {"steady", "joint_zero"}: + settled = self.visual_motion.settle_record(self.segment.finished_at, + self.ports.monotonic(), epoch=epoch, through_stamp=stamp) + if not settled: + rows = tuple(row for row in rows if row.get("kind") not in { + "joint_zero_sample", "joint_sample", "secondary_joint_sample", + "pnp_candidate_frame", "image_observation_frame"}) + self._flush_visual_evidence() + # A cached parent or a late image cannot borrow another + # exposure's motion/stability witness. + rows = tuple(row for row in rows if row.get("kind") not in { + "joint_zero_sample", "joint_sample", "secondary_joint_sample"} + or self.visual_motion.has_image(row.get("joint", row.get("observation_joint")), stamp)) + branch_events = [row for row in rows if row.get("kind") == "pnp_branch_event"] + self.capture_index.extend(branch_events) + # Per-record fsync while holding this lock stalls SDK feedback + # and command ticks. Persist references and scan checkpoints; + # flush continuous image evidence in batches between them. + append_jsonl_many(self.raw_path, branch_events, durable=False) + for row in branch_events: + if self._accept_branch_event(row): + return + sample_rows = [row for row in rows if row.get("kind") != "pnp_branch_event" + and (record_motion is not None + or (self.raw_joint and row.get("kind") == "raw_observation_frame") + or (self.diagnostic_capture is not None and motion is not None + and motion.phase == "steady" and motion.minimum_hold_seconds > 0 + and row.get("kind") == "diagnostic_observation_frame") + or row.get("kind") not in { + "joint_zero_sample", "joint_sample", "secondary_joint_sample", "pnp_candidate_frame", "image_observation_frame", + "diagnostic_observation_frame", "raw_observation_frame"})] + for row in sample_rows: + if row.get("kind") == "image_observation_frame": + self._image_record_stamps[view] = stamp + row.update(session_epoch=epoch, motion_version=motion_version, + motion_started_ns=self._motion_started_ns) + if not self.raw_joint and not self.raw_feedback: + self.branch_initialization.observer_preparation.observe(row) + self.branch_initialization.parent_references.handoff.observe(row) + if row.get("kind") in {"diagnostic_observation_frame", "raw_observation_frame"}: + row.update(session_epoch=epoch, motion_version=motion_version, + motion_started_ns=self._motion_started_ns) + if self.stall_retry is not None and self.stall_retry.waiting: + row.update(sample_phase='stall_retry_wait', accepted_sample_window_open=False) + if motion.phase == "steady" and motion.minimum_hold_seconds > 0: + row.update(diagnostic_hold_timing(command_history, target=motion.target, + image_stamp_ns=stamp, session_epoch=epoch, motion_version=motion_version, + motion_started_ns=self._motion_started_ns, + feedback_stable_since_ns=steady_after)) + row["accepted_sample_window_open"] = record_motion is not None + if self.chain_capture is not None: + self.chain_capture.observe(row) + if row.get("kind") == "motion_branch_observation": + row.update(session_epoch=epoch, motion_version=motion_version) + if motion.reference_path_index is not None: + row["reference_path_index"] = motion.reference_path_index + self.branch_initialization.observe(row) + self.capture_index.append(row) + continue + for item in row.get("pnp_observation_evidence", {}).values(): + diagnostics = item["candidate_diagnostics"] + if (diagnostics.get("observation_stamp_ns") == row.get("image_stamp_ns") + and diagnostics.get("branch_status") == "tracking"): + self._branch_observation_reasons.pop((row["view"], item["tag_role"]), None) + self.capture_index.append(row) + self._unit_rows.append(row) + if motion is not None and motion.phase in {"steady", "joint_zero"}: + if self.visual_motion is not None and row.get("kind") in { + "joint_zero_sample", "joint_sample", "secondary_joint_sample"}: + row["visual_settled_evidence_id"] = self.visual_motion.window_id + self._steady_rows.append(row) + if row.get("kind") == "joint_zero_sample": + row["capture_timing"] = { + "received_stamp_ns": received_stamp, + "committed_stamp_ns": self.ports.clock_ns(), + "history_snapshot_stamp_ns": timing.history_snapshot_stamp_ns, + } + if row.get("kind") == "joint_zero_sample" and self._zero_capture_started_at is None: + self._zero_capture_started_at = self.ports.monotonic() + append_jsonl_many(self.raw_path, sample_rows, durable=False) + + def _diagnostic_accepted_joints(self, motion): + """Immutable sample permissions, captured under the observation lock.""" + if self.raw_joint or self.raw_feedback or self.chain_capture is not None: + return frozenset() # Deferred raw visits never authorize angles. + if self.diagnostic_capture is None: + return None + if motion is not None and motion.phase == "joint_zero": + ready = motion.reference_reuse or motion.reference_check or self.branch_initialization.ready(motion) + return frozenset(motion.zero_joints) if ready else frozenset() + return frozenset(self.execution.zero_references) + + def _accept_branch_event(self, row): + """Apply captured diagnostics only after the ordinary observation version gate.""" + if row["view"] not in self.required_observation_views: + return False + diagnostics = row["pnp_observation_evidence"]["candidate_diagnostics"] + if diagnostics.get("observation_stamp_ns") != row["image_stamp_ns"]: + return False + key = (row["view"], row["tag_role"]) + if diagnostics.get("branch_status") == "tracking": + self._branch_observation_reasons.pop(key, None) + return False + self._branch_observation_reasons[key] = (row["image_stamp_ns"], row["reason"]) + tag = next((tag for tag in self._view(row["view"]).tags + if tag.tag_id == row["tag_id"] and tag.role == row["tag_role"]), None) + if tag is None or row["reason"] != "pose_branch_conflict": + return False + required = tag.fixed_reference + unit = self.execution.session.current_unit + if unit is not None and not self.raw_joint: + from .scan_quality import observation_streams + task = next(task for task in self.profile.motion.tasks if task.key == unit.task_key) + required = required or any(spec.view == row["view"] + and tag.role in {spec.parent_role, spec.child_role} + and (self._motion is None or self._motion.phase != "joint_zero" or name in self._motion.zero_joints) + for _, name, spec in observation_streams(self.profile, task)) + if required: + reason = f"{row['reason']}:view={row['view']}:tag={tag.tag_id}:role={tag.role}" + if tag.fixed_reference and diagnostics.get("pose_constraint") == "fixed_reference": + error = diagnostics.get("fixed_reference_reprojection_error_px", "unavailable") + reason = (f"fixed_reference_pose_inconsistent:view={row['view']}:tag={tag.tag_id}:" + f"role={tag.role}:reprojection_error_px={error}") + self._pause(reason) + return True + return False + + def tick(self) -> None: + with self.step_data_lock: + self._advance() + from .timing_diagnostics import acquisition_stage + self.stage_timing.enter(acquisition_stage(self), self.ports.monotonic()) + if self.state in _TERMINAL_STATES and not self._timing_saved: + self._save_stage_timing() + + def _save_stage_timing(self): + atomic_write_json(self.parameters.session_dir / "stage_timing.json", + self.stage_timing.as_dict(self.ports.monotonic())) + self._timing_saved = True + + def snapshot(self) -> RuntimeSnapshot: + with self.step_data_lock: + return build_snapshot(self) + + def feedback_fresh(self) -> bool: + with self.step_data_lock: + return bool(self.state_receive_times and self.ports.monotonic()-self.state_receive_times[-1] <= 1.0) + + def close(self) -> None: + with self.step_data_lock: + self._observation_epoch += 1 + self.branch_initialization.clear() + try: + self.journal_durability.close() + sync_jsonl(self.raw_path) + finally: + self.finalization.close() + if self.training_worker is not None: + self.training_worker.close() + self._save_stage_timing() + + def _handle_motion_failure(self, decision, now): + if decision.code == 'mechanical_stall' and self.stall_retry is not None and self.segment is not None: + identity = (str(self._direction_progress.identity) if self._direction_progress is not None + else self.segment.identity) + retry = self.stall_retry.failed(identity, now) + limit = self.stall_retry.maximum_failures + append_jsonl(self.raw_path, dict(kind='motion_stall_retry', + stamp_ns=self.ports.clock_ns(), motion_id=identity, + failure_count=self.stall_retry.failures, maximum_failures=limit, + delay_seconds=self.stall_retry.delay_seconds if retry else 0., + retry_scheduled=retry, target=list(self.segment.command.target), reason=decision.details)) + if retry: + self._steady_capture_after_ns = None + self._steady_rows.clear() + self.reason = f'motion_stall_retry_wait:{self.stall_retry.failures}/{limit}:delay_seconds=3' + return + self._pause(f'{decision.code}:{decision.reason}:{decision.details},consecutive_failures={limit}') + return + self._pause(f"{decision.code}:{decision.reason}:{decision.details}") + + def _advance(self): + if self.state in _TERMINAL_STATES: + return + now = self.ports.monotonic() + session = self.execution.session + fresh = self.sdk_adapter.health() + if not self.started: + devices = self._device_status(now) + self._record_camera_preflight(devices) + if devices.ready: + if session.phase == Phase.WAIT_DEVICE: + session.device_ready() + self.reason = "ready_for_operator_start" + else: + session.devices_unavailable() + self.reason = "; ".join(devices.waiting_for) + return + current = self.last_command + if current is None: + if not self.state_history and not self.profile.vision_motion: + if now-self._started_at > self.profile.acquisition.feedback_stale_seconds: + self._pause("feedback_stale:开始后超过一秒没有新鲜反馈") + return # Require a post-Start observation, not a preview sample. + current = (self.parameters.initial_command if self.profile.vision_motion + else self.sdk_adapter.initial_command(self.latest_feedback)) + decision = self.safety.evaluate(SafetySample(now, + self.state_receive_times[-1] if self.state_receive_times else None, + tuple(current), tuple(self.latest_feedback), fresh, + competing_controller=self.ports.command_publisher_count() > 1, + motion_expected=(self.segment.motion_expected if self.segment else False) + and not (self.stall_retry and self.stall_retry.waiting), + motion_id=self.segment.identity if self.segment else "", + motion_goals=self.segment.goals if self.segment else ())) + if not decision.safe: + self._handle_motion_failure(decision, now) + return + if self.stall_retry is not None and self.stall_retry.waiting: + elapsed = self.stall_retry.resume(now) + if elapsed is None: + self.reason = f'motion_stall_retry_wait:{self.stall_retry.failures}/{self.stall_retry.maximum_failures}:remaining={self.stall_retry.remaining(now):.1f}s' + return + self.segment.suspend_elapsed(elapsed) + if self._direction_progress is not None: + self._direction_progress.retry(now, self.latest_feedback) + self._steady_capture_after_ns = None + self._steady_rows.clear() + append_jsonl(self.raw_path, dict(kind='motion_stall_retry_resumed', + stamp_ns=self.ports.clock_ns(), motion_id=self.stall_retry.motion_id, + attempt=self.stall_retry.failures+1, waited_seconds=elapsed)) + if self._direction_progress is not None: + progress = self._direction_progress.observe(self._motion, self.segment, current, + self.latest_feedback, self.state_history[-1].stamp_ns, now) + if not progress.safe: + self._handle_motion_failure(progress, now) + return + if self.visual_motion is not None and self.segment is not None: + reason = self.visual_motion.check(self.segment, now) + if reason: + self._pause(reason) + return + if self.finalization.started: + self._publish_command(list(current)) + self._poll_finalization() + return + phase = session.phase + if self._raw_resume_import is not None: + self._publish_command(list(current)) + if self._write_resume_batch(self._raw_resume_import): + interrupted = self._resume_checkpoint.restore(session) + append_jsonl_many(self.raw_path, interrupted) + self.capture_index.extend(interrupted) + self.execution.completed_units.update(self._resume_checkpoint.completed_units) + self._resumed_count = len(self._resume_checkpoint.completed_units) + self._resume_message = '原始证据与补采预算已恢复,继续剩余方向' + self._raw_resume_import = None + return + if self._passed_reference_import is not None: + self._publish_command(list(current)) + pending = self._passed_reference_import + if self._write_resume_batch(pending) and self._restore_passed_reference_batch(pending): + self._passed_reference_import = None + return + if self._reference_import is not None and not self._reference_import.complete: + self._publish_command(list(current)) + self._write_resume_batch(self._reference_import) + return + if self._resume_import is not None: + self._publish_command(list(current)) + self._import_resume_batch() + return + if phase in {Phase.PREPARE, Phase.MAPPING_PROBE} and self.segment is None and session.current_unit is not None: + unit = session.current_unit + if self.profile.quality.training_policy in STAGED_POLICIES: + used, imported = self.joint_resume.take_task(unit.task_key, cycle=unit.cycle) + else: + used, imported = self.joint_resume.take_task(unit.task_key) + if used: + from .joint_resume import TaskResumeImport + self._resume_import = TaskResumeImport(rows=imported, + task_key=session.current_unit.task_key, units=used) + self._publish_command(list(current)) + self._import_resume_batch() + return + if phase == Phase.REFERENCE_LOCKING: + self._publish_command(list(current)) + if not self.reference_lock.locking_enabled: + self.reference_lock.start_locking() + self.reason = "locking_fixed_base_references:missing="+",".join(self.reference_lock.missing_views) + if self.reference_lock.locked and self.capture.locked_reference_views() == set(self.required_observation_views): + session.reference_locked() + if session.phase != Phase.REFERENCE_POSES: + self._save_reference() + return + if phase == Phase.RESUME_VERIFY: + self._verify_resume() + return + if phase == Phase.EVALUATE: + if self._direction_progress is not None: + progress = self._direction_progress.finish() + self._direction_progress = None + if not progress.safe: + self._pause(f"{progress.code}:{progress.reason}:{progress.details}") + return + action = self.execution.action + training_decision = None + if self.execution.training_check_due(): + from .scan_quality import evaluate_capture_unit + preliminary = evaluate_capture_unit(self.execution.profile, action.scan_unit, action.retry + 1, + self.capture_index, first_cycle_spans=self.execution.first_cycle_spans) + if preliminary.passed: + # Close this motion's image identity before freezing the snapshot. + # Feedback and fixed-reference monitoring continue while fitting. + self._motion = None + if self._training_request is None: + from ..core.fitting.training_quality import training_snapshot + cycles = tuple(range(action.scan_unit.cycle + 1)) + if self.profile.quality.training_policy == STAGED: + from .staged_training import staged_snapshot + rows = staged_snapshot(self.execution.profile, self.capture_index) + else: + rows = training_snapshot(self.execution.profile, self.capture_index, action.scan_unit.task_key, cycles) + self._training_request = dict(profile=self.execution.profile, + task_key=action.scan_unit.task_key, cycles=cycles, + rows=rows, + references=dict(self.execution.zero_references), source_urdf=self.parameters.source_urdf) + try: + training_decision = self.training_worker.poll(**self._training_request) + except Exception as error: + self._pause(f"training_assessment_failed:{error}") + return + if training_decision is None: + self.reason = "training_quality_assessment:" + action.scan_unit.task_key + self._publish_command(list(current)) + return + if self.profile.quality.training_policy == STAGED: + payload = training_decision["frozen_training"] + training_decision = training_decision["decision"] + if payload is not None: + atomic_write_json(self.parameters.session_dir / "frozen_training.json", payload) + self._frozen_training_sha256 = training_decision["frozen_training_sha256"] + self._training_request = None + # Diagnostic coverage needs raw corners, not the full session's + # candidate graph. The same bounded scan window drives live status + # and the end-of-scan decision; immutable evidence stays on disk. + quality = self.execution.evaluate( + self._unit_rows if self.diagnostic_capture is not None or self.raw_joint or self.raw_feedback else self.capture_index, + training_decision=training_decision) + record = {"kind": "scan_unit_complete", "task_name": action.scan_unit.task_key, + "cycle": action.scan_unit.cycle, "direction": action.scan_unit.direction, + **({"segment_key": action.scan_unit.segment_key} if action.scan_unit.segment_key else {}), + "attempt": action.retry+1, "passed": quality.passed, + **({"capture_plan_sha256": CapturePlan.from_profile(self.execution.profile).sha256} + if action.retry else {}), + "failures": list(quality.failures), "metrics": dict(quality.metrics), + **({"quality_scope": "diagnostic_observation_coverage", + "accepted_pose_quality": self.execution.last_diagnostic_quality.accepted_pose_report(), + "observation_timing": dict(self.execution.last_diagnostic_quality.observation_timing)} + if self.execution.last_diagnostic_quality is not None else {})} + self.capture_index.append(record) + append_jsonl(self.raw_path, record) + next_unit = session.current_unit + visit_complete = (quality.passed and (next_unit is None + or (next_unit.task_key, next_unit.cycle) != ( + action.scan_unit.task_key, action.scan_unit.cycle))) + if visit_complete: + resolved_deferral = session.task_deferrals.resolve( + action.scan_unit.task_key, action.scan_unit.cycle) + if resolved_deferral is not None: + resolved_record = resolved_deferral.as_record(stamp_ns=self.ports.clock_ns()) + self.capture_index.append(resolved_record) + append_jsonl(self.raw_path, resolved_record) + if self.execution.last_training_decision is not None: + decision = self.execution.last_training_decision + append_jsonl(self.raw_path, decision) + self.capture_index.append(decision) + if decision["decision"] == "fail": + self._observation_epoch += 1 + self.branch_initialization.clear() + self.training_worker.close() + self._publish_command(list(current)) + self.reason = "training_quality_failed:" + ",".join(decision["failures"]) + return + task_quality = self.execution.last_task_quality + if task_quality is not None: + task_record = {"kind": "task_input_support_checked", "task_name": action.scan_unit.task_key, + "passed": task_quality.passed, "failures": list(task_quality.failures), + "metrics": dict(task_quality.metrics)} + self.capture_index.append(task_record) + append_jsonl(self.raw_path, task_record) + if not task_quality.passed: + self._pause("task_input_support_failed:"+",".join(task_quality.failures)) + return + if session.phase == Phase.PAUSED: + if "observation_timing" in record: + pause = session.status().pause + session.pause(pause.code, pause.reason, + {**pause.details, "observation_timing": record["observation_timing"]}, + suggestion=pause.suggestion) + task = next(task for task in self.profile.motion.tasks if task.key == action.scan_unit.task_key) + self._pause("sweep_quality_failed:"+",".join(quality.failures)+self._task_branch_details(task)) + return + if phase == Phase.FIT: + self._motion = None + self._finalize() + return + if (phase == Phase.PREPARE and session.current_unit is not None + and session.current_unit.sample_phase == "steady" and self.diagnostic_capture is None): + self._prepare_command_sampling(session.current_unit.task_key) + motion = self.execution.motion(current) + if motion is None: + if phase == Phase.PREPARE and session.current_unit is None: + session.preparation_complete() + return + self._pause(f"unhandled_session_phase:{phase.value}") + return + if self.segment is None and self._reuse_settled_preparation(motion, now): + return + if self.segment is None: + if self.visual_motion is not None: + names = self.visual_motion.names_for(motion, current) + if not self.visual_motion.available(names, now): + if self._visual_wait_started_at is None: + self._visual_wait_started_at = now + self._publish_command(list(current)) + self.reason = "waiting_for_visual_motion_tags:" + ",".join(names) + if now-self._visual_wait_started_at >= self.profile.acquisition.steady_timeout_seconds: + self._pause(self.reason) + return + self._visual_wait_started_at = None + if self.commanded_speed != motion.speed: + self._publish_speed(motion.speed) + self.step_speed_ready_at = now+float(self.parameters.speed_settle_seconds) + return + if now < self.step_speed_ready_at: + return + self._segment_number += 1 + self._motion = motion + self._motion_started_ns = self.ports.clock_ns() + self._steady_capture_after_ns = None + self._zero_geometry_started_at = None + self._zero_geometry_completed_at = None + self._zero_capture_started_at = None + self._reference_capture_key = None + self._reference_observation_started = None + self._begin_motion_capture(motion) + if session.phase == Phase.PAUSED: + return + if self.visual_motion is not None: + self.visual_motion.begin(motion, current, now=now, version=self._segment_number) + self._flush_visual_evidence() + if self.raw_joint and motion.phase in {"sweep", "steady"} and motion.direction is not None: + unit = session.current_unit + identity = (*unit.identity, motion.attempt) + if self._direction_progress is None or self._direction_progress.identity != identity: + from .direction_progress import DirectionProgress + self._direction_progress = DirectionProgress(self.profile, unit, motion.attempt, + self.latest_feedback, now) + self.segment = MotionExecution(self.profile, motion, initial_command=current, + initial_feedback=self.latest_feedback, now=now, identity=str(self._segment_number), + visual_observer=self.visual_motion, raw_scan=self.raw_joint) + shaped = self.segment.sample(now) + self._publish_command(list(shaped)) + if self._direction_progress is not None: + self._direction_progress.observe(motion, self.segment, shaped, + self.latest_feedback, self.state_history[-1].stamp_ns, now) + self.segment.observe(self.latest_feedback, stamp=self.state_history[-1].stamp_ns if self.state_history else None, now=now) + if self.visual_motion is not None: + self.visual_motion.settle_record(self.segment.finished_at, now, epoch=self._observation_epoch) + self._flush_visual_evidence() + self.reason = motion.phase+":"+str(motion.task_key) + steady_complete = False + waiting_for_reference = False + if motion.phase == "steady": + if self.segment.steady_ready(now): + if self._steady_capture_after_ns is None: + self._steady_capture_after_ns = self.ports.clock_ns() + from .scan_quality import observation_streams + task = next(t for t in self.profile.motion.tasks if t.key == motion.task_key) + rows = self._steady_rows + if self.raw_joint: + from .raw_quality import coverage_records + rows = tuple(coverage_records(self.profile, session.current_unit, + motion.attempt, self._steady_rows)) + elif self.raw_feedback: + from .feedback_image_coverage import feedback_image_coverage_records + rows = tuple(feedback_image_coverage_records(self.profile, session.current_unit, + motion.attempt, self._steady_rows)) + steady_complete = all(len({r["image_stamp_ns"] for r in rows + if r.get(field) == joint and r.get("view") == spec.view + and r.get("sample_phase") == "steady"}) >= self.profile.acquisition.steady_minimum_samples + for field, joint, spec in observation_streams(self.profile, task) + if not motion.observed_joints or joint in motion.observed_joints) + steady_complete = steady_complete and self.segment.minimum_hold_complete(now) + if self.chain_capture is not None: + try: + reference_record = self.chain_capture.steady_visit(motion, self._steady_rows, + epoch=self._observation_epoch, version=self._segment_number) + if reference_record is not None: + append_jsonl(self.raw_path, reference_record) + self.capture_index.append(reference_record) + steady_complete = self.segment.minimum_hold_complete(now) + waiting_for_reference = not self.chain_capture.reference_ready(motion, self._observation_epoch) + steady_complete = steady_complete and not waiting_for_reference + except ValueError as error: + self._zero_reference_error = str(error) + steady_complete = False + else: + self._reset_steady_capture(motion, now) + if waiting_for_reference: + self.reason = 'training_return_reference_solving:' + str(motion.task_key) + if (self._zero_geometry_started_at is not None + and now-self._zero_geometry_started_at > 120.): + self._pause('deferred_chain_reference_model_unresolved:image_motion_solver_timeout') + return + if self.chain_capture is not None and self.segment.arrived(now) and not steady_complete: + self._pause('deferred_chain_steady_unavailable:' + self._zero_reference_error) + return + if motion.phase == "joint_zero" and self.chain_capture is not None: + if self.segment.steady_ready(now): + if self._steady_capture_after_ns is None: + self._steady_capture_after_ns = self.ports.clock_ns() + try: + visit = self.chain_capture.reference_visit(motion, self._steady_rows, + epoch=self._observation_epoch, version=self._segment_number) + records = [visit.record] + if visit.attempt is not None: + self.execution.record_diagnostic_zero_attempt(visit.attempt) + records.append(visit.attempt.as_record()) + append_jsonl_many(self.raw_path, records) + self.capture_index.extend(records) + steady_complete = True + except ValueError as error: + self._zero_reference_error = str(error) + else: + self._reset_steady_capture(motion, now) + if self.segment.arrived(now) and not steady_complete: + self._pause('deferred_chain_reference_unavailable:' + self._zero_reference_error) + return + if motion.phase == "joint_zero" and self.raw_feedback: + if self.segment.steady_ready(now): + if self._steady_capture_after_ns is None: + self._steady_capture_after_ns = self.ports.clock_ns() + self._zero_geometry_completed_at = now + from .feedback_image_coverage import feedback_reference_coverage + counts = feedback_reference_coverage(self.profile, motion, self._steady_rows) + minimum = self.profile.acquisition.fixed_reference_minimum_frames + steady_complete = bool(counts) and all(value >= minimum for value in counts.values()) + else: + self._reset_steady_capture(motion, now) + if self.segment.arrived(now) and self._zero_geometry_completed_at is None: + self._zero_geometry_completed_at = now + if (self.segment.arrived(now) and not steady_complete + and now-self._zero_geometry_completed_at >= self.profile.acquisition.joint_zero_timeout_seconds): + key = (motion.task_key, motion.cycle) + self.execution.session.incomplete_references[key] = dict( + joints=list(motion.zero_joints), observed=counts if self.segment.steady_ready(now) else {}, + required=self.profile.acquisition.fixed_reference_minimum_frames) + steady_complete = True + elif motion.phase == "joint_zero" and self.chain_capture is None: + if self.segment.steady_ready(now): + if self._steady_capture_after_ns is None: + self._steady_capture_after_ns = self.ports.clock_ns() + steady_complete = (self._confirm_model_reference(motion) if motion.reference_only else + self._lock_joint_zeros(motion)) + if session.phase == Phase.PAUSED: + return + if self._reference_import is not None: + # The pose has already been measured and checked. Journal + # transfer is not an observation timeout; keep holding it + # while feedback and safety run between bounded writes. + self.reason = "joint_zero_resume_evidence_import:" + str(motion.task_key) + return + else: + self._reset_steady_capture(motion, now) + if self.branch_initialization.pending(): + # Optimizing the immutable preparation images is not a loss + # of current Tag observations. SDK feedback/safety keeps + # updating while this bounded operation holds the same pose. + self.reason = "joint_zero_geometry_solving:" + str(motion.task_key) + if (self._zero_geometry_started_at is not None + and now-self._zero_geometry_started_at > 120.0): + self._pause("joint_zero_motion_unresolved:image_motion_solver_timeout") + return + # A long preparation solve can require the tracker to recover + # before any zero image is valid. Give that recovery the existing + # observation timeout, then collect the fixed number of stable + # frames within the dedicated zero window. Zero needs ten images; + # an ordinary mapping hold needs only three. Only the + # first accepted zero sample starts it; dropouts and feedback + # resets never extend it. Recovery plus capture remains bounded, + # with no relaxation of sample quality. + timeout = self.profile.acquisition.steady_timeout_seconds + capture_timeout = self.profile.acquisition.joint_zero_timeout_seconds + zero_started = self._zero_geometry_completed_at + if zero_started is not None and self._zero_capture_started_at is not None: + zero_started = min(self._zero_capture_started_at, zero_started+timeout) + timeout = capture_timeout + observation_timed_out = self.segment.arrived(now) and ( + zero_started is None or now-zero_started >= timeout) + if observation_timed_out and not steady_complete: + geometry_error = self.branch_initialization.error() + if geometry_error and self._complete_diagnostic_zero_attempt(motion, now, geometry_error): + steady_complete = True + elif geometry_error: + if self._recover_joint_zero(motion, now, geometry_error): + return + if self._defer_unobservable_task(motion, geometry_error): + return + if self.diagnostic_capture is not None: + geometry_error += ":diagnostic_reference=" + self._zero_reference_error + self._pause("joint_zero_motion_unresolved:" + geometry_error) + return + else: + if self._recover_joint_zero(motion, now, ""): + return + unavailable = self._zero_reference_error+self._joint_zero_branch_details(motion) + if self._defer_unobservable_task(motion, unavailable): + return + self._pause("joint_zero_unavailable:"+unavailable) + return + # All ordinary holds share this bounded exit, even without stable + # images. Unit evaluation owns missing-data retries; motion arrival + # still requires physical feedback progress. + if (self.segment.arrived(now) and motion.phase != "joint_zero") or steady_complete: + if motion.phase in {'observer_preflight', 'observer_probe'}: + self._advance_observer_preparation(motion, now) + return + if not self._witness_departure_ready(motion, now): + return + if motion.phase == "reference_pose": + waypoint = next(w for w in self.profile.motion.resume_verification_waypoints if w.key == motion.task_key) + if self._reference_observation_started is None: + self._reference_observation_started = now + self._reference_capture_key = waypoint.key + required = [f"{waypoint.key}/{view.name}:{tag.role}" + for view in self.profile.vision.views for tag in view.tags + if tag.tag_id in waypoint.tag_ids_by_view.get(view.name, ())] + enough = all(self.capture.installation_count(key) >= self.reference_lock.minimum_frames for key in required) + if not enough and now-self._reference_observation_started < 2.0: + return + # Missing installation evidence invalidates reuse, not the + # entire fresh capture. Never forge a matching fingerprint. + self._reference_capture_key = None + if self.segment.steady_ready(now) or ( + motion.phase not in {"steady", "joint_zero"} and not motion.defer_settling_to_hold + and self.segment.arrived(now)): + self._settled_pose = (tuple(motion.target), tuple(self.latest_feedback), now) + self.execution.motion_complete() + if phase == Phase.REFERENCE_POSES and session.phase != phase: + self._save_reference() + self.segment, self._motion = None, None + if session.phase == Phase.CAPTURE_COMPLETE: + self._finish_capture() + if session.phase == Phase.DIAGNOSTIC_COMPLETE: + self._finish_diagnostic_capture() + + def _reset_steady_capture(self, motion, now): + if self._steady_capture_after_ns is not None or self._steady_rows: + record = {"kind": "steady_capture_reset", "stamp_ns": self.ports.clock_ns(), + "task_name": motion.task_key, "motion_phase": motion.phase, + "discarded_joint_samples": sum(r.get("kind") in {"joint_sample", "joint_zero_sample"} + for r in self._steady_rows), + "feedback_window_seconds": self.profile.acquisition.steady_window_seconds, + "feedback_history": [{"age_seconds": now-stamp, "values": list(values)} + for stamp, values in list(self.segment.stamped_history)[-20:]]} + self.capture_index.append(record) + append_jsonl_many(self.raw_path, (record,), durable=False) + self._steady_capture_after_ns = None + self._steady_rows.clear() + + def _finish_capture(self): + self._raw_capture_closed = True + self._observation_epoch += 1 + self._direction_progress = None + self.journal_durability.close() + session = self.execution.session + try: + append_jsonl(self.raw_path, dict(kind="raw_capture_finished", + stamp_ns=self.ports.clock_ns(), returned_to_baseline=True)) + sync_jsonl(self.raw_path) + from .raw_completion import save_capture_manifest + save_capture_manifest(self.raw_path, profile=self.profile, + serial_number=self.parameters.serial_number, + protected_inputs=self.parameters.protected_inputs, + completed_units=self.execution.completed_units, + incomplete_units=session.incomplete_units, retries=session._retry_by_unit, + scheduled_units=None if self.raw_joint else session.scheduled_units, + unobservable_tasks=session.task_deferrals.unobservable, + incomplete_references=session.incomplete_references) + self.reason = "capture_finished_offline_only" + except Exception as error: + session.fail("raw_capture_manifest_failed", str(error)) + self.reason = "raw_capture_manifest_failed:" + str(error) + + def _finish_diagnostic_capture(self): + """Save diagnostics under the state lock before exposing completion.""" + from .diagnostic_report import build_diagnostic_report + from .resume_storage import load_passed_capture + self._observation_epoch += 1 + try: + sync_jsonl(self.raw_path) + # Motion has returned to baseline and acquisition is closed. Read + # full evidence lazily, without retaining all expanded image/PnP + # dictionaries in the live interpreter throughout the run. + records = load_passed_capture(self.raw_path) + report = build_diagnostic_report(self.profile, self.diagnostic_capture, + raw_path=self.raw_path, records=records, + references=self.execution.zero_references, + diagnostic_zero_attempts=self.execution.diagnostic_zero_attempts, + completed_units=self.execution.completed_units, + expected_units=self.execution.session.engine.scan_units(), + protected_inputs=self._current_fingerprint.get("protected_hashes", self.parameters.protected_inputs), + command=self.last_command, feedback=self.latest_feedback) + atomic_write_json(self.parameters.session_dir / "diagnostic_capture.json", report) + except (OSError, ValueError, TypeError, KeyError) as error: + self.execution.session.fail("diagnostic_capture_report_failed", str(error)) + self.reason = f"diagnostic_capture_report_failed:{error}" + return + self.reason = "diagnostic_capture_complete_not_calibration_acceptance" + + def _complete_diagnostic_zero_attempt(self, motion, now, geometry_error): + """Continue diagnostics only after a real stable raw reference visit.""" + if self.diagnostic_capture is None: + return False + if not self.segment.steady_ready(now): + self._zero_reference_error = "diagnostic_joint_zero_feedback_unstable" + return False + try: + attempt = build_diagnostic_zero_attempt(self.profile, motion, self._steady_rows, + reason=geometry_error, session_epoch=self._observation_epoch, + motion_version=self._segment_number) + except ValueError as error: + self._zero_reference_error = str(error) + return False + self.execution.record_diagnostic_zero_attempt(attempt) + row = attempt.as_record() + append_jsonl(self.raw_path, row) + self.capture_index.append(row) + return True + + def _confirm_model_reference(self, motion): + """Authorize a held parent in this pose without replacing its measured zero.""" + if not motion.reference_reuse and not self.branch_initialization.ready(motion): + return False + minimum = self.profile.acquisition.fixed_reference_minimum_frames + rows = [] + for name in motion.zero_joints: + specs = [self.profile.measurement.measurements[name]] + secondary = self.profile.measurement.cross_view_sources.get(name) + if secondary is not None: + specs.append(self.profile.measurement.measurements[secondary]) + for spec in specs: + frames = {row["image_stamp_ns"]: row for row in self._steady_rows + if row.get("kind") == "joint_zero_sample" and row.get("joint") == name + and row.get("view") == spec.view} + if len(frames) < minimum: + self._zero_reference_error = ( + f"parent_reference_samples_missing:{name}:{spec.view}:{len(frames)}/{minimum}") + return False + rows.extend(frames[stamp] for stamp in sorted(frames)[-minimum:]) + try: + revisions = reference_branch_revisions(rows, profile=self.profile, require_motion_evidence=True) + record = None + if motion.reference_reuse: + task = next(task for task in self.profile.motion.tasks if task.key == motion.task_key) + reference = self.execution.zero_references.get(task.parent_reference.pose_joint) + if reference is None: + raise ValueError("parent_reference_zero_missing") + record = self.branch_initialization.parent_references.confirm(task, + self._observation_epoch, self._segment_number, reference, rows) + elif motion.parent_model_refresh_for: + task = next(task for task in self.profile.motion.tasks + if task.key == motion.parent_model_refresh_for) + reference = self.execution.zero_references.get(task.parent_reference.pose_joint) + if reference is None: + raise ValueError("parent_reference_zero_missing") + record = self.branch_initialization.parent_references.authorize_refreshed_pose( + task, self._observation_epoch, self._segment_number, reference) + except ValueError as error: + self._zero_reference_error = str(error) + return False + if not self._freeze_reference_branches(revisions): + self._zero_reference_error = "parent_reference_motion_branch_not_confirmed" + return False + if record is not None: + append_jsonl(self.raw_path, record) + self.capture_index.append(record) + return True + + def _freeze_reference_branches(self, revisions): + return self.capture.freeze_reference_branches(revisions) + + def _lock_joint_zeros(self, motion): + pending = self._reference_import + if pending is not None: + if (pending.motion_version != self._segment_number + or set(pending.references) != set(motion.zero_joints)): + raise RuntimeError("resume_reference_motion_changed_during_import") + if not pending.complete: + return False + self.execution.zero_references.update(pending.references) + if self.visual_motion is not None: + self.visual_motion.freeze_zeros(pending.references) + self._reference_import = None + return True + if not motion.reference_check and not self.branch_initialization.ready(motion): + self._zero_reference_error = (self.branch_initialization.error() + or "motion_geometry_confirmation_pending") + return False + references = {} + branch_rows = [] + try: + for name in motion.zero_joints: + rows = [r for r in self._steady_rows if r.get("kind") == "joint_zero_sample" and r.get("joint") == name] + # A transient bad pose must age out once vision has settled. + # Keep the raw journal intact; freeze only the latest distinct + # frames per view, with the unchanged minimum/stability gate. + frames = {(r["view"], r["image_stamp_ns"]): r for r in rows} + minimum = self.profile.acquisition.fixed_reference_minimum_frames + rows = [row for view in sorted({r["view"] for r in rows}) + for row in sorted((r for r in frames.values() if r["view"] == view), + key=lambda r: r["image_stamp_ns"])[-minimum:]] + references[name] = build_joint_zero_reference(self.profile, name, rows, + session_epoch=self._observation_epoch, motion_version=self._segment_number) + branch_rows.extend(rows) + revisions = reference_branch_revisions(branch_rows, profile=self.profile, + require_motion_evidence=True) + except ValueError as error: + self._zero_reference_error = str(error) + return False + if motion.reference_check: + from .revisit import revisit_record + try: + checks = [revisit_record(self.profile, self.execution.zero_references[name], reference, motion.cycle) + for name, reference in references.items()] + except (ValueError, KeyError) as error: + self._pause(str(error)) + return False + if not self._freeze_reference_branches(revisions): + self._zero_reference_error = "joint_zero_motion_branch_not_confirmed" + return False + append_jsonl_many(self.raw_path, checks) + self.capture_index.extend(checks) + self.joint_resume.verified_visits.update((name, motion.cycle) for name in references) + return True + if references.keys() & self.execution.zero_references.keys(): + raise RuntimeError("a frozen joint reference cannot be replaced") + current_references = dict(references) + try: + references = {name: self.joint_resume.verify(reference) for name, reference in references.items()} + except ValueError as error: + self._pause(str(error)) + return False + if not self._freeze_reference_branches(revisions): + self._zero_reference_error = "joint_zero_motion_branch_not_confirmed" + return False + for reference in current_references.values(): + self.branch_initialization.parent_references.remember_zero(reference, self._observation_epoch) + provenance = self.joint_resume.take_motion_provenance_records() + reference_rows = tuple(reference.as_record() for reference in references.values()) + if provenance: + from .joint_resume import ReferenceResumeImport + self._reference_import = ReferenceResumeImport( + rows=(*provenance, *reference_rows), references=references, + motion_version=self._segment_number) + return False + append_jsonl_many(self.raw_path, reference_rows) + self.capture_index.extend(reference_rows) + self.execution.zero_references.update(references) + if self.visual_motion is not None: + self.visual_motion.freeze_zeros(references) + return True + + def _reuse_settled_preparation(self, motion, now): + if self.profile.vision_motion: + return False # A repeated command still requires fresh visual stability. + if motion.phase != "prepare" or self._settled_pose is None: + return False + command, feedback, stamp = self._settled_pose + tolerance = .001 if self.command_unit == "rad" else 1. + if (tuple(motion.target) != command or tuple(self.last_command or ()) != command + or now-stamp > 1.0 or len(feedback) != len(self.latest_feedback) + or any(abs(old-new) > tolerance for old, new in zip(feedback, self.latest_feedback))): + return False + # The previous segment already completed its endpoint/feedback hold. + # Repeating an identical preparatory target needs no second dwell. + self.execution.motion_complete() + record = {"kind": "preparation_reused_settled_pose", "task_name": motion.task_key, + "cycle": motion.cycle, "direction": motion.direction, "stamp_ns": self.ports.clock_ns()} + append_jsonl_many(self.raw_path, (record,), durable=False) + self.capture_index.append(record) + return True + + def _prepare_command_sampling(self, task_key): + if task_key in self.execution.sampling_plans: + return + from ..core.fitting.command_sampling import build_sampling_plan + existing = [row for row in self.capture_index if row.get("kind") == "command_sampling_plan" + and row.get("task_name") == task_key] + if existing: + plan = existing[0] # PreparedResume already verified its source and content. + else: + task = next(task for task in self.profile.motion.tasks if task.key == task_key) + plan = build_sampling_plan(self.profile, task, self.capture_index) + append_jsonl(self.raw_path, plan) + self.capture_index.append(plan) + self.execution.sampling_plans[task_key] = plan + + def _witness_departure_ready(self, motion, now): + """Hold a completed witness pose until its existing endpoint gate passes.""" + error = self.branch_initialization.witness_capture.endpoint_error( + motion, self._observation_epoch, self.ports.clock_ns()) + if not error: + return True + self.reason = "preparation_witness_endpoint_wait:" + error + if now-self.segment.finished_at >= self.profile.acquisition.steady_timeout_seconds: + self._pause(error) + return False + + def _recover_joint_zero(self, motion, now, geometry_error): + if self.diagnostic_capture is not None: + return False + branch_details = self._joint_zero_branch_details(motion) + task = next((task for task in self.profile.motion.tasks + if task.key == motion.task_key), None) + stale_parent_anchor = (motion.reference_reuse + and task is not None and self.capture.current_image_reference_stable(task.view) + and self._zero_reference_error.startswith("parent_reference_samples_missing:") + and "image_reference_current_image_moved" in branch_details) + action = self.zero_recovery.take_parent_model_refresh( + motion, stale_image_anchor=stale_parent_anchor) + if action is not None: + from .zero_recovery import FailureCategory + record = {"kind": "joint_zero_recovery", "task_name": motion.task_key, + "failure_category": FailureCategory.REFERENCE_CHANGED.value, + "capture_plan_sha256": CapturePlan.from_profile(self.execution.profile).sha256, + "joints": list(motion.zero_joints), "action": action, + "reason": self._zero_reference_error+branch_details, + "previous_session_epoch": self._observation_epoch, + "session_epoch": self._observation_epoch+1, + "attempt": 1, "stamp_ns": self.ports.clock_ns()} + append_jsonl(self.raw_path, record) + self.capture_index.append(record) + self._observation_epoch += 1 + self.branch_initialization.parent_references.advance_recovery_epoch( + self._observation_epoch-1, self._observation_epoch) + self.execution.refresh_parent_model(self.last_command or motion.target) + self.branch_initialization.clear() + self._steady_rows.clear() + self._zero_capture_started_at = self._steady_capture_after_ns = None + self._motion = self.segment = None + self._zero_geometry_started_at = self._zero_geometry_completed_at = None + self.reason = "joint_zero_recovery:"+action+":"+str(motion.task_key) + return True + if geometry_error and self._recover_observer_preparation(motion): + return True + action = self.zero_recovery.take(motion, geometry_error=geometry_error, + reports=self.branch_initialization.reports, + referenced_joints=() if motion.reference_only else self.execution.zero_references) + if action is None: + return False + from .zero_recovery import FailureCategory + record = {"kind": "joint_zero_recovery", "task_name": motion.task_key, + # Admission above allows only missing evidence, even when the + # human-readable message wraps a structured per-view reason. + "failure_category": FailureCategory.MISSING_SAMPLES.value, + "capture_plan_sha256": CapturePlan.from_profile(self.execution.profile).sha256, + "joints": list(motion.zero_joints), "action": action, "reason": geometry_error or self._zero_reference_error, + "previous_session_epoch": self._observation_epoch, "session_epoch": self._observation_epoch+1, + "attempt": 1, "stamp_ns": self.ports.clock_ns()} + append_jsonl(self.raw_path, record) + self.capture_index.append(record) + self._observation_epoch += 1 + self.branch_initialization.parent_references.advance_recovery_epoch( + self._observation_epoch-1, self._observation_epoch) + self._steady_rows.clear() + self._zero_capture_started_at = None + self._steady_capture_after_ns = None + if action == "repeat_approach": + self.execution.repeat_zero_approach(self.last_command or motion.target) + self.branch_initialization.clear() + self._motion = self.segment = None + self._zero_geometry_started_at = self._zero_geometry_completed_at = None + else: + # Keep the frozen model and current physical holding pose. Only + # a fresh image window is opened; feedback and base guards run. + self._zero_geometry_completed_at = now + self.reason = "joint_zero_recovery:" + action + ":" + str(motion.task_key) + return True + + def _journal_observer(self, record): + append_jsonl(self.raw_path, record) + self.capture_index.append(record) + self.branch_initialization.observer_preparation.observe(record) + + def _advance_observer_preparation(self, motion, now): + preparation = self.branch_initialization.observer_preparation + effects = [] + if motion.phase == 'observer_preflight': + try: + cancelled = preparation.cancel_unstarted(motion.reference_joints[0], + epoch=self._observation_epoch, stamp_ns=self.ports.clock_ns()) + if cancelled is not None: + self._journal_observer(cancelled) + record = preparation.decide(motion, epoch=self._observation_epoch, stamp_ns=self.ports.clock_ns()) + except ValueError as error: + self._pause(str(error)) + return + if record is not None: + self._journal_observer(record) + if record['action'] == 'excite': + effects = preparation.effects(motion, record) + else: + error = preparation.endpoint_error(motion, epoch=self._observation_epoch, + motion_version=self._segment_number, stamp_ns=self.ports.clock_ns()) + if error: + self.reason = error + if now-self.segment.finished_at >= self.profile.acquisition.steady_timeout_seconds: + self._pause(error) + return + self._journal_observer(dict(kind='observer_preparation_segment_complete', + observer_preparation_id=motion.observer_preparation_id, + path_index=motion.reference_path_index, session_epoch=self._observation_epoch, + motion_version=self._segment_number, stamp_ns=self.ports.clock_ns())) + if motion.reference_path_index == 2: + # Assess what the completed action actually observed before + # spending time moving and fitting the recipient joint. + from dataclasses import replace + record = preparation.decide(replace(motion, phase='observer_preflight'), + epoch=self._observation_epoch, stamp_ns=self.ports.clock_ns()) + if record is not None: + self._journal_observer(record) + effects = preparation.effects(motion, record) + self.execution.motion_complete() + if effects: + self.execution.prepend_observer_effects(effects) + self.segment, self._motion = None, None + + def _recover_observer_preparation(self, motion): + from .observer_preparation import RECOVERABLE + if (motion.reference_only or motion.reference_check or len(motion.zero_joints) != 1 + or motion.zero_joints[0] in self.execution.zero_references + or motion.zero_joints[0] not in self.profile.motion.observer_preparations): + return False + preparation = self.branch_initialization.observer_preparation + reports = self.branch_initialization.reports.values() + if not reports or any(r.get('status') == 'resolved' or r.get('reason') not in RECOVERABLE for r in reports): + return False + reason = next(iter(reports))['reason'] + record = preparation.decide(motion, epoch=self._observation_epoch, + stamp_ns=self.ports.clock_ns(), reason=reason) + if record is None: + return False + self._journal_observer(record) + self.execution.prepare_observer_recovery(preparation.effects(motion, record), self.last_command or motion.target) + self.branch_initialization.clear() + self.segment, self._motion = None, None + self._zero_geometry_started_at = self._zero_geometry_completed_at = None + self.reason = 'observer_preparation:' + motion.zero_joints[0] + return True + + def _defer_unobservable_task(self, motion, geometry_error): + """Continue independent collection after bounded v3 observation fails.""" + from .task_deferral import recoverable_task_observation, taskwise_deferral + taskwise = taskwise_deferral(self.profile) + # A geometry ambiguity can defer an unstarted task once. Safety, + # changed references and a failed validation visit still stop. + if (motion is None or motion.phase != "joint_zero" or motion.reference_check + or self.diagnostic_capture is not None + or not self.execution.session.can_defer_current_task() + or not recoverable_task_observation(geometry_error, self.branch_initialization.reports)): + return False + if not taskwise and (motion.reference_only and not + (motion.parent_model_refresh_for or motion.reference_reuse)): + return False + import hashlib + import json + reports = tuple(self.branch_initialization.reports.values()) + hashes = {report.get('view', ''): report.get('source_frame_hashes', {}) + for report in reports} + corner_digest = hashlib.sha256(json.dumps(hashes, sort_keys=True, + separators=(',', ':'), allow_nan=False).encode()).hexdigest() + decision = self.execution.defer_current_task(geometry_error) + record = decision.as_record(stamp_ns=self.ports.clock_ns(), + corner_evidence_sha256=corner_digest) + append_jsonl(self.raw_path, record) + self.capture_index.append(record) + self._observation_epoch += 1 + self.branch_initialization.parent_references.advance_recovery_epoch( + self._observation_epoch-1, self._observation_epoch) + self.branch_initialization.clear() + self._steady_rows.clear() + self._zero_capture_started_at = None + self._steady_capture_after_ns = None + self._zero_geometry_started_at = self._zero_geometry_completed_at = None + self.segment, self._motion = None, None + self.reason = f"task_observation_{decision.state.value}:{decision.task_name}" + return True + + def _joint_zero_branch_details(self, motion): + task = next(task for task in self.profile.motion.tasks if task.key == motion.task_key) + if motion.reference_only: + task = replace(task, joints=motion.zero_joints) + return self._task_branch_details(task, joints=motion.zero_joints) + + def _task_branch_details(self, task, *, joints=None): + from .scan_quality import observation_streams + details = [] + required_views = set() + for _, name, spec in observation_streams(self.profile, task): + if joints is not None and name not in joints: + continue + required_views.add(spec.view) + for role in (spec.parent_role, spec.child_role): + previous = self._branch_observation_reasons.get((spec.view, role)) + if previous is None: + continue + tag = next(tag for tag in self._view(spec.view).tags if tag.role == role) + details.append(f"{name}:{spec.view}:tag={tag.tag_id}:{previous[1]}") + for view in self.profile.vision.views: + if view.name not in required_views: + continue + for tag in view.tags: + previous = self._branch_observation_reasons.get((view.name, tag.role)) + if tag.fixed_reference and previous is not None: + details.append(f"fixed_reference:{view.name}:tag={tag.tag_id}:{previous[1]}") + return "" if not details else ":pose_branches="+",".join(sorted(set(details))) + + def _begin_motion_capture(self, motion): + """Aggregate one direction across its moving and stationary segments.""" + self._steady_rows = [] + self._zero_reference_error = "" + self.capture.begin_motion(motion) + if motion.phase == 'observer_probe' and motion.reference_path_index == 1: + self._journal_observer(dict(kind='observer_preparation_excursion_started', + observer_preparation_id=motion.observer_preparation_id, + session_epoch=self._observation_epoch, motion_version=self._segment_number, + stamp_ns=self.ports.clock_ns())) + if not self.raw_feedback and self.chain_capture is None and motion.reference_check and motion.phase == "joint_zero": + try: + self.branch_initialization.parent_references.activate_joints( + motion.zero_joints, self._observation_epoch, self.capture) + self._zero_geometry_completed_at = self.ports.monotonic() + except ValueError as error: + self._pause(str(error)) + return + if not self.raw_feedback and self.chain_capture is None and motion.reference_reuse: + task = next(task for task in self.profile.motion.tasks if task.key == motion.task_key) + try: + self.branch_initialization.parent_references.activate(task, self._observation_epoch, self.capture) + self._zero_geometry_completed_at = self.ports.monotonic() + except ValueError as error: + self._pause(str(error)) + return + if self.chain_capture is None and not self.raw_joint and not self.raw_feedback: + self.branch_initialization.begin(motion, session_epoch=self._observation_epoch, + motion_version=self._segment_number) + if motion.recording: + key = (motion.task_key, motion.cycle, motion.direction, motion.attempt, motion.segment_key) + if key != self._capture_unit_key: + self._unit_rows = [] + self._capture_unit_key = key + + def _verify_optical_preflight(self): + from .optical_verification import verify_optical_observations + from .camera_preflight import CameraCheck + path = self.parameters.camera_optical_observations_file + if path is None and self.parameters.reuse_camera_calibration: + from .optical_verification import accept_existing_camera_calibration + report = accept_existing_camera_calibration(self.profile, + self.parameters.camera_extrinsics_file, + self.parameters.protected_inputs['camera_extrinsics_sha256']) + append_jsonl(self.raw_path, dict(kind='existing_camera_calibration_reused', + stamp_ns=self.ports.clock_ns(), acceptance=report)) + atomic_write_json(self.parameters.session_dir / 'camera_preflight.json', + dict(kind='camera_preflight', stage='at_start', + **self._camera_preflight.as_dict(), camera_acceptance=report)) + return + if path is None: + raise ValueError('missing_measured_optical_observations') + dataset = json.loads(path.read_text(encoding='utf-8')) + report = verify_optical_observations(dataset, self.parameters.extrinsics, + self.cameras.matrices, + extrinsics_sha256=self.parameters.protected_inputs['camera_extrinsics_sha256']) + append_jsonl(self.raw_path, dict(kind='measured_optical_verification', + stamp_ns=self.ports.clock_ns(), observations=dataset, verification=report)) + current = self._camera_preflight + checked = CameraCheck('passed', '当前锁定参数通过多姿态同步标定板实测重投影核验') + self._camera_preflight = CameraPreflight(current.configuration, checked, checked) + atomic_write_json(self.parameters.session_dir / 'camera_preflight.json', + dict(kind='camera_preflight', stage='at_start', **self._camera_preflight.as_dict(), + optical_verification=report)) + + def _record_camera_preflight(self, devices: DeviceReadiness, *, at_start: bool = False) -> None: + """Journal changed checks and freeze the last check before any motion.""" + report = CameraPreflight.from_readiness(devices.cameras) + if not at_start and report == self._camera_preflight: + return + record = { + "kind": "camera_preflight", "schema_version": 1, + "stage": "at_start" if at_start else "before_start", + "stamp_ns": self.ports.clock_ns(), + "protected_inputs": dict(self.parameters.protected_inputs), + # These are the expected configuration identities, not live + # measurements of serial numbers or physical camera geometry. + "expected_cameras": {view: asdict(identity) + for view, identity in self.parameters.extrinsics.cameras.items() + if view in self.required_observation_views}, + **report.as_dict(), + } + atomic_write_json(self.parameters.session_dir / "camera_preflight.json", record) + append_jsonl(self.raw_path, record) + self._camera_preflight = report + + def _device_status(self, now): + """Readiness is live, and independent of whether a Tag is visible. + + The two-second camera window is only a pre-Start condition. During + scans, transient visual loss still uses the post-direction data gate. + """ + health = self.sdk_adapter.health() + waiting = [] + if not health.connected: + waiting.append("SDK 未连接") + if not self.profile.vision_motion and (len(self.latest_feedback) != self.command_count or not health.feedback_fresh): + waiting.append("等待完整、新鲜的 SDK 反馈") + if self.profile.vision_motion and self.parameters.commands_enabled and len(self.parameters.initial_command) != self.command_count: + waiting.append("缺少启动前读取的 SDK 目标指令,不能用位置反馈替代") + if self.profile.vision_motion and self.parameters.initial_device_uid: + try: + if json.loads(health.diagnostic).get("uid") != self.parameters.initial_device_uid: + waiting.append("SDK 设备身份与启动目标读数不一致") + except (ValueError, TypeError): + waiting.append("等待设备身份确认") + if not health.position_mode: + waiting.append("SDK 尚未确认位置控制模式") + if health.active_faults: + waiting.append("SDK 活动故障:" + ",".join(health.active_faults)) + if self.ports.command_publisher_count() > 1: + waiting.append("存在其他机械手指令发布者") + cameras = {} + for view in self.required_observation_views: + info_at = self.cameras.info_received_at.get(view) + detection_at = self.cameras.detections_received_at.get(view) + info_ready = (view in self.cameras.matrices and info_at is not None + and 0 <= now-info_at <= 2.0) + detection_ready = detection_at is not None and 0 <= now-detection_at <= 2.0 + error = self.cameras.errors.get(view, "") + cameras[view] = CameraReadiness(info_ready, detection_ready, error) + if error: + waiting.append(f"{view} 相机内参与外参不匹配或无效:{error}") + elif not info_ready: + waiting.append(f"{view} 未收到有效、新鲜的 camera_info(检查相机是否出图)") + if not detection_ready: + waiting.append(f"{view} 未收到新鲜的 Tag 检测消息(检查图像、整流和检测节点)") + return DeviceReadiness(not waiting, tuple(waiting), cameras) + + def _flush_visual_evidence(self): + rows = self.visual_motion.drain() + self.capture_index.extend(rows) + append_jsonl_many(self.raw_path, rows, durable=False) + + def _accept_feedback(self, names, positions, stamp: int, *, channel_stamps_ns=()) -> StateSample | None: + state = self.sdk_adapter.parse_feedback(names, positions) + if state is None: + return + if stamp <= 0 and not channel_stamps_ns: + stamp = self.ports.clock_ns() + if channel_stamps_ns: + from .adapters.base import ordered_feedback_values + ordered = ordered_feedback_values(self.sdk_adapter.command_layout, names, channel_stamps_ns) + if (ordered is None or any(type(value) is not int or value <= 0 for value in ordered) + or max(ordered) != stamp): + return + channel_stamps_ns = ordered + now_ns = self.ports.clock_ns() + if (max(ordered) > now_ns+self.parameters.maximum_state_image_skew_ns + or now_ns-min(ordered) > self.profile.acquisition.feedback_stale_seconds*1e9): + return + if self.state_history and stamp <= self.state_history[-1].stamp_ns: + return # Duplicate/out-of-order publication is not a new measurement. + if self.state_history and channel_stamps_ns: + previous = self.state_history[-1] + if previous.channel_stamps_ns and any(new < old or (new == old and value != old_value) + for new, old, value, old_value in zip(channel_stamps_ns, previous.channel_stamps_ns, state, previous.position_u8)): + return + violation = next(( + (index, value) + for index, value in enumerate(state) + if value < self.feedback_lower[index] + or value > self.feedback_upper[index] + ), None) + if violation is not None and not self.profile.vision_motion: + index, value = violation + # Preserve the offending observation for the operator diagnostic, + # while the pause path continues to hold the last safe command. + self.latest_feedback = state + self._pause( + "feedback_outside_registered_feedback_domain:" + f"channel={self.command_names[index]}:value={value:.9f}:" + f"lower={self.feedback_lower[index]:.9f}:" + f"upper={self.feedback_upper[index]:.9f}" + ) + return + received_at = self.ports.monotonic() + if not self.state_history or stamp > self.state_history[-1].stamp_ns: + self.state_history.append(StateSample(stamp, state, tuple(channel_stamps_ns))) + if self.segment is not None: + # Stability is a property of independent SDK observations, + # not of how often the control timer happened to run. + self.segment.observe(state, stamp=stamp, now=received_at) + self.latest_feedback = state + self.state_receive_times.append(received_at - max(0, self.ports.clock_ns()-min(channel_stamps_ns))/1e9 + if channel_stamps_ns else received_at) + if self.started and channel_stamps_ns and not self.finalization.started: + record = {"kind": "sdk_feedback_sample", "stamp_ns": stamp, + "received_stamp_ns": self.ports.clock_ns(), "source": "can_feedback_v1", + "state_values": list(state), "channel_stamps_ns": list(channel_stamps_ns)} + self.capture_index.append(record) + append_jsonl_many(self.raw_path, (record,), durable=False) + return self.state_history[-1] + + def _publish_command(self, values): + if self.parameters.commands_enabled and not self._raw_capture_closed: + self.sdk_adapter.publish_position(values) + + def _write_position(self, values): + if not self.parameters.commands_enabled or self._raw_capture_closed: + return + bounded = self.sdk_adapter.validate_command(values) + self.ports.publish_position(bounded) + self.last_command = bounded + if self.command_history: + for index, (previous, current) in enumerate(zip(self.command_history[-1].position_u8, bounded)): + if abs(current-previous) > 1e-9: + direction = "increasing" if current > previous else "decreasing" + if self._command_directions[index] and self._command_directions[index] != direction: + self._actual_direction_changes[index] += 1 + self._command_directions[index] = direction + stamp = self.ports.clock_ns() + self.command_history.append(StateSample(stamp, bounded)) + self.command_direction_history.append((stamp, tuple(self._command_directions))) + self._actual_command_count += 1 + if self.raw_joint and self.started and not self.finalization.started: + motion = self._motion + append_jsonl_many(self.raw_path, (dict(kind='raw_command_sent', stamp_ns=stamp, + command_vector=list(bounded), direction_by_index=list(self._command_directions), + phase=motion.phase if motion else self.execution.session.phase.value, + task_name=motion.task_key if motion else None, + cycle=motion.cycle if motion else None, + segment_key=motion.segment_key if motion else '', + direction=motion.direction if motion else None, + attempt=motion.attempt if motion else None, + command_index=motion.command_index if motion else None),), durable=False) + + def _publish_speed(self, speed): + indices = self.profile.command.command_index_by_joint.values() + # Position and speed slots are mapped inside the protocol adapter. + for index in sorted(set(indices)): + self.sdk_adapter.set_speed(index, speed) + + def _write_speed(self, _slot, speed): + if self.command_unit != "u8": + self.commanded_speed = speed + return + if not self.parameters.commands_enabled or self.commanded_speed == int(speed): + return + # Position and speed vectors have separate layouts in the SDK protocol. + count = max(self.profile.command.speed_slot_by_command_index.values(), default=self.command_count-1)+1 + self.ports.publish_setting({"setting_cmd": "set_speed", "params": { + "hand_type": self.profile.key.side, "speed": [int(speed)]*count}}) + self.commanded_speed = int(speed) + + def _publish_torque(self): + if self.parameters.commands_enabled and self.command_unit == "u8": + self.ports.publish_setting({"setting_cmd": "set_max_torque_limits", "params": { + "hand_type": self.profile.key.side, + "torque": [self.parameters.torque_u8]*self.command_count}}) + + def _pause(self, reason: str) -> None: + with self.step_data_lock: + if self.state in {"PASSED", "DIAGNOSTIC_COMPLETE", "ABORTED", "FAILED"} or self._pause_effects_applied: + return + self.finalization.cancel() + if self.training_worker is not None: + self.training_worker.close() + self._training_request = None + self._observation_epoch += 1 + self.branch_initialization.clear() + self._pause_effects_applied = True + if self.execution.session.phase != Phase.PAUSED: + from .reporting.reasons_zh import reason_zh + code, explanation, suggestion = reason_zh({"reason": str(reason)}, model_name=self.model_name) + self.execution.session.pause(code, explanation, {"raw_reason": str(reason)}, suggestion=suggestion) + self._pause_locked(reason) + + def _pause_locked(self, reason: str) -> None: + self.reason = str(reason) + # In radian mode, hold the last command rather than feeding an + # uncalibrated feedback value back into the command domain. + if self.last_command is not None: + self._publish_command(list(self.last_command)) + # No prior command means no movement was authorized. In particular, + # never echo out-of-domain feedback as a "hold" during preview. + step = self._motion + target = [] if step is None else list(step.target) + errors = ( + [] + if len(target) != len(self.latest_feedback) + else [ + abs(float(actual) - float(expected)) + for actual, expected in zip(self.latest_feedback, target) + ] + ) + append_jsonl(self.raw_path, { + "kind": "paused", + "reason": self.reason, + "command_unit": self.command_unit, + f"last_command_{self.command_unit}": list(self.last_command) if self.last_command is not None else [], + f"latest_state_{self.command_unit}": list(self.latest_feedback), + f"target_state_{self.command_unit}": target, + f"channel_errors_{self.command_unit}": errors, + "maximum_error_channel": ( + None + if not errors + else self.command_names[int(np.argmax(errors))] + ), + f"maximum_error_{self.command_unit}": ( + None if not errors else max(errors) + ), + }) + + def _new_reference_lock(self): + return ReferenceLock( + { + view.name: next( + tag.tag_id for tag in view.tags if tag.fixed_reference + ) + for view in self.profile.vision.views + if view.name in self.required_observation_views + }, + minimum_frames=self.profile.acquisition.fixed_reference_minimum_frames, + maximum_corner_drift_px=( + self.profile.acquisition.fixed_reference_maximum_drift_px + ), + confirmation_frames=( + self.profile.acquisition.fixed_reference_confirmation_frames + ), + ) + + def _save_reference(self): + fixed, moving = self.capture.fingerprint_poses() + self._current_fingerprint = {"profile_id": self.profile.key.profile_id, + "acquisition_policy_version": self.execution.session.engine.checkpoint_token, + "protected_hashes": {**self.parameters.protected_inputs, "intrinsics_sha256": hashlib.sha256( + json.dumps({v: self.cameras.matrices[v].tolist() + for v in sorted(self.required_observation_views)}, sort_keys=True).encode()).hexdigest()}, + "fixed_corners_by_view": self.reference_lock.fingerprint(), "fixed_poses": fixed, + "moving_tag_poses": moving, + "fixed_reference_mode": self.profile.acquisition.fixed_reference_mode, + "stationary_image_references": self.capture.image_reference_payloads()} + if self._raw_installation is not None: + self._current_fingerprint['raw_installation_reference'] = self._raw_installation.payload() + append_jsonl(self.raw_path, {"kind": "fixed_base_reference_locked", **self._current_fingerprint}) + + def _write_resume_batch(self, pending): + """Transfer bounded rows and poll a non-blocking durability barrier.""" + if not pending.transfer_complete: + rows = pending.take_batch() + append_jsonl_many(self.raw_path, rows, durable=False) + self.capture_index.extend(rows) + if not pending.transfer_complete: + return False + if pending.durability_future is None: + pending.durability_future = self.journal_durability.submit( + lambda: sync_jsonl(self.raw_path)) + return False + if not pending.durability_future.done(): + return False + pending.durability_future.result() + pending.durable = True + return True + + def _restore_passed_reference_batch(self, pending): + """Restore imported runtime indexes in bounded control-loop slices.""" + if pending.restore_phase == "binding": + from .passed_resume import restored_model_record + binding = restored_model_record(pending.model_records, + self._observation_epoch, self.ports.clock_ns()) + if self.profile.quality.training_policy in STAGED_POLICIES and self.parameters.resume_mode != "passed": + binding.update(kind="staged_pose_models_restored", resume_mode="verify", + physical_zero_reverification_required=True) + binding.pop("unchanged_installation_declared", None) + append_jsonl_many(self.raw_path, (binding,), durable=False) + self.capture_index.append(binding) + pending.durability_future = self.journal_durability.submit( + lambda: sync_jsonl(self.raw_path)) + pending.restore_phase = "binding_sync" + return False + + if pending.restore_phase == "binding_sync": + if not pending.durability_future.done(): + return False + pending.durability_future.result() + pending.restore_phase = "models" + return False + + if pending.restore_phase == "models": + from .passed_resume import restore_parent_models + restore_parent_models(self.branch_initialization.parent_references, + pending.model_records, self._observation_epoch, pending.rows) + pending.restore_rows = tuple(row for row in pending.rows + if row.get("kind") == "motion_branch_observation") + pending.restore_offset = 0 + pending.restore_phase = "observer_records" + return False + + if pending.restore_phase == "observer_records": + from .observer_reference import restore_observer_records + batch = pending.restore_rows[pending.restore_offset:pending.restore_offset + 512] + restore_observer_records(self.branch_initialization, batch) + pending.restore_offset += len(batch) + if pending.restore_offset == len(pending.restore_rows): + if self.parameters.resume_mode == "passed": + # Passed tasks contribute immutable zero/model evidence, + # never unfinished live actions. Replaying an old active + # observer decision can move an already accepted joint + # while the next task is preparing. + pending.restore_rows = tuple(row for row in pending.rows + if row.get("kind") == "motion_branch_observation" + and row.get("preparation_witness_joint")) + pending.restore_offset = 0 + pending.restore_phase = "witness" + return False + preparation_kinds = {"observer_preparation_decision", + "image_observation_frame", "observer_preparation_segment_complete", + "observer_preparation_excursion_started", + "observer_preparation_cancelled_before_excursion"} + pending.restore_rows = tuple(row for row in pending.rows + if row.get("kind") in preparation_kinds) + pending.restore_offset = 0 + pending.restore_phase = "observer_preparation" + return False + + if pending.restore_phase == "observer_preparation": + batch = pending.restore_rows[pending.restore_offset:pending.restore_offset + 256] + self.branch_initialization.observer_preparation.restore(batch) + pending.restore_offset += len(batch) + if pending.restore_offset == len(pending.restore_rows): + pending.restore_rows = tuple(row for row in pending.rows + if row.get("kind") == "motion_branch_observation" + and row.get("preparation_witness_joint")) + pending.restore_offset = 0 + pending.restore_phase = "witness" + return False + + if pending.restore_phase == "witness": + batch = pending.restore_rows[pending.restore_offset:pending.restore_offset + 64] + for row in batch: + self.branch_initialization.witness_capture.observe(row) + pending.restore_offset += len(batch) + if pending.restore_offset < len(pending.restore_rows): + return False + pending.restore_rows = () + pending.restore_phase = "complete" + self.execution.zero_references.update(pending.references) + if self.visual_motion is not None: + self.visual_motion.freeze_zeros(pending.references) + return True + + if pending.restore_phase == "complete": + return True + raise RuntimeError("unknown_passed_reference_restore_phase") + + def _import_resume_batch(self): + pending = self._resume_import + self._write_resume_batch(pending) + if pending.complete: + # No scan is skipped until every imported row is durable. Between + # batches the ordinary feedback, abort and safety callbacks run. + self.execution.first_cycle_spans.update(self.joint_resume.spans_for_task(pending.task_key)) + cycles = self.joint_resume.profile.quality.task_training_cycles.get(pending.task_key) + staged = self.profile.quality.training_policy == STAGED + if cycles is not None and not staged: + self.execution.session.select_training(pending.task_key, cycles) + self.execution.profile = self.execution.session.profile + decisions = [r for r in pending.rows if r.get("kind") == "staged_training_decision"] if staged else [] + for record in decisions: + if record["decision"] == "supplement": + self.execution.session.supplement_training(record["supplement_tasks"]) + self.execution.profile = self.execution.session.profile + elif record["decision"] == "freeze": + self._frozen_training_sha256 = record["frozen_training_sha256"] + self.execution.authorize_task_reuse(pending.units) + if staged and not decisions: + last = max((i for i, u in enumerate(self.execution.session._units) if u.identity in pending.units)) + unit = self.execution.session._units[last] + if unit.cycle in {1, 2} and unit == [u for u in self.execution.session._units if u.cycle == unit.cycle][-1]: + self.execution.session._unit_index = last + self.execution.session.phase = Phase.EVALUATE + self._resumed_count += len(pending.units) + self._resume_import = None + + def _verify_resume(self): + if self.raw_joint: + try: + if self._resume_checkpoint is None: + raise ValueError(self._resume_checkpoint_error or 'raw_checkpoint_missing') + verification = self._resume_checkpoint.verify_reference(self.profile, self._current_fingerprint, + require_installation=False) + from .joint_resume import ResumeJournalImport + self._raw_resume_import = ResumeJournalImport(self._resume_checkpoint.import_rows()) + self._resume_message = ('固定基准检查通过,活动标签差异已记录待离线复核;正在导入原始证据和补采预算' + if verification['requires_offline_review'] else + '固定基准与活动标签基准一致,正在导入原始证据和补采预算') + append_jsonl(self.raw_path, dict(kind='raw_resume_verified', + source_header=self._resume_checkpoint.header, + source_reference=self._resume_checkpoint.fixed_reference, + installation_verification=verification)) + except (ValueError, KeyError, TypeError) as error: + self._pause('raw_resume_rejected:' + str(error)) + return + if self.parameters.resume_mode == "passed": + self._restore_passed_tasks() + return + decision = ResumeDecision(False, "基准变化,已放弃旧断点并重新采集") + rows = [] + try: + checkpoint = self._resume_checkpoint + if checkpoint is None: + raise ValueError(self._resume_checkpoint_error or "resume_checkpoint_not_prepared") + rows, header, complete = checkpoint.rows, checkpoint.header, checkpoint.completed_units + used_tasks = {key[0] for key in complete} + from .scan_quality import observation_streams + required = {f"{spec.view}:{role}" for task in self.profile.motion.tasks if task.key in used_tasks + for _, _, spec in observation_streams(self.profile, task) + for role in (spec.parent_role, spec.child_role) + if not any(tag.role == role and tag.fixed_reference for tag in self._view(spec.view).tags)} + if self.profile.artifacts.output_schema_version >= 3: + required = set() + verifier = ResumeVerifier(required_fixed_views=self.profile.vision.view_names, + required_fixed_poses=self.profile.vision.view_names, required_moving_poses=required, + required_hashes=self._current_fingerprint["protected_hashes"]) + previous = {**checkpoint.fixed_reference, "acquisition_policy_version": header["acquisition_policy_version"]} + from .resume import select_installation_evidence + old, new = select_installation_evidence(fingerprint_from_mapping(previous), + fingerprint_from_mapping(self._current_fingerprint), required) + decision = verifier.compare(old, new) + if decision.reuse: + from dataclasses import replace + if self.profile.artifacts.output_schema_version >= 3: + self.joint_resume = checkpoint.joints + self._restore_taskwise_recovery(checkpoint) + decision = replace(decision, reason="整场参考通过,等待逐关节验证原零位后复用") + if self.profile.quality.training_policy in STAGED_POLICIES: + from .staged_resume import restore_recovery + self._passed_reference_import = checkpoint.passed_import + restore_recovery(self.execution.session, self.zero_recovery, rows) + if checkpoint.frozen_training is not None: + atomic_write_json(self.parameters.session_dir / "frozen_training.json", checkpoint.frozen_training) + else: + decision = replace(decision, completed_units=tuple(sorted(complete))) + except (OSError, ValueError, KeyError, TypeError) as error: + decision = ResumeDecision(False, "旧断点校验未通过,已重新采集", (str(error),)) + if self.profile.quality.training_policy in STAGED_POLICIES and not decision.reuse: + self._pause("staged_resume_reference_or_evidence_changed:" + str(decision.incompatible_fields)) + return + decision = self.execution.restore(decision, rows) + if decision.reuse: + used = set(decision.completed_units) + imported = [r for r in rows if record_scan_identity(r) in used] + append_jsonl_many(self.raw_path, imported) + self.capture_index.extend(imported) + self._resumed_count = len(used) + self._resume_message = decision.reason + append_jsonl(self.raw_path, {"kind": "resume_verification", "reuse": decision.reuse, + "reason": decision.reason, "incompatible_fields": list(decision.incompatible_fields), + "completed_units": list(decision.completed_units)}) + + def _restore_passed_tasks(self): + checkpoint = self._resume_checkpoint + if checkpoint is None: + self._pause("passed_resume_unavailable:" + self._resume_checkpoint_error) + return + if checkpoint.fixed_reference.get("protected_hashes") != self._current_fingerprint.get("protected_hashes"): + self._pause("passed_resume_protected_inputs_changed") + return + self.joint_resume = checkpoint.joints + self._passed_reference_import = checkpoint.passed_import + self._restore_taskwise_recovery(checkpoint) + if self.profile.quality.training_policy in STAGED_POLICIES: + from .staged_resume import restore_recovery + restore_recovery(self.execution.session, self.zero_recovery, checkpoint.rows) + if checkpoint.frozen_training is not None: + atomic_write_json(self.parameters.session_dir / "frozen_training.json", checkpoint.frozen_training) + # The existing bounded importer skips each task only after its original + # rows and zero references are durable. No old task is moved or scanned. + self._resume_message = "按已通过记录续采,跳过历史回放和已完成关节零位复核" + if self.profile.quality.training_policy in STAGED_POLICIES: + self._resume_message = "断点证据校验通过,直接复用已完成访问;不重复运动或零位复核" + self.execution.restore(ResumeDecision(True, self._resume_message), ()) + + def _restore_taskwise_recovery(self, checkpoint): + """Restore and persist the task budget even when no old task is reusable.""" + from .task_deferral import taskwise_deferral + if not taskwise_deferral(self.profile): + return + self.execution.session.restore_task_deferrals(checkpoint.rows) + records = tuple(row for row in checkpoint.rows if row.get("kind") == "task_observation_state") + for row in checkpoint.rows: + if row.get("kind") == "joint_zero_recovery": + self.zero_recovery.restore(row["task_name"], row["joints"]) + append_jsonl_many(self.raw_path, records) + self.capture_index.extend(records) + # The recovery journal has one owner. Per-reference and passed-task + # importers must not append the same state transitions again. + from .motion_provenance import source_frame_sha256 + self.joint_resume._motion_provenance_emitted.update(source_frame_sha256(row) for row in records) + if checkpoint.passed_import is not None: + checkpoint.passed_import.rows = tuple(row for row in checkpoint.passed_import.rows + if row.get("kind") != "task_observation_state") + + def _view(self, name: str): + return next(view for view in self.profile.vision.views if view.name == name) + + def _feedback_hz(self) -> float: + if len(self.state_receive_times) < 2: + return 0.0 + elapsed = self.state_receive_times[-1] - self.state_receive_times[0] + return 0.0 if elapsed <= 0 else (len(self.state_receive_times) - 1) / elapsed + + def _finalize(self) -> None: + if self.diagnostic_capture is not None: + self._pause("diagnostic_capture_not_for_publication_or_resume") + return + if self.finalization.started or self.execution.session.phase != Phase.FIT: + return + sync_jsonl(self.raw_path) + # Closing acquisition freezes the already collected camera/reference + # evidence. Later images cannot invalidate or mutate the fit input; + # feedback, device safety and explicit abort remain live in _advance. + self._observation_epoch += 1 + self.branch_initialization.clear() + self.reason = "fitting_validating_and_writing_artifacts" + self.finalization.start(FinalizationInputs( + self.parameters.session_dir, self.parameters.serial_number, self.parameters.source_urdf, + self._current_fingerprint.get("protected_hashes", self.parameters.protected_inputs), + (tuple(self.capture_index) + tuple(self.cameras.models.values()) + if self.capture_index.retain_complete else ()), require_motion_evidence=True, + journal_path=self.raw_path, journal_size=self.raw_path.stat().st_size, + camera_extrinsics_file=self.parameters.camera_extrinsics_file, + frozen_training_sha256=self._frozen_training_sha256, + )) + + def _poll_finalization(self) -> None: + try: + result = self.finalization.poll(self._finalizer_event, self._authorize_commit) + if result is None: + return + correction = result[2] + except FinalizationProtocolError as error: + self._fail_finalization("finalization_protocol_error", error) + return + except Exception as error: + self._fail_finalization("fit_or_publication_failed", error) + return + self.execution.session.published() + self.reason = "partial_calibration_passed" if self.profile.scope.default_scope != "full" else "full_calibration_passed" + self.final_json = str(self.parameters.session_dir / self.profile.artifacts.calibration_filename.format( + serial_number=self.parameters.serial_number, side=self.profile.key.side, model=self.model_name.lower())) + self.final_urdf = str(correction.path) + + def _fail_finalization(self, code: str, error: Exception) -> None: + """End a completed acquisition without suggesting another motion run. + + Numeric, final-file and worker-protocol failures share this boundary. + Feedback/safety failures during motion still use the ordinary pause. + Cancellation and epoch invalidation precede diagnostic I/O so even an + unwritable report cannot leave a worker authorized to publish. + """ + stage = self.execution.session.phase.value + self.finalization.cancel() + self._observation_epoch += 1 + self.branch_initialization.clear() + self._pause_effects_applied = True + self.reason = f"{code}:{error}" + details = {"stage": stage, "raw_reason": self.reason, + "raw_samples": str(self.raw_path), + "completed_unit_count": len(self.execution.completed_units), + "expected_unit_count": len(self.execution.session.engine.scan_units())} + self.execution.session.fail(code, "采集已结束,拟合或文件验收失败", details, + suggestion="保留原始采集和配置,先离线复算并检查失败诊断;仅在证据不足时重新采集。") + if self.last_command is not None: + self._publish_command(list(self.last_command)) + diagnostic = {"profile_id": self.profile.key.profile_id, "reason": str(error), + "state": "FAILED", **details, "traceback": traceback.format_exc()} + atomic_write_json(self.parameters.session_dir / "failure_diagnostic.json", diagnostic) + append_jsonl(self.raw_path, {"kind": "finalization_failed", **diagnostic}) + + def _finalizer_event(self, event: str) -> None: + session = self.execution.session + if event == "fit_complete": + session.fit_complete() + elif event == "holdout_complete": + session.holdout_complete(passed=True) + elif event == "artifacts_built": + session.artifacts_built() + elif event == "urdf_validated": + session.urdf_validated(passed=True) + else: + raise ValueError(f"unknown finalizer event:{event}") + + def _authorize_commit(self) -> None: + if self.diagnostic_capture is not None: + raise RuntimeError("diagnostic_capture_not_for_publication_or_resume") + if self.execution.session.phase != Phase.PUBLISH: + raise RuntimeError("finalization did not complete all acceptance stages") + sync_jsonl(self.raw_path) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/detection_dispatch.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/detection_dispatch.py new file mode 100644 index 0000000..3152d3a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/detection_dispatch.py @@ -0,0 +1,98 @@ +"""Bounded image work outside ROS callbacks, with measurement-time lookahead.""" + +from concurrent.futures import ThreadPoolExecutor +from threading import Condition +import math +import time + + +class DetectionDispatcher: + """One active and one pending image per view; SDK callbacks remain short. + + A detected image can arrive before the matching CAN observation is + delivered. Wait at most the existing synchronization tolerance for that + observation, without blocking ROS feedback or motor commands. The capture + layer still enforces its original timestamp and observation-quality gates. + """ + + def __init__(self, views, deliver, *, maximum_wait_seconds, failed): + self._deliver, self._failed = deliver, failed + self._maximum_wait = float(maximum_wait_seconds) + if not math.isfinite(self._maximum_wait) or self._maximum_wait <= 0 or not views or len(set(views)) != len(views): + raise ValueError("invalid image dispatch views or synchronization wait") + self._condition = Condition() + self._pending = dict.fromkeys(views) + self._generation, self._closed = 0, False + self._feedback_stamp_ns = 0 + self._error = None + self._executor = ThreadPoolExecutor(max_workers=len(views), thread_name_prefix="calibration_image") + self._workers = [self._executor.submit(self._guarded_run, view) for view in views] + + def _guarded_run(self, view): + try: + self._run(view) + except Exception as error: + with self._condition: + self._error = error + self._failed(error) + + def raise_if_failed(self): + with self._condition: + if self._error is not None: + raise RuntimeError("image dispatch failed") from self._error + + def submit(self, observation): + with self._condition: + if self._closed: + return + if observation.view not in self._pending: + raise ValueError("undeclared image dispatch view") + self._pending[observation.view] = observation + self._condition.notify_all() + + def feedback_available(self, stamp_ns): + """Advance to the oldest channel of an accepted measurement snapshot. + + The queue never calls back into the coordinator while holding its + condition. Control messages can therefore wake image workers without + waiting for another worker to acquire the session lock. + """ + with self._condition: + self._feedback_stamp_ns = max(self._feedback_stamp_ns, stamp_ns) + self._condition.notify_all() + + def clear(self): + with self._condition: + self._generation += 1 + self._feedback_stamp_ns = 0 + self._pending = dict.fromkeys(self._pending) + self._condition.notify_all() + + def _run(self, view): + while True: + with self._condition: + self._condition.wait_for(lambda: self._closed or self._pending[view] is not None) + if self._closed: + return + observation, generation = self._pending[view], self._generation + self._pending[view] = None + deadline = time.monotonic()+self._maximum_wait + while not self._closed and generation == self._generation: + if self._feedback_stamp_ns >= observation.stamp_ns: + break + remaining = deadline-time.monotonic() + if remaining <= 0: + break + self._condition.wait(timeout=remaining) + if self._closed: + return + if generation != self._generation: + continue + self._deliver(observation) + + def close(self): + with self._condition: + self._closed = True + self._pending = dict.fromkeys(self._pending) + self._condition.notify_all() + self._executor.shutdown(wait=True, cancel_futures=True) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/detection_filter.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/detection_filter.py new file mode 100644 index 0000000..b3471e9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/detection_filter.py @@ -0,0 +1,26 @@ +"""Shared detector-quality filter for fast motion witnesses and pose fitting.""" + +import numpy as np + + +def filter_detections(view_spec, policy, observation, width, height, motion=None): + view, stamp = observation.view, observation.stamp_ns + roles = {tag.tag_id: tag.role for tag in view_spec.tags} + corners, quality_events = {}, [] + observed_roles = frozenset(roles[item.tag_id] for item in observation.detections if item.tag_id in roles) + for detection in observation.detections: + points = np.asarray(detection.corners, dtype=float) + if detection.border_quality is not None and not detection.border_quality["passed"]: + quality_events.append({"kind": "detection_quality_rejected", "view": view, + "image_stamp_ns": stamp, "tag_id": detection.tag_id, + "corners_xy": points.tolist(), "quality": dict(detection.border_quality), + "task_name": None if motion is None else motion.task_key, + "motion_phase": None if motion is None else motion.phase}) + continue + if (detection.tag_id not in roles or points.shape != (4, 2) or not np.all(np.isfinite(points)) + or detection.hamming > policy.maximum_hamming or detection.decision_margin < policy.minimum_decision_margin + or np.min(np.linalg.norm(points-np.roll(points, -1, axis=0), axis=1)) < policy.minimum_edge_pixels + or np.min(points) < 2 or np.max(points[:, 0]) > width-3 or np.max(points[:, 1]) > height-3): + continue + corners[roles[detection.tag_id]] = points + return corners, quality_events, observed_roles diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_analysis.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_analysis.py new file mode 100644 index 0000000..8dfddc6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_analysis.py @@ -0,0 +1,317 @@ +"""Analyze one stopped capture, without moving hardware or authorizing poses. + +Each acquisition stage and session keeps its own image identities and mounting +context. This report is separate from calibration artifacts and the original +capture report; none of its fitted geometry can enter the live reference path. +""" + +from __future__ import annotations + +import argparse +from collections import defaultdict +from dataclasses import asdict +import hashlib +import json +import math +from pathlib import Path + +from ..core.geometry.tag_pose.motion_evidence import MotionEvidenceFrame, MotionRelation, RoleCandidates +from ..core.geometry.tag_pose.types import SquareTagPose +from ..storage import atomic_write_json, load_jsonl +from .motion_provenance import source_frame_sha256 +from .scan_quality import observation_streams + + +def _file_sha256(path): + digest = hashlib.sha256() + with path.open("rb") as source: + for block in iter(lambda: source.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _check_output_targets(raw_path, output): + raw_path = raw_path.resolve() + for name in ("diagnostic_analysis.json", "diagnostic_analysis.md"): + target = output / name + if target.resolve() == raw_path or (target.exists() and target.samefile(raw_path)): + raise ValueError("diagnostic_analysis_output_overwrites_source") + + +def _pose(payload): + return SquareTagPose(tuple(payload["quaternion_xyzw"]), + tuple(payload["translation_xyz_m"]), float(payload["reprojection_error_px"])) + + +def image_frames(records, relations): + """Convert detached, same-image evidence; never substitute a later pose.""" + from ..core.geometry.tag_pose.motion_image_diagnostics import ImageMotionFrame, ImageRoleObservation + from ..core.geometry.tag_pose.image_reference import IMAGE_REFERENCE_SOURCE, reference_from_evidence + + roots = {relation.parent_role for relation in relations} - {relation.child_role for relation in relations} + roles = tuple(dict.fromkeys(role for relation in relations + for role in (relation.parent_role, relation.child_role))) + frames = [] + for row in records: + stamp = row["image_stamp_ns"] + candidates, observations = [], [] + for role in roles: + item = row.get("tags", {}).get(role) + if item is None or item.get("candidate_diagnostics", {}).get("observation_stamp_ns") != stamp: + break + diagnostics = item["candidate_diagnostics"] + # This offline comparison may inspect rejected moving candidates, + # including old captures. Preserve the verified root, but never + # reinterpret this counterfactual fit as a new live authorization. + frozen = role in roots and diagnostics.get("branch_frozen") is True + payloads = ([item["selected_pose"]] if frozen and item.get("selected_pose") is not None + else [] if frozen else item.get("reprojection_valid_candidates", ())) + if not payloads or item.get("corners_xy") is None: + break + candidates.append(RoleCandidates(role, tuple(_pose(p) for p in payloads), frozen)) + observations.append(ImageRoleObservation(role, float(item["tag_size_m"]), + tuple(tuple(point) for point in item["corners_xy"]))) + else: + references = tuple(reference_from_evidence(row["tags"][role], stamp_ns=stamp, + camera_matrix=row["camera_matrix"]) for role in roles + if row["tags"][role].get("pose_source") == IMAGE_REFERENCE_SOURCE) + frames.append(ImageMotionFrame(MotionEvidenceFrame(stamp, tuple(candidates)), + tuple(tuple(values) for values in row["camera_matrix"]), tuple(observations), references)) + return tuple(frames) + + +def _stages(profile, rows): + observations = {} + sweeps = defaultdict(dict) + headers = [] + initializations = [] + for row in rows: + kind = row.get("kind") + if kind == "session_start": + headers.append(row) + if kind == "motion_branch_initialization": + initializations.append(row) + if kind not in {"motion_branch_observation", "diagnostic_observation_frame"}: + continue + identity = (row["view"], row["image_stamp_ns"]) + if identity in observations and observations[identity] != row: + raise ValueError("diagnostic_analysis_image_identity_changed") + observations[identity] = row + if kind == "diagnostic_observation_frame" and row.get("sample_phase") == "sweep": + if row.get("cycle") == 3: + raise ValueError("diagnostic_analysis_refuses_holdout_training") + key = (row["task_name"], row["view"], row["cycle"], row["direction"], row.get("attempt", 1)) + sweeps[key][row["image_stamp_ns"]] = row + if len(headers) != 1 or headers[0].get("profile_id") != profile.key.profile_id: + raise ValueError("diagnostic_analysis_profile_or_session_mismatch") + tasks = {task.key: task for task in profile.motion.tasks} + stages = [] + for number, initial in enumerate(initializations): + task = tasks[initial["task_name"]] + relations = tuple(MotionRelation(name, spec.parent_role, spec.child_role) + for _, name, spec in observation_streams(profile, task) + if name in initial["zero_joints"] and spec.view == initial["view"]) + selected = [] + for stamp in initial["source_image_stamps"]: + row = observations.get((initial["view"], stamp)) + if row is None or any(row.get(key) != initial.get(key) + for key in ("task_name", "zero_joints", "session_epoch", "motion_version")): + raise ValueError("diagnostic_analysis_initialization_source_mismatch") + expected = initial.get("source_frame_hashes", {}).get(str(stamp)) + if expected is None or source_frame_sha256(row) != expected: + raise ValueError("diagnostic_analysis_initialization_hash_mismatch") + selected.append(row) + stages.append(({"key": f"initialization:{number}", "task_name": task.key, + "view": initial["view"], "sample_phase": "zero_approach", + "recorded_branch_status": initial["status"], + "recorded_branch_reason": initial["reason"], + "recorded_hypotheses": initial["hypotheses"]}, relations, tuple(selected))) + for (task_key, view, cycle, direction, attempt), images in sorted(sweeps.items()): + task = tasks[task_key] + relations = tuple(MotionRelation(name, spec.parent_role, spec.child_role) + for _, name, spec in observation_streams(profile, task) if spec.view == view) + if not relations: + continue # Retained camera context is not a task measurement. + stages.append(({"key": f"sweep:{task_key}:{view}:{cycle}:{direction}:{attempt}", + "task_name": task_key, "view": view, "sample_phase": "sweep", + "cycle": cycle, "direction": direction, "attempt": attempt}, relations, + tuple(row for _, row in sorted(images.items())))) + return headers[0], stages + + +def _image_tables(report): + lines = [] + labels = {"interleaved": "交错留出", "early_to_late": "前段训练→后段验证", + "late_to_early": "后段训练→前段验证"} + for hypothesis in report.get("hypotheses", ()): + label = ", ".join(f"{role}={index}" for role, index in hypothesis["branches"]) + lines += [f"### 候选 {label}", ""] + if hypothesis.get("reason"): + lines += [f"分析限制:`{hypothesis['reason']}`。", ""] + pnp = hypothesis.get("pnp_geometry", ()) + if pnp: + lines += ["| 关节 | 原 PnP 转心 RMS | 原 PnP 位置 P95 | 深度误差占比 |", + "| --- | ---: | ---: | ---: |"] + lines += [f"| {item['joint']} | {item['translation_rms_m']*1000:.3f} mm | " + f"{item['translation_p95_m']*1000:.3f} mm | {item['camera_depth_squared_error_fraction']*100:.1f}% |" + for item in pnp] + lines.append("") + intervals = hypothesis.get("intervals", ()) + if intervals: + lines += ["| 独立图像检查 | Tag | 留出图像数 | RMS | 逐帧 RMS 的 P95 | 优化收敛 |", + "| --- | --- | ---: | ---: | ---: | --- |"] + for interval in intervals: + state = "是(不代表精度通过)" if interval["converged"] else "否" + for item in interval.get("validation_quality", ()): + lines.append(f"| {labels.get(interval['name'], interval['name'])} | {item['role']} | " + f"{item['frames']} | {item['rms_px']:.3f} px | {item['frame_rms_p95_px']:.3f} px | {state} |") + lines.append("") + if hypothesis.get("repeatability"): + lines += ["| 关节 | 前后段转轴方向差 |", "| --- | ---: |"] + lines += [f"| {item['joint']} | {math.degrees(item['early_late_axis_difference_rad']):.3f}° |" + for item in hypothesis["repeatability"]] + lines += ["", "轴方向差可与现行分支检查的 3° 要求对照;该图像诊断不会代替原验收。", ""] + return lines + + +def _summary_markdown(report): + lines = ["# 原始观测的图像几何诊断", "", + "本报告只解释原始角点,不授权姿态分支、关节零位、JSON 或 URDF。", + "各任务和方向分别拟合;未跨会话拼接,也未作为正式独立验证轮验收。", "", + f"来源:`{report['raw_samples_path']}`", f"SHA-256:`{report['raw_samples_sha256']}`", ""] + if report.get("missing_evidence"): + lines += ["尚缺以下记录,当前报告不能补出这些真实观测:", ""] + lines += [f"- `{item}`" for item in report["missing_evidence"]] + lines.append("") + if report.get("status") == "failed": + lines += [f"分析未完成:`{report['reason']}`", "原始采集数据仍然保留。"] + for stage in report.get("stages", ()): + lines += [f"## {stage['task_name']} / {stage['view']} / {stage.get('direction', '归零准备')}", "", + f"原始图像 {stage['source_image_count']} 张,可用完整图像 {stage['usable_image_count']} 张。"] + if "recorded_branch_status" in stage: + lines.append(f"原分支判定:`{stage['recorded_branch_status']}`;原因:`{stage['recorded_branch_reason']}`。") + image = stage["image_diagnostics"] + lines += [f"图像诊断:`{image['status']}`;原因:`{image.get('reason', '')}`。", "", + "候选编号只在本阶段有效。下列所有候选均保留,没有把最低分候选写成正确零位。", ""] + lines.extend(_image_tables(image)) + lines += ["## 如何使用", "", + "- 采集完成只代表原始观测已保存;未确认关节仍没有有效零位和角度样本。", + "- 图像误差较小不能换算成毫米精度通过,也不能单凭最低分选择一个分支。", + "- 分段模型不一致或多个候选仍可解释图像时,保留未确认结论。", + "- 正式标定仍须满足原有几何、JSON 映射和正式独立验证轮验收。", ""] + return "\n".join(lines) + + +def _missing_evidence(profile, header, stages): + missing = [] if stages else ["no_recorded_motion_images"] + diagnostic = header.get("diagnostic_capture") + if not diagnostic: + return missing + observed = {(stage["task_name"], stage["view"], stage.get("cycle"), stage.get("direction")) + for stage in stages if stage["sample_phase"] == "sweep"} + for task in profile.motion.tasks: + if task.key not in diagnostic.get("task_keys", ()): + continue + views = {spec.view for _, _, spec in observation_streams(profile, task)} + for view in sorted(views): + for cycle in diagnostic.get("cycles", ()): + for direction in ("decreasing", "increasing"): + if (task.key, view, cycle, direction) not in observed: + missing.append(f"sweep:{task.key}:{view}:{cycle}:{direction}") + if not any(stage["sample_phase"] == "zero_approach" for stage in stages): + missing.append("no_pre_zero_motion_record; old_sweeps_cannot_replace_initialization") + return missing + + +def analyze_capture(profile, raw_path: Path, *, output_dir: Path | None = None, progress=None): + """Generate bounded per-stage image diagnostics after the ROS stack stops.""" + from ..core.geometry.tag_pose.motion_image_diagnostics import analyze_motion_images + + raw_path = raw_path.resolve() + output = raw_path.parent if output_dir is None else output_dir.resolve() + _check_output_targets(raw_path, output) + before = _file_sha256(raw_path) + rows = load_jsonl(raw_path) + header, stages = _stages(profile, rows) + analyzed = [] + for index, (identity, relations, records) in enumerate(stages): + if progress is not None: + progress(f"分析观测 {index+1}/{len(stages)}:{identity['task_name']} / {identity['view']} / " + + identity.get("direction", "归零准备")) + frames = image_frames(records, relations) + result = analyze_motion_images(frames, relations) + analyzed.append({**identity, "source_image_count": len(records), + "usable_image_count": len(frames), "image_diagnostics": asdict(result)}) + if _file_sha256(raw_path) != before: + raise ValueError("diagnostic_analysis_source_changed_during_read") + report = {"format": "calibration_image_diagnostic_v1", "schema_version": 1, + "scope": "diagnostic_not_branch_authorization", "status": "complete", + "accuracy_validated": False, "publication_allowed": False, + "moving_candidates_counterfactual": True, + "raw_samples_path": str(raw_path), "raw_samples_sha256": before, + "profile_id": profile.key.profile_id, + "source_protected_inputs": {key: value for key, value in header.items() if key.endswith("_sha256")}, + "stages": analyzed, "missing_evidence": _missing_evidence(profile, header, analyzed), + "limitations": ["Independent sessions are never combined.", + "Per-stage image fits do not authorize a branch or certify 3D accuracy.", + "Training images are not independent validation; split metrics are reported separately."]} + output.mkdir(parents=True, exist_ok=True) + atomic_write_json(output / "diagnostic_analysis.json", report) + (output / "diagnostic_analysis.md").write_text(_summary_markdown(report), encoding="utf-8") + return report + + +def finish_diagnostic_analysis(profile, session: Path): + """Analysis failure must not relabel a completed capture as an SDK failure.""" + try: + capture_path = session / 'diagnostic_capture.json' + capture = json.loads(capture_path.read_text()) if capture_path.exists() else {} + from ..profiles.diagnostics import DIAGNOSTIC_CAPTURE_PRESETS + preset = DIAGNOSTIC_CAPTURE_PRESETS.get(capture.get('mode')) + if preset is not None and preset.chain_joints: + # The old per-stage analyzer intentionally rejects cycle 3. Never + # send batch holdout data into its training/branch-selection path. + report = dict(status='pending_joint_chain_validation', + accuracy_validated=False, publication_allowed=False, + raw_samples_path=str(session / 'raw_samples.jsonl'), + raw_samples_sha256=_file_sha256(session / 'raw_samples.jsonl'), + training_cycles=[0, 1], holdout_cycles=[3]) + _check_output_targets(session / 'raw_samples.jsonl', session) + atomic_write_json(session / 'diagnostic_analysis.json', report) + print('小指数据已保存:两轮训练与第三轮验证保持隔离,等待运动曲线及 JSON/URDF 验收。', flush=True) + return report + report = analyze_capture(profile, session / "raw_samples.jsonl", progress=lambda message: print(message, flush=True)) + except Exception as error: + # This is the boundary between a completed acquisition and optional + # offline computation, including failures raised by numerical libraries. + # KeyboardInterrupt/SystemExit still propagate to the runner. + report = {"status": "failed", "scope": "diagnostic_not_branch_authorization", + "reason": str(error), "accuracy_validated": False, "publication_allowed": False, + "raw_samples_path": str(session / "raw_samples.jsonl"), "raw_samples_sha256": ""} + try: + _check_output_targets(session / "raw_samples.jsonl", session) + atomic_write_json(session / "diagnostic_analysis.json", report) + (session / "diagnostic_analysis.md").write_text(_summary_markdown(report), encoding="utf-8") + except (OSError, ValueError) as write_error: + print(f"离线分析结果也无法保存:{write_error}。原始采集状态保持不变。", flush=True) + print(f"原始采集已完成,但离线图像分析未完成:{error}。数据已保留,可离线复算。", flush=True) + print(f"图像几何诊断:{session / 'diagnostic_analysis.md'}", flush=True) + return report + + +def main(args=None): + from ..product import load_product_config + + parser = argparse.ArgumentParser(description="离线分析已保存的运动 Tag 角点,不启动实机、不发布标定产物") + parser.add_argument("--config", required=True) + parser.add_argument("--raw", required=True) + parser.add_argument("--output", default=None) + selected = parser.parse_args(args) + config = load_product_config(selected.config, check_can=False) + analyze_capture(config.calibration_contract.typed_profile, Path(selected.raw), + output_dir=None if selected.output is None else Path(selected.output), + progress=lambda message: print(message, flush=True)) + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_capture.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_capture.py new file mode 100644 index 0000000..c0b6419 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_capture.py @@ -0,0 +1,151 @@ +"""Explicit, non-publishing capture presets over the shared motion schedule.""" + +from dataclasses import asdict, dataclass +import math +from numbers import Real +from typing import Mapping, Sequence + +from ..core.domain.profile import CalibrationProfile +from ..profiles.diagnostics import DIAGNOSTIC_CAPTURE_PRESETS +from ..acquisition import StateSample + + +def _finite_number(value) -> bool: + return isinstance(value, Real) and not isinstance(value, bool) and math.isfinite(value) + + +@dataclass(frozen=True) +class DiagnosticCapturePlan: + mode: str + task_keys: tuple[str, ...] + cycles: tuple[int, ...] = (0,) + hold_command_values: tuple[float, ...] = () + hold_seconds: float = 0.0 + observer_views: tuple[str, ...] = () + chain_joints: tuple[str, ...] = () + + def __post_init__(self) -> None: + if (not isinstance(self.cycles, tuple) or not self.cycles + or any(type(cycle) is not int or cycle < 0 for cycle in self.cycles) + or tuple(sorted(set(self.cycles))) != self.cycles): + raise ValueError("diagnostic_cycles_invalid") + if self.chain_joints and (len(self.chain_joints) != 3 + or len(set(self.chain_joints)) != 3 or self.cycles != (0, 1, 3) + or self.hold_command_values or self.observer_views): + raise ValueError("diagnostic_chain_contract_invalid") + if (not isinstance(self.observer_views, tuple) + or any(not isinstance(view, str) or not view for view in self.observer_views) + or len(set(self.observer_views)) != len(self.observer_views)): + raise ValueError("diagnostic_observer_views_invalid") + # The declared diagnostic allows at most ten seconds per arrival; + # extending that motion contract requires an explicit preset review. + if (not _finite_number(self.hold_seconds) + or (not self.hold_command_values and self.hold_seconds != 0.0) + or (self.hold_command_values and not 0.0 < self.hold_seconds <= 10.0)): + raise ValueError("diagnostic_hold_seconds_invalid") + if (not isinstance(self.hold_command_values, tuple) + or any(not _finite_number(value) for value in self.hold_command_values) + or any(left >= right for left, right in zip( + self.hold_command_values, self.hold_command_values[1:]))): + raise ValueError("diagnostic_hold_values_invalid") + + def as_dict(self) -> dict: + result = asdict(self) + if not self.hold_command_values: + result.pop("hold_command_values") + result.pop("hold_seconds") + if not self.observer_views: + result.pop("observer_views") + if not self.chain_joints: + result.pop("chain_joints") + else: + result['reference_policy'] = 'first_training_return_v1' + result['parent_pose_policy'] = 'original_training_return_handoff_v1' + return result + + +def diagnostic_capture_label(mode: str) -> str: + preset = DIAGNOSTIC_CAPTURE_PRESETS.get(mode) + return preset.label_zh if preset else "诊断采集" + + +def diagnostic_hold_timing(history: Sequence[StateSample], *, target: tuple[float, ...], + image_stamp_ns: int, session_epoch: int, motion_version: int, motion_started_ns: int, + feedback_stable_since_ns: int | None) -> dict: + """Describe the actual held command without assigning unmeasured exposure time. + + Only command samples at or before this image are considered. A rounded u8 + target may be issued before the trajectory finishes, so its first issue + is retained separately from the motion's start and feedback stability. + """ + first_target = next((sample.stamp_ns for sample in history + if motion_started_ns <= sample.stamp_ns <= image_stamp_ns + and tuple(sample.position_u8) == target), None) + stable_since = feedback_stable_since_ns + if stable_since is not None and not motion_started_ns <= stable_since <= image_stamp_ns: + stable_since = None + return { + "hold_id": f"{session_epoch}:{motion_version}", + "target_first_command_stamp_ns": first_target, + "feedback_stable_since_ns": stable_since, + } + + +def resolve_diagnostic_capture(profile: CalibrationProfile, mode: str) -> DiagnosticCapturePlan | None: + """Select an audited task subset without changing a protected Profile. + + Presets select tasks and optional directional holds. Safety, references + and vision remain the common implementations; no alternative fitter is + created, and these observations cannot certify calibration artifacts. + """ + if not mode: + return None + preset = DIAGNOSTIC_CAPTURE_PRESETS.get(mode) + if preset is None or profile.key != preset.profile_key: + raise ValueError(f"unsupported_diagnostic_capture:{mode}:{profile.key.profile_id}") + expected = dict(preset.tasks) + tasks = tuple(task for task in profile.motion.tasks if task.key in expected) + if len(tasks) != len(expected) or profile.artifacts.output_schema_version < 3: + raise ValueError("diagnostic_thumb_tasks_or_joint_zeros_missing") + for task in tasks: + if (set(task.joints) != set(expected[task.key]) or task.validation_only + or task.command_index != profile.command.command_index_by_joint.get(expected[task.key][0]) + or any(name not in profile.motion.joint_zero_references + or profile.motion.joint_zero_references[name].task_key != task.key for name in task.joints)): + raise ValueError(f"diagnostic_thumb_task_binding_changed:{task.key}") + plan = DiagnosticCapturePlan(mode, tuple(task.key for task in tasks), + cycles=(0, 1, 3) if preset.chain_joints else (0,), chain_joints=preset.chain_joints, + hold_command_values=preset.hold_command_values, hold_seconds=preset.hold_seconds, + observer_views=preset.observer_views) + if plan.chain_joints: + from ..core.domain.capture_plan import TASKWISE_TWO_ROUND + if (profile.quality.training_policy != TASKWISE_TWO_ROUND + or profile.vision_motion or profile.acquisition.command_capture_mode != 'interleaved' + or tuple(task.joints for task in tasks) != tuple((name,) for name in plan.chain_joints) + or len({task.view for task in tasks}) != 1 + or profile.motion.preparation_witnesses or profile.motion.observer_preparations): + raise ValueError('diagnostic_chain_requires_taskwise_feedback_interleaved_plan') + for task in tasks: + reference = profile.motion.joint_zero_references[task.joints[0]] + if (task.segments or task.model_preparations or reference.evidence_scope != 'arrival' + or reference.command[task.command_index] != task.start_value + or task.start_value >= task.end_value): + raise ValueError('deferred_chain_requires_return_to_reference_endpoint') + if not set(plan.observer_views) <= set(profile.vision.view_names): + raise ValueError("diagnostic_observation_views_invalid") + for task in tasks: + lower = max(min(task.start_value, task.end_value), + profile.command.minimum_values[task.command_index]) + upper = min(max(task.start_value, task.end_value), + profile.command.maximum_values[task.command_index]) + if any(not lower < value < upper for value in plan.hold_command_values): + raise ValueError(f"diagnostic_hold_outside_task_domain:{task.key}") + return plan + + +def reject_diagnostic_capture(records: Sequence[Mapping]) -> None: + """Diagnostic samples must never be promoted to formal fit or resume data.""" + if any((row.get("kind") == "session_start" and row.get("diagnostic_capture")) + or row.get("kind") in {"diagnostic_observation_frame", "diagnostic_joint_zero_attempt"} + or row.get("quality_scope") == "diagnostic_observation_coverage" for row in records): + raise ValueError("diagnostic_capture_not_for_publication_or_resume") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_quality.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_quality.py new file mode 100644 index 0000000..241740e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_quality.py @@ -0,0 +1,73 @@ +"""Separate diagnostic image coverage from accepted-pose calibration quality.""" + +from dataclasses import dataclass +from collections.abc import Mapping, Sequence +from .observation_coverage import complete_vector, visible_roles + +from ..core.domain.profile import CalibrationProfile +from ..core.domain.motion_path import record_scan_identity, segment_metadata, task_segment +from ..core.fitting.motion_fit import channel_for_joint +from .engine import ScanUnit, SweepQuality +from .scan_quality import evaluate_capture_unit, observation_streams +from .observation_timing import summarize_observation_timing + + +@dataclass(frozen=True) +class DiagnosticUnitQuality: + observations: SweepQuality + accepted_poses: SweepQuality + observation_timing: Mapping[str, Mapping] + + def accepted_pose_report(self) -> dict: + return {"passed": self.accepted_poses.passed, + "failures": list(self.accepted_poses.failures), + "metrics": dict(self.accepted_poses.metrics), "accuracy_validated": False} + + +def evaluate_diagnostic_unit(profile: CalibrationProfile, unit: ScanUnit, attempt: int, + records: Sequence[Mapping], +) -> DiagnosticUnitQuality: + """Same motion/coverage limits; ambiguous poses are evidence for diagnosis. + + Temporary records carry feedback coverage only, never measured angles. + They remain local to this check and cannot be serialized as joint samples. + Missing current moving-Tag corners still fail the ordinary one-retry gate. + """ + if hasattr(records, "task_records"): + records = records.task_records(unit.task_key) + accepted = evaluate_capture_unit(profile, unit, attempt, records, + first_cycle_spans={}, include_steady=False) + task = next(task for task in profile.motion.tasks if task.key == unit.task_key) + segment = task_segment(task, unit.segment_key) if unit.segment_key else None + tags_by_view = {view.name: {tag.role: tag for tag in view.tags} for view in profile.vision.views} + required = {} + for field, name, spec in observation_streams(profile, task): + if segment is not None and name not in segment.joints: + continue + moving_roles = {tag.role for tag in tags_by_view[spec.view].values() if not tag.fixed_reference} + required[(field, name, spec.view)] = moving_roles & {spec.parent_role, spec.child_role} + coverage = [row for row in records if row.get("kind") != "diagnostic_observation_frame"] + for row in records: + if (row.get("kind") != "diagnostic_observation_frame" + or row.get("sample_phase") != "sweep" + or record_scan_identity(row) != unit.identity or row.get("attempt") != attempt): + continue + feedback = row.get("feedback_vector") + if (row.get("command_unit") != profile.command.unit + or not complete_vector(feedback, profile.command.command_count) + or not complete_vector(row.get("command_vector"), profile.command.command_count)): + continue + visible = visible_roles(row, tags_by_view.get(row.get("view"), {})) + for (field, name, view), roles in required.items(): + if row.get("view") == view and roles and roles <= visible: + channel = channel_for_joint(profile, name) + coverage.append({field: name, "view": view, "task_name": unit.task_key, + "cycle": unit.cycle, "direction": unit.direction, "attempt": attempt, + **segment_metadata(unit.segment_key), + "image_stamp_ns": row["image_stamp_ns"], "sample_phase": "sweep", + f"feedback_{profile.command.unit}": feedback[channel], + f"command_{profile.command.unit}": row["command_vector"][channel]}) + observed = evaluate_capture_unit(profile, unit, attempt, coverage, + first_cycle_spans={}, include_steady=False) + return DiagnosticUnitQuality(observed, accepted, + summarize_observation_timing(profile, unit, attempt, records)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_reference.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_reference.py new file mode 100644 index 0000000..f95bc77 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_reference.py @@ -0,0 +1,101 @@ +"""Unresolved reference observations cannot become calibrated joint zeros. + +The diagnostic runner may finish its declared motion with raw corner evidence. +This record proves only that the reference pose was visited and observed; it +does not supply an angle, a mounting transform, or permission to publish. +""" + +from dataclasses import asdict, dataclass +import math + +import numpy as np + +from .scan_quality import observation_streams + + +@dataclass(frozen=True) +class DiagnosticZeroAttempt: + joint_names: tuple[str, ...] + task_name: str + reason: str + session_epoch: int + motion_version: int + command_vector: tuple[float, ...] + feedback_vector: tuple[float, ...] + source_images: tuple[tuple[str, int], ...] + joint_views: tuple[tuple[str, str], ...] + + def as_record(self): + return {"kind": "diagnostic_joint_zero_attempt", "schema_version": 1, + "status": "unresolved", "no_zero_locked": True, + "is_accepted_joint_sample": False, **asdict(self)} + + +def _complete_vector(values, count): + return (isinstance(values, (list, tuple)) and len(values) == count + and all(isinstance(v, (float, int)) and not isinstance(v, bool) + and math.isfinite(v) for v in values)) + + +def build_diagnostic_zero_attempt(profile, motion, records, *, reason, + session_epoch, motion_version): + """Check current raw images after the caller's SDK steady-window gate. + + Each moving parent/child must have real current-image corners. A stationary + base may use the already frozen session reference, as during normal scans. + Pose selection and geometric stability are intentionally not certified. + """ + if motion.phase != "joint_zero" or not motion.zero_joints or not reason: + raise ValueError("diagnostic_joint_zero_attempt_invalid") + task = next(task for task in profile.motion.tasks if task.key == motion.task_key) + declared = profile.motion.joint_zero_references + if (not set(motion.zero_joints) <= set(task.joints) + or any(name not in declared or declared[name].task_key != motion.task_key + or declared[name].command != motion.target for name in motion.zero_joints)): + raise ValueError("diagnostic_joint_zero_declared_pose_mismatch") + streams = [(name, spec) for _, name, spec in observation_streams(profile, task) + if name in motion.zero_joints] + tags = {view.name: {tag.role: tag for tag in view.tags} for view in profile.vision.views} + frames = {(name, spec.view): {} for name, spec in streams} + count = profile.command.command_count + for row in records: + if (row.get("kind") != "diagnostic_observation_frame" + or row.get("sample_phase") != "joint_zero" + or (row.get("task_name"), row.get("session_epoch"), row.get("motion_version")) + != (motion.task_key, session_epoch, motion_version) + or tuple(row.get("zero_joints", ())) != motion.zero_joints + or row.get("command_unit") != profile.command.unit): + continue + stamp = row.get("image_stamp_ns") + command, feedback = row.get("command_vector"), row.get("feedback_vector") + if (not isinstance(stamp, int) or isinstance(stamp, bool) or stamp <= 0 + or not _complete_vector(command, count) + or (not profile.vision_motion and not _complete_vector(feedback, count)) + or any(abs(a-b) > 1e-9 for a, b in zip(command, motion.target))): + continue + for name, spec in streams: + if row.get("view") != spec.view: + continue + roles = [role for role in (spec.parent_role, spec.child_role) + if not tags[spec.view][role].fixed_reference] + complete = bool(roles) + for role in roles: + item = row.get("tags", {}).get(role, {}) + points = np.asarray(item.get("corners_xy"), dtype=float) + complete &= (item.get("tag_role") == role + and item.get("tag_id") == tags[spec.view][role].tag_id + and item.get("candidate_diagnostics", {}).get("observation_stamp_ns") == stamp + and points.shape == (4, 2) and np.all(np.isfinite(points))) + if complete: + frames[name, spec.view][stamp] = row + minimum = profile.acquisition.fixed_reference_minimum_frames + missing = [f"{name}:{view}:{len(items)}/{minimum}" + for (name, view), items in frames.items() if len(items) < minimum] + if not frames or missing: + raise ValueError("diagnostic_joint_zero_observations_missing:" + ",".join(missing)) + selected = {(view, stamp): row for (_, view), items in frames.items() + for stamp, row in sorted(items.items())[-minimum:]} + latest = max(selected.values(), key=lambda row: row["image_stamp_ns"]) + return DiagnosticZeroAttempt(tuple(motion.zero_joints), motion.task_key, reason, + session_epoch, motion_version, tuple(latest["command_vector"]), + tuple(latest.get("feedback_vector") or ()), tuple(sorted(selected)), tuple(sorted(frames))) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_report.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_report.py new file mode 100644 index 0000000..6a201aa --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/diagnostic_report.py @@ -0,0 +1,237 @@ +"""Summarize captured pose evidence without fitting or certifying motion.""" + +from collections import defaultdict +import hashlib +import json +import math +from pathlib import Path + +from ..core.geometry.pnp import rotation_distance_rad + + +def task_observation_summary(profile, plan, records): + """Audit every planned task, including unseen tasks and passive cameras. + + Pair visibility is counted in its actual camera and motion phase. It is + not evidence that the associated joint was calibrated, nor that another + finger has the same visibility. Duplicate exposures count only once. + """ + tasks = {task.key: task for task in profile.motion.tasks if task.key in plan.task_keys} + pairs = defaultdict(set) + for spec in profile.measurement.measurements.values(): + pairs[spec.view].add((spec.parent_role, spec.child_role)) + result = {key: dict(primary_view=task.view, joints=list(task.joints), + image_observation_count=0, views={}, preparation=[], completed_segments=[], + accuracy_validated=False) for key, task in tasks.items()} + seen = {} + for row in records: + task = result.get(row.get('task_name')) + if task is None: + continue + kind = row.get('kind') + if kind == 'motion_branch_initialization': + task['preparation'].append(dict(view=row['view'], status=row['status'], + reason=row['reason'], frames=len(row.get('source_image_stamps', ())))) + elif kind == 'scan_unit_complete': + task['completed_segments'].append({key: row.get(key) for key in + ('cycle', 'direction', 'segment_key', 'attempt', 'passed', 'quality_scope')}) + elif kind == 'image_observation_frame': + identity = (row.get('session_epoch'), row['view'], row['image_stamp_ns']) + previous = seen.get(identity) + if previous is not None: + if previous != row: + raise ValueError('task_audit_duplicate_image_changed') + continue + seen[identity] = row + task['image_observation_count'] += 1 + phase = task['views'].setdefault(row['view'], {}).setdefault( + row.get('sample_phase', 'unknown'), + dict(frames=0, synchronized_frames=0, tag_frames={}, pair_frames={})) + phase['frames'] += 1 + phase['synchronized_frames'] += int(row.get('command_vector') is not None + and row.get('feedback_vector') is not None) + tags = row['tags'] + for role in tags: + phase['tag_frames'][role] = phase['tag_frames'].get(role, 0)+1 + for parent, child in sorted(pairs[row['view']]): + key = f'{parent}/{child}' + phase['pair_frames'][key] = phase['pair_frames'].get(key, 0)+int( + parent in tags and child in tags) + return result + + +def pose_step_summary(records): + """Compare adjacent accepted images within one uninterrupted scan unit. + + Multiple joint observations of the same Tag image count once. Cached + and image-verified fixed poses and long gaps are excluded from the step statistic, + and all original evidence remains in the raw journal. + """ + streams = defaultdict(dict) + for row in records: + if row.get("sample_phase") != "sweep": + continue + for pose in row.get("pnp_observation_evidence", {}).values(): + if pose["pose_source"] != "current_image": + continue + key = (row["view"], pose["tag_role"], row["task_name"], row["cycle"], + row["direction"], row.get("attempt", 1)) + streams[key][row["image_stamp_ns"]] = pose + tags = {} + for (view, role, task, cycle, direction, attempt), frames in streams.items(): + tag = tags.setdefault(f"{view}:{role}", { + "view": view, "tag_role": role, "tag_id": next(iter(frames.values()))["tag_id"], + "accepted_image_count": 0, "adjacent_pair_count": 0, + "maximum_rotation_step_deg": None, "largest_steps": [], + }) + tag["accepted_image_count"] += len(frames) + ordered = sorted(frames.items()) + steps = [] + for (before, a), (after, b) in zip(ordered, ordered[1:]): + interval = (after-before)/1e9 + if not 0 < interval <= .2: + continue + angle = math.degrees(rotation_distance_rad( + a["selected_pose"]["quaternion_xyzw"], b["selected_pose"]["quaternion_xyzw"])) + steps.append({"rotation_step_deg": angle, "interval_ms": interval*1000, + "from_image": f"{view}:{before}", "to_image": f"{view}:{after}", + "task": task, "cycle": cycle, "direction": direction, "attempt": attempt}) + tag["adjacent_pair_count"] += len(steps) + tag["largest_steps"] = sorted((*tag["largest_steps"], *steps), + key=lambda item: item["rotation_step_deg"], reverse=True)[:5] + if tag["largest_steps"]: + tag["maximum_rotation_step_deg"] = tag["largest_steps"][0]["rotation_step_deg"] + return tags + + +def fixed_reference_summary(records): + """Report image consistency, not fabricated zero angular motion of a base.""" + images = {} + for row in records: + evidence = row.get("tags", {}) if row.get("kind") == "diagnostic_observation_frame" else row.get("pnp_observation_evidence", {}) + items = (evidence,) if row.get("kind") == "pnp_branch_event" else evidence.values() + for item in items: + diagnostics = item.get("candidate_diagnostics", {}) + if diagnostics.get("pose_constraint") != "fixed_reference": + continue + stamp = row["image_stamp_ns"] + if diagnostics.get("observation_stamp_ns") == stamp: + images[(row["view"], item["tag_role"], stamp)] = item + summary = {} + for (view, role, _), item in images.items(): + tag = summary.setdefault(f"{view}:{role}", {"view": view, "tag_role": role, + "tag_id": item["tag_id"], "image_count": 0, "accepted_image_count": 0, + "maximum_reprojection_error_px": None}) + tag["image_count"] += 1 + tag["accepted_image_count"] += int(item.get("selected_pose") is not None) + error = item["candidate_diagnostics"].get("fixed_reference_reprojection_error_px") + if error is not None and math.isfinite(float(error)): + previous = tag["maximum_reprojection_error_px"] + tag["maximum_reprojection_error_px"] = float(error) if previous is None else max(previous, float(error)) + return summary + + +def motion_initialization_summary(records): + """Keep per-joint hypothesis evidence without promoting a local score. + + A relation can fit in one hypothesis while the coupled chain remains + unresolved. Both the local result and that dependency are reported; the + smallest residual is never presented as a confirmed physical branch. + """ + summaries = [] + for row in records: + if row.get("kind") != "motion_branch_initialization": + continue + joints = defaultdict(list) + for hypothesis in row.get("hypotheses", ()): + relations = hypothesis.get("relations", ()) + for relation in relations: + joints[relation["joint"]].append({ + **relation, + "branches": hypothesis["branches"], + "chain_accepted": hypothesis["accepted"], + "other_relations_passed": all(not other["reason"] + for other in relations if other["joint"] != relation["joint"]), + }) + summary = { + "task_name": row["task_name"], "view": row["view"], + "status": row["status"], "reason": row["reason"], + "source_image_count": len(row.get("source_image_stamps", ())), + "joint_hypotheses": dict(joints), + "accuracy_validated": False, + } + if row.get("image_model_selection_policy") or row.get("image_solve_diagnosis"): + from ..core.geometry.tag_pose.image_solve_diagnosis import diagnose_image_solve_record + summary["image_solve_diagnosis"] = row.get("image_solve_diagnosis") or diagnose_image_solve_record(row) + summaries.append(summary) + return summaries + + +def _joint_zero_status(profile, joints, references, attempts, records): + """Every attempted zero is either actual frozen evidence or explicit raw-only.""" + if (set(references) & set(attempts) + or set(references) | set(attempts) != joints): + raise ValueError("diagnostic_capture_incomplete_units_or_joint_zeros") + recorded = {json.dumps(row, sort_keys=True, allow_nan=False) + for row in records if row.get("kind") == "diagnostic_joint_zero_attempt"} + statuses = {name: {"status": "confirmed", "raw_only": False} + for name in sorted(references)} + for name, attempt in sorted(attempts.items()): + if (name not in attempt.joint_names + or attempt.task_name != profile.motion.joint_zero_references[name].task_key + or json.dumps(attempt.as_record(), sort_keys=True, allow_nan=False) not in recorded): + raise ValueError("diagnostic_joint_zero_attempt_evidence_missing") + if any(row.get("kind") in {"joint_sample", "secondary_joint_sample", "joint_zero_reference"} + and row.get("joint", row.get("observation_joint")) == name for row in records): + raise ValueError("diagnostic_unresolved_joint_has_accepted_samples") + statuses[name] = {"status": "unresolved", "raw_only": True, + "reason": attempt.reason, "attempt": attempt.as_record()} + return statuses + + +def build_diagnostic_report(profile, plan, *, raw_path: Path, records, references, + completed_units, expected_units, protected_inputs, command, feedback, + diagnostic_zero_attempts=None): + expected = {unit.identity for unit in expected_units} + joints = {name for task in profile.motion.tasks if task.key in plan.task_keys for name in task.joints} + if set(completed_units) != expected: + raise ValueError("diagnostic_capture_incomplete_units_or_joint_zeros") + attempts = {} if diagnostic_zero_attempts is None else diagnostic_zero_attempts + zero_status = _joint_zero_status(profile, joints, references, attempts, records) + counts = {name: {} for name in sorted(joints)} + phase_counts = {name: {} for name in sorted(joints)} + raw_phase_counts = {} + for row in records: + if row.get("kind") == "joint_sample" and row.get("joint") in joints: + key = f"{row['view']}:{row['direction']}:attempt={row.get('attempt', 1)}" + counts[row["joint"]][key] = counts[row["joint"]].get(key, 0)+1 + phase = phase_counts[row["joint"]].setdefault(row.get("sample_phase", "unknown"), {}) + phase[key] = phase.get(key, 0) + 1 + elif row.get("kind") == "diagnostic_observation_frame" and row.get("task_name") in plan.task_keys: + key = f"{row['view']}:{row['direction']}:attempt={row.get('attempt', 1)}" + phase = raw_phase_counts.setdefault(row.get("sample_phase", "unknown"), {}) + phase[key] = phase.get(key, 0) + 1 + unit_quality = [dict(row) for row in records if row.get("kind") == "scan_unit_complete"] + pose_gaps = [row for row in unit_quality if row.get("accepted_pose_quality", {}).get("passed") is False] + return { + "format": "calibration_diagnostic_capture_v1", "schema_version": 1, + **plan.as_dict(), "result": "DIAGNOSTIC_COMPLETE", "publication_allowed": False, + "accuracy_validated": False, "profile_id": profile.key.profile_id, + "raw_samples_path": str(raw_path.resolve()), + "raw_samples_sha256": hashlib.sha256(raw_path.read_bytes()).hexdigest(), + "protected_inputs": dict(protected_inputs), + "completed_units": sorted(completed_units), "joint_sample_counts": counts, + "joint_sample_counts_by_phase": phase_counts, + "raw_observation_counts_by_phase": raw_phase_counts, + "joint_zero_references": {name: references[name].as_record() for name in sorted(references)}, + "joint_zero_status": zero_status, + "missing_joint_zero_references": sorted(attempts), + "motion_initialization_summary": motion_initialization_summary(records), + "task_observation_summary": task_observation_summary(profile, plan, records), + "final_command": list(command), "final_feedback": list(feedback), + "pose_step_summary": pose_step_summary(records), + "fixed_reference_summary": fixed_reference_summary(records), + "unit_quality": unit_quality, + "accepted_pose_quality_incomplete_attempts": len(pose_gaps), + "note": "仅完成原始观测诊断采集;未确认零位的关节仅保留原始角点和候选,不生成关节角样本。零位状态另见 joint_zero_status,可信姿态覆盖另见 unit_quality。未进行精度验收,未拟合或发布正式 JSON/URDF。", + } diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/direction_progress.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/direction_progress.py new file mode 100644 index 0000000..9276235 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/direction_progress.py @@ -0,0 +1,83 @@ +"""Feedback watchdog for one raw scan direction, across its bounded holds. + +No command/encoder scale is inferred. Only real signed encoder progress +refreshes the motion-time budget; a waypoint transition never refreshes it. +""" +import math + +from .motion_execution import feedback_tolerances +from .safety import SafetyDecision +from .trajectory import build_calibration_motion_command + + +class DirectionProgress: + def __init__(self, profile, unit, attempt, feedback, now): + self.profile = profile + self.identity = (*unit.identity, attempt) + task = next(t for t in profile.motion.tasks if t.key == unit.task_key) + self.start = build_calibration_motion_command(task, unit.start, + profile=profile, segment_key=unit.segment_key) + end = build_calibration_motion_command(task, unit.end, + profile=profile, segment_key=unit.segment_key) + self.thresholds = [max(2., .05*(hi-lo)) for lo, hi in + zip(profile.command.minimum_values, profile.command.maximum_values)] + self.directions = {i: math.copysign(1., b-a) for i, (a, b) in + enumerate(zip(self.start, end)) if abs(b-a) > self.thresholds[i]} + self.mark = {i: direction*feedback[i] for i, direction in self.directions.items()} + self.turning = dict(self.mark) + self.advancing = set() + self.travel = {i: 0. for i in self.directions} + self.elapsed = dict(self.travel) + self.active = set() + self.now = now + self.stamp = None + self.tolerances = feedback_tolerances(profile.command.unit) + + def observe(self, motion, segment, command, feedback, stamp, now): + dt = max(0., now-self.now) + self.now = now + for i in self.active: + self.elapsed[i] += dt + if stamp != self.stamp: + self.stamp = stamp + for i, direction in self.directions.items(): + value = direction*feedback[i] + self.turning[i] = min(self.turning[i], value) + self.travel[i] = max(self.travel[i], value-self.turning[i]) + if value >= self.mark[i]+self.tolerances.resolution: + self.mark[i] = value + self.elapsed[i] = 0. + self.advancing.add(i) + elif i not in self.advancing and value < self.mark[i]: + # Follow the initial reversal only. Once advancing, a + # rebound inside the observed range is noise, not progress. + self.mark[i] = value + self.active = {i for i in self.directions + if motion is not None and motion.phase == 'sweep' + and segment is not None and segment.phase < 1. + and abs(command[i]-self.start[i]) > self.thresholds[i] + and abs(segment.deltas[i]) > 0.} + for i, elapsed in self.elapsed.items(): + if elapsed >= self.profile.acquisition.stall_timeout_seconds: + return self._stop(i, feedback[i], elapsed) + return SafetyDecision(True) + + def retry(self, now, feedback): + """One explicitly budgeted retry; retain direction and actual travel.""" + self.now = now + self.active.clear() + for i, direction in self.directions.items(): + self.elapsed[i] = 0. + self.mark[i] = direction*feedback[i] + + def finish(self): + for i, travel in self.travel.items(): + if travel+self.tolerances.resolution < self.tolerances.minimum_travel: + return self._stop(i, None, self.elapsed[i]) + return SafetyDecision(True) + + def _stop(self, channel, feedback, elapsed): + return SafetyDecision(False, 'mechanical_stall', '扫描方向缺少真实同向反馈推进', + f'direction={self.identity},channel={channel},feedback={feedback},' + f'timeout_seconds={self.profile.acquisition.stall_timeout_seconds:g},' + f'active_no_progress_seconds={elapsed:.6f}') diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/engine.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/engine.py new file mode 100644 index 0000000..dcf0250 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/engine.py @@ -0,0 +1,352 @@ +"""Model-independent calibration schedule and lightweight acceptance policy.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Any, Mapping, Sequence + +import numpy as np + +from ..core import CalibrationProfile, TaskSpec, validate_profile +from ..core.geometry.pnp import POSE_TRACKING_POLICY_VERSION +from .diagnostic_capture import DiagnosticCapturePlan + + +from ..core.domain.profile import ACQUISITION_POLICY_VERSION +from ..core.domain.motion_path import task_segments, scan_identity +from ..core.domain.capture_plan import (CapturePlan, ADAPTIVE, STAGED, + TASKWISE_STAGED, TASKWISE_TWO_ROUND, STAGED_POLICIES, LEGACY_TRAINING, LEGACY_HOLDOUT) +TRAINING_CYCLES = LEGACY_TRAINING +HOLDOUT_CYCLE = LEGACY_HOLDOUT +CAPTURE_SCHEDULE_VERSION = "unified_schedule_v7_single_pass_endpoint_images" +SEPARATE_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v5_separate_mapping_feedback_motion" +SEGMENTED_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v7_segmented_endpoint_images" +PATH_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v8_approach_path" +VISUAL_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v9_visual_motion" +PARENT_REFERENCE_SCHEDULE_VERSION = "unified_schedule_v10_verified_parent_geometry" +IMAGE_REFERENCE_SCHEDULE_VERSION = "unified_schedule_v11_stationary_image_reference" +ADAPTIVE_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v12_adaptive_training" +STAGED_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v13_staged_training" +TASKWISE_STAGED_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v14_taskwise_staged_training" +TASKWISE_TWO_ROUND_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v16_taskwise_bounded_recovery" +LEGACY_RAW_JOINT_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v17_raw_joint" +RAW_JOINT_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v18_raw_corners_immediate" +RAW_FEEDBACK_CAPTURE_SCHEDULE_VERSION = "unified_schedule_v19_feedback_raw_corners" +SUPPORTED_CAPTURE_SCHEDULE_VERSIONS = frozenset((CAPTURE_SCHEDULE_VERSION, + STAGED_CAPTURE_SCHEDULE_VERSION, TASKWISE_STAGED_CAPTURE_SCHEDULE_VERSION, + TASKWISE_TWO_ROUND_CAPTURE_SCHEDULE_VERSION, RAW_JOINT_CAPTURE_SCHEDULE_VERSION, + RAW_FEEDBACK_CAPTURE_SCHEDULE_VERSION, + ADAPTIVE_CAPTURE_SCHEDULE_VERSION, SEPARATE_CAPTURE_SCHEDULE_VERSION, *(f"{SEGMENTED_CAPTURE_SCHEDULE_VERSION}_{mode}" + for mode in ("interleaved", "separate")), *(f"{PATH_CAPTURE_SCHEDULE_VERSION}_{mode}" + for mode in ("interleaved", "separate")), *(f"{VISUAL_CAPTURE_SCHEDULE_VERSION}_{mode}" + for mode in ("interleaved", "separate")), *(f"{PARENT_REFERENCE_SCHEDULE_VERSION}_{feedback}_{mode}" + for feedback in ("feedback", "visual") for mode in ("interleaved", "separate")), + *(f"{IMAGE_REFERENCE_SCHEDULE_VERSION}_{feedback}_{mode}" + for feedback in ("feedback", "visual") for mode in ("interleaved", "separate")))) + + +def capture_schedule_version(profile): + from ..core.domain.capture_plan import raw_joint_capture, raw_feedback_capture + if raw_feedback_capture(profile): + return RAW_FEEDBACK_CAPTURE_SCHEDULE_VERSION + if raw_joint_capture(profile): + return RAW_JOINT_CAPTURE_SCHEDULE_VERSION + if profile.quality.training_policy == TASKWISE_TWO_ROUND: + return TASKWISE_TWO_ROUND_CAPTURE_SCHEDULE_VERSION + if profile.quality.training_policy == STAGED: + return STAGED_CAPTURE_SCHEDULE_VERSION + if profile.quality.training_policy == TASKWISE_STAGED: + return TASKWISE_STAGED_CAPTURE_SCHEDULE_VERSION + if profile.quality.training_policy == ADAPTIVE: + return ADAPTIVE_CAPTURE_SCHEDULE_VERSION + if profile.acquisition.fixed_reference_mode == "stationary_image": + feedback = "visual" if profile.vision_motion else "feedback" + return f"{IMAGE_REFERENCE_SCHEDULE_VERSION}_{feedback}_{profile.acquisition.command_capture_mode}" + if any(task.parent_reference is not None for task in profile.motion.tasks): + feedback = "visual" if profile.vision_motion else "feedback" + return f"{PARENT_REFERENCE_SCHEDULE_VERSION}_{feedback}_{profile.acquisition.command_capture_mode}" + if profile.vision_motion: + return f"{VISUAL_CAPTURE_SCHEDULE_VERSION}_{profile.acquisition.command_capture_mode}" + if any(spec.evidence_scope == "path" for spec in profile.motion.joint_zero_references.values()): + return f"{PATH_CAPTURE_SCHEDULE_VERSION}_{profile.acquisition.command_capture_mode}" + if any(task.segments for task in profile.motion.tasks): + return f"{SEGMENTED_CAPTURE_SCHEDULE_VERSION}_{profile.acquisition.command_capture_mode}" + return (SEPARATE_CAPTURE_SCHEDULE_VERSION if profile.acquisition.command_capture_mode == "separate" + else CAPTURE_SCHEDULE_VERSION) + + +@dataclass(frozen=True) +class ScanUnit: + task_key: str + cycle: int + direction: str + start: float + end: float + speed: float + sample_phase: str = "sweep" + segment_key: str = "" + + @property + def identity(self): + return scan_identity(self.task_key, self.cycle, self.direction, self.segment_key) + + +@dataclass(frozen=True) +class SweepQuality: + passed: bool + failures: tuple[str, ...] + warnings: tuple[str, ...] + metrics: Mapping[str, Any] + + + + +def evaluate_observability( + feedback_progress_01: Sequence[float], + *, + minimum_span: float, + minimum_valid_samples: int, + minimum_bins: int, + maximum_unobserved_fraction: float, + total_frames: int, + joint_frame_rate: float, + feedback_hz: float, + detection_rate: float, + bin_count: int = 256, + include_endpoint_gaps: bool = False, +) -> SweepQuality: + """Evaluate the one model-independent post-sweep data gate.""" + if int(bin_count) < 32: + raise ValueError("normalized sweep bin count must be at least 32") + values = np.asarray(feedback_progress_01, dtype=float) + if values.ndim != 1: + raise ValueError("normalized sweep samples must be a vector") + valid = np.isfinite(values) & (values >= 0.0) & (values <= 1.0) + invalid_count = int(np.count_nonzero(~valid)) + # Out-of-domain data is not an observation of the nearest endpoint. + values = values[valid] + bins = sorted(set( + min(bin_count - 1, max(0, int(value * bin_count))) + for value in values + )) + span = float(np.ptp(values)) if values.size else 0.0 + internal_missing_runs = [ + right - left - 1 for left, right in zip(bins, bins[1:]) + ] + gap_scope = ( + "full_command_domain" if include_endpoint_gaps + else "observed_feedback_span" + ) + missing_runs = ( + [bins[0], bin_count - 1 - bins[-1], *internal_missing_runs] + if bins and include_endpoint_gaps + else internal_missing_runs + if bins + else [bin_count] + ) + maximum_gap = max(missing_runs, default=0) + allowed_gap = max( + 1, int(math.floor(bin_count * maximum_unobserved_fraction)) + ) + failures: list[str] = [] + if values.size < int(minimum_valid_samples): + failures.append(f"frames={values.size}") + if span < float(minimum_span): + failures.append("feedback_span") + if len(bins) < int(minimum_bins): + failures.append(f"bins={len(bins)}") + if maximum_gap > allowed_gap: + failures.append(f"maximum_gap={maximum_gap}") + warnings: list[str] = [] + if detection_rate < 0.95: + warnings.append(f"tag_rate={detection_rate:.3f}") + if joint_frame_rate < 0.85: + warnings.append(f"joint_frame_rate={joint_frame_rate:.3f}") + if feedback_hz <= 0.0: + warnings.append("feedback_rate_unavailable") + metrics = { + "policy_version": ACQUISITION_POLICY_VERSION, + "valid_frames": int(values.size), + "discarded_domain_samples": invalid_count, + "total_frames": int(total_frames), + "feedback_span": span, + "feedback_bins": len(bins), + "maximum_bin_gap": maximum_gap, + "allowed_maximum_bin_gap": allowed_gap, + "gap_scope": gap_scope, + "joint_frame_rate": float(joint_frame_rate), + "feedback_hz": float(feedback_hz), + "tag_detection_rate": float(detection_rate), + } + return SweepQuality(not failures, tuple(failures), tuple(warnings), metrics) + + +class CalibrationEngine: + """Schedule and post-direction quality policy used by the single session executor.""" + + def __init__( + self, profile: CalibrationProfile, *, + diagnostic_capture: DiagnosticCapturePlan | None = None, + ) -> None: + validate_profile(profile) + self.profile = profile + self.diagnostic_capture = diagnostic_capture + + @property + def checkpoint_token(self) -> str: + return ACQUISITION_POLICY_VERSION + + @property + def capture_schedule_version(self) -> str: + return capture_schedule_version(self.profile) + + def scan_units(self) -> tuple[ScanUnit, ...]: + units: list[ScanUnit] = [] + plan = self.diagnostic_capture + capture_plan = CapturePlan.from_profile(self.profile) + for task in self.profile.motion.tasks: + if plan is not None and task.key not in plan.task_keys: + continue + speed = self._formal_speed(task) + cycles = plan.cycles if plan is not None else capture_plan.task(task.key).motion_cycles + for cycle in cycles: + units.extend(ScanUnit(task.key, cycle, segment.direction, segment.start, + segment.end, speed, segment_key=segment.key) for segment in task_segments(task)) + if plan is None and self.profile.acquisition.command_capture_mode == "separate": + from ..core.domain.sampling import command_training_cycles, command_holdout_cycle + for cycle in (*command_training_cycles(self.profile, task), command_holdout_cycle(self.profile)): + units.extend(ScanUnit(task.key, cycle, segment.direction, segment.start, + segment.end, speed, "steady", segment.key) for segment in task_segments(task)) + if self.profile.quality.training_policy == STAGED: + units.sort(key=lambda unit: unit.cycle) # Stable: declared task/segment order within a pass. + elif self.profile.quality.training_policy == TASKWISE_STAGED: + # Keep the already collected first whole-hand pass reusable. During + # the second pass each task's optional third training visit is + # placed immediately after that task. Validation remains a final, + # isolated whole-hand pass and can never precede future training. + task_order = {task.key: index for index, task in enumerate(self.profile.motion.tasks)} + units.sort(key=lambda unit: ( + 0 if unit.cycle == 0 else 1 if unit.cycle in {1, 2} else 2, + task_order[unit.task_key], + unit.cycle, + )) + return tuple(units) + + def mapping_probe_delta(self, task: TaskSpec) -> float | None: + """Only physical-angle profiles perform a single <=3 degree jog.""" + if self.profile.command.unit != "rad": + return None + if self.profile.acquisition.mapping_probe_maximum_rad <= 0: + return None + distance = task.end_value - task.start_value + return math.copysign( + min(abs(distance), self.profile.acquisition.mapping_probe_maximum_rad), + distance, + ) + + def retry_speed(self, original_speed: float, attempt: int) -> float: + if int(attempt) != 2: + raise ValueError("unified engine permits exactly one rescan") + return float(original_speed) + + @staticmethod + def permits_retry(stage: str, completed_retries: int) -> bool: + """Only an under-sampled scan direction gets one same-speed retry.""" + from .zero_recovery import permits_recovery + return str(stage) == "sweep_acquisition" and permits_recovery((stage,), int(completed_retries)) + + def evaluate_sweep( + self, + feedback_progress_01: Sequence[float], + *, + minimum_span: float, + total_frames: int, + joint_frame_rate: float, + feedback_hz: float, + detection_rate: float, + bin_count: int = 256, + observed_command_progress_01: Sequence[float] | None = None, + ) -> SweepQuality: + """Judge fitting observability; ideal rates are diagnostics only.""" + policy = self.profile.acquisition + quality = evaluate_observability( + feedback_progress_01, + minimum_span=minimum_span, + minimum_valid_samples=policy.minimum_valid_samples, + minimum_bins=policy.minimum_bins, + maximum_unobserved_fraction=policy.maximum_unobserved_fraction, + total_frames=total_frames, + joint_frame_rate=joint_frame_rate, + feedback_hz=feedback_hz, + detection_rate=detection_rate, + bin_count=bin_count, + include_endpoint_gaps=False, + ) + if policy.require_endpoint_observations: + # Endpoints belong to the requested trajectory. An SDK whose + # command and encoder domains differ must prove those commands + # with synchronized images, without relabelling encoder values. + independent_feedback = self.profile.vision_motion or not policy.feedback_travel_matches_command + endpoint_values = (observed_command_progress_01 if independent_feedback + else feedback_progress_01) + values = np.asarray(() if endpoint_values is None else endpoint_values, dtype=float) + values = values[np.isfinite(values) & (values >= 0) & (values <= 1)] + metrics = {**quality.metrics, + "endpoint_observation_domain": "command" if independent_feedback else "feedback", + "endpoint_observed_minimum_01": float(np.min(values)) if values.size else None, + "endpoint_observed_maximum_01": float(np.max(values)) if values.size else None} + quality = SweepQuality(quality.passed, quality.failures, quality.warnings, metrics) + if not values.size or float(np.min(values)) > policy.endpoint_tolerance_01 or float(np.max(values)) < 1.0 - policy.endpoint_tolerance_01: + return SweepQuality(False, (*quality.failures, "endpoint_observation"), quality.warnings, quality.metrics) + return quality + + def capture_compatible(self, session_start: Mapping[str, Any]) -> bool: + """Known capture schedules share the unchanged measurement contract. + + Historical full-sweep/steady journals have no schedule field. They + can still be evaluated on their own, but cannot be mixed into a new + directional-waypoint session through resume. + """ + from ..core.urdf.partial_scope import profile_scope + return ( + self.diagnostic_capture is None + and session_start.get("calibration_scope") == profile_scope(self.profile) + and not session_start.get("diagnostic_capture") + and session_start.get("acquisition_policy_version") + == ACQUISITION_POLICY_VERSION + and session_start.get("capture_schedule_version") in ( + (capture_schedule_version(self.profile), LEGACY_RAW_JOINT_CAPTURE_SCHEDULE_VERSION) if self.profile.quality.training_policy == "raw_joint_2_plus_1" else + (capture_schedule_version(self.profile),) if (self.profile.quality.training_policy in {ADAPTIVE, *STAGED_POLICIES} or self.profile.acquisition.fixed_reference_mode == "stationary_image" + or self.profile.vision_motion or any(task.segments for task in self.profile.motion.tasks) + or any(task.parent_reference is not None for task in self.profile.motion.tasks) + or any(spec.evidence_scope == "path" for spec in self.profile.motion.joint_zero_references.values()) + or self.profile.acquisition.command_capture_mode == "separate") + else (None, CAPTURE_SCHEDULE_VERSION)) + and session_start.get("pose_tracking_policy_version") + == POSE_TRACKING_POLICY_VERSION + and session_start.get("profile_id") == self.profile.key.profile_id + ) + + def resume_compatible(self, session_start: Mapping[str, Any]) -> bool: + from ..profiles.preparation import preparation_contract + return (self.capture_compatible(session_start) + and session_start.get("preparation_contract") == preparation_contract(self.profile) + and session_start.get("capture_schedule_version") == capture_schedule_version(self.profile)) + + + def _formal_speed(self, task: TaskSpec) -> float: + if self.profile.command.unit == "rad": + assert task.formal_speed is not None + return float(task.formal_speed) + return float( + task.formal_speed_u8 + if task.formal_speed_u8 is not None + else self.profile.motion.speed_parameters.get("formal_u8", 1.0) + ) + + +__all__ = [ + "ACQUISITION_POLICY_VERSION", "CAPTURE_SCHEDULE_VERSION", "CalibrationEngine", + "HOLDOUT_CYCLE", "ScanUnit", "SweepQuality", "TRAINING_CYCLES", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/execution.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/execution.py new file mode 100644 index 0000000..3b80470 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/execution.py @@ -0,0 +1,519 @@ +"""Translate the single session's actions into declarative motion effects. + +No ROS dependency, hand-identity branch, alternate retry loop or serializer. +The same driver is usable with real SDK transport and a virtual clock. +""" + +from __future__ import annotations + +from dataclasses import replace +import math +from statistics import median + +from .diagnostic_capture import DiagnosticCapturePlan +from .diagnostic_reference import DiagnosticZeroAttempt +from .session import CalibrationPhase as Phase, CalibrationSession +from .motion_execution import MotionCommand +from .scan_quality import evaluate_capture_unit +from ..core.domain.motion_path import task_segment, record_scan_identity +from ..core.domain.capture_plan import raw_joint_capture, raw_feedback_capture +from .trajectory import (build_calibration_preparation_waypoints, + build_calibration_return_waypoints, build_calibration_motion_command, build_joint_reference_waypoints) + + +class SessionExecution: + def __init__(self, profile, *, diagnostic_capture: DiagnosticCapturePlan | None = None): + self.profile = profile + self.diagnostic_capture = diagnostic_capture + self.session = CalibrationSession(profile, diagnostic_capture=diagnostic_capture) + self.first_cycle_spans = {} + self.completed_units = set() + self.last_quality = None + self.last_task_quality = None + self.last_training_decision = None + self._training_checks = set() + self.last_diagnostic_quality = None + self._effects = [] + self._action_key = None + self._entered_task = None + self._entered_visit = None + self.zero_references = {} + self.sampling_plans = {} + self.diagnostic_zero_attempts: dict[str, DiagnosticZeroAttempt] = {} + + @property + def deferred_geometry(self): + return self.diagnostic_capture is not None and bool(self.diagnostic_capture.chain_joints) + + @property + def action(self): + return self.session.action() + + def motion(self, current_command): + """Return the next effect for the current phase, without advancing it.""" + action = self.action + key = (action.phase, action.scan_unit, action.retry) + if key != self._action_key: + self._effects = list(self._make_effects(current_command)) + self._action_key = key + return self._effects[0] if self._effects else None + + def _make_effects(self, current): + action = self.action + from ..core.domain.capture_plan import STAGED_POLICIES + staged = self.profile.quality.training_policy in STAGED_POLICIES + visit = None if action.scan_unit is None else (action.scan_unit.task_key, action.scan_unit.cycle) + new_visit = staged and visit != self._entered_visit + previous_visit = self._entered_visit + params = self.profile.motion.speed_parameters + baseline_speed = float(params.get("baseline_rad_s", 0.1) if self.profile.command.unit == "rad" + else params.get("baseline_u8", params.get("preflight_u8", 1))) + exits = () + if action.phase in {Phase.PREPARE, Phase.RETURN_BASELINE}: + next_task = None if action.scan_unit is None else action.scan_unit.task_key + if self._entered_task is not None and (self._entered_task != next_task or new_visit): + previous = next(t for t in self.profile.motion.tasks if t.key == self._entered_task) + pose, effects = list(current), [] + # A completed raw chain already ends at the whole-hand + # baseline. Do not curl it again merely to return to the same + # pose. Non-baseline exits still use the reviewed avoidance. + already_home = ((self.deferred_geometry or raw_joint_capture(self.profile)) and action.phase == Phase.RETURN_BASELINE + and tuple(current) == self.profile.command.baseline_values) + for waypoint in (() if already_home else previous.exit_waypoints): + for index, value in waypoint: + pose[index] = value + zero_returns = tuple(reference for reference in self.zero_references.values() + if reference.task_key == previous.key and reference.samples + and all(sample.command == tuple(pose) for sample in reference.samples)) + feedback_targets = () if self.profile.vision_motion else tuple((reference.channel, + float(median(sample.feedback[reference.channel] for sample in reference.samples))) + for reference in zero_returns) + effects.append(MotionCommand("task_exit", tuple(pose), baseline_speed, + task_key=previous.key, feedback_targets=feedback_targets, + visual_return_joints=tuple(r.joint for r in zero_returns) if self.profile.vision_motion else ())) + exits = tuple(effects) + current = tuple(pose) + self._entered_task = None + if action.phase == Phase.REFERENCE_POSES: + waypoints = self.profile.motion.resume_verification_waypoints + result = [MotionCommand("reference_pose", waypoint.command, baseline_speed, task_key=waypoint.key) + for waypoint in waypoints] + result.extend(MotionCommand("reference_return", target, baseline_speed) + for target in build_calibration_return_waypoints(profile=self.profile, current_command=waypoints[-1].command)) + return tuple(result) + if action.phase in {Phase.BASELINE, Phase.RETURN_BASELINE}: + return exits + tuple(MotionCommand("baseline" if action.phase == Phase.BASELINE else "return", target, baseline_speed) + for target in build_calibration_return_waypoints(profile=self.profile, current_command=current)) + unit = action.scan_unit + if unit is None: + return () + task = next(t for t in self.profile.motion.tasks if t.key == unit.task_key) + segment = task_segment(task, unit.segment_key) if unit.segment_key else None + common = dict(task_key=task.key, command_index=segment.command_index if segment else task.command_index, + cycle=unit.cycle, attempt=action.retry+1) + if segment: + common.update(segment_key=segment.key, observed_joints=segment.joints, + measured_channels=segment.moving_channels) + if action.phase == Phase.PREPARE: + entry = [] + if new_visit and previous_visit is not None and (previous_visit[1] != unit.cycle or unit.cycle == 2): + targets = build_calibration_return_waypoints(profile=self.profile, current_command=current) + for target in targets: + entry.append(MotionCommand("stage_return", target, baseline_speed, **common)) + current = target + entering = self._entered_task != task.key or new_visit + if entering: + pose = list(current) + for waypoint in task.entry_waypoints: + for index, value in waypoint: + pose[index] = value + entry.append(MotionCommand("clearance", tuple(pose), unit.speed, **common)) + self._entered_task = task.key + self._entered_visit = visit + current = tuple(pose) + if raw_feedback_capture(self.profile): + # Preserve each declared directed zero-approach motion and its + # stationary image window. No pose branch or zero is chosen in + # this process; the raw images are solved after capture closes. + if entering and unit.cycle == 0: + groups = {} + for name, spec in self.profile.motion.joint_zero_references.items(): + if spec.task_key == task.key: + groups.setdefault((spec.command, spec.approach_commands, + spec.evidence_scope), []).append(name) + for (target, approach, scope), names in groups.items(): + for path_index, pose in enumerate((*approach, target)): + entry.extend(MotionCommand("zero_approach", point, unit.speed, + reference_joints=tuple(sorted(names)), + reference_path_index=path_index if scope == "path" else None, + **common) for point in build_joint_reference_waypoints( + task, pose, profile=self.profile, current_command=current)) + current = pose + entry.append(MotionCommand("joint_zero", target, unit.speed, + zero_joints=tuple(sorted(names)), **common)) + current = target + elif self.profile.artifacts.output_schema_version >= 3 and not raw_joint_capture(self.profile): + pending = {name: spec for name, spec in self.profile.motion.joint_zero_references.items() + if spec.task_key == task.key and (name not in self.zero_references or staged and entering) + and not (self.diagnostic_capture is not None and name in self.diagnostic_zero_attempts)} + chain_visit_observed = (self.diagnostic_capture is not None + and bool(self.diagnostic_capture.chain_joints) + and all(name in self.diagnostic_zero_attempts for name in task.joints)) + if entering or (not chain_visit_observed and not any(name in self.zero_references for name in task.joints)): + for name in task.joints: + witness = self.profile.motion.preparation_witnesses.get(name) + if witness is None or name in self.zero_references or unit.cycle == self.profile.quality.holdout_cycle: + continue + # Reach the existing task-specific avoidance pose first. + # Excitation then changes exactly one upstream channel; + # it is not a new curve/zero or a formal scan repetition. + entry.extend(MotionCommand("clearance", point, unit.speed, **common) + for point in build_joint_reference_waypoints(task, witness.command, + profile=self.profile, current_command=current)) + current = witness.command + from ..core.fitting.motion_fit import channel_for_joint + metadata = dict(common, command_index=channel_for_joint(self.profile, witness.joint), + reference_joints=(name,), preparation_witness_joint=witness.joint) + for path_index, target in enumerate((*witness.approach_commands, witness.command)): + entry.append(MotionCommand("zero_approach", target, unit.speed, + reference_path_index=path_index, **metadata)) + current = target + if task.parent_reference is not None: + name = task.parent_reference.pose_joint + target = self.profile.motion.joint_zero_references[task.joints[0]].command + entry.extend(MotionCommand("clearance", point, unit.speed, **common) + for point in build_joint_reference_waypoints(task, target, profile=self.profile, + current_command=current)) + for joint in task.joints: + if joint in self.profile.motion.observer_preparations and joint not in self.zero_references: + entry.append(MotionCommand('observer_preflight', target, unit.speed, + reference_joints=(joint,), **common)) + entry.append(MotionCommand("joint_zero", target, unit.speed, + zero_joints=(name,), reference_only=True, reference_reuse=True, **common)) + current = target + preparations = () if staged and all(name in self.zero_references for name in task.joints) else task.model_preparations + for preparation in preparations: + metadata = dict(common, reference_only=True, + reference_command=preparation.command, + reference_approach=preparation.approach_commands) + for pose in (*preparation.approach_commands, preparation.command): + entry.extend(MotionCommand("zero_approach", point, unit.speed, + reference_joints=(preparation.joint,), **metadata) + for point in build_joint_reference_waypoints(task, pose, profile=self.profile, + current_command=current)) + current = pose + entry.append(MotionCommand("joint_zero", preparation.command, unit.speed, + zero_joints=(preparation.joint,), **metadata)) + groups = {} + for name, spec in pending.items(): + groups.setdefault((spec.command, spec.approach_commands, spec.evidence_scope, + name if task.segments else ""), []).append(name) + for (target, approach, scope, _), names in groups.items(): + checking = all(name in self.zero_references for name in names) + # Deferred fitting needs a stationary initial observation, + # not a pre-fitted zero. The directed reference is observed + # at the first training return, with no separate excursion. + if self.deferred_geometry: + approach = () + for path_index, pose in enumerate((*approach, target)): + entry.extend(MotionCommand("zero_approach", point, unit.speed, + reference_joints=tuple(sorted(names)), + reference_check=checking, + reference_path_index=path_index if scope == "path" else None, **common) + for point in build_joint_reference_waypoints(task, pose, profile=self.profile, + current_command=current)) + current = pose + entry.append(MotionCommand("joint_zero", target, unit.speed, + zero_joints=tuple(sorted(names)), reference_check=checking, **common)) + current = target + return exits + tuple(entry) + tuple(MotionCommand("prepare", target, unit.speed, **common) + for target in build_calibration_preparation_waypoints(task, profile=self.profile, + current_command=current, start_value=unit.start, segment_key=unit.segment_key)) + if action.phase == Phase.MAPPING_PROBE: + delta = self.session.engine.mapping_probe_delta(task) + start = tuple(build_calibration_motion_command(task, unit.start, profile=self.profile, segment_key=unit.segment_key)) + target = list(start) + # Probe toward this task's other endpoint. The complete two-leg + # motion is <=3 degrees from the already prepared pose. + target[task.command_index] += math.copysign(abs(delta), unit.end-unit.start) + speed = float(task.preflight_speed) + return (MotionCommand("mapping_probe", tuple(target), speed, **common), + MotionCommand("mapping_return", start, speed, **common)) + if action.phase in {Phase.SWEEP, Phase.RESCAN}: + if self.diagnostic_capture is None and self.profile.acquisition.command_capture_mode == "separate": + if unit.sample_phase == "sweep": + return (MotionCommand("sweep", tuple(build_calibration_motion_command(task, unit.end, + profile=self.profile, segment_key=unit.segment_key)), unit.speed, direction=unit.direction, **common),) + from .steady import steady_targets + plan = self.sampling_plans.get(task.key) + nodes = tuple(plan["training_nodes"]) if plan is not None else None + metadata = {} if plan is None else {"steady_training_nodes": nodes, + "sampling_plan_sha256": plan["plan_sha256"]} + # One move-and-hold effect per mapping point: arrival and the + # stable image window share the same feedback history. + return tuple(MotionCommand("steady", tuple(build_calibration_motion_command(task, value, + profile=self.profile, segment_key=unit.segment_key)), unit.speed, direction=unit.direction, steady_index=index, **common, **metadata) + for index, value in enumerate(steady_targets(self.profile, unit, training_nodes=nodes))) + if self.diagnostic_capture is not None and not self.diagnostic_capture.chain_joints: + target = tuple(build_calibration_motion_command(task, unit.end, profile=self.profile, segment_key=unit.segment_key)) + sweep = MotionCommand("sweep", target, unit.speed, direction=unit.direction, **common) + if not self.diagnostic_capture.hold_command_values: + return (sweep,) + # Compare the same declared commands after arrival from both + # endpoints. Keep the ordinary safety/trajectory driver and + # retain the complete hold for time-dependent diagnostics. + start = tuple(build_calibration_motion_command(task, unit.start, profile=self.profile, segment_key=unit.segment_key)) + values = sorted(self.diagnostic_capture.hold_command_values, + reverse=unit.direction == "decreasing") + return (sweep, MotionCommand("steady_prepare", start, unit.speed, **common), + *(MotionCommand("steady", + tuple(build_calibration_motion_command(task, value, profile=self.profile, segment_key=unit.segment_key)), + unit.speed, direction=unit.direction, steady_index=index, + minimum_hold_seconds=self.diagnostic_capture.hold_seconds, **common) + for index, value in enumerate(values))) + from .steady import steady_targets + effects = [] + # Traverse the direction once. Separate motion effects preserve + # the original sweep/steady image identities and capture gates; + # a held frame is never copied into the moving sample set. + targets = steady_targets(self.profile, unit) + for index, value in enumerate(targets): + point = tuple(build_calibration_motion_command(task, value, profile=self.profile, segment_key=unit.segment_key)) + # Both direction endpoints need their own motion-domain + # images, including a zero-distance hold before departure. + # Static mapping images remain a separate observation set. + effects.append(MotionCommand("sweep", point, unit.speed, + direction=unit.direction, defer_settling_to_hold=0 < index < len(targets)-1, **common)) + effects.append(MotionCommand("steady", point, unit.speed, + direction=unit.direction, steady_index=index, **common)) + return tuple(effects) + return () + + def motion_complete(self): + if not self._effects: + raise RuntimeError("cannot complete a motion that was not requested") + if (not raw_feedback_capture(self.profile) and not self._effects[0].reference_only + and any(name not in self.zero_references and not ( + self.diagnostic_capture is not None and name in self.diagnostic_zero_attempts) + for name in self._effects[0].zero_joints)): + raise RuntimeError("joint zero acquisition cannot complete without frozen evidence") + self._effects.pop(0) + if self._effects: + return + phase = self.session.phase + if phase == Phase.BASELINE: + self.session.baseline_complete() + elif phase == Phase.REFERENCE_POSES: + self.session.reference_poses_complete() + elif phase == Phase.RETURN_BASELINE: + self.session.return_complete() + elif phase == Phase.PREPARE: + self.session.preparation_complete() + elif phase == Phase.MAPPING_PROBE: + self.session.mapping_probe_complete() + elif phase in {Phase.SWEEP, Phase.RESCAN}: + self.session.sweep_complete() + else: + raise RuntimeError(f"unexpected completed motion:{phase.value}") + + def repeat_zero_approach(self, current): + """Replace only the current unreferenced preparation, preserving the scan.""" + motion = self._effects[0] if self._effects else None + if (self.session.phase != Phase.PREPARE or motion is None or motion.phase != "joint_zero" + or (not motion.reference_only and set(motion.zero_joints) & self.zero_references.keys())): + raise ValueError("zero_recovery_outside_unreferenced_preparation") + task = next(task for task in self.profile.motion.tasks if task.key == motion.task_key) + from ..core.domain.profile import JointZeroSpec + specs = ([JointZeroSpec(task.key, motion.reference_command, motion.reference_approach)] + if motion.reference_only else [self.profile.motion.joint_zero_references[name] for name in motion.zero_joints]) + if any(spec != specs[0] for spec in specs): + raise ValueError("zero_recovery_incompatible_group") + effects = [] + for path_index, target in enumerate((*specs[0].approach_commands, specs[0].command)): + effects.extend(replace(motion, phase="zero_approach", target=point, + zero_joints=(), reference_joints=motion.zero_joints, + reference_path_index=path_index if specs[0].evidence_scope == "path" else None) + for point in build_joint_reference_waypoints(task, target, profile=self.profile, + current_command=current)) + current = target + self._effects[:1] = [*effects, motion] + + def refresh_parent_model(self, current): + """Acquire a current image model without replacing a passed zero. + + Parent-reference reuse deliberately starts with the immutable passed + model. If only its stationary image anchor is stale, run the same + reviewed approach used by that parent's original zero acquisition and + fit a session-local model before retrying the held-pose check. + """ + motion = self._effects[0] if self._effects else None + if (self.session.phase != Phase.PREPARE or motion is None + or motion.phase != "joint_zero" or not motion.reference_reuse + or len(motion.zero_joints) != 1): + raise ValueError("parent_model_refresh_outside_reference_reuse") + name = motion.zero_joints[0] + spec = self.profile.motion.joint_zero_references[name] + source_task = next(task for task in self.profile.motion.tasks + if task.key == spec.task_key) + metadata = dict(task_key=motion.task_key, command_index=motion.command_index, + cycle=motion.cycle, attempt=motion.attempt, reference_only=True, + reference_command=spec.command, reference_approach=spec.approach_commands, + parent_model_refresh_for=motion.task_key) + effects = [] + for target in (*spec.approach_commands, spec.command): + effects.extend(MotionCommand("zero_approach", point, motion.speed, + reference_joints=(name,), **metadata) + for point in build_joint_reference_waypoints( + source_task, target, profile=self.profile, current_command=current)) + current = target + effects.append(MotionCommand("joint_zero", spec.command, motion.speed, + zero_joints=(name,), **metadata)) + self._effects[:0] = effects + + def prepend_observer_effects(self, effects): + if (self.session.phase != Phase.PREPARE or not self._effects or not effects + or any(effect.phase != 'observer_probe' or len(effect.reference_joints) != 1 + or effect.reference_joints[0] in self.zero_references for effect in effects)): + raise ValueError('observer_preparation_outside_unmeasured_task') + self._effects[:0] = effects + + def prepare_observer_recovery(self, effects, current): + motion = self._effects[0] + task = next(t for t in self.profile.motion.tasks if t.key == motion.task_key) + self.repeat_zero_approach(current) + self._effects.insert(0, replace(motion, reference_only=True, reference_reuse=True, + zero_joints=(task.parent_reference.pose_joint,))) + self.prepend_observer_effects(effects) + + def defer_current_task(self, reason): + decision = self.session.defer_current_task(reason) + self._effects.clear() + self._action_key = None + return decision + + def record_diagnostic_zero_attempt(self, attempt: DiagnosticZeroAttempt): + """A diagnostic observation closes an attempt, never creates a zero.""" + motion = self._effects[0] if self._effects else None + if (self.diagnostic_capture is None or motion is None or motion.phase != "joint_zero" + or (attempt.task_name, attempt.joint_names) != (motion.task_key, motion.zero_joints)): + raise ValueError("diagnostic_joint_zero_attempt_outside_current_motion") + if any(name in self.zero_references or name in self.diagnostic_zero_attempts + for name in attempt.joint_names): + raise ValueError("diagnostic_joint_zero_attempt_replacement_forbidden") + self.diagnostic_zero_attempts.update({name: attempt for name in attempt.joint_names}) + + def training_check_due(self): + from ..core.domain.capture_plan import ADAPTIVE, STAGED, TASKWISE_STAGED + unit = self.action.scan_unit + if (self.profile.quality.training_policy not in {ADAPTIVE, STAGED, TASKWISE_STAGED} or self.diagnostic_capture is not None + or unit is None or unit.cycle not in (1, 2) + or (unit.task_key, unit.cycle) in self._training_checks): + return False + round_units = [u for u in self.session.scheduled_units + if (self.profile.quality.training_policy == STAGED or u.task_key == unit.task_key) + and u.cycle == unit.cycle] + return unit.identity == round_units[-1].identity + + def evaluate(self, records, *, training_decision=None): + if self.session.phase != Phase.EVALUATE: + raise RuntimeError("sweep evaluation outside EVALUATE") + action = self.action + self.last_task_quality = None + self.last_training_decision = None + if raw_feedback_capture(self.profile): + from .feedback_image_coverage import evaluate_feedback_image_unit + quality = evaluate_feedback_image_unit(self.profile, action.scan_unit, action.retry+1, + records, first_cycle_spans=self.first_cycle_spans) + elif raw_joint_capture(self.profile): + from .raw_quality import evaluate_raw_unit + quality = evaluate_raw_unit(self.profile, action.scan_unit, action.retry+1, + records, first_cycle_spans=self.first_cycle_spans) + elif self.diagnostic_capture is None: + quality = evaluate_capture_unit(self.profile, action.scan_unit, action.retry+1, + records, first_cycle_spans=self.first_cycle_spans) + else: + from .diagnostic_quality import evaluate_diagnostic_unit + self.last_diagnostic_quality = evaluate_diagnostic_unit(self.profile, + action.scan_unit, action.retry+1, records) + quality = self.last_diagnostic_quality.observations + self.last_quality = quality + if quality.passed: + unit = action.scan_unit + self.completed_units.add(unit.identity) + if self.training_check_due(): + if training_decision is None: + raise ValueError("adaptive_training_requires_assessment_before_advancing") + from ..core.domain.capture_plan import CapturePlan, STAGED, evidence_digest + staged = self.profile.quality.training_policy == STAGED + if ((not staged and training_decision.get("task_name") != unit.task_key) + or training_decision.get("input_plan_sha256") != CapturePlan.from_profile(self.profile).sha256 + or (not staged and training_decision.get("assessed_cycles") != list(range(unit.cycle + 1))) + or training_decision.get("decision_sha256") != evidence_digest({k: v + for k, v in training_decision.items() if k != "decision_sha256"})): + raise ValueError("training_assessment_does_not_match_current_round") + self.last_training_decision = training_decision + self._training_checks.add((unit.task_key, unit.cycle)) + decision = training_decision["decision"] + if decision == "freeze": + if not staged: + self.session.select_training(unit.task_key, training_decision["assessed_cycles"]) + self.profile = self.session.profile + elif staged and decision == "supplement" and unit.cycle == 1: + self.session.supplement_training(training_decision["supplement_tasks"]) + self.profile = self.session.profile + elif decision == "fail": + self.session.fail("training_quality_failed", ",".join(training_decision["failures"])) + return quality + elif decision != "add_training" or unit.cycle != 1: + raise ValueError("training_assessment_cannot_add_more_rounds") + support_phase = ("steady" if self.profile.command_based_release + and self.profile.acquisition.command_capture_mode == "separate" else "sweep") + task_units = {u.identity for u in self.session.engine.scan_units() + if u.task_key == unit.task_key and u.sample_phase == support_phase} + if (not raw_joint_capture(self.profile) and not raw_feedback_capture(self.profile) + and self.diagnostic_capture is None and self.profile.artifacts.output_schema_version >= 3 + and unit.sample_phase == support_phase and task_units <= self.completed_units): + from .task_quality import evaluate_task_input_support + task = next(task for task in self.profile.motion.tasks if task.key == unit.task_key) + self.last_task_quality = evaluate_task_input_support(self.profile, task, records) + if not self.last_task_quality.passed: + self.completed_units.difference_update(task_units) + domain = "稳态指令" if self.profile.command_based_release else "反馈" + self.session.pause("task_input_support_failed", + f"独立验证的{domain}超出训练实测曲线范围,需要完整重采当前任务", + {"failures": self.last_task_quality.failures, "metrics": dict(self.last_task_quality.metrics)}, + suggestion="检查端点重复性;不能裁剪输入、外推或只重采验证轮") + return quality + self.session.evaluation_complete(quality) + return quality + + def restore(self, decision, records): + """Recheck each durable unit using the current, hash-bound policy.""" + if self.diagnostic_capture is not None: + raise ValueError("diagnostic capture cannot restore previous data") + self.first_cycle_spans.clear() + completed = set(decision.completed_units) if decision.reuse else set() + valid = [] + for unit in self.session.engine.scan_units(): + key = unit.identity + if key not in completed or next(t for t in self.profile.motion.tasks if t.key == unit.task_key).segments: + continue + attempts = [int(r.get("attempt", 1)) for r in records + if record_scan_identity(r) == key] + quality = evaluate_capture_unit(self.profile, unit, max(attempts, default=1), + records, first_cycle_spans=self.first_cycle_spans) + if quality.passed: + valid.append(key) + checked = replace(decision, completed_units=tuple(valid)) + self.session.resume_checked(checked) + self.completed_units = set(valid) + return checked + + def authorize_task_reuse(self, units): + self.session.authorize_task_reuse(units) + self.completed_units.update(units) + self._effects.clear() + self._action_key = None + + +__all__ = ["SessionExecution"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback.py new file mode 100644 index 0000000..5c910b6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback.py @@ -0,0 +1,19 @@ +"""Validate the SDK measurement-time contract before accepting any feedback.""" + +import json +import math + + +def decode_timed_feedback(text): + data = json.loads(text) + if not isinstance(data, dict) or data.get("schema") != "can_feedback_v1": + raise ValueError("feedback_timing_schema_invalid") + names, positions, stamps = (data.get(key) for key in ("name", "position", "channel_stamps_ns")) + if (not isinstance(names, list) or not isinstance(positions, list) or not isinstance(stamps, list) + or not positions or len(positions) != len(stamps) or len(names) != len(positions) + or any(not isinstance(name, str) for name in names) + or any(isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) for value in positions) + or any(type(stamp) is not int or stamp <= 0 for stamp in stamps) + or type(data.get("stamp_ns")) is not int or data["stamp_ns"] != max(stamps)): + raise ValueError("feedback_timing_payload_invalid") + return tuple(names), tuple(positions), data["stamp_ns"], tuple(stamps) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_candidates.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_candidates.py new file mode 100644 index 0000000..d35ff93 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_candidates.py @@ -0,0 +1,33 @@ +"""Offline IPPE candidates from immutable feedback-profile image partitions.""" +from dataclasses import asdict +from dataclasses import dataclass + +from ..core.domain.capture_plan import evidence_digest +from ..core.geometry.tag_pose.ippe import solve_square_tag_ippe + + +@dataclass(frozen=True) +class FeedbackImageCandidates: + input_sha256: str + partitions: dict + sha256: str + + +def solve_feedback_image_candidates(dataset): + """Keep every positive-depth candidate; never authorize a pose or zero.""" + result = {} + for key in ('references', 'motion_training', 'motion_holdout', + 'command_training', 'command_holdout'): + frames = [] + for row in getattr(dataset, key): + tags = {} + for role, tag in sorted(row['tags'].items()): + poses = solve_square_tag_ippe(tag['corners_xy'], + tag_size_m=tag['tag_size_m'], camera_matrix=row['camera_matrix']) + tags[role] = [asdict(pose) for pose in poses] + frames.append(dict(view=row['view'], image_stamp_ns=row['image_stamp_ns'], + task_name=row['task_name'], cycle=row['cycle'], sample_phase=row['sample_phase'], + candidates_by_role=tags)) + result[key] = tuple(frames) + return FeedbackImageCandidates(dataset.sha256, result, + evidence_digest({'input_sha256': dataset.sha256, 'partitions': result})) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_coverage.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_coverage.py new file mode 100644 index 0000000..533a4ad --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_coverage.py @@ -0,0 +1,113 @@ +"""Reassess feedback-hand scan coverage from raw corners alone. + +The temporary scalar rows only count synchronized visible images. They are +never joint-angle samples and must never enter fitting or release records. +""" +from __future__ import annotations + +import math + +import numpy as np + +from ..core.domain.motion_path import record_scan_identity, task_segment, segment_metadata +from ..core.fitting.motion_fit import channel_for_joint +from .scan_quality import evaluate_capture_unit, observation_streams + + +def _valid_vector(vector, count): + return (isinstance(vector, (tuple, list)) and len(vector) == count + and all(isinstance(value, (int, float)) and not isinstance(value, bool) + and math.isfinite(value) for value in vector)) + + +def _synchronized_image(profile, row): + count = profile.command.command_count + return (row.get('kind') == 'image_observation_frame' + and row.get('command_unit') == profile.command.unit + and row.get('input_is_rectified') is True + and _valid_vector(row.get('command_vector'), count) + and _valid_vector(row.get('feedback_vector'), count) + and all(isinstance(row.get(key), (int, float)) and not isinstance(row[key], bool) + and 0 <= row[key] <= 50_000_000 for key in + ('command_image_skew_ns', 'state_image_sync_error_ns'))) + + +def _visible_pair(profile, row, spec): + if row.get('view') != spec.view: + return False + tags = row.get('tags', {}) + if not isinstance(tags, dict) or not {spec.parent_role, spec.child_role} <= tags.keys(): + return False + declared = {tag.role: tag for view in profile.vision.views + if view.name == spec.view for tag in view.tags} + for role in (spec.parent_role, spec.child_role): + item = tags[role] + if not isinstance(item, dict): + return False + corners = np.asarray(item.get('corners_xy')) + if (item.get('tag_id') != declared[role].tag_id + or not math.isclose(float(item.get('tag_size_m', -1)), declared[role].size_m, abs_tol=1e-12) + or corners.shape != (4, 2)): + return False + try: + if not np.all(np.isfinite(corners.astype(float))): + return False + except (TypeError, ValueError): + return False + return True + + +def feedback_reference_coverage(profile, motion, rows): + """Count stable, synchronized zero-hold images by required joint and view.""" + task = next(task for task in profile.motion.tasks if task.key == motion.task_key) + streams = [(joint, spec) for _, joint, spec in observation_streams(profile, task) + if joint in motion.zero_joints] + counts = {} + for joint, spec in streams: + stamps = {row['image_stamp_ns'] for row in rows + if row.get('sample_phase') == 'joint_zero' + and row.get('task_name') == motion.task_key + and row.get('cycle') == motion.cycle + and _synchronized_image(profile, row) + and tuple(row['command_vector']) == tuple(motion.target) + and _visible_pair(profile, row, spec)} + counts[f'{joint}:{spec.view}'] = len(stamps) + return counts + + +def feedback_image_coverage_records(profile, unit, attempt, records): + task = next(task for task in profile.motion.tasks if task.key == unit.task_key) + segment = task_segment(task, unit.segment_key) if unit.segment_key else None + for row in records: + if (record_scan_identity(row) != unit.identity + or row.get('attempt') != attempt + or row.get('sample_phase') != unit.sample_phase + or not _synchronized_image(profile, row)): + continue + command, feedback = row['command_vector'], row['feedback_vector'] + for field, joint, spec in observation_streams(profile, task): + if segment is not None and joint not in segment.joints: + continue + if not _visible_pair(profile, row, spec): + continue + channel = channel_for_joint(profile, joint) + result = {field: joint, 'view': row['view'], 'image_stamp_ns': row['image_stamp_ns'], + 'task_name': unit.task_key, 'cycle': unit.cycle, 'direction': unit.direction, + 'attempt': attempt, 'sample_phase': unit.sample_phase, + **segment_metadata(unit.segment_key), + f'command_{profile.command.unit}': command[channel], + f'feedback_{profile.command.unit}': feedback[channel]} + if unit.sample_phase == 'steady': + index, target = row.get('steady_index'), row.get('steady_target') + if (type(index) is not int or not isinstance(target, (int, float)) + or not math.isfinite(target) or not math.isclose(command[channel], target, abs_tol=1e-9)): + continue + result.update(steady_index=index, steady_target=float(target)) + yield result + + +def evaluate_feedback_image_unit(profile, unit, attempt, records, *, first_cycle_spans): + """Apply the unchanged scan thresholds without reading selected PnP poses.""" + rows = tuple(feedback_image_coverage_records(profile, unit, attempt, records)) + return evaluate_capture_unit(profile, unit, attempt, rows, + first_cycle_spans=first_cycle_spans) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_dataset.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_dataset.py new file mode 100644 index 0000000..cfa802d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_dataset.py @@ -0,0 +1,112 @@ +"""Partition raw corner images for a future feedback-based offline image solver. + +This module never selects an IPPE pose, invents joint angles, or certifies a +calibration. The declared capture plan alone determines training and holdout. +""" +from dataclasses import dataclass +from collections.abc import Mapping +import math + +import numpy as np + +from ..core.domain.capture_plan import CapturePlan, evidence_digest +from ..core.geometry.frozen_evidence import freeze_evidence +from .image_capture import IMAGE_OBSERVATION_POLICY + + +@dataclass(frozen=True) +class FeedbackImageDataset: + references: tuple + motion_training: tuple + motion_holdout: tuple + command_training: tuple + command_holdout: tuple + sha256: str + + @property + def image_count(self): + return sum(len(part) for part in ( + self.references, self.motion_training, self.motion_holdout, + self.command_training, self.command_holdout)) + + +def _finite_vector(value, count): + return (isinstance(value, (tuple, list)) and len(value) == count + and all(isinstance(item, (int, float)) and not isinstance(item, bool) + and math.isfinite(item) for item in value)) + + +def _validate_frame(profile, row, tags): + view = row.get('view') + if view not in tags or row.get('policy') != IMAGE_OBSERVATION_POLICY: + raise ValueError('feedback_image_view_or_policy_invalid') + stamp = row.get('image_stamp_ns') + if type(stamp) is not int or stamp <= 0 or row.get('input_is_rectified') is not True: + raise ValueError('feedback_image_identity_or_projection_invalid') + matrix = np.asarray(row.get('camera_matrix'), dtype=float) + if matrix.shape != (3, 3) or not np.all(np.isfinite(matrix)) or matrix[0, 0] <= 0 or matrix[1, 1] <= 0: + raise ValueError('feedback_image_intrinsics_invalid') + if row.get('command_unit') != profile.command.unit: + raise ValueError('feedback_image_command_unit_invalid') + for field in ('command_vector', 'feedback_vector'): + value = row.get(field) + if value is not None and not _finite_vector(value, profile.command.command_count): + raise ValueError('feedback_image_vector_invalid:' + field) + observed = row.get('tags') + if not isinstance(observed, Mapping): + raise ValueError('feedback_image_tags_invalid') + for role, item in observed.items(): + tag = tags[view].get(role) + corners = np.asarray(item.get('corners_xy'), dtype=float) if isinstance(item, Mapping) else np.empty(0) + if (tag is None or item.get('tag_id') != tag.tag_id + or not math.isclose(float(item.get('tag_size_m', -1)), tag.size_m, abs_tol=1e-12) + or corners.shape != (4, 2) or not np.all(np.isfinite(corners))): + raise ValueError('feedback_image_tag_geometry_invalid') + + +def partition_feedback_images(profile, records): + """Keep raw images separate from accepted online pose or angle samples.""" + if profile.command_based_release or profile.acquisition.command_capture_mode != 'separate': + raise ValueError('feedback_image_separate_profile_required') + plan = CapturePlan.from_profile(profile).as_dict() + headers = [row for row in records if row.get('kind') == 'session_start'] + if len(headers) != 1 or headers[0].get('capture_plan') != plan: + raise ValueError('feedback_image_capture_plan_mismatch') + tags = {view.name: {tag.role: tag for tag in view.tags} for view in profile.vision.views} + partitions = {key: [] for key in ('references', 'motion_training', 'motion_holdout', + 'command_training', 'command_holdout')} + seen = set() + for row in records: + if row.get('kind') != 'image_observation_frame': + continue + _validate_frame(profile, row, tags) + identity = row['view'], row['image_stamp_ns'] + if identity in seen: + raise ValueError('feedback_image_duplicate_frame') + seen.add(identity) + task = plan['tasks'].get(row.get('task_name')) + if task is None: + raise ValueError('feedback_image_unknown_task') + phase, cycle = row.get('sample_phase'), row.get('cycle') + if phase in {'zero_approach', 'joint_zero', 'observer_probe'}: + key = 'references' + elif phase == 'sweep': + if cycle in task['training_cycles']: + key = 'motion_training' + elif cycle == task['holdout_cycle']: + key = 'motion_holdout' + else: + raise ValueError('feedback_image_motion_cycle_invalid') + elif phase == 'steady': + if cycle in task['command_training_cycles']: + key = 'command_training' + elif cycle == task['command_holdout_cycle']: + key = 'command_holdout' + else: + raise ValueError('feedback_image_command_cycle_invalid') + else: + raise ValueError('feedback_image_phase_invalid') + partitions[key].append(freeze_evidence(row)) + frozen = {key: tuple(value) for key, value in partitions.items()} + return FeedbackImageDataset(**frozen, sha256=evidence_digest( + {'capture_plan': plan, 'images': frozen})) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_fit.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_fit.py new file mode 100644 index 0000000..93a719b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_fit.py @@ -0,0 +1,193 @@ +"""Fit feedback motion curves from frozen offline image observations. + +This stage reuses the production 3+1 native rotation fit and its independent +motion holdout. Spatial/CAD zero and command mapping are separate later gates. +""" +from dataclasses import dataclass +from pathlib import Path + +from ..core.domain.capture_plan import evidence_digest, raw_feedback_capture +from ..core.fitting.motion_fit import fit_profile_motion +from ..core.urdf.kinematics import UrdfKinematicModel + + +@dataclass(frozen=True) +class FeedbackImageZeroBundle: + joint: str + by_view: dict + baseline_command: float + + def quaternion(self, view): + return self.by_view[view].quaternion(view) + + def input_reference(self, view, *, feedback=False): + return self.by_view[view].input_reference(view, feedback=feedback) + + +def bundle_feedback_image_zeros(profile, estimates): + """Require the primary and every declared secondary camera zero image.""" + expected = {name for name, spec in profile.measurement.measurements.items() + if spec.view is not None and spec.kind != 'axis_cross_view_validation'} + by_joint = {joint: {} for joint in expected} + for estimate in estimates: + if estimate.joint not in expected or estimate.view in by_joint[estimate.joint]: + raise ValueError('feedback_image_zero_duplicate_or_unknown') + by_joint[estimate.joint][estimate.view] = estimate + result = {} + for joint in sorted(expected): + required = {profile.measurement.measurements[joint].view} + secondary = profile.measurement.cross_view_sources.get(joint) + if secondary is not None: + required.add(profile.measurement.measurements[secondary].view) + if set(by_joint[joint]) != required: + raise ValueError('feedback_image_zero_view_missing:' + joint) + baselines = {item.baseline_command for item in by_joint[joint].values()} + if len(baselines) != 1: + raise ValueError('feedback_image_zero_baseline_conflict:' + joint) + result[joint] = FeedbackImageZeroBundle(joint, by_joint[joint], baselines.pop()) + return result + + +@dataclass(frozen=True) +class FeedbackMotionImageFit: + fit: object + source_images_sha256: str + sample_counts: dict + primary_records: dict + secondary_records: dict + + def report(self): + return dict(feedback_motion_fit_complete=True, + source_images_sha256=self.source_images_sha256, + sample_counts=self.sample_counts, + motion_holdout_errors_rad={name: list(values) + for name, values in self.fit.holdout_errors_rad.items()}, + spatial_zero_authorized=False, command_mapping_authorized=False, + publication_allowed=False) + + +def fit_feedback_image_motion(profile, source_urdf, observations, zero_estimates): + if not raw_feedback_capture(profile): + raise ValueError('feedback_image_fit_requires_raw_protocol') + zeros = bundle_feedback_image_zeros(profile, zero_estimates) + expected = set(zeros) + primary = {joint: [] for joint in expected} + secondary = {joint: [] for joint in profile.measurement.cross_view_sources} + source = [] + seen = set() + for group in observations: + source.append((group.image_model_sha256, group.source_images_sha256)) + for row in (*group.motion_training, *group.motion_holdout): + joint = row.get('joint') + cross = row.get('observation_joint') + if (joint is None) == (cross is None): + raise ValueError('feedback_image_fit_observation_identity_invalid') + name = joint if joint is not None else cross + identity = (name, row['view'], row['image_stamp_ns']) + if identity in seen: + raise ValueError('feedback_image_fit_duplicate_observation') + seen.add(identity) + target = primary if joint is not None else secondary + if name not in target: + raise ValueError('feedback_image_fit_unknown_joint:' + name) + target[name].append(row) + if any(not rows for rows in (*primary.values(), *secondary.values())): + raise ValueError('feedback_image_fit_missing_joint_or_view') + model = UrdfKinematicModel(Path(source_urdf)) + fitted = fit_profile_motion(profile, model, primary, + cross_view_records=secondary, zero_references=zeros) + counts = {name: {str(cycle): sum(row['cycle'] == cycle for row in rows) + for cycle in (0, 1, 2, 3)} for name, rows in primary.items()} + return FeedbackMotionImageFit(fitted, evidence_digest(sorted(source)), counts, + primary, secondary) + + +@dataclass(frozen=True) +class FeedbackCommandImageFit: + mappings: dict + holdout_metrics: dict + applicability: dict + source_images_sha256: str + + def report(self): + return dict(command_mapping_fit_complete=True, + source_images_sha256=self.source_images_sha256, + command_holdout_metrics=self.holdout_metrics, + spatial_zero_authorized=False, publication_allowed=False) + + +def fit_feedback_command_images(profile, motion_fit, observations, zero_estimates): + """Reuse the production steady-node fit and independent cycle-5 gate.""" + if not raw_feedback_capture(profile): + raise ValueError('feedback_command_fit_requires_raw_protocol') + from ..core.fitting.command_mapping import fit_command_observations + from ..core.fitting.motion_fit import channel_for_joint + zeros = bundle_feedback_image_zeros(profile, zero_estimates) + steady = {name: [] for name in motion_fit.fit.observed_curves} + source, seen = [], set() + for group in observations: + source.append((group.image_model_sha256, group.source_images_sha256)) + for row in (*group.command_training, *group.command_holdout): + if 'joint' not in row: + continue # Cross-view rows are validated with the motion curve. + name = row['joint'] + if name not in steady: + raise ValueError('feedback_command_unknown_joint:' + name) + identity = name, row['view'], row['image_stamp_ns'] + if identity in seen: + raise ValueError('feedback_command_duplicate_image') + seen.add(identity) + steady[name].append(row) + if any(not rows for rows in steady.values()): + raise ValueError('feedback_command_missing_joint_images') + mappings, metrics, applicability = fit_command_observations(profile, + motion_fit.fit.observed_curves, steady, + channels={name: channel_for_joint(profile, name) for name in steady}, + reference_inputs=motion_fit.fit.reference_inputs, + zero_references=zeros) + return FeedbackCommandImageFit(mappings, metrics, applicability, + evidence_digest(sorted(source))) + + +@dataclass(frozen=True) +class FeedbackSpatialImageFit: + fit: object + source_images_sha256: str + + def report(self): + zero = self.fit.spatial_zero + return dict(spatial_zero_fit_complete=True, + source_images_sha256=self.source_images_sha256, + direct_offsets_rad=dict(zero.direct_offsets_rad), + spatial_zero_passed=bool(zero.passed), + spatial_zero_authorized=False, publication_allowed=False) + + +def fit_feedback_spatial_images(profile, source_urdf, motion_fit, zero_estimates): + """Run the existing CAD/URDF spatial zero gate on image-only motion rows. + + This is a diagnostic fit until final-file validation is connected. + """ + if not raw_feedback_capture(profile): + raise ValueError('feedback_spatial_fit_requires_raw_protocol') + from ..core.fitting.session import fit_profile_calibration + zeros = bundle_feedback_image_zeros(profile, zero_estimates) + result = fit_profile_calibration(profile, Path(source_urdf), + motion_fit.primary_records, cross_view_records=motion_fit.secondary_records, + zero_references=zeros) + return FeedbackSpatialImageFit(result, motion_fit.source_images_sha256) + + +def prepare_feedback_image_result(profile, spatial_fit, command_fit, zero_references): + """Assemble a candidate numerical result after all existing fit gates pass.""" + from dataclasses import replace + from ..core.fitting.motion_transfer import expand_profile_transfers + expected = set(spatial_fit.fit.curves) + if set(zero_references) != expected: + raise ValueError('feedback_image_zero_reference_coverage_differs') + fitted = replace(spatial_fit.fit, + joint_zero_references=dict(zero_references), + command_mappings=command_fit.mappings, + command_holdout_metrics=command_fit.holdout_metrics, + command_applicability=command_fit.applicability) + return expand_profile_transfers(profile, fitted) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_graph.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_graph.py new file mode 100644 index 0000000..4705bd3 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_graph.py @@ -0,0 +1,204 @@ +"""Build task-sized offline image graphs from sealed feedback-hand images. + +Only motion training cycles enter model construction. A root Tag must be +observed stationary before that task's sweep, whether mounted on the fixture +or on an upstream hand link. Every moving child keeps all IPPE candidates. +This module grants neither a joint zero nor calibration publication. +""" +from __future__ import annotations + +from dataclasses import asdict, dataclass + +import numpy as np + +from ..core.domain.capture_plan import evidence_digest, raw_feedback_capture +from ..core.geometry.tag_pose.image_reference import ( + ReferenceImage, StationaryImageReference, coordinate_origin, image_reference_from_dict) +from ..core.geometry.tag_pose.ippe import solve_square_tag_ippe +from ..core.geometry.tag_pose.motion_evidence import MotionEvidenceFrame, MotionRelation, RoleCandidates +from ..core.geometry.tag_pose.motion_image_types import ImageMotionFrame, ImageRoleObservation +from ..core.geometry.tag_pose.motion_image_diagnostics import _ordered_relations +from ..core.geometry.tag_pose.production_image_motion import resolve_image_motion +from .feedback_image_coverage import _synchronized_image + + +MAXIMUM_CANDIDATE_REPROJECTION_PX = 1.5 +MAXIMUM_SOURCE_FRAMES = 120 + + +@dataclass(frozen=True) +class FeedbackTaskImageGraph: + task_name: str + view: str + relations: tuple + frames: tuple + discarded_frames: int + source_images_sha256: str + + def solve(self): + return resolve_image_motion(self.frames, self.relations) + + def report(self): + solved = self.solve() + return dict(task_name=self.task_name, view=self.view, + joints=[relation.joint for relation in self.relations], + source_frames=len(self.frames), discarded_frames=self.discarded_frames, + source_images_sha256=self.source_images_sha256, + resolved=solved.resolved, reason=solved.reason, + selected_hypothesis=solved.selected_hypothesis, + hypotheses=[asdict(item) for item in solved.hypotheses], + joint_zero_authorized=False, publication_allowed=False) + + +def _uniform_subset(rows, maximum): + if len(rows) <= maximum: + return tuple(rows) + indices = np.linspace(0, len(rows)-1, maximum, dtype=int) + return tuple(rows[int(index)] for index in indices) + + +def feedback_task_image_graph(profile, records, dataset, task_name, view): + """Build one connected graph with a proved stationary task root.""" + if not raw_feedback_capture(profile): + raise ValueError('feedback_task_graph_requires_raw_protocol') + task = next((item for item in profile.motion.tasks if item.key == task_name), None) + if task is None: + raise ValueError('feedback_task_graph_unknown_task') + specs = [(joint, profile.measurement.measurements[joint]) for joint in task.joints + if joint in profile.measurement.measurements + and profile.measurement.measurements[joint].view == view] + specs.extend((joint, profile.measurement.measurements[source]) + for joint, source in profile.measurement.cross_view_sources.items() + if joint in task.joints and profile.measurement.measurements[source].view == view) + if not specs: + raise ValueError('feedback_task_graph_view_has_no_joint') + relations = _ordered_relations(tuple(MotionRelation(joint, spec.parent_role, + spec.child_role) for joint, spec in specs)) + children = {relation.child_role for relation in relations} + roots = {relation.parent_role for relation in relations} - children + declared = {tag.role: tag for entry in profile.vision.views if entry.name == view + for tag in entry.tags} + if len(roots) != 1: + raise ValueError('feedback_task_graph_multiple_roots') + root_role = next(iter(roots)) + roles = (root_role, *(relation.child_role for relation in relations)) + rows = [row for row in dataset.motion_training + if row['task_name'] == task_name and row['view'] == view] + rows.sort(key=lambda row: row['image_stamp_ns']) + if declared[root_role].fixed_reference: + locked = [row for row in records if row.get('kind') == 'fixed_base_reference_locked'] + if len(locked) != 1: + raise ValueError('feedback_task_graph_reference_missing') + snapshot = locked[0].get('stationary_image_references', {}).get(view) + if snapshot is None: + raise ValueError('feedback_task_graph_stationary_images_missing') + reference = image_reference_from_dict(snapshot) + else: + # The upstream link may be held still for this task. Prove that from + # zero-hold images captured before any formal training sweep. + eligible = [row for row in dataset.references + if row.get('task_name') == task_name and row.get('view') == view + and row.get('cycle') == 0 and _synchronized_image(profile, row) + and root_role in row['tags'] + and (not rows or row['image_stamp_ns'] < rows[0]['image_stamp_ns'])] + approach = sorted((row for row in eligible + if row.get('sample_phase') == 'zero_approach'), + key=lambda row: row['image_stamp_ns']) + held = sorted((row for row in eligible + if row.get('sample_phase') == 'joint_zero'), + key=lambda row: row['image_stamp_ns']) + # Prefer the directed approach: it precedes the zero hold, leaving + # every held image independent for the physical zero estimate. + source = (approach if len(approach) >= 10 else held)[:10] + if len(source) < 10: + raise ValueError('feedback_task_graph_stationary_parent_images_missing') + matrix = tuple(tuple(value) for value in source[0]['camera_matrix']) + if any(not np.array_equal(row['camera_matrix'], matrix) for row in source): + raise ValueError('feedback_task_graph_reference_camera_changed') + images = tuple(ReferenceImage(row['image_stamp_ns'], + tuple(tuple(point) for point in row['tags'][root_role]['corners_xy'])) + for row in source) + reference = StationaryImageReference(root_role, declared[root_role].size_m, + matrix, images, coordinate_origin(images, declared[root_role].size_m, matrix)) + if reference.role != root_role or reference.tag_size_m != declared[root_role].size_m: + raise ValueError('feedback_task_graph_reference_binding_changed') + for row in rows: + if root_role in row['tags'] and _synchronized_image(profile, row): + reference.check_image(root_role, declared[root_role].size_m, + row['camera_matrix'], row['tags'][root_role]['corners_xy'], row['image_stamp_ns']) + # Bound the optimizer without choosing only one motion interval or cycle. + groups = {} + for row in rows: + groups.setdefault((row['cycle'], row.get('direction'), row.get('segment_key', '')), []).append(row) + per_group = max(12, MAXIMUM_SOURCE_FRAMES // max(1, len(groups))) + chosen = sorted((row for group in groups.values() + for row in _uniform_subset(group, per_group)), key=lambda row: row['image_stamp_ns']) + if len(chosen) > MAXIMUM_SOURCE_FRAMES: + chosen = list(_uniform_subset(chosen, MAXIMUM_SOURCE_FRAMES)) + frames, discarded = [], len(rows)-len(chosen) + for row in chosen: + if not _synchronized_image(profile, row) or not all(role in row['tags'] for role in roles): + discarded += 1 + continue + # A moving root changes the meaning of every fitted hinge angle. + # Reject the task instead of quietly dropping its difficult frames. + reference.check_image(root_role, declared[root_role].size_m, + row['camera_matrix'], row['tags'][root_role]['corners_xy'], row['image_stamp_ns']) + if not np.array_equal(row['camera_matrix'], reference.camera_matrix): + raise ValueError('feedback_task_graph_camera_changed') + try: + candidates = {role: tuple(candidate for candidate in solve_square_tag_ippe( + row['tags'][role]['corners_xy'], tag_size_m=declared[role].size_m, + camera_matrix=row['camera_matrix']) + if candidate.reprojection_error_px <= MAXIMUM_CANDIDATE_REPROJECTION_PX) + for role in roles if role != root_role} + except ValueError: + discarded += 1 + continue + if any(not poses for poses in candidates.values()): + discarded += 1 + continue + evidence = MotionEvidenceFrame(row['image_stamp_ns'], + (RoleCandidates(root_role, (reference.pose,), True), + *(RoleCandidates(role, candidates[role], False) for role in roles[1:]))) + observations = tuple(ImageRoleObservation(role, declared[role].size_m, + tuple(tuple(point) for point in row['tags'][role]['corners_xy'])) for role in roles) + frames.append(ImageMotionFrame(evidence, + tuple(tuple(value) for value in row['camera_matrix']), observations, (reference,))) + stamps = tuple(frame.evidence.stamp_ns for frame in frames) + if stamps != tuple(sorted(set(stamps))): + raise ValueError('feedback_task_graph_image_identity_invalid') + return FeedbackTaskImageGraph(task_name, view, relations, tuple(frames), discarded, + evidence_digest({'dataset_sha256': dataset.sha256, 'task_name': task_name, + 'view': view, 'source_stamps_ns': stamps, + 'stationary_reference_sha256': reference.identity})) + + +def image_frame_for_graph(profile, graph, row): + """Read one later image against the graph's frozen root and role contract.""" + if (row.get('task_name') != graph.task_name or row.get('view') != graph.view + or not _synchronized_image(profile, row)): + raise ValueError('feedback_graph_frame_identity_or_sync_invalid') + reference = graph.frames[0].reference_frames[0] + roles = (reference.role, *(relation.child_role for relation in graph.relations)) + declared = {tag.role: tag for entry in profile.vision.views if entry.name == graph.view + for tag in entry.tags} + tags = row.get('tags', {}) + if any(role not in tags for role in roles): + raise ValueError('feedback_graph_frame_roles_missing') + reference.check_image(reference.role, reference.tag_size_m, + row['camera_matrix'], tags[reference.role]['corners_xy'], row['image_stamp_ns']) + candidates = {role: tuple(candidate for candidate in solve_square_tag_ippe( + tags[role]['corners_xy'], tag_size_m=declared[role].size_m, + camera_matrix=row['camera_matrix']) + if candidate.reprojection_error_px <= MAXIMUM_CANDIDATE_REPROJECTION_PX) + for role in roles[1:]} + if any(not poses for poses in candidates.values()): + raise ValueError('feedback_graph_frame_candidates_missing') + return ImageMotionFrame(MotionEvidenceFrame(row['image_stamp_ns'], + (RoleCandidates(reference.role, (reference.pose,), True), + *(RoleCandidates(role, candidates[role], False) for role in roles[1:]))), + tuple(tuple(value) for value in row['camera_matrix']), + tuple(ImageRoleObservation(role, declared[role].size_m, + tuple(tuple(point) for point in tags[role]['corners_xy'])) for role in roles), + (reference,)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_motion.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_motion.py new file mode 100644 index 0000000..28c67d5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_motion.py @@ -0,0 +1,163 @@ +"""Offline reference-arc geometry for feedback-based calibration profiles. + +The image model is trained only on pre-zero approach images. A stationary +fixture tag supplies a camera-aligned coordinate convention, not a chosen IPPE +normal. The moving tag retains every valid IPPE family. No result from this +module is a joint zero, fitted curve, or publication authority. +""" +from __future__ import annotations + +from dataclasses import asdict +from dataclasses import dataclass + +import numpy as np + +from ..core.domain.capture_plan import evidence_digest +from ..core.geometry.tag_pose.ippe import solve_square_tag_ippe +from ..core.geometry.tag_pose.motion_evidence import MotionEvidenceFrame, MotionRelation, RoleCandidates +from ..core.geometry.tag_pose.motion_image_types import ImageMotionFrame, ImageRoleObservation +from ..core.geometry.tag_pose.production_image_motion import resolve_image_motion +from ..core.geometry.tag_pose.types import SquareTagPose +from ..core.geometry.tag_pose.image_reference import image_reference_from_dict +from ..core.domain.capture_plan import raw_feedback_capture +from .feedback_image_dataset import partition_feedback_images + + +MAXIMUM_REFERENCE_CORNER_DRIFT_PX = 1.5 +MAXIMUM_CANDIDATE_REPROJECTION_PX = 1.5 + + +@dataclass(frozen=True) +class FeedbackReferenceMotion: + joint: str + task_name: str + view: str + source_images_sha256: str + source_stamps_ns: tuple[int, ...] + discarded_frames: int + resolved: bool + reason: str + selected_hypothesis: int | None + hypotheses: tuple + model: object | None = None + + def report(self): + return dict(joint=self.joint, task_name=self.task_name, view=self.view, + source_images_sha256=self.source_images_sha256, + source_stamps_ns=self.source_stamps_ns, discarded_frames=self.discarded_frames, + resolved=self.resolved, reason=self.reason, + selected_hypothesis=self.selected_hypothesis, hypotheses=self.hypotheses, + joint_zero_authorized=False, publication_allowed=False) + + +def _fixed_tag(profile, view, role): + return next((tag for entry in profile.vision.views if entry.name == view + for tag in entry.tags if tag.role == role and tag.fixed_reference), None) + + +def _reference_pose(corners, tag_size, matrix): + candidates = solve_square_tag_ippe(corners, tag_size_m=tag_size, camera_matrix=matrix) + valid = [candidate for candidate in candidates + if candidate.reprojection_error_px <= MAXIMUM_CANDIDATE_REPROJECTION_PX] + if not valid: + raise ValueError('feedback_fixed_reference_projection_unresolved') + # A stationary root is a coordinate convention. Its normal is never + # inferred from the better of two nearly identical planar projections. + origin = tuple(float(value) for value in np.mean( + [candidate.translation_xyz_m for candidate in valid], axis=0)) + return SquareTagPose((0., 0., 0., 1.), origin, 0.) + + +def reference_motion_frames(profile, records, dataset, joint): + """Build one immutable first-visit arc; never include formal holdout images.""" + spec = profile.measurement.measurements[joint] + task = next(task for task in profile.motion.tasks if joint in task.joints) + view = spec.view + parent_tag = _fixed_tag(profile, view, spec.parent_role) + if parent_tag is None: + raise ValueError('feedback_reference_parent_requires_prior_offline_geometry:' + joint) + references = [row for row in records if row.get('kind') == 'fixed_base_reference_locked'] + if len(references) != 1 or view not in references[0].get('fixed_corners_by_view', {}): + raise ValueError('feedback_fixed_reference_missing:' + view) + locked = np.asarray(references[0]['fixed_corners_by_view'][view], dtype=float) + if locked.shape != (4, 2) or not np.all(np.isfinite(locked)): + raise ValueError('feedback_fixed_reference_invalid:' + view) + source = [row for row in dataset.references + if row['view'] == view and row['task_name'] == task.key + and row['sample_phase'] == 'zero_approach' and row['cycle'] == 0 + and joint in row.get('reference_joints', ())] + if not source: + raise ValueError('feedback_reference_approach_images_missing:' + joint) + attempts = {int(row.get('attempt', 1)) for row in source} + if len(attempts) != 1: + raise ValueError('feedback_reference_multiple_attempts:' + joint) + versions = {int(row.get('session_epoch', 0)) for row in source} + if len(versions) != 1 or min(versions) < 1: + raise ValueError('feedback_reference_epoch_invalid:' + joint) + source.sort(key=lambda row: row['image_stamp_ns']) + matrices = [np.asarray(row['camera_matrix'], dtype=float) for row in source] + if any(not np.array_equal(matrix, matrices[0]) for matrix in matrices[1:]): + raise ValueError('feedback_reference_camera_changed:' + view) + snapshot = references[0].get('stationary_image_references', {}).get(view) + if raw_feedback_capture(profile) and snapshot is None: + raise ValueError('feedback_stationary_reference_images_missing:' + view) + reference = image_reference_from_dict(snapshot) if snapshot is not None else None + if reference is not None: + if (reference.role != spec.parent_role or reference.tag_size_m != parent_tag.size_m + or not np.array_equal(reference.camera_matrix, matrices[0]) + or not np.allclose(reference.corners_xy, locked, + atol=MAXIMUM_REFERENCE_CORNER_DRIFT_PX, rtol=0)): + raise ValueError('feedback_stationary_reference_binding_changed:' + view) + root = reference.pose + else: + # Historical diagnostic journals only retained the median corners. + # Their root convention cannot authorize a release. + root = _reference_pose(locked, parent_tag.size_m, matrices[0]) + relation = MotionRelation(joint, spec.parent_role, spec.child_role) + frames, discarded = [], 0 + for row in source: + tags = row['tags'] + if spec.parent_role not in tags or spec.child_role not in tags: + discarded += 1 + continue + parent, child = tags[spec.parent_role], tags[spec.child_role] + drift = float(np.max(np.linalg.norm(np.asarray(parent['corners_xy'])-locked, axis=1))) + candidates = tuple(candidate for candidate in solve_square_tag_ippe( + child['corners_xy'], tag_size_m=child['tag_size_m'], camera_matrix=row['camera_matrix']) + if candidate.reprojection_error_px <= MAXIMUM_CANDIDATE_REPROJECTION_PX) + if drift > MAXIMUM_REFERENCE_CORNER_DRIFT_PX or not candidates: + discarded += 1 + continue + stamp = row['image_stamp_ns'] + roles = (RoleCandidates(spec.parent_role, (root,), True), + RoleCandidates(spec.child_role, candidates, False)) + observations = tuple(ImageRoleObservation(role, tags[role]['tag_size_m'], + tuple(map(tuple, tags[role]['corners_xy']))) + for role in (spec.parent_role, spec.child_role)) + if reference is not None: + try: + reference.check_image(spec.parent_role, parent['tag_size_m'], + row['camera_matrix'], parent['corners_xy'], stamp) + except ValueError: + discarded += 1 + continue + frames.append(ImageMotionFrame(MotionEvidenceFrame(stamp, roles), + tuple(map(tuple, row['camera_matrix'])), observations, + (reference,) if reference is not None else ())) + stamps = tuple(frame.evidence.stamp_ns for frame in frames) + if stamps != tuple(sorted(set(stamps))): + raise ValueError('feedback_reference_image_identity_invalid:' + joint) + return relation, tuple(frames), discarded + + +def solve_feedback_reference_motion(profile, records, joint, *, dataset=None): + dataset = dataset or partition_feedback_images(profile, records) + relation, frames, discarded = reference_motion_frames(profile, records, dataset, joint) + digest = evidence_digest({'dataset_sha256': dataset.sha256, 'joint': joint, + 'source_stamps_ns': [frame.evidence.stamp_ns for frame in frames]}) + result = resolve_image_motion(frames, (relation,)) + task = next(task for task in profile.motion.tasks if joint in task.joints) + return FeedbackReferenceMotion(joint, task.key, profile.measurement.measurements[joint].view, + digest, tuple(frame.evidence.stamp_ns for frame in frames), discarded, + result.resolved, result.reason, result.selected_hypothesis, + tuple(asdict(item) for item in result.hypotheses), result.model) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_observations.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_observations.py new file mode 100644 index 0000000..1b74062 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_observations.py @@ -0,0 +1,156 @@ +"""Convert frozen offline image selections into measured fitting observations. + +Every row is derived from one retained raw image and one content-bound image +model. No pose, joint angle, or acceptance flag from the online journal is +used. Missing/ambiguous images stay rejected rather than borrowing a neighbor. +""" +from __future__ import annotations + +from dataclasses import dataclass + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.domain.capture_plan import evidence_digest +from ..core.fitting.motion_fit import channel_for_joint +from ..core.geometry.extrinsics import matrix_payload, transform_matrix +from ..core.geometry.tag_pose.image_motion_model import image_model_payload +from ..core.geometry.tag_pose.production_image_motion import select_image_motion_frame +from .feedback_image_coverage import _synchronized_image +from .feedback_image_graph import image_frame_for_graph + + +@dataclass(frozen=True) +class FeedbackImageObservations: + motion_training: tuple + motion_holdout: tuple + command_training: tuple + command_holdout: tuple + rejected_images: tuple + image_model_sha256: str + source_images_sha256: str + + def all_records(self): + return (*self.motion_training, *self.motion_holdout, + *self.command_training, *self.command_holdout) + + +def _measurement_spec(profile, joint, view): + primary = profile.measurement.measurements[joint] + if primary.view == view: + return 'joint', primary + secondary = profile.measurement.cross_view_sources.get(joint) + if secondary is not None: + spec = profile.measurement.measurements[secondary] + if spec.view == view: + return 'observation_joint', spec + raise ValueError('feedback_image_observation_view_not_declared:' + joint) + + +def _row_observations(profile, graph, model, raw, extrinsics, model_sha256): + if not _synchronized_image(profile, raw): + raise ValueError('feedback_image_observation_not_synchronized') + frame = image_frame_for_graph(profile, graph, raw) + selected = select_image_motion_frame(model, frame) + if not selected.resolved: + raise ValueError('feedback_image_observation_unresolved:' + selected.reason) + poses = {item.role: item.pose for item in selected.selections} + transform = extrinsics.transform(graph.view) + unit = profile.command.unit + command, feedback = raw['command_vector'], raw['feedback_vector'] + directions = raw.get('command_direction_by_index') + if (not isinstance(directions, (list, tuple)) + or len(directions) != profile.command.command_count + or any(item not in {'', 'increasing', 'decreasing'} for item in directions)): + raise ValueError('feedback_image_observation_direction_history_invalid') + output = [] + for relation in graph.relations: + joint = relation.joint + field, spec = _measurement_spec(profile, joint, graph.view) + channel = channel_for_joint(profile, joint) + parent, child = poses[relation.parent_role], poses[relation.child_role] + parent_common = transform @ transform_matrix(parent.translation_xyz_m, parent.quaternion_xyzw) + child_common = transform @ transform_matrix(child.translation_xyz_m, child.quaternion_xyzw) + relative = np.linalg.inv(parent_common) @ child_common + row = {'kind': 'offline_image_joint_observation', field: joint, + 'profile_id': profile.key.profile_id, 'task_name': graph.task_name, + 'view': graph.view, 'image_stamp_ns': raw['image_stamp_ns'], + 'sample_id': f"{graph.view}:{raw['image_stamp_ns']}", + 'cycle': raw['cycle'], 'direction': raw['direction'], + 'attempt': raw['attempt'], 'sample_phase': raw['sample_phase'], + **({'segment_key': raw['segment_key']} if raw.get('segment_key') else {}), + 'command_direction_by_index': list(directions), 'motor_index': channel, + f'feedback_{unit}': float(feedback[channel]), + f'command_{unit}': float(command[channel]), + f'state_{unit}': list(feedback), + f'command_vector_{unit}': list(command), + 'command_image_skew_ns': raw['command_image_skew_ns'], + 'state_image_sync_error_ms': raw['state_image_sync_error_ns']/1e6, + 'relative_quaternion_xyzw': Rotation.from_matrix(relative[:3, :3]).as_quat().tolist(), + 'relative_translation_xyz_m': relative[:3, 3].tolist(), + 'parent_pose_common': matrix_payload(parent_common), + 'child_pose_common': matrix_payload(child_common), + 'view_normal_common_xyz': transform[:3, 2].tolist(), + 'camera_center_common_xyz_m': transform[:3, 3].tolist(), + 'image_relative_xy_px': (np.mean(raw['tags'][spec.child_role]['corners_xy'], axis=0) + - np.mean(raw['tags'][spec.parent_role]['corners_xy'], axis=0)).tolist(), + 'image_model_sha256': model_sha256, + 'source_image_sha256': evidence_digest(raw), + 'image_reprojection_rms_px': max(item.rms_px for item in selected.quality)} + if raw['sample_phase'] == 'steady': + row.update(steady_index=raw.get('steady_index'), + steady_target=float(command[channel])) + if raw.get('sampling_plan_sha256'): + row.update(steady_training_nodes=list(raw['steady_training_nodes']), + sampling_plan_sha256=raw['sampling_plan_sha256']) + output.append(row) + return tuple(output) + + +def reconstruct_feedback_image_observations(profile, graph, model, dataset, extrinsics): + """Reconstruct each disjoint partition with one frozen model.""" + if (not graph.frames or model.relations != graph.relations + or model.source_stamps_ns != tuple(frame.evidence.stamp_ns for frame in graph.frames) + or model.reference_frames != graph.frames[0].reference_frames + or model.camera_matrix != graph.frames[0].camera_matrix): + raise ValueError('feedback_image_observation_model_source_changed') + model_sha256 = evidence_digest(image_model_payload(model)) + parts, rejected = {}, [] + for name in ('motion_training', 'motion_holdout', 'command_training', 'command_holdout'): + accepted = [] + for raw in getattr(dataset, name): + if raw.get('task_name') != graph.task_name or raw.get('view') != graph.view: + continue + try: + accepted.extend(_row_observations(profile, graph, model, raw, + extrinsics, model_sha256)) + except ValueError as error: + rejected.append(dict(partition=name, view=graph.view, + image_stamp_ns=raw['image_stamp_ns'], reason=str(error))) + parts[name] = tuple(accepted) + return FeedbackImageObservations(**parts, rejected_images=tuple(rejected), + image_model_sha256=model_sha256, source_images_sha256=graph.source_images_sha256) + + +def reconstruct_feedback_image_zero_rows(profile, graph, model, dataset, extrinsics, zero): + """Retain the actual frozen zero-hold poses for a v3 report reference.""" + if zero.task_name != graph.task_name or zero.view != graph.view: + raise ValueError('feedback_zero_source_graph_changed') + model_sha256 = evidence_digest(image_model_payload(model)) + if model_sha256 != zero.image_model_sha256 or graph.source_images_sha256 != zero.source_images_sha256: + raise ValueError('feedback_zero_source_model_changed') + by_stamp = {row['image_stamp_ns']: row for row in dataset.references + if row.get('task_name') == graph.task_name and row.get('view') == graph.view + and row.get('sample_phase') == 'joint_zero' + and zero.joint in row.get('zero_joints', ())} + if set(zero.source_stamps_ns) - by_stamp.keys(): + raise ValueError('feedback_zero_source_images_missing') + result = [] + for stamp in zero.source_stamps_ns: + rows = _row_observations(profile, graph, model, by_stamp[stamp], extrinsics, + model_sha256) + selected = [row for row in rows if row.get('joint', row.get('observation_joint')) == zero.joint] + if len(selected) != 1: + raise ValueError('feedback_zero_source_joint_missing') + result.append(selected[0]) + return tuple(result) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_zero.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_zero.py new file mode 100644 index 0000000..96bc3ed --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_image_zero.py @@ -0,0 +1,116 @@ +"""Read zero-hold angles with frozen offline image geometry. + +This is a geometric measurement only. Spatial/CAD zero, curve fit, independent +holdout and publication still require the formal offline finalizer. +""" +from dataclasses import dataclass +import math + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.domain.capture_plan import evidence_digest +from ..core.fitting.motion_fit import channel_for_joint +from ..core.geometry.tag_pose.production_image_motion import select_image_motion_frame +from .feedback_image_graph import image_frame_for_graph + + +MAXIMUM_ZERO_ANGLE_DEVIATION_RAD = math.radians(1.) + + +@dataclass(frozen=True) +class FeedbackImageZeroAngle: + joint: str + task_name: str + view: str + angle_rad: float + relative_quaternion_xyzw: tuple + feedback_reference: float + baseline_command: float + source_stamps_ns: tuple + maximum_deviation_rad: float + image_model_sha256: str + source_images_sha256: str + + def quaternion(self, view): + if view != self.view: + raise ValueError('feedback_zero_view_not_measured:' + view) + return self.relative_quaternion_xyzw + + def input_reference(self, view, *, feedback=False): + if view != self.view or not feedback: + raise ValueError('feedback_zero_input_reference_unavailable') + return self.feedback_reference + + def report(self): + return dict(joint=self.joint, task_name=self.task_name, view=self.view, + angle_rad=self.angle_rad, + relative_quaternion_xyzw=self.relative_quaternion_xyzw, + feedback_reference=self.feedback_reference, + baseline_command=self.baseline_command, + source_stamps_ns=self.source_stamps_ns, + maximum_deviation_rad=self.maximum_deviation_rad, + image_model_sha256=self.image_model_sha256, + source_images_sha256=self.source_images_sha256, + spatial_zero_authorized=False, publication_allowed=False) + + +def measure_feedback_zero_angle(profile, graph, model, dataset, joint): + if joint not in {relation.joint for relation in graph.relations}: + raise ValueError('feedback_zero_joint_not_in_image_graph') + if (not graph.frames or model.relations != graph.relations + or model.source_stamps_ns != tuple(frame.evidence.stamp_ns for frame in graph.frames) + or model.reference_frames != graph.frames[0].reference_frames + or model.camera_matrix != graph.frames[0].camera_matrix): + raise ValueError('feedback_zero_image_model_source_changed') + from ..core.geometry.tag_pose.image_motion_model import image_model_payload + model_sha256 = evidence_digest(image_model_payload(model)) + spec = profile.motion.joint_zero_references[joint] + channel = channel_for_joint(profile, joint) + source_last = graph.frames[0].reference_frames[0].source_images[-1].stamp_ns + rows = [row for row in dataset.references + if row.get('task_name') == graph.task_name and row.get('view') == graph.view + and row.get('sample_phase') == 'joint_zero' and row.get('cycle') == 0 + and joint in row.get('zero_joints', ()) + and row['image_stamp_ns'] > source_last] + selected = [] + for row in rows: + if tuple(row.get('command_vector') or ()) != tuple(spec.command): + continue + frame = image_frame_for_graph(profile, graph, row) + measured = select_image_motion_frame(model, frame) + if not measured.resolved: + continue + angle = dict(measured.angles_rad)[joint] + relation = next(item for item in graph.relations if item.joint == joint) + poses = {item.role: item.pose for item in measured.selections} + parent = Rotation.from_quat(poses[relation.parent_role].quaternion_xyzw) + child = Rotation.from_quat(poses[relation.child_role].quaternion_xyzw) + relative = (parent.inv()*child).as_quat() + selected.append((row['image_stamp_ns'], angle, + row['feedback_vector'][channel], tuple(relative))) + minimum = profile.acquisition.fixed_reference_minimum_frames + if len(selected) < minimum: + raise ValueError(f'feedback_zero_image_angles_missing:{joint}:{len(selected)}/{minimum}') + selected.sort() + stamps = tuple(item[0] for item in selected) + if stamps != tuple(sorted(set(stamps))): + raise ValueError('feedback_zero_image_identity_invalid:' + joint) + angles = np.unwrap([item[1] for item in selected]) + median = float(np.median(angles)) + deviation = float(np.max(np.abs(angles-median))) + if deviation > MAXIMUM_ZERO_ANGLE_DEVIATION_RAD: + raise ValueError('feedback_zero_image_angle_unstable:' + joint) + rotations = Rotation.from_quat([item[3] for item in selected]) + mean = rotations.mean() + if float(np.max((mean.inv()*rotations).magnitude())) > MAXIMUM_ZERO_ANGLE_DEVIATION_RAD: + raise ValueError('feedback_zero_relative_pose_unstable:' + joint) + from .motion_execution import feedback_tolerances + feedback = [item[2] for item in selected] + if max(feedback)-min(feedback) > feedback_tolerances(profile.command.unit).stability: + raise ValueError('feedback_zero_encoder_unstable:' + joint) + return FeedbackImageZeroAngle(joint, graph.task_name, graph.view, + median, tuple(float(value) for value in mean.as_quat()), + float(np.median([item[2] for item in selected])), + float(profile.command.baseline_values[channel]), stamps, + deviation, model_sha256, graph.source_images_sha256) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_raw_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_raw_evidence.py new file mode 100644 index 0000000..b1db226 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/feedback_raw_evidence.py @@ -0,0 +1,94 @@ +"""Select complete feedback-image attempts before any offline geometry fit. + +The journal may contain a failed first attempt. It remains auditable, but no +image from it can enter training or the independent holdout partition. +""" +from collections import defaultdict +from dataclasses import dataclass + +from ..core.domain.capture_plan import CapturePlan, evidence_digest, raw_feedback_capture +from ..core.domain.motion_path import record_scan_identity +from .engine import CalibrationEngine +from .feedback_image_coverage import evaluate_feedback_image_unit +from .feedback_image_dataset import FeedbackImageDataset, partition_feedback_images + + +@dataclass(frozen=True) +class FeedbackRawEvidence: + images: FeedbackImageDataset + completed_units: tuple + missing_units: tuple + selected_attempts: tuple + sha256: str + + +def partition_feedback_raw_capture(profile, records, *, require_complete=True): + """Check the journal and independently recompute every selected scan gate.""" + if not raw_feedback_capture(profile): + raise ValueError('feedback_raw_capture_protocol_required') + records = tuple(records) + plan = CapturePlan.from_profile(profile).as_dict() + headers = [row for row in records if row.get('kind') == 'session_start'] + if len(headers) != 1 or headers[0].get('capture_plan') != plan: + raise ValueError('feedback_raw_capture_plan_mismatch') + units = {unit.identity: unit for unit in CalibrationEngine(profile).scan_units()} + groups = defaultdict(list) + completions = {} + latest = {} + reference_images = [] + for row in records: + kind = row.get('kind') + if kind in {'joint_sample', 'joint_zero_sample', 'joint_zero_reference', + 'secondary_joint_sample', 'accepted_pose_sample'}: + raise ValueError('feedback_raw_mixed_online_geometry') + if kind not in {'image_observation_frame', 'scan_unit_complete'}: + continue + if kind == 'image_observation_frame' and row.get('sample_phase') in { + 'zero_approach', 'joint_zero', 'observer_probe'}: + if row.get('task_name') not in plan['tasks'] or row.get('cycle') != 0: + raise ValueError('feedback_raw_reference_identity_invalid') + reference_images.append(row) + continue + identity = record_scan_identity(row) + if identity not in units or (kind == 'image_observation_frame' + and row.get('sample_phase') != units[identity].sample_phase): + raise ValueError('feedback_raw_unknown_unit') + attempt = row.get('attempt') + if type(attempt) is not int or attempt not in (1, 2): + raise ValueError('feedback_raw_retry_budget_changed') + if attempt < latest.get(identity, 1): + raise ValueError('feedback_raw_attempt_order_invalid') + latest[identity] = attempt + if kind == 'scan_unit_complete': + if attempt <= completions.get(identity, {}).get('attempt', 0): + raise ValueError('feedback_raw_completion_order_invalid') + completions[identity] = row + else: + groups[identity, attempt].append(row) + # Validate every image, including discarded attempts, before selecting. + partition_feedback_images(profile, (headers[0], *reference_images, + *(row for rows in groups.values() for row in rows))) + selected, accepted, missing, attempts, spans = [], [], [], [], {} + for identity, unit in units.items(): + completion = completions.get(identity) + if (completion is None or completion.get('passed') is not True + or 'interrupted_attempt' in completion.get('failures', ()) + or completion['attempt'] != latest.get(identity)): + missing.append(dict(unit=list(identity), failures=['scan_incomplete'])) + continue + attempt = completion['attempt'] + rows = groups[identity, attempt] + quality = evaluate_feedback_image_unit(profile, unit, attempt, rows, + first_cycle_spans=spans) + if not quality.passed: + missing.append(dict(unit=list(identity), failures=list(quality.failures))) + continue + accepted.append(identity) + attempts.append(dict(unit=list(identity), attempt=attempt)) + selected.extend(rows) + if missing and require_complete: + raise ValueError('feedback_raw_capture_incomplete:' + str(missing)) + dataset = partition_feedback_images(profile, (headers[0], *reference_images, *selected)) + return FeedbackRawEvidence(dataset, tuple(accepted), tuple(missing), + tuple(attempts), evidence_digest({'capture_plan': plan, + 'dataset_sha256': dataset.sha256, 'attempts': attempts})) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/image_capture.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_capture.py new file mode 100644 index 0000000..63548a6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_capture.py @@ -0,0 +1,50 @@ +"""Keep every camera's measured corners under the same motion/time identity. + +These records do not depend on a PnP branch or a task-local hinge model. +Additional views observe the existing motion; they never request a movement, +declare a joint measured, or change the primary stream's acquisition gates. +""" + +from ..core.domain.motion_path import segment_metadata + +IMAGE_OBSERVATION_POLICY = "all_view_rectified_corners_v1" + + +def image_observation_record(profile, frame, motion): + if motion is None or not (motion.recording or motion.reference_joints) or motion.phase not in { + "zero_approach", "sweep", "steady", "joint_zero", "observer_probe"}: + return None + tags = next(view.tags for view in profile.vision.views if view.name == frame.view) + return { + "kind": "image_observation_frame", "policy": IMAGE_OBSERVATION_POLICY, + "task_name": motion.task_key, "cycle": motion.cycle, + "direction": motion.direction, "attempt": motion.attempt, + **segment_metadata(motion.segment_key), + "sample_phase": motion.phase, "steady_index": motion.steady_index, + **({'steady_target': motion.target[motion.command_index]} + if motion.phase == 'steady' and motion.command_index is not None else {}), + **({'steady_training_nodes': list(motion.steady_training_nodes), + 'sampling_plan_sha256': motion.sampling_plan_sha256} + if motion.phase == 'steady' and motion.sampling_plan_sha256 else {}), + **({'zero_joints': list(motion.zero_joints)} if motion.phase == 'joint_zero' else {}), + **(dict(observer_preparation_id=motion.observer_preparation_id, + observer_joint=motion.reference_joints[0], reference_path_index=motion.reference_path_index) + if motion.phase == 'observer_probe' else {}), + **({"reference_joints": list(motion.reference_joints), + "reference_path_index": motion.reference_path_index, "is_accepted_joint_sample": False} + if motion.phase == "zero_approach" else {}), + "view": frame.view, "image_stamp_ns": frame.stamp_ns, + "command_unit": profile.command.unit, + "command_vector": None if frame.command is None else list(frame.command), + "feedback_vector": None if frame.feedback is None else list(frame.feedback), + "command_direction_by_index": list(frame.command_directions), + "state_image_sync_error_ns": None if frame.feedback is None else frame.skew_ns, + "command_image_skew_ns": frame.command_skew_ns, + "camera_matrix": frame.camera_matrix.tolist(), + "camera_matrix_source": "CameraInfo.P[:3,:3]", "input_is_rectified": True, + "tags": {tag.role: { + "tag_id": tag.tag_id, "tag_size_m": tag.size_m, + "fixed_reference": tag.fixed_reference, + "corners_xy": frame.corners[tag.role].tolist(), + } for tag in tags if tag.role in frame.corners}, + } diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/image_pairing.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_pairing.py new file mode 100644 index 0000000..340a6b4 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_pairing.py @@ -0,0 +1,27 @@ +"""Bounded exact-stamp pairing; transport arrival order is not image identity.""" + +from collections import OrderedDict + + +class ExactImagePairing: + def __init__(self, capacity=8): + self.capacity = capacity + self.images, self.detections = OrderedDict(), OrderedDict() + self.last_emitted = -1 + + def add(self, kind, stamp, message): + if stamp <= self.last_emitted: + return None + own, other = ((self.images, self.detections) if kind == "image" + else (self.detections, self.images)) + own[stamp] = message + while len(own) > self.capacity: + own.popitem(last=False) + if stamp not in other: + return None + image, detection = self.images.pop(stamp), self.detections.pop(stamp) + self.last_emitted = stamp + for buffer in (self.images, self.detections): + for old in [value for value in buffer if value <= stamp]: + del buffer[old] + return image, detection diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/image_reference.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_reference.py new file mode 100644 index 0000000..a772d96 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_reference.py @@ -0,0 +1,132 @@ +"""Own a stationary image reference independently of physical pose branches.""" + +from collections import deque +from dataclasses import asdict +from threading import RLock + +import cv2 + +from ..core.geometry.tag_pose.image_reference import ( + ImageReferenceSnapshot, ReferenceImage, StationaryImageReference, coordinate_origin, +) +from ..core.geometry.tag_pose.ippe import solve_square_tag_ippe +from ..core.geometry.tag_pose.parameters import DEFAULT_POSE_TRACKING_PARAMETERS +from ..core.geometry.frozen_evidence import freeze_evidence + + +class ImageReferenceTracker: + """One camera's immutable anchor; keeps both IPPE candidates as diagnostics.""" + + def __init__(self, minimum_frames, *, reference=None): + self.minimum_frames = max(10, int(minimum_frames)) + self._lock = RLock() + self.reset() + if reference is not None: + # Restore the immutable coordinate convention, not historical + # observations or tracker authorization. Only a fresh image can + # create a current snapshot for a resumed model. + self._bind(reference) + + def _bind(self, reference): + self.reference = reference + self._reference_payload = freeze_evidence(asdict(reference)) + self._reference_identity = reference.identity + + def reset(self): + with self._lock: + self.reference = None + self._reference_payload = None + self._reference_identity = None + self._images = deque(maxlen=self.minimum_frames) + self._last_stamp = 0 + self._snapshot = None + self._motion_snapshot = None + self._epoch = getattr(self, "_epoch", 0) + 1 + + def estimate(self, role, points, *, size, matrix, stamp_ns, locking): + points = tuple(tuple(float(value) for value in point) for point in points) + matrix = tuple(tuple(float(value) for value in row) for row in matrix) + with self._lock: + epoch = self._epoch + try: + candidates = tuple(p for p in solve_square_tag_ippe(points, + tag_size_m=size, camera_matrix=matrix) + if p.reprojection_error_px <= DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px) + except (ValueError, cv2.error): + candidates = () + with self._lock: + if epoch != self._epoch or stamp_ns <= self._last_stamp: + return None, "pose_observation_not_new" + self._last_stamp = stamp_ns + if locking and candidates and self.reference is None: + self._images.append(ReferenceImage(stamp_ns, tuple(map(tuple, points)))) + if len(self._images) >= self.minimum_frames: + try: + images = tuple(self._images) + self._bind(StationaryImageReference(role, size, tuple(map(tuple, matrix)), + images, coordinate_origin(images, size, matrix))) + except (ValueError, cv2.error): + pass # Sliding window must first prove stationarity. + pose, reason = None, "image_reference_initializing" + diagnostics = {"observation_stamp_ns": stamp_ns, + "reference_frame_is_tag_pose": False, + "branch_status": "initializing", "branch_revision": 0, + "branch_frozen": False, "motion_managed": False, + "motion_evidence_verified": False, "reprojection_candidate_count": len(candidates)} + if self.reference is not None: + ref = self.reference + diagnostics.update(reference_frame=self._reference_payload, + reference_frame_sha256=self._reference_identity, + branch_revision=1, branch_frozen=True) + try: + if not candidates: + raise ValueError("image_reference_current_projection_invalid") + diagnostics["image_reference_corner_error_px"] = ref.check_image( + role, size, matrix, points, stamp_ns) + pose, reason = ref.pose, "" + diagnostics["branch_status"] = "tracking" + except ValueError as error: + reason = str(error) + diagnostics["branch_status"] = "unavailable" + diagnostics["branch_reason"] = reason + self._snapshot = (role, stamp_ns, candidates, diagnostics) + self._motion_snapshot = None + if pose is not None: + from ..core.geometry.tag_pose.tracking import TrackerImageObservation + observation = TrackerImageObservation(stamp_ns, tuple(map(tuple, points)), + tuple(map(tuple, matrix)), size) + self._motion_snapshot = ImageReferenceSnapshot(self, role, epoch, + stamp_ns, self.reference, observation) + return pose, reason + + def observation_snapshot(self, role, stamp_ns): + with self._lock: + value = self._snapshot + if value is None or value[:2] != (role, stamp_ns): + return None + return value[2], dict(value[3]), 0 + + def motion_snapshot(self, role, stamp_ns): + with self._lock: + snapshot = self._motion_snapshot + if snapshot is None or (snapshot.role, snapshot.stamp_ns) != (role, stamp_ns): + return None + return snapshot + + def snapshot_current(self, snapshot): + with self._lock: + return (snapshot is self._motion_snapshot and snapshot.epoch == self._epoch + and snapshot.reference is self.reference and snapshot.stamp_ns == self._last_stamp) + + def tracking_current_image(self): + """Whether the latest frame still matches this tracker's own anchor.""" + with self._lock: + return (self.reference is not None and self._snapshot is not None + and self._snapshot[3].get("branch_status") == "tracking" + and self._snapshot[1] == self._last_stamp) + + def reference_confirmed(self, role, revision): + with self._lock: + snapshot = self._motion_snapshot + return (type(revision) is int and revision == 1 and snapshot is not None + and snapshot.role == role and self.snapshot_current(snapshot)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/image_replay.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_replay.py new file mode 100644 index 0000000..3010e1f --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/image_replay.py @@ -0,0 +1,59 @@ +"""Bounded offline image replay; workers never own ROS nodes or command output.""" + +from collections import deque +from concurrent.futures import ProcessPoolExecutor +from itertools import islice +import multiprocessing +import os + +from ..core.geometry.image_motion_replay import replay_image_models, validate_image_sample + + +def checkpoint_replay_workers(): + """Reserve host capacity for cameras and feedback while preparing a resume.""" + return min(4, max(1, (os.cpu_count() or 1) // 2)) + + +def _validate_image_group(group): + frame, samples = group + replayed = replay_image_models(frame) + for row in samples: + validate_image_sample(row, frame, replayed) + + +def _validate_batch(batch): + for group in batch: + _validate_image_group(group) + + +def _batches(groups, size=32): + iterator = iter(groups) + while batch := tuple(islice(iterator, size)): + yield batch + + +def validate_image_groups(groups, *, workers=1): + """Recompute every frame once and check all associated samples. + + Only checkpoint preparation requests parallelism. Spawn avoids inheriting + ROS threads; small inputs and daemon finalizers use the same serial checks. + Batches share immutable model payloads during transport. No replay result + is persisted or reused across captures. + """ + if workers <= 1 or len(groups) < 256 or multiprocessing.current_process().daemon: + for group in groups: + _validate_image_group(group) + return + executor = ProcessPoolExecutor(max_workers=workers, + mp_context=multiprocessing.get_context("spawn")) + try: + batches = _batches(groups) + pending = deque(executor.submit(_validate_batch, batch) + for batch in islice(batches, 2 * workers)) + while pending: + pending.popleft().result() # Propagate errors in capture order. + batch = next(batches, None) + if batch is not None: + pending.append(executor.submit(_validate_batch, batch)) + finally: + executor.shutdown(wait=True, cancel_futures=True) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/inputs.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/inputs.py new file mode 100644 index 0000000..0edf454 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/inputs.py @@ -0,0 +1,55 @@ +"""Transport-neutral observations and explicit coordinator I/O ports.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Callable, Mapping, Sequence + +from .adapters.base import SdkAdapter + + +@dataclass(frozen=True) +class CameraModelInput: + width: int + height: int + k: tuple[float, ...] + d: tuple[float, ...] + r: tuple[float, ...] + p: tuple[float, ...] + + +@dataclass(frozen=True) +class TagDetection: + tag_id: int + corners: tuple[tuple[float, float], ...] + hamming: int + decision_margin: float + border_quality: Mapping[str, object] | None = None + + +@dataclass(frozen=True) +class DetectionInput: + view: str + stamp_ns: int + detections: tuple[TagDetection, ...] + + +@dataclass(frozen=True) +class ServiceResult: + success: bool + message: str + + +@dataclass(frozen=True) +class RuntimePorts: + clock_ns: Callable[[], int] + monotonic: Callable[[], float] + command_publisher_count: Callable[[], int] + publish_position: Callable[[Sequence[float]], None] + publish_setting: Callable[[Mapping[str, object]], None] + + +AdapterFactory = Callable[ + [Callable[[Sequence[float]], None], Callable[[int, float], None], Callable[[], bool]], + SdkAdapter, +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/joint_resume.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/joint_resume.py new file mode 100644 index 0000000..079245c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/joint_resume.py @@ -0,0 +1,360 @@ +"""Stage checkpoint data under the explicitly selected reuse policy.""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.domain.reference import read_joint_zero_references +from ..core.domain.motion_path import record_scan_identity +from .scan_quality import evaluate_capture_unit +from .resume import ResumeVerifier, TagPoseFingerprint + + +@dataclass +class ResumeJournalImport: + """An ordered transfer that yields between bounded journal writes.""" + + rows: tuple + offset: int = field(default=0, init=False) + durability_future: object | None = field(default=None, init=False, repr=False) + durable: bool = field(default=False, init=False) + + def take_batch(self): + from .resume_storage import DeferredCaptureRecord, materialize_record + linked = (self.offset < len(self.rows) + and isinstance(self.rows[self.offset], DeferredCaptureRecord) + and self.rows[self.offset].reference is not None) + # Linked evidence can normally be copied without decompression. Scan + # samples additionally feed the live training index, which reads their + # geometry and digest. Find that boundary across the whole candidate + # batch so a cheap image row cannot hide dozens of expensive samples. + limit = 64 + if linked: + geometry_kinds = {"joint_sample", "secondary_joint_sample"} + candidate = self.rows[self.offset:self.offset + 512] + first_geometry = next((index for index, row in enumerate(candidate) + if row.get("kind") in geometry_kinds), None) + if first_geometry is None: + limit = 512 + elif first_geometry > 0: + limit = first_geometry + else: + # Training geometry is materialized once per row by the live + # index. A 512-row slice remains bounded while avoiding one + # control-loop turn for every 64 historical records. + limit = 512 + batch = tuple(row if isinstance(row, DeferredCaptureRecord) and row.reference is not None + else materialize_record(row) for row in self.rows[self.offset:self.offset + limit]) + self.offset += len(batch) + return batch + + @property + def transfer_complete(self): + return self.offset == len(self.rows) + + @property + def complete(self): + return self.durable + + +@dataclass +class TaskResumeImport(ResumeJournalImport): + task_key: str + units: tuple + + +@dataclass +class ReferenceResumeImport(ResumeJournalImport): + """A verified zero cannot authorize motion until all its evidence is durable.""" + + references: dict + motion_version: int + + +@dataclass(frozen=True) +class PreparedResume: + """Static checkpoint checks completed before live callbacks or motion. + + The default policy replays evidence and requires current physical zeros. + Passed-task mode reads persisted passes under the declared unchanged + installation assumption; imports still precede skipped motion. + """ + + header: dict + fixed_reference: dict + rows: tuple + completed_units: frozenset + joints: JointResume + passed_import: ResumeJournalImport | None = None + frozen_training: dict | None = None + + @classmethod + def load(cls, profile, engine, path, serial_number, *, image_replay_workers=1, resume_mode="verify", source_urdf=None): + from .acquisition import load_capture + from .resume_storage import load_passed_capture + from .diagnostic_capture import reject_diagnostic_capture + + if resume_mode not in {"verify", "passed"}: + raise ValueError("unknown resume mode") + rows = tuple(load_passed_capture(path) if resume_mode == "passed" else load_capture(path)) + reject_diagnostic_capture(rows) + headers = [r for r in rows if r.get("kind") == "session_start"] + references = [r for r in rows if r.get("kind") == "fixed_base_reference_locked"] + if len(headers) != 1 or len(references) != 1: + raise ValueError("missing unique checkpoint header/reference") + header = headers[0] + if header.get("serial_number") != serial_number or not engine.resume_compatible(header): + raise ValueError("checkpoint identity/policy changed") + from .training import resolve_capture_plan + from .engine import CalibrationEngine + from ..core.domain.capture_plan import STAGED, STAGED_POLICIES + profile = resolve_capture_plan(profile, rows, source_urdf=source_urdf, + verify_decisions=profile.quality.training_policy in STAGED_POLICIES and source_urdf is not None) + engine = CalibrationEngine(profile) + complete = frozenset(record_scan_identity(r) for r in rows + if r.get("kind") == "scan_unit_complete" and r.get("passed") is True) + joints = JointResume(profile, image_replay_workers=image_replay_workers) + if profile.quality.training_policy in STAGED_POLICIES: + from .staged_resume import stage_visits, stage_passed_visits, load_frozen_checkpoint, reference_import + (stage_passed_visits if resume_mode == "passed" else stage_visits)(joints, engine, rows) + frozen = (load_frozen_checkpoint(profile, rows, path, source_urdf) + if profile.quality.training_policy == STAGED else None) + # Index/hash historical provenance before live callbacks start. + # The control loop only authorizes and drains this bounded import. + pending = reference_import(joints, reuse_passed_visits=resume_mode == "passed") + return cls(header, references[0], rows, frozenset(joints.units), joints, + passed_import=pending, frozen_training=frozen) + passed_import = None + if profile.artifacts.output_schema_version >= 3: + if resume_mode == "passed": + from .passed_resume import reference_import, stage_passed_tasks + stage_passed_tasks(joints, engine, rows) + else: + joints.stage(engine, rows, complete) + joints.restrict_adaptive_prefix(engine) + if resume_mode == "passed": + passed_import = reference_import(joints) + return cls(header, references[0], rows, complete, joints, passed_import) + + +def _pose(samples, field): + poses = [getattr(sample, field) for sample in samples] + return TagPoseFingerprint(tuple(Rotation.from_quat([p.quaternion_xyzw for p in poses]).mean().as_quat()), + tuple(np.median([p.translation_xyz_m for p in poses], axis=0))) + + +def _index_motion_provenance(rows): + from .motion_provenance import source_frame_sha256 + from .resume_storage import DeferredCaptureRecord, materialize_record + + zero_images = {(r.get("view"), r.get("image_stamp_ns")) for r in rows + if r.get("kind") == "joint_zero_sample"} + handoff_images = {(r.get('view'), int(stamp)) for r in rows + if r.get('kind') == 'motion_branch_initialization' + for bridge in r.get('shared_tag_pose_bridges', ()) + for stamp in bridge.get('source_window_hashes', {})} + kinds = {"motion_branch_observation", "motion_branch_initialization", + "observer_preparation_decision", "observer_preparation_segment_complete", + "observer_preparation_excursion_started", "observer_preparation_cancelled_before_excursion", + "task_observation_state", + "capture_scope_extension", "capture_observation_revision", + "passed_tasks_reused", "passed_pose_models_restored", + "staged_pose_models_restored", "resume_verification", + "parent_reference_verified", "parent_reference_model_refreshed", + "joint_zero_recovery", + "joint_zero_motion_reference_verified", "joint_zero_sample", + "visual_motion_observation", "visual_motion_settled"} + selected = (row for row in rows + if row.get("kind") in kinds or (row.get('kind') == 'image_observation_frame' + and ((row.get('view'), row.get('image_stamp_ns')) in handoff_images + or row.get('observer_preparation_id'))) + or (row.get("kind") == "pnp_candidate_frame" + and (row.get("view"), row.get("image_stamp_ns")) in zero_images)) + result = {} + for row in selected: + deferred_identity = (row.canonical_sha256 + if isinstance(row, DeferredCaptureRecord) else None) + if deferred_identity: + result[deferred_identity] = row + else: + materialized = materialize_record(row) + result[source_frame_sha256(materialized)] = materialized + return result + + +def reference_pose_failures(previous, current): + """The same read-back check authorizes live and persisted reference reuse.""" + failures = [] + if (previous.joint != current.joint or previous.task_key != current.task_key + or previous.channel != current.channel or previous.baseline_command != current.baseline_command): + failures.append("reference_contract") + verifier = ResumeVerifier() + for view in {s.view for s in previous.samples}: + old = [s for s in previous.samples if s.view == view] + new = [s for s in current.samples if s.view == view] + if not new or {s.command for s in old} != {s.command for s in new}: + failures.append(f"held_pose:{view}") + continue + for field in ("parent_pose_common", "child_pose_common"): + verifier._compare_poses(field, {view: _pose(old, field)}, {view: _pose(new, field)}, failures) + return failures + + +class JointResume: + def __init__(self, profile, *, image_replay_workers=1): + self.profile = profile + self.image_replay_workers = image_replay_workers + self.references = {} + self.verified = set() + self.verified_visits = set() + self.units = set() + self.rows = () + self.first_cycle_spans = {} + self._motion_provenance_pending = {} + self._motion_provenance_source = None + self._motion_provenance_emitted = set() + + def restrict_adaptive_prefix(self, engine): + """A restarted task invalidates later decisions' causal training inputs. + + Reuse complete tasks up to that point. New preparation and decisions + restart the incomplete suffix, without rewriting the source journal. + """ + from ..core.domain.capture_plan import ADAPTIVE, configure_training, select_task_training + if self.profile.quality.training_policy != ADAPTIVE: + return + profile = configure_training(self.profile, ADAPTIVE) + kept, joints = set(), set() + for task in self.profile.motion.tasks: + expected = {u.identity for u in engine.scan_units() if u.task_key == task.key} + cycles = self.profile.quality.task_training_cycles.get(task.key) + if not expected <= self.units or cycles is None: + break + kept.update(expected) + joints.update(task.joints) + profile = select_task_training(profile, task.key, cycles) + self.profile = profile + self.units = kept + self.references = {name: ref for name, ref in self.references.items() if name in joints} + self.verified.intersection_update(joints) + + def stage(self, engine, rows, units): + headers = [row for row in rows if row.get("kind") == "session_start"] + if len(headers) != 1 or not engine.resume_compatible(headers[0]): + raise ValueError("joint_resume_checkpoint_policy_incompatible") + references = read_joint_zero_references(self.profile, rows) + from .motion_provenance import validate_motion_provenance + validate_motion_provenance(self.profile, rows, references=references, + image_replay_workers=self.image_replay_workers) + from ..core.fitting.command_sampling import validate_sampling_plans + validate_sampling_plans(self.profile, rows) + spans, valid = {}, set() + for unit in engine.scan_units(): + key = unit.identity + task = next(t for t in self.profile.motion.tasks if t.key == unit.task_key) + if task.segments: + continue + if key not in units or not set(task.joints) <= references.keys(): + continue + attempts = [int(r.get("attempt", 1)) for r in rows + if record_scan_identity(r) == key] + if evaluate_capture_unit(self.profile, unit, max(attempts, default=1), rows, + first_cycle_spans=spans).passed: + valid.add(key) + # Restart a segmented task with fresh references as well as fresh rows. + restarted = {name for task in self.profile.motion.tasks if task.segments for name in task.joints} + from .task_quality import evaluate_task_input_support + support_phase = ("steady" if self.profile.command_based_release + and self.profile.acquisition.command_capture_mode == "separate" else "sweep") + for task in self.profile.motion.tasks: + motion_units = {unit.identity for unit in engine.scan_units() + if unit.task_key == task.key and unit.sample_phase == support_phase} + if motion_units <= valid and not evaluate_task_input_support(self.profile, task, rows).passed: + valid = {key for key in valid if key[0] != task.key} + restarted.update(task.joints) + self.references = {name: reference for name, reference in references.items() if name not in restarted} + self.units, self.rows = valid, tuple(rows) + self.first_cycle_spans = spans + self._motion_provenance_source = _index_motion_provenance(self.rows) + self._motion_provenance_pending.clear() + self._motion_provenance_emitted.clear() + + def spans_for_task(self, task_key): + from .scan_quality import observation_streams + task = next(t for t in self.profile.motion.tasks if t.key == task_key) + keys = {f"{field}:{name}:{spec.view}:{direction}" for field, name, spec in observation_streams(self.profile, task) + for direction in ("increasing", "decreasing")} + return {key: value for key, value in self.first_cycle_spans.items() if key in keys} + + def verify(self, reference): + previous = self.references.get(reference.joint) + if previous is None: + return reference + failures = reference_pose_failures(previous, reference) + if previous.branch_references and not reference.branch_references: + failures.append("motion_evidence_missing") + if failures: + raise ValueError(f"joint_resume_reference_changed:{reference.joint}:{','.join(failures)}; 旧数据不能与新零位拼接,请重新开始") + self.verified.add(reference.joint) + if previous.branch_references: + if self._motion_provenance_source is None: + self._motion_provenance_source = _index_motion_provenance(self.rows) + zero_images = {(row.get("view"), row.get("image_stamp_ns")) + for row in self._motion_provenance_source.values() + if row.get("kind") == "joint_zero_sample" and row.get("joint") == reference.joint} + parent_images = {(row["view"], int(stamp)) for row in self._motion_provenance_source.values() + if row.get("kind") == "parent_reference_verified" for stamp in row["source_frame_hashes"]} + parent_images.update((sample["view"], sample["image_stamp_ns"]) + for row in self._motion_provenance_source.values() if row.get("kind") == "parent_reference_verified" + for sample in row["source_reference"]["samples"]) + zero_images.update(parent_images) + for identity, row in self._motion_provenance_source.items(): + if (row["kind"] in {"joint_zero_sample", "joint_zero_motion_reference_verified"} + and row.get("joint") != reference.joint + and (row.get("view"), row.get("image_stamp_ns")) not in parent_images): + continue # An interrupted resume must not import unverified joints' references. + if (row["kind"] == "pnp_candidate_frame" + and (row.get("view"), row.get("image_stamp_ns")) not in zero_images): + continue + if identity not in self._motion_provenance_emitted: + self._motion_provenance_pending[identity] = row + self._motion_provenance_pending[f"verified:{reference.joint}"] = { + "kind": "joint_zero_motion_reference_verified", "joint": reference.joint, + "current_reference": reference.as_record(), "preserved_reference": previous.as_record(), + } + return previous # Preserve the original measured zero, including its identity. + + def take_motion_provenance_records(self): + """Drain only after the caller atomically freezes all verified roles.""" + from .motion_provenance import source_frame_sha256 + rows = [] + for key, row in self._motion_provenance_pending.items(): + identity = source_frame_sha256(row) if key.startswith("verified:") else key + if identity not in self._motion_provenance_emitted: + rows.append(row) + self._motion_provenance_emitted.add(identity) + self._motion_provenance_pending.clear() + return tuple(rows) + + def take_task(self, task_key, cycle=None): + from ..core.domain.capture_plan import STAGED_POLICIES + if self.profile.quality.training_policy in STAGED_POLICIES: + from .staged_resume import visit_rows + return visit_rows(self, task_key, cycle) + task = next(t for t in self.profile.motion.tasks if t.key == task_key) + if not set(task.joints) <= self.verified: + return (), () + units = {key for key in self.units if key[0] == task_key} + rows = tuple(r for r in self.rows if (record_scan_identity(r) in units + and r.get("kind") not in {"joint_zero_reference", "joint_zero_sample"}) + or (units and r.get("kind") == "training_decision" and r.get("task_name") == task_key)) + if units: + plans = tuple(r for r in self.rows if r.get("kind") == "command_sampling_plan" + and r.get("task_name") == task_key) + rows = plans + rows + tuple(r for r in self.rows if r.get("kind") == "task_input_support_checked" + and r.get("task_name") == task_key) + self.units.difference_update(units) + return tuple(sorted(units)), rows diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/journal_durability.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/journal_durability.py new file mode 100644 index 0000000..dd6e3c9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/journal_durability.py @@ -0,0 +1,22 @@ +"""Run journal persistence barriers without blocking the control callback.""" + +from concurrent.futures import ThreadPoolExecutor + + +class JournalDurabilityWorker: + """Single ordered worker for resume-import fsync barriers. + + Resume rows are appended by the coordinator in bounded batches. The + final fsync can still take seconds on a large journal, so it runs here + while the coordinator continues feedback, safety and hold commands. + """ + + def __init__(self): + self._executor = ThreadPoolExecutor( + max_workers=1, thread_name_prefix="calibration-journal-sync") + + def submit(self, operation): + return self._executor.submit(operation) + + def close(self): + self._executor.shutdown(wait=True, cancel_futures=False) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/motion_execution.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/motion_execution.py new file mode 100644 index 0000000..b43daf8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/motion_execution.py @@ -0,0 +1,349 @@ +"""Clock-driven trajectory execution, independent of ROS and hand identity. + +The session owns business transitions. This module executes one whole segment +and supplies feedback-space motion evidence; it never retries or fits. +""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass +import math + +from .safety import MotionGoal +from .trajectory import cosine_position_trajectory_u8, cosine_ramp_velocity_trajectory + + +@dataclass(frozen=True) +class FeedbackTolerances: + resolution: float + stability: float + + @property + def minimum_travel(self): + return max(3*self.resolution, self.stability+self.resolution) + + +def feedback_tolerances(unit): + """Shared native-unit thresholds for live movement and captured travel.""" + return FeedbackTolerances(.5, 2.) if unit == "u8" else FeedbackTolerances(.001, .02) + + +@dataclass(frozen=True) +class MotionCommand: + phase: str + target: tuple[float, ...] + speed: float + task_key: str | None = None + command_index: int | None = None + cycle: int | None = None + direction: str | None = None + attempt: int = 1 + steady_index: int | None = None + zero_joints: tuple[str, ...] = () + reference_joints: tuple[str, ...] = () + minimum_hold_seconds: float = 0.0 + steady_training_nodes: tuple[float, ...] = () + sampling_plan_sha256: str = "" + segment_key: str = "" + observed_joints: tuple[str, ...] = () + measured_channels: tuple[int, ...] = () + reference_only: bool = False + reference_reuse: bool = False + reference_check: bool = False + reference_command: tuple[float, ...] = () + reference_approach: tuple[tuple[float, ...], ...] = () + reference_path_index: int | None = None + preparation_witness_joint: str = "" + feedback_targets: tuple[tuple[int, float], ...] = () + visual_return_joints: tuple[str, ...] = () + defer_settling_to_hold: bool = False + observer_preparation_id: str = '' + # A session-local model acquisition for a parent whose historical image + # anchor no longer matches the current, stable fixed-Tag image. The + # accepted joint zero and completed scan stay immutable. + parent_model_refresh_for: str = '' + + @property + def recording(self): + return self.direction is not None or bool(self.zero_joints) + + +class MotionExecution: + def __init__(self, profile, command: MotionCommand, *, initial_command, + initial_feedback, now: float, identity: str, visual_observer=None, raw_scan=False): + self.profile, self.command, self.identity = profile, command, str(identity) + from ..core.domain.capture_plan import raw_joint_capture + self.raw_scan = (raw_scan and raw_joint_capture(profile) and command.phase in {"sweep", "steady"} + and command.direction is not None and not command.feedback_targets) + self.visual = visual_observer + if profile.vision_motion and visual_observer is None: + raise ValueError("visual motion requires its independent image observer") + if not math.isfinite(command.minimum_hold_seconds) or command.minimum_hold_seconds < 0: + raise ValueError("minimum hold must be finite and nonnegative") + if command.defer_settling_to_hold and command.phase != "sweep": + raise ValueError("only a sweep followed by a steady hold can defer settling") + self.start = tuple(float(v) for v in initial_command) + self.start_feedback = tuple(float(v) for v in initial_feedback) + self.started_at = float(now) + self.last_feedback_stamp = None + self.history = deque(maxlen=10) + self.stamped_history = deque(maxlen=200) + self.finished_at = None + self.phase = 0.0 + self.duration = 0.0 + self.fraction = 0.0 + layout = profile.command + for vector in (self.start, command.target): + if len(vector) != layout.command_count or any(not math.isfinite(v) or not lo <= v <= hi + for v, lo, hi in zip(vector, layout.minimum_values, layout.maximum_values)): + raise ValueError("motion command outside declared command domain") + if not profile.vision_motion and len(self.start_feedback) != layout.command_count: + raise ValueError("motion starts without complete feedback") + tolerances = feedback_tolerances(layout.unit) + self.resolution, self.stability = tolerances.resolution, tolerances.stability + # u8 endpoint feedback jitters within the measured stable band. Do not + # require sub-count agreement after meaningful signed travel. + self.goal_tolerance = self.stability if layout.unit == "u8" else self.resolution + probe = command.phase in {"mapping_probe", "mapping_return"} + # A mapping jog proves direction and basic electrical movement, not + # servo accuracy. A profile may declare a measured u8 command dead + # band; corrections inside it are not a reliable motion witness. + # Larger movements still require proportional encoder travel. + self.minimum_request = (profile.acquisition.minimum_significant_request_u8 + if layout.unit == "u8" else self.resolution if probe + else max(profile.acquisition.mapping_probe_maximum_rad, math.radians(3))) + self.required_fraction = 0.10 if probe else 0.80 + self.feedback_travel_matches_command = profile.acquisition.feedback_travel_matches_command + self.deltas = tuple(end-start for start, end in zip(self.start, command.target)) + # Without a measured command/encoder mapping, substantial requests + # still need an electrical movement witness. Small endpoint corrections + # can remain inside a dead zone; do not fabricate proportional travel. + self.minimum_requests = tuple(self.minimum_request if self.feedback_travel_matches_command + else max(self.minimum_request, .05*(hi-lo)) + for lo, hi in zip(layout.minimum_values, layout.maximum_values)) + self.minimum_feedback_travel = tolerances.minimum_travel + self.moving = tuple(i for i, delta in enumerate(self.deltas) + if abs(delta) > self.minimum_requests[i] and i not in layout.disabled_indices) + self.required_feedback_travel = tuple(self.required_fraction*abs(delta) + if self.feedback_travel_matches_command else self.minimum_feedback_travel for delta in self.deltas) + self._travel_origins = list(self.start_feedback) + # A return to a measured zero has an encoder reference, even when the + # last sent command already equals zero. Never infer that return from + # command equality or from a small amount of unrelated motion. + self.reference_targets = dict(command.feedback_targets) + if (len(self.reference_targets) != len(command.feedback_targets) + or any(not 0 <= i < layout.command_count or not math.isfinite(value) + or not layout.minimum_feedback_values[i] <= value <= layout.maximum_feedback_values[i] + for i, value in self.reference_targets.items())): + raise ValueError("invalid measured feedback target") + self.reference_tolerance = 2*self.stability + + def suspend_elapsed(self, seconds): + """Exclude a retry delay from motion and settling clocks.""" + self.started_at += seconds + if self.finished_at is not None: + self.finished_at += seconds + self.history.clear() + self.stamped_history.clear() + + def sample(self, now: float) -> tuple[float, ...]: + distance = max((abs(v) for v in self.deltas), default=0.0) + elapsed = max(0.0, float(now)-self.started_at) + params = self.profile.motion.speed_parameters + if self.profile.command.unit == "u8": + duration_key = ("scan_trajectory_full_range_seconds" + if self.command.phase in {"sweep", "steady"} else "command_trajectory_full_range_seconds") + full_range_duration = float(params.get(duration_key, + params.get("command_trajectory_full_range_seconds", 6.0))) + if len(self.command.measured_channels) > 1: + # O30's reviewed range-calibration group motion pairs SDK + # speed 200 with a 20 u8/s command path. Preserve that rate + # for coupled calibration segments: a faster continuous ramp + # can let the middle finger's feedback lag behind the intended + # 80-unit clearance while the ring finger is already loaded. + coupled_rate = float(self.command.speed)/10.0 + if coupled_rate <= 0.0: + raise ValueError("coupled u8 motion speed must be positive") + full_range_duration = max(full_range_duration, + math.pi*255.0/(2.0*coupled_rate)) + travelled, phase, duration = cosine_position_trajectory_u8(0, distance, + elapsed, full_range_duration) + else: + speed = self.command.speed + caps = self.profile.command.maximum_velocity + if caps and distance > 0: + speed = min([speed] + [caps[i]*distance/abs(delta) + for i, delta in enumerate(self.deltas) if delta != 0]) + travelled, phase, duration = cosine_ramp_velocity_trajectory(0, distance, + elapsed, speed, float(params.get("trajectory_ramp_seconds", 0.4))) + self.phase, self.duration = phase, duration + fraction = 1.0 if distance == 0 else travelled/distance + self.fraction = fraction + values = tuple(start+delta*fraction for start, delta in zip(self.start, self.deltas)) + return tuple(float(round(v)) for v in values) if self.profile.command.unit == "u8" else values + + def observe(self, feedback, *, stamp, now): + if self.visual is not None: + if self.phase >= 1.0 and self.finished_at is None: + self.finished_at = float(now) + return + # A fast timer is not ten independent feedback samples. + if stamp == self.last_feedback_stamp: + return + self.last_feedback_stamp = stamp + if not self.feedback_travel_matches_command: + # At a reversal, a delayed encoder can first finish reporting the + # preceding movement. Count subsequent travel in the requested + # direction from that observed turning point, not an invented + # endpoint beyond the segment's initial feedback. An opposite-only + # excursion is not movement evidence, and cannot restart the + # watchdog: the segment identity and requested direction stay fixed. + for i in self.moving: + if i not in self.reference_targets: + direction = math.copysign(1., self.deltas[i]) + if direction*(feedback[i]-self._travel_origins[i]) < 0: + self._travel_origins[i] = float(feedback[i]) + self.history.append(tuple(feedback)) + self.stamped_history.append((float(now), tuple(feedback))) + if self.phase >= 1.0 and self.finished_at is None: + self.finished_at = float(now) + + def _required_travel(self, index): + required = self.required_feedback_travel[index] + if self.profile.command.unit == "u8" and self.feedback_travel_matches_command: + # G20's endpoint encoder can start several counts inside the + # requested command. Reaching the target command after real signed + # travel is sufficient; demanding another 80% of the command delta + # would call a physically reached endpoint a mechanical stall. + direction = math.copysign(1., self.deltas[index]) + to_command = direction*(self.command.target[index]-self._travel_origins[index]) + if self.minimum_feedback_travel <= to_command < required: + return to_command + return required + + @property + def goals(self): + goals = {} if self.profile.vision_motion or self.raw_scan else { + i: MotionGoal(i, self._travel_origins[i], self._travel_origins[i] + + math.copysign(self._required_travel(i), self.deltas[i]), + self.goal_tolerance, self.resolution) + for i in self.moving} + # Measured zero/return targets remain absolute. Travel, including a + # reversal, never substitutes for reaching the measured reference. + goals.update({i: MotionGoal(i, self.start_feedback[i], value, + self.reference_tolerance, self.resolution) for i, value in self.reference_targets.items()}) + if self.feedback_travel_matches_command: + return tuple(goals.values()) + # Coupled trajectories reach meaningful demand at different times. + # A fast channel cannot start a slow channel's no-motion clock. + return tuple(goal for goal in goals.values() + if abs(self.deltas[goal.channel])*self.fraction > self.minimum_requests[goal.channel] + or (goal.channel in self.reference_targets + and abs(self.deltas[goal.channel]) <= self.minimum_requests[goal.channel])) + + @property + def motion_expected(self): + # A cosine ramp initially requests less than encoder resolution. Start + # the watchdog only after meaningful demand, then keep the segment ID. + return bool(self.goals and self.phase > 0 and (self.reference_targets or + any(abs(self.deltas[i])*self.fraction > self.minimum_requests[i] for i in self.moving))) + + def feedback_motion_complete(self): + """Physical completion is shared by capture and transition decisions.""" + if self.raw_scan: + # Raw waypoints are sample locations, not calibrated encoder goals. + # The coordinator checks physical progress over the whole direction. + return True + if self.visual is not None: + return self.visual.motion_complete() + if not self.history: + return False + latest = self.history[-1] + if any(abs(latest[i]-target) > self.reference_tolerance + for i, target in self.reference_targets.items()): + return False + return all(i in self.reference_targets or + math.copysign(1, self.deltas[i])*(latest[i]-self._travel_origins[i])+self.goal_tolerance + >= self._required_travel(i) for i in self.moving) + + def arrived(self, now): + if self.visual is not None: + if self.phase < 1 or self.finished_at is None or not self.visual.motion_complete(): + return False + if self.command.phase in {"steady", "joint_zero"}: + return now-self.finished_at >= max(self.profile.acquisition.steady_timeout_seconds, + self.command.minimum_hold_seconds) + if self.command.defer_settling_to_hold: + return True + hold = float(self.profile.motion.speed_parameters.get("endpoint_hold_seconds", .25)) + return now-self.finished_at >= hold and self.visual.stable_window(self.finished_at, now) is not None + if (self.phase < 1 or self.finished_at is None or len(self.history) < 3 + or not self.feedback_motion_complete()): + return False + if self.raw_scan and self.command.phase == "sweep": + # Every raw waypoint is followed by a bounded steady effect. + # Waiting for stability here would duplicate that effect and + # create an unbounded wait before its timeout can even start. + return True + if self.command.phase in {"steady", "joint_zero"}: + # Data sufficiency is evaluated after the direction; never wait + # indefinitely for a Tag. Missing physical motion is instead + # stopped by the watchdog; a capture timeout cannot waive it. + timeout = self.profile.acquisition.steady_timeout_seconds + if self.raw_scan and self.command.phase == "steady": + # A slow physical endpoint can become stable near the normal + # timeout, leaving less than three camera exposures. Give raw + # scan holds one bounded second more; the feedback and image + # quality gates remain unchanged. + timeout += 1.0 + return now-self.finished_at >= max(timeout, self.command.minimum_hold_seconds) + if self.command.defer_settling_to_hold: + # The immediately following steady effect holds this same target + # and independently gates its image window on stable feedback. + # Do not wait twice at each interior mapping node. + return True + hold = float(self.profile.motion.speed_parameters.get("endpoint_hold_seconds", 0.25)) + if now-self.finished_at < hold: + return False + for i in set(self.moving) | self.reference_targets.keys(): + if max(row[i] for row in self.history)-min(row[i] for row in self.history) > self.stability: + return False + return True + + def minimum_hold_complete(self, now): + return self.finished_at is not None and now-self.finished_at >= self.command.minimum_hold_seconds + + def steady_ready(self, now): + if self.visual is not None: + return (self.command.phase in {"steady", "joint_zero"} + and self.visual.stable_window(self.finished_at, now) is not None) + if (self.command.phase not in {"steady", "joint_zero"} or self.finished_at is None + or not self.feedback_motion_complete()): + return False + window = self.profile.acquisition.steady_window_seconds + rows = [(stamp, value) for stamp, value in self.stamped_history + if stamp >= self.finished_at] + if not rows or now-rows[-1][0] > window: + return False + # Use the latest independent feedback as the window end, so timer + # ticks between feedback messages cannot turn stable data unstable. + # Keep the sample bracketing its start: a fixed 50 ms margin loses it + # under scheduler jitter. Add the duration to avoid cancellation when + # subtracting large monotonic timestamps at the exact window edge. + end = rows[-1][0] + boundary = next((i for i in range(len(rows)-1, -1, -1) + if rows[i][0]+window <= end), None) + if boundary is None: + return False + rows = rows[boundary:] + if len(rows) < 3: + return False + indices = (range(self.profile.command.command_count) if self.command.phase == "joint_zero" + else self.command.measured_channels or (self.command.command_index,)) + return all(max(v[i] for _, v in rows)-min(v[i] for _, v in rows) <= max(2*self.resolution, + 0.005*(self.profile.command.maximum_feedback_values[i]-self.profile.command.minimum_feedback_values[i])) + for i in indices) + + +__all__ = ["MotionCommand", "MotionExecution"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/motion_provenance.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/motion_provenance.py new file mode 100644 index 0000000..22a77d2 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/motion_provenance.py @@ -0,0 +1,467 @@ +"""Read-back of pre-zero geometric branch evidence, without fitting new poses. + +Legacy journals remain readable with their original meaning. A motion-aware +journal cannot lose its header and silently fall back to legacy confirmation. +""" + +import hashlib +import json +import re +from collections.abc import Mapping + +from ..core.domain.reference import joint_zero_moving_roles, read_joint_zero_references +from ..core.geometry.image_motion_replay import ( + IMAGE_POSE_SOURCE, frozen_image_model, has_image_model, +) +from ..core.geometry.tag_pose.parameters import POSE_TRACKING_POLICY_VERSION +from ..core.geometry.tag_pose.image_reference import IMAGE_REFERENCE_SOURCE, reference_from_evidence +from ..core.geometry.tag_pose.pose_bridge import ( + SHARED_TAG_CONDITIONING_POLICIES, +) + + +MOTION_BRANCH_POLICY_VERSION = POSE_TRACKING_POLICY_VERSION +MOTION_BRANCH_POLICY_VERSIONS = { + "confirmed_branch_v4_motion_geometry", "confirmed_branch_v5_image_motion", + "confirmed_branch_v6_source_geometry", "confirmed_branch_v7_final_image_sampling", + MOTION_BRANCH_POLICY_VERSION, +} + + +def uses_motion_evidence(records): + explicit = any( + row.get("kind") in {"motion_branch_initialization", "motion_branch_observation", + "joint_zero_motion_reference_verified"} + or row.get("pose_tracking_policy_version") in MOTION_BRANCH_POLICY_VERSIONS + or bool(row.get("branch_references")) + for row in records) + if explicit: + return True + # Legacy captures may only carry the marker inside the full PnP payload. + # Check it only when no explicit modern marker exists, so indexed resume + # never expands every sample merely to answer this header-level question. + return any( + row.get("pnp_observation_evidence", {}).get("candidate_diagnostics", {}).get("motion_evidence_verified") is True + or any(isinstance(item, Mapping) and item.get("candidate_diagnostics", {}).get("motion_evidence_verified") is True + for item in row.get("pnp_observation_evidence", {}).values()) + for row in records) + + +def _fail(reason): + raise ValueError(f"motion_branch_provenance_{reason}") + + +def _canonical(value): + from .resume_storage import DeferredCaptureRecord + if isinstance(value, DeferredCaptureRecord): + value = value.materialize() + return json.dumps(value, sort_keys=True, separators=(",", ":"), allow_nan=False) + + +def source_frame_sha256(record): + """Bind the entire captured frame, including corners, candidates and SDK state.""" + from .resume_storage import DeferredCaptureRecord + if isinstance(record, DeferredCaptureRecord) and record.canonical_sha256: + # The compact index was derived from the content-bound archived record. + # Final artifact replay expands that record and recomputes this hash. + return record.canonical_sha256 + return hashlib.sha256(_canonical(record).encode()).hexdigest() + + +def _check_source_hashes(payload, observations, hashes): + stamps = payload.get("source_image_stamps", ()) + declared = payload.get("source_frame_hashes") + if (not isinstance(stamps, (tuple, list)) or not stamps + or any(type(stamp) is not int or stamp < 1 for stamp in stamps) + or list(stamps) != sorted(set(stamps)) + or not isinstance(declared, Mapping) or set(declared) != {str(stamp) for stamp in stamps} + or any(not isinstance(value, str) or re.fullmatch(r"[0-9a-f]{64}", value) is None + for value in declared.values())): + _fail("source_hash_coverage_invalid") + versions = payload.get("source_motion_versions") + path = payload.get("approach_evidence_scope") == "path" + if path or versions is not None: + if (not path or not isinstance(versions, Mapping) + or set(versions) != {str(stamp) for stamp in stamps} + or any(type(version) is not int or not 1 <= version <= payload["motion_version"] + for version in versions.values()) + or [versions[str(stamp)] for stamp in stamps] != sorted(versions.values())): + _fail("source_motion_versions_invalid") + for stamp in stamps: + key = (payload["view"], stamp) + source = observations.get(key) + if (source is None or any(source.get(field) != payload[field] for field in ( + "task_name", "zero_joints", "session_epoch")) + or source.get("motion_version") != (versions[str(stamp)] if path else payload["motion_version"]) + or path and (type(source.get("reference_path_index")) is not int + or source["reference_path_index"] < 1 + or source.get("sample_phase") != "zero_approach")): + _fail("source_image_missing_or_changed") + if key not in hashes: + hashes[key] = source_frame_sha256(source) + if hashes[key] != declared[str(stamp)]: + _fail("source_content_changed") + + +def _initializations(records): + observations, evidence, resolved = {}, {}, [] + for row in records: + if row.get("kind") == "motion_branch_observation": + key = (row.get("view"), row.get("image_stamp_ns")) + if key in observations and _canonical(observations[key]) != _canonical(row): + _fail("source_image_changed") + observations[key] = row + if row.get("kind") == "motion_branch_initialization" and row.get("status") == "resolved": + if ("image_solver_policy" in row or "image_solver_attempts" in row + or any(len(h.get("training_solver_attempts", ())) > 1 for h in row.get("hypotheses", ()))): + from ..core.geometry.tag_pose.image_bundle_optimizer import IMAGE_BUNDLE_SOLVER_POLICY + expected_attempts = [{key: hypothesis.get(key) for key in ( + "branches", "training_solver_attempts", "training_solver_status", "training_solver_evaluations")} + for hypothesis in row.get("hypotheses", ())] + if (row.get("image_solver_policy") != IMAGE_BUNDLE_SOLVER_POLICY + or row.get("image_solver_attempts") != expected_attempts): + _fail("solver_report_changed") + from .preparation_transition_evidence import check_transition_report + check_transition_report(row) + from .preparation_witness_evidence import check_witness_report + check_witness_report(row) + from ..core.geometry.tag_pose.pose_bridge import OBSERVER_POSE_SELECTION_POLICIES + policy = row.get('image_model_selection_policy') + if (policy in OBSERVER_POSE_SELECTION_POLICIES) != bool(row.get('observer_pose_bridges')): + _fail('observer_pose_selection_policy_changed') + from ..core.geometry.tag_pose.pose_bridge import RIGID_OBSERVER_SELECTION_POLICY + rigid = any(b.get('version') in {'observer_pose_bridge_v2', 'observer_pose_bridge_v3'} for b in row.get('observer_pose_bridges', ())) + if rigid != (policy == RIGID_OBSERVER_SELECTION_POLICY): + _fail('rigid_pair_selection_policy_changed') + _check_measured_transfer_report(row) + shared_policy = OBSERVER_POSE_SELECTION_POLICIES.get(policy, policy) + from ..core.geometry.tag_pose.pose_bridge import SHARED_TAG_HANDOFF_POLICY + from .shared_pose_handoff import HANDOFF_POLICY + if any((bridge.get('handoff_policy') == HANDOFF_POLICY) + != (shared_policy == SHARED_TAG_HANDOFF_POLICY) + for bridge in row.get('shared_tag_pose_bridges', ())): + _fail('shared_pose_handoff_policy_changed') + if ((shared_policy in SHARED_TAG_CONDITIONING_POLICIES) + != bool(row.get('shared_tag_pose_bridges'))): + _fail('shared_pose_selection_policy_changed') + conditioning = SHARED_TAG_CONDITIONING_POLICIES.get(shared_policy) + if any(bridge.get('conditioning') != conditioning + for bridge in row.get('shared_tag_pose_bridges', ())): + _fail('shared_pose_conditioning_policy_changed') + resolved.append(row) + for role, payload in row.get("evidence_payloads", {}).items(): + if (shared_policy == SHARED_TAG_HANDOFF_POLICY + or 'image_model_selection_policy' in payload): + if payload.get('image_model_selection_policy') != policy: + _fail('shared_pose_handoff_policy_changed') + identity = row.get("evidence_ids", {}).get(role) + if (not isinstance(identity, str) or re.fullmatch(r"[0-9a-f]{64}", identity) is None + or hashlib.sha256(_canonical(payload).encode()).hexdigest() != identity): + _fail("initialization_hash_invalid") + if payload.get("tag_role") != role or any(payload.get(key) != row.get(key) for key in ( + "task_name", "view", "zero_joints", "session_epoch", "motion_version", + "source_image_stamps", "source_frame_hashes", "constraints", + "frozen_image_model", "image_model_sha256", + "image_solver_policy", "image_solver_attempts", "image_sampling_policy", + "geometry_uncertainty", "parent_reference_sha256", + "approach_evidence_scope", "source_motion_versions", "shared_tag_pose_bridges", "observer_pose_bridges", + "preparation_transitions", "preparation_witnesses")): + _fail("initialization_binding_changed") + stamps = payload.get("source_image_stamps", ()) + if (not stamps or any(type(stamp) is not int or stamp < 1 for stamp in stamps) + or list(stamps) != sorted(set(stamps)) + or not (payload.get("constraints") or payload.get("frozen_image_model")) + or any(type(payload.get(key)) is not int or payload[key] < 1 + for key in ("session_epoch", "motion_version"))): + _fail("initialization_support_invalid") + if identity in evidence and _canonical(evidence[identity]) != _canonical(payload): + _fail("initialization_identity_reused") + evidence[identity] = payload + source_hashes = {} + for row in resolved: + _check_source_hashes(row, observations, source_hashes) + for role, identity in row.get("evidence_ids", {}).items(): + payload = evidence.get(identity) + if payload is None or (payload["view"], payload["tag_role"]) != (row.get("view"), role): + _fail("initialization_role_unbound") + for payload in evidence.values(): + _check_source_hashes(payload, observations, source_hashes) + if has_image_model(payload): + _check_image_initialization(payload, observations) + model = frozen_image_model(payload) + source_hash = getattr(model, "source_urdf_sha256", "") + if source_hash: + headers = [row for row in records if row.get("kind") == "session_start"] + if len(headers) != 1 or headers[0].get("source_urdf_sha256") != source_hash: + _fail("image_model_source_urdf_changed") + from .parent_reference_evidence import validate_source_hinges + validate_source_hinges(evidence, records) + if any(payload.get('preparation_transitions') for payload in evidence.values()): + from .preparation_transition_evidence import transition_inputs + tuple(transition_inputs(records, evidence)) + if any(payload.get('preparation_witnesses') for payload in evidence.values()): + from .preparation_witness_evidence import witness_inputs + tuple(witness_inputs(records, evidence)) + return evidence + + +def _check_measured_transfer_report(row): + """Bind the fitted prior domain and uncertainty to the accepted hypothesis.""" + from dataclasses import asdict + from ..core.geometry.tag_pose.measured_transfer import MEASURED_TRANSFER_POLICY, transfer_geometry_checks + + if row.get("frozen_image_model", {}).get("policy") != MEASURED_TRANSFER_POLICY: + return + model = frozen_image_model(row) + candidates = [h for h in row.get("hypotheses", ()) + if _canonical(h.get("branches")) == _canonical(model.branches)] + if len(candidates) != 1: + _fail("measured_transfer_hypothesis_missing") + winner = candidates[0] + checks, inherited = transfer_geometry_checks(model.geometry, model.constraints, + model.source_hinges, model.current_geometry_uncertainty) + axes = [(name, axis+inherited[name][0]) for name, axis, _ in model.current_geometry_uncertainty] + points = [(name, point+inherited[name][1]) for name, _, point in model.current_geometry_uncertainty] + if (winner.get("training_accepted") is not True or winner.get("converged") is not True + or winner.get("reason") or _canonical(winner.get("source_geometry_checks")) != _canonical([asdict(c) for c in checks]) + or _canonical(winner.get("axis_uncertainty_95_rad")) != _canonical(axes) + or _canonical(winner.get("pivot_uncertainty_95_m")) != _canonical(points) + or _canonical(winner.get("child_frame_uncertainty")) != _canonical(row.get("geometry_uncertainty"))): + _fail("measured_transfer_uncertainty_binding_changed") + + +def validate_source_geometry(profile, source_urdf, records): + """Re-derive source constraints before finalization; never trust labels alone.""" + from ..core.geometry.tag_pose.cad_image_model import CAD_IMAGE_MOTION_MODEL_POLICY, TRANSFERRED_IMAGE_MOTION_MODEL_POLICY + from ..core.geometry.tag_pose.measured_transfer import MEASURED_TRANSFER_POLICY + from ..core.urdf.kinematics import UrdfKinematicModel + from ..profiles.observations import compile_parallel_axis_geometry + + source_model = None + for row in records: + if row.get("kind") != "motion_branch_initialization" or row.get("status") != "resolved": + continue + payload = row.get("frozen_image_model", {}) + if payload.get("policy") not in {CAD_IMAGE_MOTION_MODEL_POLICY, TRANSFERRED_IMAGE_MOTION_MODEL_POLICY, MEASURED_TRANSFER_POLICY}: + continue + model = frozen_image_model(row) + if source_model is None: + source_model = UrdfKinematicModel(source_urdf) + source_hash = hashlib.sha256(source_model.source.read_bytes()).hexdigest() + if (model.source_urdf_sha256 != source_hash + or model.constraints != compile_parallel_axis_geometry(profile, source_model, + tuple(item.geometry.relation for item in getattr(model, "source_hinges", ())) + model.relations)): + _fail("image_model_source_geometry_changed") + if any(row.get('observer_pose_bridges') for row in records): + from .observer_reference import validate_observer_channels + if source_model is None: + source_model = UrdfKinematicModel(source_urdf) + validate_observer_channels(profile, records, source_model) + if profile.motion.preparation_witnesses or any(row.get('preparation_witnesses') for row in records): + from .preparation_witness_evidence import validate_witness_topology + if source_model is None: + source_model = UrdfKinematicModel(source_urdf) + validate_witness_topology(profile, records, _initializations(records), source_model) + if any(row.get('preparation_transitions') for row in records): + from .preparation_transition_evidence import validate_transition_topology + if source_model is None: + source_model = UrdfKinematicModel(source_urdf) + validate_transition_topology(profile, records, _initializations(records), source_model) + if source_model is not None and any(task.parent_reference is not None for task in profile.motion.tasks): + from .parent_reference_evidence import validate_parent_references + validate_parent_references(profile, records, _initializations(records), source_model=source_model) + if any(row.get('shared_tag_pose_bridges') for row in records): + from .shared_tag_evidence import validate_shared_tag_references + if source_model is None: + source_model = UrdfKinematicModel(source_urdf) + validate_shared_tag_references(profile, records, _initializations(records), source_model=source_model) + + +def _check_image_initialization(payload, observations): + model = frozen_image_model(payload) + from ..core.geometry.tag_pose.production_image_motion import image_parameters_for_sampling + limits = image_parameters_for_sampling(payload.get("image_sampling_policy")) + if (list(model.source_stamps_ns) != payload["source_image_stamps"] + or len(model.source_stamps_ns) < 24 + or min(len(model.training_stamps_ns), len(model.validation_stamps_ns)) < 12 + or len(model.training_stamps_ns) > limits.maximum_training_frames + or len(model.validation_stamps_ns) > limits.maximum_validation_frames + or payload["tag_role"] not in {item.relation.child_role for item in model.geometry} + or not {item.relation.joint for item in model.geometry} <= set(payload["zero_joints"])): + _fail("image_model_support_or_roles_changed") + for stamp in model.source_stamps_ns: + source = observations[(payload["view"], stamp)] + if (source.get("cycle") == 3 or source.get("sample_phase") != "zero_approach" + or source.get("input_is_rectified") is not True + or _canonical(source.get("camera_matrix")) != _canonical(model.camera_matrix)): + _fail("image_model_support_not_pre_zero") + for role, size in model.tag_sizes: + item = source.get("tags", {}).get(role, {}) + if item.get("tag_size_m") != size: + _fail("image_model_tag_size_changed") + references = {ref.role: ref for ref in model.reference_frames} + if role in references or item.get("pose_source") == IMAGE_REFERENCE_SOURCE: + reference = reference_from_evidence(item, stamp_ns=stamp, camera_matrix=model.camera_matrix) + if reference != references.get(role): + _fail("image_model_reference_changed") + + +def _check_reference_modes(profile, records, evidence): + """Only declared fixed Tags can supply camera-aligned coordinates.""" + mode = profile.acquisition.fixed_reference_mode + headers = [row for row in records if row.get("kind") == "session_start"] + if mode == "stationary_image": + from .engine import capture_schedule_version + if (len(headers) != 1 or headers[0].get("fixed_reference_mode") != mode + or headers[0].get("capture_schedule_version") != capture_schedule_version(profile)): + _fail("image_reference_header_changed") + fixed = {view.name: {tag.role for tag in view.tags if tag.fixed_reference} + for view in profile.vision.views} + for payload in evidence.values(): + if not has_image_model(payload): + continue + model = frozen_image_model(payload) + expected = (fixed.get(payload["view"], set()) & set(dict(model.tag_sizes)) + if mode == "stationary_image" else set()) + if {ref.role for ref in model.reference_frames} != expected: + _fail("image_reference_profile_binding_changed") + + +def _image_frames(records): + frames = {} + for row in records: + if row.get("kind") != "pnp_candidate_frame": + continue + key = (row.get("view"), row.get("image_stamp_ns")) + if key in frames and _canonical(frames[key]) != _canonical(row): + _fail("image_frame_identity_reused") + frames[key] = row + return frames + + +def _reference_authorizations(profile, reference, evidence): + roles = {(item.view, item.tag_role) for item in reference.branch_references} + if roles != joint_zero_moving_roles(profile, reference.joint): + _fail(f"zero_evidence_missing:{reference.joint}") + result = {} + for item in reference.branch_references: + payload = evidence.get(item.motion_evidence_id) + if payload is None or (payload["view"], payload["tag_role"]) != (item.view, item.tag_role): + _fail(f"zero_evidence_unbound:{reference.joint}") + first_zero = min(sample.image_stamp_ns for sample in reference.samples if sample.view == item.view) + if max(payload["source_image_stamps"]) >= first_zero: + _fail(f"initialization_not_before_zero:{reference.joint}") + result[(item.view, item.tag_role, item.motion_evidence_id, item.branch_revision)] = first_zero + return result + + +def validate_motion_provenance(profile, records, *, required=False, require_complete=False, + references=None, image_replay_workers=1): + """Check capture authorization, never certify physical accuracy. + + The explicit ``required`` flag is set by the production owner. Independent + record markers preserve this requirement after a header is removed. + """ + from ..profiles.preparation import validate_preparation_contract + validate_preparation_contract(profile, records) + if not required and not uses_motion_evidence(records): + return {"status": "legacy_image_confirmation", "motion_evidence_verified": False} + from .visual_motion import validate_visual_motion_evidence + validate_visual_motion_evidence(profile, records) + references = read_joint_zero_references(profile, records) if references is None else references + expected = {name for task in profile.motion.tasks for name in task.joints} + if not references or (require_complete and not expected <= references.keys()): + _fail("joint_zero_references_missing") + evidence = _initializations(records) + if any(payload.get('preparation_transitions') for payload in evidence.values()): + from .preparation_transition_evidence import validate_preparation_transitions + validate_preparation_transitions(profile, records, evidence) + if profile.motion.preparation_witnesses or any(payload.get('preparation_witnesses') for payload in evidence.values()): + from .preparation_witness_evidence import validate_preparation_witnesses + validate_preparation_witnesses(profile, records, evidence) + _check_reference_modes(profile, records, evidence) + from .parent_reference_evidence import validate_parent_references + validate_parent_references(profile, records, evidence) + from .shared_tag_evidence import validate_shared_tag_references + if any(payload.get('shared_tag_pose_bridges') for payload in evidence.values()): + validate_shared_tag_references(profile, records, evidence) + from ..profiles.observer_policy import is_rigid_observer + if (any(payload.get('observer_pose_bridges') for payload in evidence.values()) + or any(is_rigid_observer(s.observer_pose_policy) for s in profile.measurement.measurements.values())): + from .observer_reference import validate_observer_references + validate_observer_references(profile, records, evidence) + image_frames, image_samples = _image_frames(records), {} + authorizations = {name: _reference_authorizations(profile, reference, evidence) + for name, reference in references.items()} + zero_images = {(name, sample.view, sample.image_stamp_ns) + for name, reference in references.items() for sample in reference.samples} + for row in records: + if row.get("kind") != "joint_zero_motion_reference_verified": + continue + from .joint_resume import reference_pose_failures + original = read_joint_zero_references(profile, [row["preserved_reference"]]) + current = read_joint_zero_references(profile, [row["current_reference"]]) + name = row.get("joint") + if set(original) != {name} or set(current) != {name} or name not in references: + _fail("resume_reference_binding_invalid") + if (_canonical(original[name].as_record()) != _canonical(references[name].as_record()) + or reference_pose_failures(original[name], current[name])): + _fail(f"resume_reference_changed:{name}") + if str(row.get("verification", "")).startswith("staged_revisit"): + from .revisit import verify_revisit + verify_revisit(profile, original[name], current[name], verification=row["verification"], + feedback_limits=row.get("feedback_limits")) + for key, stamp in _reference_authorizations(profile, current[name], evidence).items(): + authorizations[name][key] = min(authorizations[name].get(key, stamp), stamp) + zero_images.update((name, sample.view, sample.image_stamp_ns) for sample in current[name].samples) + cycles = {} + for row in records: + kind = row.get("kind") + if kind not in {"joint_sample", "secondary_joint_sample", "joint_zero_sample"}: + continue + name, view, stamp = row.get("joint", row.get("observation_joint")), row.get("view"), row.get("image_stamp_ns") + is_zero = kind == "joint_zero_sample" or row.get("sample_phase") == "joint_zero" + if is_zero and (name, view, stamp) not in zero_images: + continue # Earlier unsettled zero images are retained diagnostics. + if name not in authorizations: + _fail(f"sample_zero_missing:{name}") + roles = {role for role_view, role in joint_zero_moving_roles(profile, name) if role_view == view} + observed = row.get("pnp_observation_evidence", {}) + by_role = {item.get("tag_role"): item for item in observed.values()} + if not roles or not roles <= by_role.keys(): + _fail(f"sample_role_missing:{name}") + image_group = None + for role in roles: + item = by_role[role] + diagnostics = item.get("candidate_diagnostics", {}) + key = (view, role, diagnostics.get("motion_evidence_id"), diagnostics.get("branch_revision")) + authorization = authorizations[name].get(key) + if (authorization is None or item.get("pose_source") not in {"current_image", IMAGE_POSE_SOURCE} + or diagnostics.get("motion_evidence_verified") is not True + or diagnostics.get("observation_stamp_ns") != stamp + or diagnostics.get("branch_status") != "tracking" + or (not is_zero and (diagnostics.get("branch_frozen") is not True or stamp <= authorization))): + _fail(f"sample_not_authorized:{name}:{view}:{role}") + payload = evidence[diagnostics["motion_evidence_id"]] + if has_image_model(payload) or has_image_model(item): + if (item.get("pose_source") != IMAGE_POSE_SOURCE + or not has_image_model(payload) + or item.get("image_model_sha256") != payload.get("image_model_sha256")): + _fail(f"sample_image_model_changed:{name}:{view}:{role}") + frame_key = (view, stamp) + frame = image_frames.get(frame_key) + if frame is None: + _fail(f"sample_image_frame_missing:{name}:{view}:{role}") + image_group = image_samples.setdefault(frame_key, (frame, [])) + if image_group is not None: + image_group[1].append(row) + if not is_zero: + cycles.setdefault(name, set()).add(row.get("cycle")) + from .image_replay import validate_image_groups + validate_image_groups(image_samples.values(), workers=image_replay_workers) + from ..core.domain.capture_plan import training_cycles + if require_complete and any(not {*training_cycles(profile, joint=name), profile.quality.holdout_cycle} + <= cycles.get(name, set()) for name in expected): + _fail("independent_cycles_missing") + return {"status": "motion_evidence_verified", "motion_evidence_verified": True, + "joint_count": len(references), "evidence_count": len(evidence), "is_accuracy_certificate": False} diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_coverage.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_coverage.py new file mode 100644 index 0000000..3026e2c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_coverage.py @@ -0,0 +1,37 @@ +"""Shared checks for synchronized raw corner observations.""" +from collections.abc import Mapping +import math +import numpy as np + + +def complete_vector(values, count: int) -> bool: + return (isinstance(values, (list, tuple)) and len(values) == count + and all(isinstance(value, (int, float)) and not isinstance(value, bool) + and math.isfinite(value) for value in values)) + + +def visible_roles(row: Mapping, tags: Mapping) -> set[str]: + visible = set() + observations = row.get("tags") + if not isinstance(observations, Mapping): + return visible + for role, item in observations.items(): + tag = tags.get(role) + raw = row.get("observation_protocol") == "raw_joint_images_v2" + diagnostics = item.get("candidate_diagnostics", {}) if isinstance(item, Mapping) else {} + stamp = (item.get("image_stamp_ns") if raw else + diagnostics.get("observation_stamp_ns") if isinstance(diagnostics, Mapping) else None + ) if isinstance(item, Mapping) else None + if (tag is None or not isinstance(item, Mapping) + or item.get("tag_role") != role or item.get("tag_id") != tag.tag_id + or stamp != row.get("image_stamp_ns") + or (raw and item.get("pose_source") != "raw_corners")): + continue + try: + points = np.asarray(item.get("corners_xy"), dtype=float) + except (TypeError, ValueError): + continue + if points.shape == (4, 2) and np.all(np.isfinite(points)): + visible.add(role) + return visible + diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_scope.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_scope.py new file mode 100644 index 0000000..f1bbdcc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_scope.py @@ -0,0 +1,39 @@ +"""Resolve the immutable observation scope of one complete capture session. + +Formal calibration keeps the Profile's full reference contract. A diagnostic +subset needs every primary and secondary view of its selected tasks, including +tasks scheduled later. This never changes as individual scan units advance. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING + +from ..core.domain.profile import CalibrationProfile + +if TYPE_CHECKING: + from .diagnostic_capture import DiagnosticCapturePlan + + +def required_observation_views( + profile: CalibrationProfile, + diagnostic_capture: DiagnosticCapturePlan | None = None, +) -> tuple[str, ...]: + declared = profile.vision.view_names + if diagnostic_capture is None: + return declared + keys = set(diagnostic_capture.task_keys) + tasks = {task.key: task for task in profile.motion.tasks} + if not keys or not keys <= tasks.keys(): + raise ValueError("diagnostic_observation_tasks_invalid") + measurements = profile.measurement + names = {name for key in keys for name in tasks[key].joints} + names.update(measurements.cross_view_sources[name] + for name in tuple(names) if name in measurements.cross_view_sources) + views = {measurements.measurements[name].view for name in names} + # Explicit passive observers record the existing trajectory only. They + # neither add scan units nor become primary joint measurements. + views.update(diagnostic_capture.observer_views) + if not views or not views <= set(declared): + raise ValueError("diagnostic_observation_views_invalid") + return tuple(view for view in declared if view in views) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_timing.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_timing.py new file mode 100644 index 0000000..55d6abd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/observation_timing.py @@ -0,0 +1,115 @@ +"""Describe recorded image and synchronized-observation gaps without judging them.""" + +from collections.abc import Mapping, Sequence +import math +from numbers import Real + +from ..core.domain.motion_path import record_scan_identity, task_segment +from ..core.domain.profile import CalibrationProfile +from .engine import ScanUnit +from .scan_quality import observation_streams + + +def _finite_number(value: object) -> bool: + return isinstance(value, Real) and not isinstance(value, bool) and math.isfinite(value) + + +def _complete_vector(values: object, count: int) -> bool: + return (isinstance(values, (list, tuple)) and len(values) == count + and all(_finite_number(value) for value in values)) + + +def _current_corners(item: object, role: str, tag_id: int, stamp_ns: int) -> bool: + if not isinstance(item, Mapping): + return False + diagnostics = item.get("candidate_diagnostics") + if (item.get("tag_role") != role or item.get("tag_id") != tag_id + or not isinstance(diagnostics, Mapping) + or diagnostics.get("observation_stamp_ns") != stamp_ns): + return False + corners = item.get("corners_xy") + return (isinstance(corners, (list, tuple)) and len(corners) == 4 + and all(isinstance(point, (list, tuple)) and len(point) == 2 + and all(_finite_number(value) for value in point) for point in corners)) + + +def _maximum_gap_seconds(stamps: Sequence[int]) -> float | None: + ordered = sorted(set(stamps)) + if len(ordered) < 2: + return None + return max(right - left for left, right in zip(ordered, ordered[1:])) / 1e9 + + +def summarize_observation_timing( + profile: CalibrationProfile, + unit: ScanUnit, + attempt: int, + records: Sequence[Mapping], +) -> dict[str, dict[str, int | float | None]]: + """Count raw diagnostic images separately for each required observation stream. + + Only explicit raw image records supply the denominator; accepted joint + samples cannot establish how many images were received. A duplicate image + uses its first record, so separate duplicates cannot manufacture a complete + Tag pair or synchronized command/feedback vectors. + + Visibility requires current corners for every required moving Tag. A + synchronized observation additionally needs complete finite command and + feedback vectors in the Profile's unit. Missing-vector counts cover all raw + images, including those without visible Tags. Gaps use image timestamps; + fewer than two images yield None, and unknown sweep boundaries are not + inferred. These facts neither apply thresholds nor imply accuracy. + """ + task = next(task for task in profile.motion.tasks if task.key == unit.task_key) + segment = task_segment(task, unit.segment_key) if unit.segment_key else None + streams = tuple(item for item in observation_streams(profile, task) + if segment is None or item[1] in segment.joints) + required_views = {spec.view for _, _, spec in streams} + frames: dict[str, dict[int, Mapping]] = {view: {} for view in required_views} + for row in records: + if (row.get("kind") != "diagnostic_observation_frame" + or row.get("sample_phase") != "sweep" + or record_scan_identity(row) != unit.identity or row.get("attempt") != attempt): + continue + view, stamp = row.get("view"), row.get("image_stamp_ns") + if (view not in frames or not isinstance(stamp, int) + or isinstance(stamp, bool) or stamp <= 0): + continue + frames[view].setdefault(stamp, row) + + tags_by_view = {view.name: {tag.role: tag for tag in view.tags} + for view in profile.vision.views} + result = {} + for field, name, spec in streams: + required = {role: tags_by_view[spec.view][role].tag_id + for role in {spec.parent_role, spec.child_role} + if not tags_by_view[spec.view][role].fixed_reference} + visible_stamps, synchronized_stamps = [], [] + missing_command, missing_feedback = 0, 0 + for stamp, row in frames[spec.view].items(): + correct_unit = row.get("command_unit") == profile.command.unit + command = correct_unit and _complete_vector(row.get("command_vector"), profile.command.command_count) + feedback = correct_unit and _complete_vector(row.get("feedback_vector"), profile.command.command_count) + missing_command += not command + missing_feedback += not feedback + tags = row.get("tags") + visible = (bool(required) and isinstance(tags, Mapping) + and all(_current_corners(tags.get(role), role, tag_id, stamp) + for role, tag_id in required.items())) + if visible: + visible_stamps.append(stamp) + if command and (feedback or profile.vision_motion): + synchronized_stamps.append(stamp) + result[f"{field}:{name}:{spec.view}:{unit.direction}"] = { + "raw_frames": len(frames[spec.view]), + "visible_frames": len(visible_stamps), + "synchronized_frames": len(synchronized_stamps), + "missing_command_frames": missing_command, + "missing_feedback_frames": missing_feedback, + "maximum_image_gap_seconds": _maximum_gap_seconds(tuple(frames[spec.view])), + "maximum_synchronized_gap_seconds": _maximum_gap_seconds(synchronized_stamps), + } + return result + + +__all__ = ["summarize_observation_timing"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_preparation.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_preparation.py new file mode 100644 index 0000000..e18b345 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_preparation.py @@ -0,0 +1,284 @@ +"""One bounded independent observation, before an unmeasured hinge is fitted. + +Decisions and completed segments are journaled. A restart cannot replenish the +motion budget or relabel an incomplete excursion as usable evidence. +""" +from dataclasses import dataclass, replace +import hashlib +import json +import math +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.fitting.motion_fit import channel_for_joint +from ..core.geometry.tag_pose.ippe import solve_square_tag_ippe +from .motion_execution import MotionCommand +from .motion_provenance import source_frame_sha256 +from ..profiles.observer_preparation import observer_action, observer_actions + +POLICY = 'bounded_rigid_observation_v1' +SEQUENCE_POLICY = 'bounded_rigid_observation_v2' +TRAJECTORY_POLICY = 'occlusion_aware_trajectory_v3' +PHASES = frozenset({'observer_preflight', 'observer_probe'}) +RECOVERABLE = frozenset({'rigid_pair_candidates_unresolved', 'rigid_pair_pose_uncertain', + 'rigid_pair_viewpoint_span_insufficient', 'rigid_pair_source_missing', 'observer_images_missing'}) + + +def normal_coverage(rows, role): + """Conservative two-branch normal diversity; in-plane rotation earns nothing. + +This is an acquisition trigger, never a substitute for independent image +validation or a statement that a pose is observable. +""" + normals = [] + selected = sorted(rows, key=lambda row: row['image_stamp_ns']) + for i in np.linspace(0, len(selected)-1, min(36, len(selected))).round().astype(int): + row = selected[i] + tag = row.get('tags', {}).get(role) + if tag is None: + continue + poses = solve_square_tag_ippe(np.asarray(tag['corners_xy']), tag_size_m=tag['tag_size_m'], + camera_matrix=np.asarray(row['camera_matrix'])) + if poses: + normals.append(np.asarray([Rotation.from_quat(p.quaternion_xyzw).apply([0., 0., 1.]) for p in poses])) + span = max((math.degrees(math.acos(float(np.clip(np.max(np.abs(a@b.T)), 0., 1.)))) + for i, a in enumerate(normals) for b in normals[i+1:]), default=0.) + return dict(source_frames=len(selected), normal_span_deg=span, + needs_excitation=len(selected) < 24 or span < 15.) + + +def trajectory_observability(rows, parent_role, child_role): + """Measure whether a monocular trajectory can distinguish planar branches. + + This is an acquisition decision only. It never marks geometry as passed; + the independent rigid-pair fit and final holdout still own acceptance. + """ + rows = tuple(sorted(rows, key=lambda row: row['image_stamp_ns'])) + coverage = normal_coverage(rows, parent_role) + paired = [row for row in rows if {parent_role, child_role} <= set(row.get('tags', {}))] + separations, diagonals = [], [] + for row in paired[::max(1, len(paired)//36)]: + tag = row['tags'][parent_role] + poses = solve_square_tag_ippe(np.asarray(tag['corners_xy']), tag_size_m=tag['tag_size_m'], + camera_matrix=np.asarray(row['camera_matrix'])) + if len(poses) > 1: + separations.append(math.degrees((Rotation.from_quat(poses[0].quaternion_xyzw).inv() + * Rotation.from_quat(poses[1].quaternion_xyzw)).magnitude())) + corners = np.asarray(tag['corners_xy'], dtype=float) + diagonals.append(float(np.mean((np.linalg.norm(corners[0]-corners[2]), + np.linalg.norm(corners[1]-corners[3]))))) + completeness = len(paired)/max(1, len(rows)) + branch_separation = float(np.median(separations)) if separations else 0. + tag_diagonal = float(np.median(diagonals)) if diagonals else 0. + needs = (coverage['needs_excitation'] or completeness < .9 + or branch_separation < 1.) + return {**coverage, 'paired_frames': len(paired), + 'pair_detection_fraction': completeness, + 'median_planar_branch_separation_deg': branch_separation, + 'median_tag_diagonal_px': tag_diagonal, + 'needs_excitation': needs} + + +def observation_action_utility(profile, joint, plan, rows): + """Rank a declared safe action by expected out-of-plane information.""" + spec = profile.measurement.measurements[joint] + metrics = trajectory_observability(rows, spec.parent_role, spec.child_role) + channel = channel_for_joint(profile, plan.joint) + lower, upper = profile.command.minimum_values[channel], profile.command.maximum_values[channel] + excursion = max(abs(point[channel]-plan.command[channel]) for point in plan.approach_commands) + fraction = excursion/(upper-lower) + # The donor was selected from the URDF dependency graph for a transverse + # axis. This conservative estimate is only used to choose acquisition; + # it is never reported as a measured joint angle. + expected_normal_gain = 60.*fraction + expected_pixel_separation = metrics['median_tag_diagonal_px'] * math.sin(math.radians(expected_normal_gain)) + reliability = metrics['pair_detection_fraction'] + return {**metrics, 'donor': plan.joint, 'excursion_fraction': fraction, + 'expected_normal_gain_deg': expected_normal_gain, + 'expected_candidate_separation_px': expected_pixel_separation, + 'utility': expected_pixel_separation*reliability} + + +def corner_evidence_sha256(rows, roles): + payload = [{"stamp": row['image_stamp_ns'], "camera_matrix": row.get('camera_matrix'), + "tags": {role: row.get('tags', {}).get(role, {}).get('corners_xy') for role in roles}} + for row in rows] + return hashlib.sha256(json.dumps(payload, sort_keys=True, separators=(',', ':'), + allow_nan=False).encode()).hexdigest() + + +def latest_source_rows(owner, joint, epoch): + spec = owner.profile.measurement.measurements[joint] + reports = [report for (source_epoch, view, _), (model, report) in owner.parent_references.models.items() + if source_epoch == epoch and view == spec.view and model.image_model is not None + and len(model.image_model.geometry) == 1 + and model.image_model.geometry[0].relation.child_role == spec.parent_role] + if not reports: + return () + report = max(reports, key=lambda row: max(row['source_image_stamps'])) + observed = owner.observer_records.get((report['session_epoch'], report['task_name'], spec.view), {}) + return tuple(observed[s] for s in sorted(report['source_image_stamps']) + if s in observed and spec.parent_role in observed[s]['tags'] and spec.child_role in observed[s]['tags']) + + +@dataclass(frozen=True) +class ObserverProbeEvidence: + decision: dict + rows: tuple + segments: tuple + started: dict | None = None + + +class ObserverPreparation: + def __init__(self, owner): + self.owner = owner + self.decisions, self.rows, self.segments = {}, {}, {} + self.started = {} + self.history = {} + + def clear(self): + self.decisions.clear(); self.rows.clear(); self.segments.clear() + self.started.clear() + self.history.clear() + + def restore(self, records): + for row in records: + self.observe(row) + + def observe(self, row): + kind = row.get('kind') + if kind == 'observer_preparation_decision' and row.get('action') == 'excite': + identity = source_frame_sha256(row) + joint = row['joint'] + previous = self.decisions.get(joint) + if previous is not None and previous != row: + index = previous.get('action_index', 0)+1 + if (row.get('policy') not in {SEQUENCE_POLICY, TRAJECTORY_POLICY} + or row.get('action_index') != index + or index >= len(observer_actions(self.owner.profile, joint)) + or row.get('previous_preparation_id') != source_frame_sha256(previous) + or self.source(joint) is None): + raise ValueError('observer_preparation_budget_reused') + from .observer_preparation_evidence import validate_probe_evidence + validate_probe_evidence(self.owner.profile, joint, self.source(joint)) + self.history.setdefault(joint, []).append(previous) + elif previous is None and row.get('action_index', 0) != 0: + raise ValueError('observer_preparation_previous_action_missing') + self.decisions[joint] = row + self.rows.setdefault(identity, {}) + self.segments.setdefault(identity, {}) + elif kind == 'image_observation_frame' and row.get('observer_preparation_id'): + identity = row['observer_preparation_id'] + if identity in self.rows: + self.rows[identity][(row['view'], row['image_stamp_ns'])] = row + elif kind == 'observer_preparation_segment_complete': + identity = row['observer_preparation_id'] + if identity in self.segments: + self.segments[identity][row['path_index']] = row + elif kind == 'observer_preparation_excursion_started': + identity = row['observer_preparation_id'] + if identity in self.started and self.started[identity] != row: + raise ValueError('observer_preparation_budget_reused') + self.started[identity] = row + elif kind == 'observer_preparation_cancelled_before_excursion': + joint = row['joint'] + decision = self.decisions.get(joint) + if decision is None or source_frame_sha256(decision) != row['observer_preparation_id']: + raise ValueError('observer_preparation_cancellation_changed') + self._require_unstarted(joint) + del self.decisions[joint] + if self.history.get(joint): + self.decisions[joint] = self.history[joint].pop() + + def _require_unstarted(self, joint): + decision = self.decisions[joint] + identity = source_frame_sha256(decision) + target = observer_action(self.owner.profile, joint, decision).command + if (identity in self.started or any(i != 0 for i in self.segments[identity]) + or not decision.get('motion_authorization_required') and self.segments[identity] + or any(r['reference_path_index'] != 0 or tuple(r.get('command_vector') or ()) != target + for r in self.rows[identity].values())): + raise ValueError('observer_preparation_motion_budget_consumed') + + def cancel_unstarted(self, joint, *, epoch, stamp_ns): + if joint not in self.decisions or self.source(joint) is not None: + return None + self._require_unstarted(joint) + return dict(kind='observer_preparation_cancelled_before_excursion', joint=joint, + observer_preparation_id=source_frame_sha256(self.decisions[joint]), + session_epoch=epoch, stamp_ns=stamp_ns) + + def source(self, joint): + decision = self.decisions.get(joint) + if decision is None: + return None + identity = source_frame_sha256(decision) + if set(self.segments[identity]) != {0, 1, 2} or identity not in self.started: + return None + view = self.owner.profile.measurement.measurements[joint].view + rows = tuple(sorted((r for r in self.rows[identity].values() if r['view'] == view), + key=lambda row: row['image_stamp_ns'])) + return ObserverProbeEvidence(decision, rows, tuple(self.segments[identity][i] for i in range(3)), + self.started.get(identity)) + + def decide(self, motion, *, epoch, stamp_ns, reason=''): + joint = motion.reference_joints[0] if motion.phase == 'observer_preflight' else motion.zero_joints[0] + actions = observer_actions(self.owner.profile, joint) + previous, index = self.decisions.get(joint), 0 + if joint in self.decisions: + source = self.source(joint) + if source is None: + raise ValueError('observer_preparation_incomplete_checkpoint') + spec = self.owner.profile.measurement.measurements[joint] + coverage = normal_coverage(source.rows, spec.parent_role) + if not reason and not coverage['needs_excitation']: + return None + index = previous.get('action_index', 0)+1 + if index >= len(actions): + return None + plan = actions[index] + spec = self.owner.profile.measurement.measurements[joint] + rows = self.source(joint).rows if previous is not None else latest_source_rows(self.owner, joint, epoch) + coverage = (trajectory_observability(rows, spec.parent_role, spec.child_role) + if spec.observer_pose_policy == 'rigid_pair_trajectory_v3' + else normal_coverage(rows, spec.parent_role)) + utility = observation_action_utility(self.owner.profile, joint, plan, rows) + policy = (TRAJECTORY_POLICY if spec.observer_pose_policy == 'rigid_pair_trajectory_v3' + else POLICY if len(actions)==1 else SEQUENCE_POLICY) + record = dict(kind='observer_preparation_decision', policy=POLICY if len(actions)==1 else SEQUENCE_POLICY, joint=joint, + task_name=motion.task_key, session_epoch=epoch, stamp_ns=stamp_ns, + action='excite' if reason or coverage['needs_excitation'] else 'reuse_source', + reason=reason or 'normal_coverage_preflight', coverage=coverage, + source_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in rows}, + donor=plan.joint, path=[list(p) for p in (*plan.approach_commands, plan.command)]) + record.update(policy=policy, observability=coverage, action_utility=utility, + corner_evidence_sha256=corner_evidence_sha256(rows, (spec.parent_role, spec.child_role))) + if policy in {SEQUENCE_POLICY, TRAJECTORY_POLICY}: + record.update(action_index=index, action_limit=len(actions), + previous_preparation_id=None if previous is None else source_frame_sha256(previous)) + record['motion_authorization_required'] = True + self.observe(record) + return record + + def effects(self, motion, decision): + plan = observer_action(self.owner.profile, decision['joint'], decision) + identity = source_frame_sha256(decision) + return [MotionCommand('observer_probe', target, motion.speed, task_key=motion.task_key, + cycle=motion.cycle, command_index=channel_for_joint(self.owner.profile, plan.joint), + reference_joints=(decision['joint'],), observer_preparation_id=identity, + reference_path_index=i) for i, target in enumerate((*plan.approach_commands, plan.command))] + + def endpoint_error(self, motion, *, epoch, motion_version, stamp_ns): + from .observer_preparation_evidence import stationary_probe_tail + view = self.owner.profile.measurement.measurements[motion.reference_joints[0]].view + rows = sorted((r for (v, _), r in self.rows.get(motion.observer_preparation_id, {}).items() + if v == view and r['reference_path_index'] == motion.reference_path_index + and r['session_epoch'] == epoch and r['motion_version'] == motion_version), + key=lambda row: row['image_stamp_ns']) + if not rows or not 0 <= stamp_ns-rows[-1]['image_stamp_ns'] <= self.owner.profile.acquisition.visual_stale_seconds*1e9: + return 'observer_preparation_endpoint_stale' + try: + stationary_probe_tail(self.owner.profile, motion.reference_joints[0], rows, motion.target) + except ValueError as error: + return str(error) + return '' diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_preparation_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_preparation_evidence.py new file mode 100644 index 0000000..a4c8520 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_preparation_evidence.py @@ -0,0 +1,232 @@ +"""Independent raw-pixel evidence for a declared rigid observation excursion.""" +from dataclasses import asdict +import numpy as np + +from ..core.fitting.motion_fit import channel_for_joint +from ..core.geometry.tag_pose.ippe import solve_square_tag_ippe +from ..core.geometry.tag_pose.rigid_tag_pair import fit_rigid_tag_pair, RIGID_PAIR_CONDITIONING +from ..core.geometry.tag_pose.motion_evidence import MotionRelation +from ..core.geometry.tag_pose.pose_bridge import SharedTagPoseBridge, check_source_pose +from .motion_execution import feedback_tolerances +from .motion_provenance import source_frame_sha256 +from .shared_tag_reference import bridge_frames +from ..profiles.observer_preparation import observer_action, observer_actions +from ..profiles.observer_policy import TRAJECTORY_OBSERVER + + +def stationary_probe_tail(profile, joint, rows, target): + spec = profile.measurement.measurements[joint] + minimum = max(10, profile.acquisition.fixed_reference_minimum_frames) + tail = rows[-minimum:] + if (len(tail) < minimum or len({r['image_stamp_ns'] for r in tail}) != minimum + or tail[-1]['image_stamp_ns']-tail[0]['image_stamp_ns'] < 200_000_000 + or any(tuple(r.get('command_vector') or ()) != tuple(target) + or r.get('feedback_vector') is None + or not {spec.parent_role, spec.child_role} <= r['tags'].keys() for r in tail)): + raise ValueError('observer_preparation_endpoint_missing') + feedback = np.asarray([r['feedback_vector'] for r in tail]) + if not np.all(np.isfinite(feedback)) or np.any(np.ptp(feedback, axis=0) > feedback_tolerances(profile.command.unit).stability): + raise ValueError('observer_preparation_endpoint_unstable') + return tuple(tail) + + +def validate_probe_evidence(profile, joint, evidence, *, admission=None): + from .observer_preparation import POLICY, SEQUENCE_POLICY, TRAJECTORY_POLICY + decision, rows, segments = evidence.decision, evidence.rows, evidence.segments + plan = observer_action(profile, joint, decision) + identity = source_frame_sha256(decision) + if (decision.get('policy') in {SEQUENCE_POLICY, TRAJECTORY_POLICY} + and decision.get('action_limit') != len(observer_actions(profile, joint))): + raise ValueError('observer_preparation_action_budget_changed') + path = (*plan.approach_commands, plan.command) + spec = profile.measurement.measurements[joint] + if (decision.get('policy') not in {POLICY, SEQUENCE_POLICY, TRAJECTORY_POLICY} or decision.get('action') != 'excite' + or decision.get('joint') != joint or decision.get('donor') != plan.joint + or decision.get('task_name') != profile.motion.joint_zero_references[joint].task_key + or decision.get('path') != [list(p) for p in path] + or len(segments) != 3 or [s['path_index'] for s in segments] != [0, 1, 2] + or any(s.get('observer_preparation_id') != identity for s in segments)): + raise ValueError('observer_preparation_plan_changed') + stamps = [r['image_stamp_ns'] for r in rows] + if len(rows) < 24 or stamps != sorted(set(stamps)): + raise ValueError('observer_preparation_independent_images_missing') + started = evidence.started + first_motion = next((r for r in rows if r['reference_path_index'] == 1), None) + if (started is None or first_motion is None or started.get('observer_preparation_id') != identity + or started.get('session_epoch') != decision['session_epoch'] + or started.get('motion_version') != first_motion['motion_version'] + or not decision['stamp_ns'] < started['stamp_ns'] < first_motion['image_stamp_ns']): + raise ValueError('observer_preparation_motion_authorization_missing') + channel = channel_for_joint(profile, plan.joint) + from .preparation_samples import admit_preparation_rows, ADMISSION_POLICY + complete, rejected = admit_preparation_rows(profile, rows, + held_channels=(channel_for_joint(profile, joint),), target=plan.command, group_key='reference_path_index') + if admission is not None: + admission.update(policy=ADMISSION_POLICY, rejected_frames=list(rejected)) + lo, hi = sorted((path[0][channel], path[1][channel])) + for row in rows: + command, feedback = row.get('command_vector'), row.get('feedback_vector') + if (row.get('observer_preparation_id') != identity or row.get('observer_joint') != joint + or row.get('task_name') != decision['task_name'] or row.get('view') != spec.view + or row.get('session_epoch') != decision['session_epoch'] or row.get('sample_phase') != 'observer_probe' + or row.get('reference_path_index') not in (0, 1, 2) + or command is not None and (not lo <= command[channel] <= hi + or any(value != plan.command[i] for i, value in enumerate(command) if i != channel))): + raise ValueError('observer_preparation_held_posture_changed') + previous_end = decision['stamp_ns'] + for index, target in enumerate(path): + group = [r for r in rows if r['reference_path_index'] == index] + if not group or group[0]['image_stamp_ns'] <= previous_end: + raise ValueError('observer_preparation_path_discontinuous') + end = segments[index] + if (end.get('session_epoch') != decision['session_epoch'] + or any(r['motion_version'] != end['motion_version'] for r in group) + or not 0 <= end['stamp_ns']-group[-1]['image_stamp_ns'] <= profile.acquisition.visual_stale_seconds*1e9): + raise ValueError('observer_preparation_segment_identity_changed') + stationary_probe_tail(profile, joint, group, target) + values = [r['command_vector'][channel] for r in complete if r['reference_path_index'] == index] + start = path[max(0, index-1)][channel] + if np.any(np.diff(values)*np.sign(target[channel]-start) < 0): + raise ValueError('observer_preparation_path_changed') + previous_end = end['stamp_ns'] + # Sample by declared command intervals, keeping opposite directions + # separate. Repeated stationary frames cannot inflate geometric evidence. + selected = {} + for row in complete: + if row['reference_path_index'] in (1, 2): + value = row['command_vector'][channel] + key = row['reference_path_index'], round(128*(value-lo)/(hi-lo)) + if {spec.parent_role, spec.child_role} <= row['tags'].keys(): + selected[key] = row + return tuple(sorted(selected.values(), key=lambda row: row['image_stamp_ns'])) + + +def build_probe_bridge(profile, source): + spec = profile.measurement.measurements[source.joint] + if (len(source.parent_model.geometry) != 1 + or source.parent_model.geometry[0].relation.child_role != spec.parent_role): + raise ValueError('observer_parent_model_invalid') + admission = {} + rows = validate_probe_evidence(profile, source.joint, source.preparation, admission=admission) + endpoints = source.endpoint_rows[-max(10, profile.acquisition.fixed_reference_minimum_frames):] + if (len(endpoints) < 10 or not rows or rows[-1]['image_stamp_ns'] >= endpoints[0]['image_stamp_ns'] + or source.preparation.segments[-1]['stamp_ns'] >= endpoints[0]['image_stamp_ns']): + raise ValueError('observer_preparation_current_images_missing') + target = profile.motion.joint_zero_references[source.joint].command + if any(tuple(r.get('command_vector') or ()) != target for r in endpoints): + raise ValueError('observer_preparation_current_posture_changed') + # The recipient's relative installation must remain physically held. + held = source.held_channels + feedback = np.asarray([r['feedback_vector'] for r in (*source.preparation.rows, *endpoints) + if r.get('feedback_vector') is not None])[:, held] + if not np.all(np.isfinite(feedback)) or np.any(np.ptp(feedback, axis=0) > feedback_tolerances(profile.command.unit).stability): + raise ValueError('observer_distal_feedback_changed') + parents, children, matrices, parent_pixels, child_pixels = [], [], [], [], [] + tags = {t.role: t for v in profile.vision.views if v.name == spec.view for t in v.tags} + for row in rows: + if tuple(map(tuple, row['camera_matrix'])) != source.parent_model.camera_matrix: + raise ValueError('observer_camera_changed') + pair = [] + for role in (spec.parent_role, spec.child_role): + tag = row['tags'][role] + if tag['tag_id'] != tags[role].tag_id or tag['tag_size_m'] != tags[role].size_m: + raise ValueError('observer_image_identity_changed') + poses = tuple(p for p in solve_square_tag_ippe(np.asarray(tag['corners_xy']), + tag_size_m=tag['tag_size_m'], camera_matrix=np.asarray(row['camera_matrix'])) + if p.reprojection_error_px <= 1.5) + if not poses: + raise ValueError('observer_preparation_candidates_missing') + pair.append(poses) + parents.append(pair[0]); children.append(pair[1]); matrices.append(row['camera_matrix']) + parent_pixels.append(row['tags'][spec.parent_role]['corners_xy']) + child_pixels.append(row['tags'][spec.child_role]['corners_xy']) + plan = observer_action(profile, source.joint, source.preparation.decision) + donor_channel = channel_for_joint(profile, plan.joint) + trajectory_states = (tuple((row['reference_path_index'], row['command_vector'][donor_channel]) + for row in rows) if spec.observer_pose_policy == TRAJECTORY_OBSERVER else None) + pose = fit_rigid_tag_pair([p[0] for p in parents], children, child_pixels, matrices, + tags[spec.child_role].size_m, tuple(r['image_stamp_ns'] for r in rows), + parent_corners=parent_pixels, parent_size=tags[spec.parent_role].size_m, + parent_candidates=parents, trajectory_states=trajectory_states) + relation = MotionRelation(source.joint, spec.parent_role, spec.child_role) + bridge = SharedTagPoseBridge(relation, pose.quaternion_xyzw, pose.translation_xyz_m, + bridge_frames(endpoints, relation), rotation_uncertainty_rad=pose.rotation_uncertainty_rad, + translation_uncertainty_m=pose.translation_uncertainty_m, conditioning=RIGID_PAIR_CONDITIONING) + checked = check_source_pose(bridge) + if checked.status != 'consistent': + raise ValueError('rigid_pair_current_pose_unverified:'+checked.reason) + record = dict(joint=source.joint, version='observer_pose_bridge_v3', + parent_model_sha256=source.parent_report['image_model_sha256'], + parent_evidence_ids=source.parent_report['evidence_ids'], held_channels=list(held), pose=asdict(pose), + conditioning=RIGID_PAIR_CONDITIONING, preparation=source.preparation.decision, + admission=admission, + preparation_segments=list(source.preparation.segments), + preparation_started=source.preparation.started, + source_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in source.preparation.rows}, + endpoint_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in endpoints}) + if spec.observer_pose_policy == TRAJECTORY_OBSERVER: + from .observer_preparation import trajectory_observability, corner_evidence_sha256 + record.update(version='observer_pose_bridge_v4', trajectory_branch_decision={ + 'policy': 'rigid_pair_full_trajectory_v3', + 'selection_source': 'training_trajectory', + 'holdout_role': 'veto_only', + 'observability': trajectory_observability(rows, spec.parent_role, spec.child_role), + 'adjusted_candidate_probabilities': [list(value) + for value in pose.comparison_adjusted_p_values], + 'corner_evidence_sha256': corner_evidence_sha256( + source.preparation.rows, (spec.parent_role, spec.child_role)), + }) + return bridge, record + + +def validate_probe_reference(profile, records, payload, record, parent, observations): + from .observer_preparation import ObserverProbeEvidence + from .observer_reference import ObserverBridgeInput, _replay_rigid_recipient + from .parent_reference_evidence import source_epoch_matches + from ..core.geometry.image_motion_replay import frozen_image_model + from ..core.geometry.tag_pose.pose_bridge import check_pose_bridge + joint = record['joint'] + spec = profile.measurement.measurements[joint] + identity = source_frame_sha256(record['preparation']) + from .observer_preparation import ObserverPreparation + from types import SimpleNamespace + controller = ObserverPreparation(SimpleNamespace(profile=profile)) + controller.restore(records) + selected = controller.source(joint) + if selected is None or source_frame_sha256(selected.decision) != identity: + raise ValueError('observer_preparation_decision_changed') + if selected.started != record.get('preparation_started'): + raise ValueError('observer_preparation_motion_authorization_missing') + segments = sorted((r for r in records if r.get('kind') == 'observer_preparation_segment_complete' + and r.get('observer_preparation_id') == identity), key=lambda row: row['path_index']) + if segments != record['preparation_segments']: + raise ValueError('observer_preparation_segments_changed') + rows = sorted((r for r in records if r.get('kind') == 'image_observation_frame' + and r.get('view') == spec.view and r.get('observer_preparation_id') == identity), + key=lambda row: row['image_stamp_ns']) + if {str(r['image_stamp_ns']): source_frame_sha256(r) for r in rows} != record['source_frame_hashes']: + raise ValueError('observer_preparation_pixels_changed') + target = profile.motion.joint_zero_references[joint].command + endpoint_candidates = sorted((r for r in observations.values() + if all(r.get(k) == payload[k] for k in ('view', 'task_name', 'session_epoch', 'motion_version', 'zero_joints')) + and tuple(r.get('command_vector') or ()) == target and r.get('sample_phase') == 'zero_approach' + and r['image_stamp_ns'] not in payload['source_image_stamps'] + and r['image_stamp_ns'] <= max(payload['source_image_stamps'])), key=lambda r: r['image_stamp_ns']) + endpoints = tuple(endpoint_candidates[-max(10, profile.acquisition.fixed_reference_minimum_frames):]) + if {str(r['image_stamp_ns']): source_frame_sha256(r) for r in endpoints} != record['endpoint_frame_hashes']: + raise ValueError('observer_endpoint_sampling_changed') + if not endpoints or not source_epoch_matches(records, parent, payload['session_epoch'], + record['parent_evidence_ids'][spec.parent_role], endpoints[0]['image_stamp_ns']): + raise ValueError('observer_source_epoch_changed') + held = (channel_for_joint(profile, joint),) + if list(held) != record['held_channels']: + raise ValueError('observer_held_channels_changed') + source = ObserverBridgeInput(joint, frozen_image_model(parent), + {**parent, 'evidence_ids': record['parent_evidence_ids']}, (), endpoints, held, + ObserverProbeEvidence(record['preparation'], tuple(rows), tuple(segments), record['preparation_started'])) + bridge, reproduced = build_probe_bridge(profile, source) + if source_frame_sha256(reproduced) != source_frame_sha256(record): + raise ValueError('observer_pose_evidence_changed') + if check_pose_bridge(frozen_image_model(payload), bridge).status != 'consistent': + raise ValueError('observer_current_model_inconsistent') + _replay_rigid_recipient(payload, bridge, observations) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_reference.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_reference.py new file mode 100644 index 0000000..af0ac75 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/observer_reference.py @@ -0,0 +1,309 @@ +"""Optional descendant pixels from existing preparation movements only.""" + +from dataclasses import dataclass, asdict + +import numpy as np + +from ..core.geometry.tag_pose.motion_evidence import MotionRelation +from ..core.geometry.tag_pose.pose_bridge import SharedTagPoseBridge +from ..core.geometry.tag_pose.observer_pose import fit_observer_pose, require_observer_precision_budget +from ..core.geometry.tag_pose.image_motion_projection import select_image_motion_frame +from .branch_initialization import _pose +from .shared_tag_reference import bridge_frames +from .motion_execution import feedback_tolerances +from .motion_provenance import source_frame_sha256 +from ..profiles.observer_policy import is_rigid_observer, RIGID_OBSERVER + + +def observer_roles(profile, motion): + if motion.phase != 'zero_approach' or motion.reference_check or profile.vision_motion: + return set() + parents = {profile.measurement.measurements[n].child_role for n in motion.reference_joints} + return {spec.child_role for spec in profile.measurement.measurements.values() if spec.parent_role in parents} + + +@dataclass(frozen=True) +class ObserverBridgeInput: + joint: str + parent_model: object + parent_report: dict + rows: tuple + endpoint_rows: tuple + held_channels: tuple + preparation: object = None + + +def build_observer_bridge(profile, source): + if source.preparation is not None: + from .observer_preparation_evidence import build_probe_bridge + return build_probe_bridge(profile, source) + spec = profile.measurement.measurements[source.joint] + parent_model = source.parent_model + rows, held = source.rows, source.held_channels + if len(parent_model.geometry) != 1 or parent_model.geometry[0].relation.child_role != spec.parent_role: + raise ValueError('observer_parent_model_invalid') + uncertainty = {name: (angle, point) for name, angle, point in source.parent_report['geometry_uncertainty']} + inherited = uncertainty[parent_model.geometry[0].relation.joint] + rigid = is_rigid_observer(spec.observer_pose_policy) + if not rigid: + require_observer_precision_budget(inherited) + target = profile.motion.joint_zero_references[source.joint].command + minimum = max(10, profile.acquisition.fixed_reference_minimum_frames) + endpoints = source.endpoint_rows[-minimum:] + if len(rows) < 24 or len(endpoints) < minimum or not held: + raise ValueError('observer_images_missing') + if (max(r['image_stamp_ns'] for r in rows) >= min(r['image_stamp_ns'] for r in endpoints) + or endpoints[-1]['image_stamp_ns']-endpoints[0]['image_stamp_ns'] < 200_000_000): + raise ValueError('observer_current_images_missing') + combined = rows+endpoints + if (any(r['session_epoch'] != source.parent_report['session_epoch'] for r in rows) + or any(r['session_epoch'] != endpoints[0]['session_epoch'] for r in endpoints)): + raise ValueError('observer_source_epoch_changed') + if any(r.get('command_vector') is None or r.get('feedback_vector') is None + or r['view'] != spec.view or r['sample_phase'] != 'zero_approach' + or any(r['command_vector'][i] != target[i] for i in held) for r in combined): + raise ValueError('observer_held_posture_changed') + feedback = np.asarray([r['feedback_vector'] for r in combined])[:, held] + if not np.all(np.isfinite(feedback)) or np.any(np.ptp(feedback, axis=0) > feedback_tolerances(profile.command.unit).stability): + raise ValueError('observer_distal_feedback_changed') + parent_frames = bridge_frames(rows, parent_model.geometry[0].relation) + parents, candidates, corners, matrices, sizes = [], [], [], [], set() + expected_size = next(tag.size_m for view in profile.vision.views if view.name == spec.view + for tag in view.tags if tag.role == spec.child_role) + for row, frame in zip(rows, parent_frames): + if frame.camera_matrix != parent_model.camera_matrix: + raise ValueError('observer_camera_changed') + selected = select_image_motion_frame(parent_model, frame) + if not selected.resolved: + raise ValueError('observer_parent_pose_unresolved') + parents.append(next(s.pose for s in selected.selections if s.role == spec.parent_role)) + tag = row['tags'][spec.child_role] + if (tag['candidate_diagnostics']['observation_stamp_ns'] != row['image_stamp_ns'] + or tag['tag_size_m'] != expected_size): + raise ValueError('observer_image_identity_changed') + candidates.append(tuple(_pose(p) for p in tag['reprojection_valid_candidates'])) + corners.append(tag['corners_xy']) + sizes.add(tag['tag_size_m']) + matrices.append(row['camera_matrix']) + if len(sizes) != 1: + raise ValueError('observer_tag_size_changed') + from ..core.geometry.tag_pose.rigid_tag_pair import fit_rigid_tag_pair, RIGID_PAIR_CONDITIONING + fitter = fit_rigid_tag_pair if rigid else fit_observer_pose + complete_candidates = spec.observer_pose_policy == RIGID_OBSERVER + parent_candidates = (tuple(tuple(_pose(p) for p in row['tags'][spec.parent_role] + ['reprojection_valid_candidates']) for row in rows) if complete_candidates else None) + if complete_candidates and any(not candidates for candidates in parent_candidates): + raise ValueError('rigid_pair_parent_candidates_missing') + pose = fitter(parents, candidates, corners, matrices, sizes.pop(), + tuple(r['image_stamp_ns'] for r in rows), **({} if rigid else dict(inherited=inherited)), + **(dict(parent_candidates=parent_candidates) if complete_candidates else {}), + parent_corners=[r['tags'][spec.parent_role]['corners_xy'] for r in rows], + parent_size=dict(parent_model.tag_sizes)[spec.parent_role]) + relation = MotionRelation(source.joint, spec.parent_role, spec.child_role) + bridge = SharedTagPoseBridge(relation, pose.quaternion_xyzw, pose.translation_xyz_m, + bridge_frames(endpoints, relation), rotation_uncertainty_rad=pose.rotation_uncertainty_rad, + translation_uncertainty_m=pose.translation_uncertainty_m, + **(dict(conditioning=RIGID_PAIR_CONDITIONING) if rigid else {})) + if rigid: + from ..core.geometry.tag_pose.pose_bridge import check_source_pose + check = check_source_pose(bridge) + if check.status != 'consistent': + raise ValueError('rigid_pair_current_pose_unverified:'+check.reason) + record = dict(joint=source.joint, version='observer_pose_bridge_v2' if rigid else 'observer_pose_bridge_v1', + parent_model_sha256=source.parent_report['image_model_sha256'], + parent_evidence_ids=source.parent_report['evidence_ids'], held_channels=list(held), pose=asdict(pose), + source_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in rows}, + endpoint_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in endpoints}) + if rigid: + record['conditioning'] = RIGID_PAIR_CONDITIONING + if complete_candidates: + record['candidate_policy'] = 'all_raw_parent_child_ippe_v1' + from ..profiles.observer_policy import TRAJECTORY_OBSERVER + if spec.observer_pose_policy == TRAJECTORY_OBSERVER: + from .observer_preparation import trajectory_observability, corner_evidence_sha256 + record.update(version='observer_pose_bridge_v4', trajectory_branch_decision={ + 'policy': 'rigid_pair_full_trajectory_v3', + 'selection_source': 'training_trajectory', 'holdout_role': 'veto_only', + 'observability': trajectory_observability(rows, spec.parent_role, spec.child_role), + 'adjusted_candidate_probabilities': [list(value) + for value in pose.comparison_adjusted_p_values], + 'corner_evidence_sha256': corner_evidence_sha256( + rows, (spec.parent_role, spec.child_role)), + }) + return bridge, record + + +def observer_inputs(owner, view, endpoint_rows, arc_stamps, epoch): + result = [] + if owner.tag_feedback_channels is None or owner.profile.vision_motion: + return () + for joint in owner.zero_joints: + spec = owner.profile.measurement.measurements[joint] + if spec.view != view: + continue + sources = {(report['image_model_sha256']): (model, report) + for (source_epoch, source_view, _), (model, report) in owner.parent_references.models.items() + if source_epoch == epoch and source_view == view and model.image_model is not None + and len(model.image_model.geometry) == 1 + and model.image_model.geometry[0].relation.child_role == spec.parent_role} + for model, report in sorted(sources.values(), key=lambda pair: max(pair[1]['source_image_stamps']), reverse=True): + observed = owner.observer_records.get((report['session_epoch'], report['task_name'], view), {}) + rows = tuple(observed[stamp] for stamp in sorted(report['source_image_stamps']) + if stamp in observed and spec.child_role in observed[stamp]['tags']) + endpoints = tuple(r for r in endpoint_rows if r['image_stamp_ns'] not in arc_stamps) + preparation = owner.observer_preparation.source(joint) + if preparation is not None and len(endpoints) >= 10: + held = tuple(sorted(owner.tag_feedback_channels[spec.child_role]-owner.tag_feedback_channels[spec.parent_role])) + result.append(ObserverBridgeInput(joint, model.image_model, report, (), endpoints, held, preparation)) + break + if len(rows) < 24 or len(endpoints) < 10: + continue + held = tuple(sorted(owner.tag_feedback_channels[spec.child_role]-owner.tag_feedback_channels[spec.parent_role])) + result.append(ObserverBridgeInput(joint, model.image_model, report, rows, endpoints, held)) + if is_rigid_observer(spec.observer_pose_policy): + # Select the latest eligible source before fitting. A failed + # fit cannot search older sources for a more favorable result. + break + return tuple(result) + + +def restore_observer_records(owner, records): + """Restore only the bounded source frames of already verified models.""" + selected = {} + for _, report in owner.parent_references.models.values(): + key = report['session_epoch'], report['task_name'], report['view'] + selected.setdefault(key, set()).update(report['source_image_stamps']) + for row in records: + if row.get('kind') != 'motion_branch_observation': + continue + key = row['session_epoch'], row['task_name'], row['view'] + if row['image_stamp_ns'] in selected.get(key, ()): + owner.observer_records.setdefault(key, {})[row['image_stamp_ns']] = row + + +def validate_observer_channels(profile, records, source_model): + from ..profiles.observations import compile_tag_feedback_channels + channels = compile_tag_feedback_channels(profile, source_model) + for row in records: + for record in row.get('observer_pose_bridges', ()): + spec = profile.measurement.measurements[record['joint']] + expected = sorted(channels[spec.child_role]-channels[spec.parent_role]) + if list(record['held_channels']) != expected: + raise ValueError('observer_held_channels_changed') + + +def validate_observer_references(profile, records, evidence): + """Reconstruct the measured bridge from its bound raw images, never cache.""" + from ..core.geometry.image_motion_replay import frozen_image_model + from ..core.geometry.tag_pose.pose_bridge import check_pose_bridge + from ..core.fitting.motion_fit import channel_for_joint + from .parent_reference_evidence import source_epoch_matches + observations = {(r['view'], str(r['image_stamp_ns'])): r for r in records + if r.get('kind') == 'motion_branch_observation'} + checked = set() + for payload in evidence.values(): + required = {joint for joint, spec in profile.measurement.measurements.items() + if joint in payload['zero_joints'] and is_rigid_observer(spec.observer_pose_policy)} + declared = [r['joint'] for r in payload.get('observer_pose_bridges', ()) + if r.get('version') in {'observer_pose_bridge_v2', 'observer_pose_bridge_v3', + 'observer_pose_bridge_v4'}] + if set(declared) != required or len(declared) != len(required): + raise ValueError('rigid_pair_required_evidence_missing') + for payload in evidence.values(): + for record in payload.get('observer_pose_bridges', ()): + identity = source_frame_sha256(record), payload['image_model_sha256'] + if identity in checked: + continue + checked.add(identity) + joint = record['joint'] + spec = profile.measurement.measurements[joint] + parent_id = record['parent_evidence_ids'].get(spec.parent_role) + parent = evidence.get(parent_id) + if (parent is None or parent.get('image_model_sha256') != record['parent_model_sha256'] + or parent['view'] != payload['view'] or parent['tag_role'] != spec.parent_role): + raise ValueError('observer_parent_installation_changed') + for role, evidence_id in record['parent_evidence_ids'].items(): + if (evidence_id not in evidence or evidence[evidence_id]['tag_role'] != role + or evidence[evidence_id]['image_model_sha256'] != record['parent_model_sha256']): + raise ValueError('observer_parent_identity_changed') + if record.get('version') in {'observer_pose_bridge_v3', 'observer_pose_bridge_v4'}: + from .observer_preparation_evidence import validate_probe_reference + validate_probe_reference(profile, records, payload, record, parent, observations) + continue + if record.get('version') == 'observer_pose_bridge_v2': + eligible = [p for identity, p in evidence.items() + if p.get('view') == payload['view'] and p.get('tag_role') == spec.parent_role + and max(p['source_image_stamps']) < min(payload['source_image_stamps']) + and source_epoch_matches(records, p, payload['session_epoch'], identity, + min(payload['source_image_stamps'])) + and sum(spec.child_role in observations.get((spec.view, str(stamp)), {}).get('tags', {}) + for stamp in p['source_image_stamps']) >= 24] + if (not eligible or max(eligible, key=lambda p: max(p['source_image_stamps']))['image_model_sha256'] + != parent['image_model_sha256']): + raise ValueError('rigid_pair_latest_source_changed') + held = tuple(record['held_channels']) + expected = (channel_for_joint(profile, joint),) + if held != expected: + raise ValueError('observer_held_channels_changed') + groups = [] + eligible = {str(stamp) for stamp in parent['source_image_stamps'] + if (spec.view, str(stamp)) in observations + and spec.child_role in observations[(spec.view, str(stamp))].get('tags', {})} + if set(record['source_frame_hashes']) != eligible: + raise ValueError('observer_source_sampling_changed') + for field in ('source_frame_hashes', 'endpoint_frame_hashes'): + rows = [] + for stamp, digest in record[field].items(): + row = observations.get((spec.view, stamp)) + if row is None or source_frame_sha256(row) != digest: + raise ValueError('observer_source_pixels_changed') + if field == 'source_frame_hashes': + if (int(stamp) not in parent['source_image_stamps'] + or row['task_name'] != parent['task_name'] + or row['session_epoch'] != parent['session_epoch']): + raise ValueError('observer_parent_image_binding_changed') + elif (int(stamp) in payload['source_image_stamps'] + or row['task_name'] != payload['task_name'] + or row['session_epoch'] != payload['session_epoch'] + or row['motion_version'] != payload['motion_version']): + raise ValueError('observer_endpoint_binding_changed') + rows.append(row) + groups.append(tuple(sorted(rows, key=lambda r: r['image_stamp_ns']))) + target = profile.motion.joint_zero_references[joint].command + endpoint_candidates = sorted((r for r in observations.values() + if all(r.get(k) == payload[k] for k in ('view', 'task_name', 'session_epoch', 'motion_version', 'zero_joints')) + and tuple(r.get('command_vector') or ()) == target and r.get('sample_phase') == 'zero_approach' + and r['image_stamp_ns'] not in payload['source_image_stamps'] + and r['image_stamp_ns'] <= max(payload['source_image_stamps'])), key=lambda r: r['image_stamp_ns']) + expected_endpoints = endpoint_candidates[-max(10, profile.acquisition.fixed_reference_minimum_frames):] + if [r['image_stamp_ns'] for r in groups[1]] != [r['image_stamp_ns'] for r in expected_endpoints]: + raise ValueError('observer_endpoint_sampling_changed') + parent_report = {**parent, 'evidence_ids': record['parent_evidence_ids']} + if not groups[1] or not source_epoch_matches(records, parent, payload['session_epoch'], parent_id, + groups[1][0]['image_stamp_ns']): + raise ValueError('observer_source_epoch_changed') + bridge, reproduced = build_observer_bridge(profile, ObserverBridgeInput(joint, + frozen_image_model(parent), parent_report, *groups, held)) + if source_frame_sha256(reproduced) != source_frame_sha256(record): + raise ValueError('observer_pose_evidence_changed') + if check_pose_bridge(frozen_image_model(payload), bridge).status != 'consistent': + raise ValueError('observer_current_model_inconsistent') + if record['version'] == 'observer_pose_bridge_v2': + _replay_rigid_recipient(payload, bridge, observations) + + +def _replay_rigid_recipient(payload, bridge, observations): + """Bind the new constrained solver to all original recipient pixels too.""" + from ..core.geometry.tag_pose.production_image_motion import resolve_image_motion, image_parameters_for_sampling + from ..core.geometry.image_motion_replay import frozen_image_model + from ..core.geometry.tag_pose.image_motion_model import image_model_payload + model = frozen_image_model(payload) + frames = bridge_frames(tuple(observations[payload['view'], str(stamp)] + for stamp in payload['source_image_stamps']), bridge.relation) + result = resolve_image_motion(frames, model.relations, pose_bridges=(bridge,), + parameters=image_parameters_for_sampling(payload.get('image_sampling_policy')), + geometry_constraints=model.constraints, source_hinges=model.source_hinges, + source_urdf_sha256=model.source_urdf_sha256) + if (not result.resolved + or source_frame_sha256(image_model_payload(result.model)) != payload['image_model_sha256']): + raise ValueError('rigid_pair_recipient_model_changed') diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/optical_verification.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/optical_verification.py new file mode 100644 index 0000000..3504bfe --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/optical_verification.py @@ -0,0 +1,115 @@ +"""Recheck measured calibration-target corners against frozen camera models. + +This evaluates observations; a configuration digest or a user-supplied passed +flag is never an optical test. No intrinsic or extrinsic parameter is refitted. +""" +import numpy as np +import cv2 +from scipy.optimize import least_squares + +from ..core.domain.capture_plan import evidence_digest +from ..core.geometry.tag_pose.urdf_command_images import rigid +from ..core.geometry.tag_pose.parameters import DEFAULT_POSE_TRACKING_PARAMETERS + + +def accept_existing_camera_calibration(profile, path, expected_sha256): + """Explicit reuse of prior calibration, without claiming a fresh optical check.""" + import hashlib + from pathlib import Path + from ..core.geometry.extrinsics import load_camera_extrinsics + source = Path(path) + if hashlib.sha256(source.read_bytes()).hexdigest() != expected_sha256: + raise ValueError('existing_camera_calibration_changed') + calibrated = load_camera_extrinsics(source, required_views=profile.vision.view_names, + reference_view=profile.vision.extrinsic_reference_view, + quality_limits=profile.vision.extrinsics_quality_limits, + minimum_capture_counts=profile.vision.minimum_capture_counts) + return dict(policy='reuse_validated_camera_calibration_v1', accepted=True, + passed=False, current_optical_verification='not_performed', + camera_extrinsics_sha256=expected_sha256, prior_quality=dict(calibrated.quality), + intrinsics_updated=False, extrinsics_updated=False) + + +def verify_optical_observations(dataset, extrinsics, matrices, *, extrinsics_sha256): + if (dataset.get('protocol') != 'rectified_optical_check_v1' + or dataset.get('camera_extrinsics_sha256') != extrinsics_sha256 + or not isinstance(dataset.get('board_id'), str) or not dataset['board_id']): + raise ValueError('optical_observation_identity_invalid') + objects = np.asarray(dataset.get('object_points_m'), dtype=float) + if (objects.ndim != 2 or objects.shape[1] != 3 or len(objects) < 12 + or not np.all(np.isfinite(objects)) + or np.linalg.matrix_rank(objects-np.mean(objects, axis=0), tol=1e-6) < 2): + raise ValueError('optical_target_geometry_insufficient') + if set(matrices) != set(extrinsics.cameras): + raise ValueError('optical_camera_coverage_missing') + counts = {view: 0 for view in matrices} + corners, normals, errors, identities = {v: [] for v in matrices}, {v: [] for v in matrices}, [], set() + for capture in dataset.get('captures', ()): + observations = capture.get('views', {}) + if len(observations) < 2 or extrinsics.reference_view not in observations: + raise ValueError('optical_requires_simultaneous_cross_view_observations') + samples, stamps = {}, [] + for view, row in observations.items(): + if view not in matrices or row.get('serial_number') != extrinsics.cameras[view].serial_number: + raise ValueError('optical_camera_serial_changed') + stamp = row.get('image_stamp_ns') + if type(stamp) is not int or stamp <= 0 or (view, stamp) in identities: + raise ValueError('optical_image_identity_invalid') + identities.add((view, stamp)); stamps.append(stamp) + measured, matrix = np.asarray(row.get('corners_xy'), dtype=float), np.asarray(row.get('camera_matrix'), dtype=float) + if (measured.shape != (len(objects), 2) or not np.all(np.isfinite(measured)) + or not np.array_equal(matrix, matrices[view]) or row.get('input_is_rectified') is not True): + raise ValueError('optical_projection_or_observations_changed') + identity = extrinsics.cameras[view] + if np.any(measured < 0) or np.any(measured >= [identity.width, identity.height]): + raise ValueError('optical_target_corners_outside_image') + samples[view] = measured + if max(stamps)-min(stamps) > 50_000_000: + raise ValueError('optical_cross_view_images_not_synchronized') + reference = extrinsics.reference_view + ok, rotation, translation = cv2.solvePnP(objects, samples[reference], + np.asarray(matrices[reference], dtype=float), np.zeros(5), flags=cv2.SOLVEPNP_ITERATIVE) + if not ok: + raise ValueError('optical_board_pose_unresolved') + initial = np.r_[rotation.ravel(), translation.ravel()] + def residual(parameters): + pose = rigid(parameters) + values = [] + for view, measured in samples.items(): + camera = np.linalg.inv(extrinsics.transform(view)) @ pose + points = objects @ camera[:3, :3].T + camera[:3, 3] + if np.any(points[:, 2] <= 0): + return np.full(sum(len(v)*2 for v in samples.values()), 1e6) + projected = points @ np.asarray(matrices[view]).T + values.extend((projected[:, :2]/projected[:, 2:]-measured).ravel()) + return np.asarray(values) + fit = least_squares(residual, initial, max_nfev=200) + if not fit.success: + raise ValueError('optical_board_verification_budget_exhausted') + errors.extend(np.linalg.norm(fit.fun.reshape(-1, 2), axis=1).tolist()) + pose = rigid(fit.x) + for view, measured in samples.items(): + counts[view] += 1 + corners[view].extend(measured.tolist()) + camera = np.linalg.inv(extrinsics.transform(view)) @ pose + normals[view].append(camera[:3, 2]) + coverage = {} + for view, count in counts.items(): + if count < 15: + raise ValueError('optical_pose_coverage_insufficient:' + view) + identity = extrinsics.cameras[view] + span = np.ptp(np.asarray(corners[view]), axis=0)/[identity.width, identity.height] + attitudes = np.asarray(normals[view]) + singular = np.linalg.svd(attitudes-np.mean(attitudes, axis=0), compute_uv=False) + if min(span) < .35 or singular[1] < .1: + raise ValueError('optical_image_or_tilt_coverage_insufficient:' + view) + coverage[view] = dict(poses=count, image_span=span.tolist(), tilt_singular_values=singular.tolist()) + limit = DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px + rms = float(np.sqrt(np.mean(np.square(errors)))) + p95 = float(np.percentile(errors, 95)) + if rms > 1.2 or p95 > limit: + raise ValueError('optical_measured_reprojection_failed') + return dict(protocol='rectified_optical_check_v1', passed=True, + observations_sha256=evidence_digest(dataset), camera_extrinsics_sha256=extrinsics_sha256, + intrinsics_updated=False, extrinsics_updated=False, reprojection_rms_px=rms, + reprojection_p95_px=p95, coverage=coverage) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/parameters.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/parameters.py new file mode 100644 index 0000000..5ca83cf --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/parameters.py @@ -0,0 +1,50 @@ +"""Resolved runtime inputs, independent of ROS parameter and message types.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Mapping + +from ..core.geometry.extrinsics import CameraExtrinsics +from ..core.geometry.pnp import PoseTrackingParameters, SquareTagPoseTracker + + +@dataclass(frozen=True) +class DetectionPolicy: + maximum_hamming: int + minimum_decision_margin: float + minimum_edge_pixels: float + + +@dataclass(frozen=True) +class RuntimeParameters: + serial_number: str + session_dir: Path + source_urdf: Path + camera_extrinsics_file: Path + extrinsics: CameraExtrinsics + protected_inputs: Mapping[str, str] + resume_raw_samples_path: Path | None + command_topic: str + state_topic: str + setting_topic: str + camera_info_topics: Mapping[str, str] + detection_topics: Mapping[str, str] + commands_enabled: bool + speed_settle_seconds: float + torque_u8: int + maximum_state_image_skew_ns: int + command_rate_hz: float + tag_size_m: float + detection: DetectionPolicy + tracking: PoseTrackingParameters + diagnostic_capture: str = "" + initial_command: tuple[float, ...] = () + initial_device_uid: str = "" + resume_mode: str = "verify" + reuse_camera_calibration: bool = False + camera_optical_observations_file: Path | None = None + + def new_trackers(self, views): + return {view: SquareTagPoseTracker(**asdict(self.tracking)) for view in views} diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/parent_reference.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/parent_reference.py new file mode 100644 index 0000000..a019d70 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/parent_reference.py @@ -0,0 +1,255 @@ +"""Reuse a measured Tag installation only after checking its current held pose. + +Pose authorization and local hinge geometry are deliberately separate: an +upstream pose change invalidates the former, but not a rigid Tag's mounting. +No curve, joint zero or candidate selection is copied between joints. +""" + +from dataclasses import dataclass +import math + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.domain.reference import JointZeroSample +from ..core.geometry.tag_pose.source_hinge import SourceHinge +from .resume import ResumeVerifier + + +@dataclass(frozen=True) +class RefreshedPoseSource: + """Bind a refreshed model to its immutable source epoch across restarts.""" + + image_model_sha256: str + source_epoch: int + + +def check_parent_pose(profile, task, reference, rows, channels, *, + verification='staged_revisit_v1', feedback_limits=None): + """Same pure check for live execution and persisted evidence read-back.""" + from .revisit import LEGACY_REVISIT_POLICY, REVISIT_POLICY, revisit_feedback_limits + limits = revisit_feedback_limits(profile, verification) + if ((verification == REVISIT_POLICY and feedback_limits != limits) + or (verification == LEGACY_REVISIT_POLICY and feedback_limits is not None)): + raise ValueError('parent_reference_feedback_policy_changed') + name = task.parent_reference.pose_joint + spec = profile.measurement.measurements[name] + target = profile.motion.joint_zero_references[task.joints[0]].command + selected = [JointZeroSample.from_row(row, profile.command.unit) for row in rows] + old = [sample for sample in reference.samples if sample.view == spec.view] + if (reference.joint != name or not old + or len(selected) < profile.acquisition.fixed_reference_minimum_frames + or len({sample.sample_id for sample in selected}) != len(selected) + or any(sample.view != spec.view or sample.command != target for sample in selected) + or any(sample.command[index] != target[index] for sample in old for index in channels)): + raise ValueError("parent_reference_pose_contract_changed") + if min(sample.image_stamp_ns for sample in selected) <= max(sample.image_stamp_ns for sample in old): + raise ValueError("parent_reference_check_not_current") + if not profile.vision_motion: + before = np.asarray([sample.feedback for sample in old]) + after = np.asarray([sample.feedback for sample in selected]) + if (before.shape != (len(old), profile.command.command_count) + or after.shape != (len(selected), profile.command.command_count) + or not np.all(np.isfinite(before)) or not np.all(np.isfinite(after))): + raise ValueError("parent_reference_feedback_missing") + indices = sorted(channels) + if (np.any(np.ptp(after[:, indices], axis=0) > limits['within_hold_range']) + or np.any(np.abs(after[:, indices] - np.median(before[:, indices], axis=0)) + > limits['between_visit_difference'])): + raise ValueError("parent_reference_held_feedback_changed") + policy = ResumeVerifier() + for field in ("parent_pose_common", "child_pose_common"): + before = [getattr(sample, field) for sample in old] + after = [getattr(sample, field) for sample in selected] + rotation = Rotation.from_quat([pose.quaternion_xyzw for pose in before]).mean() + rotations = Rotation.from_quat([pose.quaternion_xyzw for pose in after]) + translations = np.asarray([pose.translation_xyz_m for pose in after]) + if (np.max((rotation.inv()*rotations).magnitude()) > policy.maximum_rotation_rad + or np.max(np.linalg.norm(translations - np.median( + [pose.translation_xyz_m for pose in before], axis=0), axis=1)) > policy.maximum_translation_m): + raise ValueError(f"parent_reference_pose_changed:{field}") + if (np.max((rotations.mean().inv()*rotations).magnitude()) > math.radians(1) + or np.max(np.linalg.norm(translations-np.median(translations, axis=0), axis=1)) > .001): + raise ValueError(f"parent_reference_not_stable:{field}") + + +class ParentReferenceRegistry: + """Accepted models are immutable and isolated by observation epoch.""" + + def __init__(self, profile, tag_feedback_channels): + self.profile = profile + self.channels = tag_feedback_channels + self.clear() + + def clear(self): + from .shared_pose_handoff import SharedPoseHandoff + self.handoff = SharedPoseHandoff(self.profile) + self.models = {} + self.verified = {} + self.zero_references = {} + self.refreshed_pose_sources = {} + + def remember_zero(self, reference, epoch): + for view in {sample.view for sample in reference.samples}: + self.zero_references[(epoch, view, reference.joint)] = reference + + def remember(self, model, report, *, epoch=None): + # An explicit passed-task restore binds the original installation to + # the new observation epoch while retaining its original source report. + epoch = report["session_epoch"] if epoch is None else epoch + if model.image_model is not None: + for geometry in model.image_model.geometry: + self.models[(epoch, model.view, geometry.relation.joint)] = (model, report) + + def advance_recovery_epoch(self, previous, current): + """An internal image retry invalidates callbacks, not rigid installations. + + Called only with the journalled recovery transition, never on pause, + restart or a physical-reference fault. Evidence keeps its original epoch. + """ + if current != previous+1: + raise ValueError("parent_reference_recovery_epoch_discontinuous") + self.handoff.advance_recovery_epoch(previous, current) + self.models.update({(current, view, joint): value + for (epoch, view, joint), value in tuple(self.models.items()) if epoch == previous}) + self.verified.update({(current, task): value + for (epoch, task), value in tuple(self.verified.items()) if epoch == previous}) + self.refreshed_pose_sources.update({(current, task): value + for (epoch, task), value in tuple(self.refreshed_pose_sources.items()) if epoch == previous}) + self.zero_references.update({(current, view, joint): value + for (epoch, view, joint), value in tuple(self.zero_references.items()) if epoch == previous}) + + def sources(self, task, epoch): + reference = task.parent_reference + try: + pose = self.models[(epoch, task.view, reference.pose_joint)] + geometry = self.models[(epoch, task.view, reference.geometry_joint)] + except KeyError as error: + raise ValueError("parent_reference_current_session_source_missing") from error + return pose, geometry + + def activate(self, task, epoch, capture): + model, _ = self.pose_source(task, epoch) + self.verified.pop((epoch, task.key), None) + capture.activate_reference_model(model) + + def pose_source(self, task, epoch): + """Use the latest explicitly handed-off model for the same rigid Tag. + + Keep comparing against the ORIGINAL pose joint's measured zero. This + changes the image model, never the accepted reference or its bounds. + """ + from ..core.geometry.tag_pose.pose_bridge import is_handoff_policy + pose, geometry = self.sources(task, epoch) + refreshed = self.refreshed_pose_sources.get((epoch, task.key)) + if refreshed is not None: + if (refreshed.image_model_sha256 != pose[1].get("image_model_sha256") + or refreshed.source_epoch != pose[1].get("session_epoch")): + raise ValueError("parent_reference_refreshed_pose_source_changed") + return pose + if not is_handoff_policy(geometry[1].get('image_model_selection_policy')): + return pose + bridges = geometry[1].get('shared_tag_pose_bridges', ()) + if not any(b.get('joint') == task.parent_reference.geometry_joint + and b.get('source_reference', {}).get('joint') == task.parent_reference.pose_joint + and b.get('source_model_sha256') == pose[1]['image_model_sha256'] for b in bridges): + raise ValueError('parent_reference_handoff_source_changed') + return geometry + + def authorize_refreshed_pose(self, task, epoch, version, reference): + """Prefer a freshly measured pose model while retaining passed geometry.""" + joint = task.parent_reference.pose_joint + model, report = self.models.get((epoch, task.view, joint), (None, None)) + if (model is None or report is None or report.get("session_epoch") != epoch + or model.image_model is None + or {item.relation.joint for item in model.image_model.geometry} != {joint}): + raise ValueError("parent_reference_refresh_model_missing_or_changed") + identity = report.get("image_model_sha256") + if not isinstance(identity, str) or not identity: + raise ValueError("parent_reference_refresh_model_missing_or_changed") + self.refreshed_pose_sources[(epoch, task.key)] = RefreshedPoseSource(identity, epoch) + from .motion_provenance import source_frame_sha256 + return {"kind": "parent_reference_model_refreshed", "schema_version": 1, + "task_name": task.key, "view": task.view, "pose_joint": joint, + "session_epoch": epoch, "motion_version": version, + "image_model_sha256": identity, + "source_zero_sha256": source_frame_sha256(reference.as_record()), + "passed_zero_preserved": True, + "source_frame_hashes": dict(report.get("source_frame_hashes", {}))} + + def restore_refreshed_pose(self, record, epoch): + """Restore an explicit refresh grant without relabelling its source.""" + task = next((item for item in self.profile.motion.tasks + if item.key == record.get("task_name")), None) + if (task is None or task.parent_reference is None + or record.get("schema_version") != 1 + or record.get("view") != task.view + or record.get("pose_joint") != task.parent_reference.pose_joint + or record.get("passed_zero_preserved") is not True + or type(record.get("session_epoch")) is not int): + raise ValueError("parent_reference_refresh_record_changed") + model, report = self.models.get((epoch, task.view, + task.parent_reference.pose_joint), (None, None)) + identity = record.get("image_model_sha256") + if (model is None or report is None or model.image_model is None + or identity != report.get("image_model_sha256") + or record["session_epoch"] != report.get("session_epoch") + or dict(record.get("source_frame_hashes", {})) + != dict(report.get("source_frame_hashes", {}))): + raise ValueError("parent_reference_refresh_model_missing_or_changed") + self.refreshed_pose_sources[(epoch, task.key)] = RefreshedPoseSource( + identity, record["session_epoch"]) + + def activate_joints(self, joints, epoch, capture): + installed = set() + for joint in joints: + spec = self.profile.measurement.measurements[joint] + try: + model, report = self.models[(epoch, spec.view, joint)] + except KeyError as error: + raise ValueError(f"revisit_frozen_model_missing:{joint}") from error + identity = report["image_model_sha256"] + if identity not in installed: + capture.activate_reference_model(model) + installed.add(identity) + + def confirm(self, task, epoch, version, reference, rows): + from .motion_provenance import source_frame_sha256 + from .revisit import REVISIT_POLICY, revisit_feedback_limits + model, report = self.pose_source(task, epoch) + role = self.profile.measurement.measurements[task.parent_reference.pose_joint].child_role + limits = revisit_feedback_limits(self.profile) + check_parent_pose(self.profile, task, reference, rows, self.channels[role], + verification=REVISIT_POLICY, feedback_limits=limits) + identity = dict(model.evidence_ids)[role] + for row in rows: + items = [item for item in row.get("pnp_observation_evidence", {}).values() if item.get("tag_role") == role] + if (len(items) != 1 or items[0].get("candidate_diagnostics", {}).get("motion_evidence_id") != identity + or items[0].get("image_model_sha256") != report["image_model_sha256"]): + raise ValueError("parent_reference_current_image_source_changed") + record = {"kind": "parent_reference_verified", "schema_version": 1, + "verification": REVISIT_POLICY, "feedback_limits": limits, + "task_name": task.key, "view": task.view, "session_epoch": epoch, "motion_version": version, + "pose_joint": reference.joint, "pose_evidence_id": identity, + "source_reference": reference.as_record(), "held_channels": sorted(self.channels[role]), + "source_frame_hashes": {str(row["image_stamp_ns"]): source_frame_sha256(row) for row in rows}} + from ..core.geometry.tag_pose.pose_bridge import is_handoff_policy + if is_handoff_policy(report.get('image_model_selection_policy')): + record.update(schema_version=2, pose_model_joint=task.parent_reference.geometry_joint, + pose_model_policy='shared_pose_handoff_parent_v1') + self.verified[(epoch, task.key)] = record + return record + + def geometry(self, task, epoch): + from .motion_provenance import source_frame_sha256 + if (epoch, task.key) not in self.verified: + raise ValueError("parent_reference_current_pose_unverified") + _, (model, report) = self.sources(task, epoch) + joint = task.parent_reference.geometry_joint + geometry = next(item for item in model.image_model.geometry if item.relation.joint == joint) + bounds = {item[0]: item[1:] for item in report.get("geometry_uncertainty", ())} + if joint not in bounds: + raise ValueError("parent_reference_source_uncertainty_missing") + source = SourceHinge(geometry, dict(model.evidence_ids)[geometry.relation.child_role], + report["image_model_sha256"], *bounds[joint]) + return (source,), source_frame_sha256(self.verified[(epoch, task.key)]) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/parent_reference_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/parent_reference_evidence.py new file mode 100644 index 0000000..37a7f64 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/parent_reference_evidence.py @@ -0,0 +1,164 @@ +"""Validate transferred installation geometry against its independent sources.""" + +from ..core.domain.reference import JointZeroSample, read_joint_zero_references +from ..core.geometry.image_motion_replay import frozen_image_model, replay_image_models, validate_image_sample +from .parent_reference import check_parent_pose + + +def same_capture_epoch(records, source, target, source_stamp, target_stamp): + """Only journalled internal zero retries may carry existing installations.""" + if source == target: + return True + links = [row for row in records + if row.get("kind") == "joint_zero_recovery" + and row.get("action") in {"repeat_approach", "retry_zero_images"} + and source_stamp < row.get("stamp_ns", 0) < target_stamp] + if not (type(source) is int and type(target) is int and 0 < source < target): + return False + for epoch in range(source, target): + candidates = [row for row in links if row.get("previous_session_epoch") == epoch] + if len(candidates) != 1: + return False + link = candidates[0] + if link.get("session_epoch") != epoch+1 or source_stamp >= link["stamp_ns"]: + return False + source_stamp = link["stamp_ns"] + return True + + +def source_epoch_matches(records, source, target_epoch, identity, target_stamp): + """Bind reused model identity through an explicit passed-task restoration.""" + source_stamp = max(source["source_image_stamps"]) + if same_capture_epoch(records, source["session_epoch"], target_epoch, source_stamp, target_stamp): + return True + for row in records: + authorized = (row.get("kind") == "passed_pose_models_restored" and row.get("resume_mode") == "passed" + and row.get("unchanged_installation_declared") is True) + authorized = authorized or (row.get("kind") == "staged_pose_models_restored" and row.get("resume_mode") == "verify" + and row.get("physical_zero_reverification_required") is True + and any(r.get("kind") == "resume_verification" and r.get("reuse") is True for r in records)) + if (not authorized + or not source_stamp < row.get("stamp_ns", 0) < target_stamp + or not same_capture_epoch(records, row.get("session_epoch"), target_epoch, + row["stamp_ns"], target_stamp)): + continue + if any(item.get("source_epoch") == source["session_epoch"] + and item.get("image_model_sha256") == source["image_model_sha256"] + and item.get("task_name") == source["task_name"] + and item.get("evidence_ids", {}).get(source["tag_role"]) == identity + for item in row.get("models", ())): + return True + return False + + +def validate_source_hinges(evidence, records=()): + for payload in evidence.values(): + if not payload.get("frozen_image_model"): + continue + model = frozen_image_model(payload) + for source in getattr(model, "source_hinges", ()): + original = evidence.get(source.evidence_id) + if (original is None or original.get("image_model_sha256") != source.model_sha256 + or original["view"] != payload["view"] + or not source_epoch_matches(records, original, payload["session_epoch"], + source.evidence_id, min(payload["source_image_stamps"])) + or max(original["source_image_stamps"]) >= min(payload["source_image_stamps"])): + raise ValueError("motion_branch_provenance_source_hinge_unbound") + geometry = {item.relation.joint: item for item in frozen_image_model(original).geometry} + bounds = {item[0]: tuple(item[1:]) for item in original.get("geometry_uncertainty", ())} + joint = source.geometry.relation.joint + if (geometry.get(joint) != source.geometry + or original["tag_role"] != source.geometry.relation.child_role + or bounds.get(joint) != (source.child_axis_uncertainty_rad, source.child_point_uncertainty_m)): + raise ValueError("motion_branch_provenance_source_hinge_changed") + + +def validate_parent_references(profile, records, evidence, *, source_model=None): + from .motion_provenance import source_frame_sha256 + from ..profiles.observations import compile_tag_feedback_channels + + tasks = {task.key: task for task in profile.motion.tasks} + checks = {source_frame_sha256(row): row for row in records if row.get("kind") == "parent_reference_verified"} + samples = {(row.get("view"), str(row.get("image_stamp_ns"))): row for row in records + if row.get("kind") == "joint_zero_sample"} + frames = {(row.get("view"), row.get("image_stamp_ns")): row for row in records + if row.get("kind") == "pnp_candidate_frame"} + checked = set() + channels = None if source_model is None else compile_tag_feedback_channels(profile, source_model) + for payload in evidence.values(): + model = frozen_image_model(payload) if payload.get("frozen_image_model") else None + if not getattr(model, "source_hinges", ()): + if payload.get("parent_reference_sha256"): + raise ValueError("parent_reference_unexpected_binding") + continue + identity = payload.get("parent_reference_sha256") + check = checks.get(identity) + task = tasks.get(payload["task_name"]) + if (check is None or task is None or task.parent_reference is None + or any(check.get(key) != payload.get(key) for key in ("task_name", "view")) + or not same_capture_epoch(records, check.get("session_epoch"), payload["session_epoch"], + max(map(int, check.get("source_frame_hashes", {"0": ""}))), min(payload["source_image_stamps"])) + or check.get("pose_joint") != task.parent_reference.pose_joint + or {s.geometry.relation.joint for s in model.source_hinges} != {task.parent_reference.geometry_joint} + or check.get("motion_version", 0) >= payload["motion_version"]): + raise ValueError("parent_reference_source_check_missing_or_changed") + if identity in checked: + continue + checked.add(identity) + name = task.parent_reference.pose_joint + spec = profile.measurement.measurements[name] + pose_source = evidence.get(check.get("pose_evidence_id")) + if (pose_source is None or pose_source["view"] != spec.view + or pose_source["tag_role"] != spec.child_role + or not source_epoch_matches(records, pose_source, check["session_epoch"], + check["pose_evidence_id"], min(map(int, check.get("source_frame_hashes", {"0": ""}))))): + raise ValueError("parent_reference_pose_source_unbound") + from ..core.geometry.tag_pose.pose_bridge import is_handoff_policy + if is_handoff_policy(pose_source.get('image_model_selection_policy')) != (check.get('schema_version', 1) == 2): + raise ValueError('parent_reference_handoff_policy_changed') + if check.get('schema_version', 1) == 2: + if (check.get('pose_model_policy') != 'shared_pose_handoff_parent_v1' + or check.get('pose_model_joint') != task.parent_reference.geometry_joint + or not is_handoff_policy(pose_source.get('image_model_selection_policy')) + or not any(b.get('joint') == task.parent_reference.geometry_joint + and b.get('source_reference', {}).get('joint') == name + for b in pose_source.get('shared_tag_pose_bridges', ())) + or any(s.model_sha256 != pose_source['image_model_sha256'] for s in model.source_hinges)): + raise ValueError('parent_reference_handoff_source_changed') + elif (check.get('schema_version', 1) != 1 or 'pose_model_policy' in check + or 'pose_model_joint' in check): + raise ValueError('parent_reference_handoff_policy_changed') + rows = [] + for stamp, digest in check.get("source_frame_hashes", {}).items(): + row = samples.get((spec.view, stamp)) + if (row is None or source_frame_sha256(row) != digest or row.get("joint") != name + or row.get("task_name") != task.key or int(stamp) >= min(payload["source_image_stamps"]) + or int(stamp) <= max(pose_source["source_image_stamps"])): + raise ValueError("parent_reference_check_image_changed") + item = next((item for item in row.get("pnp_observation_evidence", {}).values() + if item.get("tag_role") == spec.child_role), {}) + if (item.get("candidate_diagnostics", {}).get("motion_evidence_id") != check["pose_evidence_id"] + or item.get("image_model_sha256") != pose_source.get("image_model_sha256")): + raise ValueError("parent_reference_check_model_changed") + frame = frames.get((spec.view, int(stamp))) + if frame is None: + raise ValueError("parent_reference_check_pixels_missing") + validate_image_sample(row, frame, replay_image_models(frame)) + rows.append(row) + original = read_joint_zero_references(profile, [check["source_reference"]]).get(name) + if original is None: + raise ValueError("parent_reference_zero_source_changed") + for sample in original.samples: + row = samples.get((sample.view, str(sample.image_stamp_ns))) + frame = frames.get((sample.view, sample.image_stamp_ns)) + if (row is None or frame is None or JointZeroSample.from_row(row, profile.command.unit) != sample): + raise ValueError("parent_reference_zero_pixels_missing_or_changed") + validate_image_sample(row, frame, replay_image_models(frame)) + held = check.get("held_channels") + if (not isinstance(held, list) or not held or held != sorted(set(held)) + or any(type(index) is not int or not 0 <= index < profile.command.command_count for index in held) + or channels is not None and set(held) != channels[spec.child_role]): + raise ValueError("parent_reference_held_channels_changed") + check_parent_pose(profile, task, original, rows, held, + verification=check.get('verification', 'staged_revisit_v1'), + feedback_limits=check.get('feedback_limits')) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/passed_resume.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/passed_resume.py new file mode 100644 index 0000000..a5762ba --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/passed_resume.py @@ -0,0 +1,138 @@ +"""Reuse durable task passes under an explicit unchanged-installation policy. + +No historical image solver, sampling-quality calculation or physical zero +reverification runs here. New acquisitions and final artifact validation keep +their normal gates. An incomplete task is restarted as a whole. +""" + +from dataclasses import dataclass, field + +from ..core.domain.motion_path import record_scan_identity +from ..core.domain.reference import read_joint_zero_references +from .joint_resume import ResumeJournalImport, _index_motion_provenance + + +@dataclass +class PassedReferenceImport(ResumeJournalImport): + references: dict + model_records: tuple + restore_phase: str = field(default="binding", init=False) + restore_rows: tuple = field(default=(), init=False, repr=False) + restore_offset: int = field(default=0, init=False) + + +def coherent_observer_preparation_rows(rows): + """Discard transition fragments whose originating decision is absent. + + Compact checkpoints may contain a cancellation after an earlier migration + already removed the decision it cancelled. Such a fragment represents no + live state and cannot be replayed on its own. Decisions and all transitions + still present together remain byte-for-byte unchanged. + """ + from .motion_provenance import source_frame_sha256 + + decisions = {source_frame_sha256(row) for row in rows + if row.get("kind") == "observer_preparation_decision" + and row.get("action") == "excite"} + bound_kinds = {"observer_preparation_segment_complete", + "observer_preparation_excursion_started", + "observer_preparation_cancelled_before_excursion"} + return tuple(row for row in rows if row.get("kind") not in bound_kinds + or row.get("observer_preparation_id") in decisions) + + +def stage_passed_tasks(resume, engine, rows): + references = read_joint_zero_references(resume.profile, rows) + latest, support = {}, {} + for index, row in enumerate(rows): + if row.get("kind") == "scan_unit_complete": + key = record_scan_identity(row) + previous = latest.get(key) + if previous is None or int(row.get("attempt", 1)) >= int(previous[1].get("attempt", 1)): + latest[key] = index, row + elif row.get("kind") == "task_input_support_checked": + support[row.get("task_name")] = index, row.get("passed") is True + units, joints = set(), set() + for task in resume.profile.motion.tasks: + expected = {unit.identity for unit in engine.scan_units() if unit.task_key == task.key} + if (not expected or not set(task.joints) <= references.keys() + or any(latest.get(key, (-1, {}))[1].get("passed") is not True for key in expected) + or support.get(task.key, (-1, False))[1] is not True + or support[task.key][0] < max(latest[key][0] for key in expected)): + continue + units.update(expected) + joints.update(task.joints) + resume.references = {name: references[name] for name in joints} + resume.verified = set(joints) + resume.units, resume.rows = units, tuple(rows) + + +def reference_import(resume): + """Import prior evidence durably before skipping any completed task.""" + provenance = _index_motion_provenance(resume.rows) + references = resume.references + tasks = {reference.task_key for reference in references.values()} + parent_images = {(row["view"], int(stamp)) for row in provenance.values() + if row.get("kind") == "parent_reference_verified" + and row.get("task_name") in tasks for stamp in row["source_frame_hashes"]} + parent_images.update((sample["view"], sample["image_stamp_ns"]) + for row in provenance.values() if row.get("kind") == "parent_reference_verified" + and row.get("task_name") in tasks + for sample in row["source_reference"]["samples"]) + zero_images = parent_images | {(row.get("view"), row.get("image_stamp_ns")) + for row in provenance.values() if row.get("kind") == "joint_zero_sample" and row.get("joint") in references} + selected = [] + for row in provenance.values(): + # Passed mode restarts every incomplete task as a whole. Its old + # branch models and preparation images belong to an abandoned visit; + # restoring them would bind the new session's current image anchor to + # a previous camera epoch. Task-independent audit rows remain useful. + task_name = row.get("task_name") + if (task_name is not None and task_name not in tasks + and row.get("kind") != "task_observation_state"): + continue + image = row.get("view"), row.get("image_stamp_ns") + if (row.get("kind") in {"joint_zero_sample", "joint_zero_motion_reference_verified"} + and row.get("joint") not in references and image not in parent_images): + continue + if row.get("kind") == "pnp_candidate_frame" and image not in zero_images: + continue + selected.append(row) + selected = coherent_observer_preparation_rows(selected) + models = tuple(row for row in selected if row.get("kind") == "motion_branch_initialization" + and row.get("status") == "resolved" and row.get("task_name") in tasks) + audit = {"kind": "passed_tasks_reused", "resume_mode": "passed", + "unchanged_installation_declared": True, "tasks": sorted(tasks), + "joints": sorted(references), "completed_units": [list(key) for key in sorted(resume.units)], + "historical_replay_performed": False, "physical_zero_reverification_performed": False} + return PassedReferenceImport(rows=(*selected, + *(reference.as_record() for reference in references.values()), audit), + references=references, model_records=models) + + +def restore_parent_models(registry, records, epoch, provenance_records=()): + """Keep source identities while making passed installations available to new tasks.""" + from ..core.geometry.image_motion_replay import frozen_image_model + from .branch_initialization import MotionBranchModel + + for row in records: + if "frozen_image_model" not in row: + continue + model = MotionBranchModel(row["task_name"], row["view"], (), + tuple(sorted(row["evidence_ids"].items())), frozen_image_model(row)) + registry.remember(model, row, epoch=epoch) + latest_refreshes = {} + for row in provenance_records: + if row.get("kind") == "parent_reference_model_refreshed": + latest_refreshes[row.get("task_name")] = row + for record in latest_refreshes.values(): + registry.restore_refreshed_pose(record, epoch) + + +def restored_model_record(records, epoch, stamp_ns): + """Bind imported evidence to this session's declared unchanged installation.""" + return dict(kind='passed_pose_models_restored', session_epoch=epoch, stamp_ns=stamp_ns, + resume_mode='passed', unchanged_installation_declared=True, + models=[dict(task_name=row['task_name'], source_epoch=row['session_epoch'], + image_model_sha256=row['image_model_sha256'], evidence_ids=row['evidence_ids']) + for row in records if 'frozen_image_model' in row]) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/pose_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/pose_evidence.py new file mode 100644 index 0000000..56dfc14 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/pose_evidence.py @@ -0,0 +1,141 @@ +"""Diagnostic snapshots of the actual inputs and candidates used by capture. + +Evidence binds accepted images to confirmed, frozen branches; it never changes +the fitting formula or refits a reference. Camera matrices remain in the +session's rectified_camera_model records, indexed by view. +""" + +from collections.abc import Mapping, Sequence +from typing import Protocol + +import numpy as np + +from ..core.domain.profile import TagSpec +from ..core.geometry.pnp import SquareTagPose + + +class PoseDiagnostics(Protocol): + def observation_snapshot(self, role: str, stamp_ns: int) -> tuple[ + tuple[SquareTagPose, ...], dict, int + ] | None: ... + + +def _pose_payload(pose: SquareTagPose) -> dict: + return { + "quaternion_xyzw": list(pose.quaternion_xyzw), + "translation_xyz_m": list(pose.translation_xyz_m), + "reprojection_error_px": float(pose.reprojection_error_px), + } + + +def snapshot_pose_evidence( + tags: Mapping[str, TagSpec], + corners: Mapping[str, np.ndarray], + selected: Mapping[str, SquareTagPose], + tracker: PoseDiagnostics, + cached_roles: Sequence[str], + *, stamp_ns: int, + reference_revisions: Mapping[str, int] | None = None, +) -> dict[str, dict]: + evidence = {} + for role in sorted(selected.keys() | corners.keys()): + pose = selected.get(role) + tag = tags[role] + points = corners.get(role) + # estimate() only runs for present corners. A missing fixed Tag may + # use a frozen pose, but its tracker's previous candidates are not + # observations of this image and must never be copied into this row. + snapshot = None if points is None else tracker.observation_snapshot(role, stamp_ns) + candidates, diagnostics, corrections = snapshot if snapshot is not None else ((), {}, 0) + source = "cached_fixed_reference" if role in cached_roles else "current_image" + if pose is not None and diagnostics.get("fixed_reference_verified") is True: + source = "verified_fixed_reference" + if diagnostics.get("frozen_image_model") is not None: + # A shared hinge model produces a current-image constrained pose; + # it must never be described as one of the raw IPPE candidates. + source = "image_constrained_current_image" + if diagnostics.get("reference_frame") is not None: + from ..core.geometry.tag_pose.image_reference import IMAGE_REFERENCE_SOURCE + source = IMAGE_REFERENCE_SOURCE + evidence[role] = { + "tag_role": role, + "tag_id": tag.tag_id, + "tag_size_m": float(tag.size_m), + "pose_source": source, + "corners_xy": None if points is None else np.asarray(points, dtype=float).tolist(), + "selected_pose": None if pose is None else _pose_payload(pose), + # The tracker retains positive-depth candidates that pass its + # reprojection gate, before independent tilt/continuity selection. + "reprojection_valid_candidates": [_pose_payload(item) for item in candidates], + "candidate_diagnostics": dict(diagnostics), + "branch_corrections_total": int(corrections), + } + if source == "image_constrained_current_image": + evidence[role].update(frozen_image_model=diagnostics["frozen_image_model"], + image_model_sha256=diagnostics.get("image_model_sha256")) + if diagnostics.get("reference_frame") is not None: + evidence[role].update(reference_frame=diagnostics["reference_frame"], + reference_frame_sha256=diagnostics["reference_frame_sha256"], + reference_branch_revision=diagnostics["branch_revision"]) + if role in cached_roles: + evidence[role]["reference_branch_revision"] = (reference_revisions or {})[role] + elif source == "verified_fixed_reference": + evidence[role]["reference_branch_revision"] = diagnostics["branch_revision"] + return evidence + + +def reference_branch_revisions(rows: Sequence[Mapping], *, profile, + require_motion_evidence=False) -> dict[tuple[str, str], int]: + """Extract one confirmed physical-Tag revision from every reference image.""" + result = {} + for row in rows: + evidence = row.get("pnp_observation_evidence", {}) + if set(evidence) != {"parent", "child"}: + raise ValueError("joint_zero_branch_evidence_missing") + joint = row["joint"] + names = (joint, profile.measurement.cross_view_sources.get(joint)) + spec = next((profile.measurement.measurements[name] for name in names + if name is not None and profile.measurement.measurements[name].view == row["view"]), None) + if spec is None: + raise ValueError("joint_zero_branch_view_invalid") + for side, role in (("parent", spec.parent_role), ("child", spec.child_role)): + item = evidence[side] + if item.get("tag_role") != role: + raise ValueError("joint_zero_branch_tag_binding_changed") + source = item["pose_source"] + from ..core.geometry.tag_pose.image_reference import IMAGE_REFERENCE_SOURCE, reference_from_evidence + if source == IMAGE_REFERENCE_SOURCE: + if not any(tag.role == role and tag.fixed_reference for view in profile.vision.views + if view.name == row["view"] for tag in view.tags): + raise ValueError("joint_zero_image_reference_is_not_fixed") + reference_from_evidence(item, stamp_ns=row["image_stamp_ns"]) + if source in {"cached_fixed_reference", "verified_fixed_reference"}: + if not any(tag.role == role and tag.fixed_reference for view in profile.vision.views + if view.name == row["view"] for tag in view.tags): + raise ValueError("joint_zero_branch_cached_moving_tag") + revision = item.get("reference_branch_revision") + if source != "cached_fixed_reference": + diagnostics = item["candidate_diagnostics"] + if (diagnostics.get("observation_stamp_ns") != row["image_stamp_ns"] + or diagnostics.get("branch_status") != "tracking"): + raise ValueError("joint_zero_branch_observation_unconfirmed") + if source == "verified_fixed_reference" and ( + diagnostics.get("fixed_reference_verified") is not True + or revision != diagnostics.get("branch_revision")): + raise ValueError("joint_zero_fixed_reference_unverified") + revision = diagnostics.get("branch_revision") + key = (row["view"], item["tag_role"]) + fixed = any(tag.role == role and tag.fixed_reference for view in profile.vision.views + if view.name == row["view"] for tag in view.tags) + if require_motion_evidence and not fixed: + from ..core.domain.reference import JointZeroBranchReference + diagnostics = item.get("candidate_diagnostics", {}) + if diagnostics.get("motion_evidence_verified") is not True: + raise ValueError("joint_zero_motion_evidence_unconfirmed") + JointZeroBranchReference(*key, revision, diagnostics.get("motion_evidence_id")) + if isinstance(revision, bool) or not isinstance(revision, int) or revision < 0: + raise ValueError("joint_zero_branch_revision_invalid") + if key in result and result[key] != revision: + raise ValueError(f"joint_zero_branch_revision_changed:{key[0]}:{key[1]}") + result[key] = revision + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_samples.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_samples.py new file mode 100644 index 0000000..c383d33 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_samples.py @@ -0,0 +1,55 @@ +"""Admit synchronized preparation frames without hiding changed observations.""" +import numpy as np + +ADMISSION_POLICY = 'bounded_preparation_sync_v1' + + +def admit_preparation_rows(profile, rows, *, held_channels, target, group_key): + """Keep raw rows intact; missing values never become fabricated commands. + + Every available command/feedback is checked, including rejected images. + Missing samples must be bracketed within the same motion leg, occupy at + most the existing unobserved fraction, and span at most one steady window. + """ + from .motion_execution import feedback_tolerances + complete, rejected, feedback = [], [], [] + for row in rows: + missing = [] + for field in ('command_vector', 'feedback_vector'): + value = row.get(field) + if value is None: + missing.append(field) + continue + vector = np.asarray(value, dtype=float) + if vector.shape != (profile.command.command_count,) or not np.all(np.isfinite(vector)): + raise ValueError('preparation_state_vector_invalid') + if field == 'command_vector' and any(vector[i] != target[i] for i in held_channels): + raise ValueError('preparation_witness_held_posture_changed') + if field == 'feedback_vector': + feedback.append(vector) + if missing: + rejected.append({'image_stamp_ns': row['image_stamp_ns'], 'missing': missing}) + else: + complete.append(row) + if feedback and np.any(np.ptp(np.asarray(feedback)[:, held_channels], axis=0) + > feedback_tolerances(profile.command.unit).stability): + raise ValueError('preparation_witness_held_posture_changed') + if not rejected: + return tuple(complete), () + if len(rejected)/len(rows) > profile.acquisition.maximum_unobserved_fraction: + raise ValueError('preparation_sync_coverage_missing') + valid = {r['image_stamp_ns'] for r in complete} + for group in dict.fromkeys(r[group_key] for r in rows): + leg = [r for r in rows if r[group_key] == group] + if leg[0]['image_stamp_ns'] not in valid or leg[-1]['image_stamp_ns'] not in valid: + raise ValueError('preparation_sync_endpoint_missing') + previous, missing = leg[0]['image_stamp_ns'], False + for row in leg[1:]: + stamp = row['image_stamp_ns'] + if stamp not in valid: + missing = True + else: + if missing and stamp-previous > int(profile.acquisition.steady_window_seconds*1e9): + raise ValueError('preparation_sync_gap_too_long') + previous, missing = stamp, False + return tuple(complete), tuple(rejected) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_transition.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_transition.py new file mode 100644 index 0000000..70b9103 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_transition.py @@ -0,0 +1,248 @@ +"""Reuse a recorded single-channel posture change between shared-Tag tasks. + +This collector never commands motion and never retries a candidate. It retains +one bounded entry leg, before the current joint's own preparation. Selection is +by command bins and endpoint time, independently of fitting residuals. +""" + +from dataclasses import dataclass +import math + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.domain.reference import JointZeroReference +from ..core.geometry.image_motion_replay import frozen_image_model +from ..core.geometry.tag_pose.motion_evidence import MotionRelation +from ..core.geometry.tag_pose.image_motion_projection import select_image_motion_frame +from ..core.geometry.tag_pose.relative import _relative_pose +from ..core.geometry.tag_pose.transition_image_solver import PreparationTransition +from .shared_tag_reference import bridge_frames +from .motion_execution import feedback_tolerances +from .motion_provenance import source_frame_sha256 + + +class PreparationTransitionUnavailable(ValueError): + """Optional entry sampling is incomplete; no transition has been fitted.""" + + +@dataclass(frozen=True) +class TransitionSource: + joint: str + transition_joint: str + channel: int + relevant_channels: tuple + reference: JointZeroReference + source_report: dict + rows: tuple = () + + +def transition_source(profile, joint, epoch, registry, channels): + if channels is None or profile.vision_motion: + return None + from ..core.fitting.motion_fit import channel_for_joint + spec = profile.measurement.measurements[joint] + if not any(t.role == spec.parent_role and t.fixed_reference + for view in profile.vision.views if view.name == spec.view for t in view.tags): + return None + relevant = tuple(sorted(channels[spec.parent_role] | channels[spec.child_role])) + target = profile.motion.joint_zero_references[joint].command + candidates = [] + for (source_epoch, view, name), reference in registry.zero_references.items(): + previous = profile.measurement.measurements[name] + if (source_epoch != epoch or name == joint or view != spec.view + or (previous.parent_role, previous.child_role) != (spec.parent_role, spec.child_role)): + continue + samples = [s for s in reference.samples if s.view == view] + if not samples: + continue + changed = [i for i in relevant if samples[0].command[i] != target[i]] + if len(changed) != 1 or changed[0] == channel_for_joint(profile, joint): + continue + names = [name for name in profile.measurement.measurements + if channel_for_joint(profile, name) == changed[0]] + source = registry.models.get((epoch, view, reference.joint)) + if (len(names) != 1 or source is None or source[0].image_model is None + or len(source[0].image_model.geometry) != 1): + continue + candidates.append(TransitionSource(joint, names[0], changed[0], relevant, reference, source[1])) + return max(candidates, key=lambda c: max(s.image_stamp_ns for s in c.reference.samples)) if candidates else None + + +class PreparationTransitionCapture: + """One entry leg per task visit; resets on a changed task, epoch or reuse.""" + + def __init__(self, owner): + self.owner = owner + self.clear() + + def clear(self): + self.identity = None + self.source = None + self.rows = [] + self.version = None + self.error = "" + + def begin(self, motion, epoch): + if motion.phase not in {'zero_approach', 'joint_zero'} or motion.reference_reuse or motion.reference_check: + self.clear() + return + joints = motion.reference_joints if motion.phase == 'zero_approach' else motion.zero_joints + identity = motion.task_key, tuple(joints), epoch + if identity == self.identity: + return + self.clear() + self.identity = identity + if len(joints) == 1 and not motion.reference_only: + self.source = transition_source(self.owner.profile, joints[0], epoch, + self.owner.parent_references, self.owner.tag_feedback_channels) + + def observe(self, row): + if self.source is None or self.error: + return + spec = self.owner.profile.measurement.measurements[self.source.joint] + if (row.get('view') != spec.view or row.get('sample_phase') != 'zero_approach' + or (row.get('task_name'), tuple(row.get('zero_joints', ())), row.get('session_epoch')) != self.identity + or row.get('command_vector') is None or row.get('feedback_vector') is None): + return + channel = self.source.channel + before = next(s.command[channel] for s in self.source.reference.samples if s.view == spec.view) + if self.version is None: + if row['command_vector'][channel] != before: + return + self.version = row['motion_version'] + if row['motion_version'] != self.version: + return + if self.rows and row['image_stamp_ns'] <= self.rows[-1]['image_stamp_ns']: + self.error = 'preparation_transition_image_identity_changed' + elif len(self.rows) >= 512: + self.error = 'preparation_transition_frame_limit' + else: + self.rows.append(row) + + def snapshot(self, view): + from dataclasses import replace + if self.source is None or self.owner.profile.measurement.measurements[self.source.joint].view != view: + return None + if self.error: + raise ValueError(self.error) + # Absent optional entry data never create an invented bridge. + if not self.rows: + return None + return replace(self.source, rows=tuple(self.rows)) + + +def select_transition_rows(profile, rows, channel, before, after): + lower, upper = profile.command.minimum_values[channel], profile.command.maximum_values[channel] + bins = {} + for row in rows: + bins[round(128*(row['command_vector'][channel]-lower)/(upper-lower))] = row + starts = [r for r in rows if r['command_vector'][channel] == before][-10:] + endings = [r for r in rows if r['command_vector'][channel] == after][-10:] + selected = {r['image_stamp_ns']: r for r in (*bins.values(), *starts, *endings)} + return tuple(selected[k] for k in sorted(selected)), tuple(starts), tuple(endings) + + +def build_preparation_transition(profile, source, current_rows): + """Live and offline admission share physical, timing and identity checks.""" + from ..core.fitting.motion_fit import channel_for_joint + spec = profile.measurement.measurements[source.joint] + target = profile.motion.joint_zero_references[source.joint].command + rows = source.rows + old = tuple(s for s in source.reference.samples if s.view == spec.view) + if len(rows) < 24: + raise PreparationTransitionUnavailable('preparation_transition_samples_missing') + if len(old) < 10 or len(rows) > 512 or len(current_rows) < 24: + raise ValueError('preparation_transition_samples_missing') + parent_model = frozen_image_model(source.source_report) + identity = source.source_report['evidence_ids'].get(spec.child_role) + if (not any(b.view == spec.view and b.tag_role == spec.child_role and b.motion_evidence_id == identity + for b in source.reference.branch_references) + or len(parent_model.geometry) != 1 + or (parent_model.relations[0].parent_role, parent_model.relations[0].child_role) + != (spec.parent_role, spec.child_role)): + raise ValueError('preparation_transition_source_model_changed') + channel = source.channel + before, after = old[0].command[channel], target[channel] + held = tuple(i for i in source.relevant_channels if i != channel) + if (before == after or any(s.command[i] != target[i] for s in old for i in held) + or any(s.command[channel] != before for s in old)): + raise ValueError('preparation_transition_held_posture_changed') + stamps = [r['image_stamp_ns'] for r in rows] + current = sorted(current_rows, key=lambda r: r['image_stamp_ns']) + if (stamps != sorted(set(stamps)) or min(stamps) <= max(s.image_stamp_ns for s in old) + or max(stamps) >= current[0]['image_stamp_ns'] + or len({r['motion_version'] for r in rows}) != 1 + or rows[-1]['motion_version'] >= current[0]['motion_version']): + raise ValueError('preparation_transition_order_changed') + for row in (*rows, *current): + if (row.get('kind') != 'motion_branch_observation' or row.get('sample_phase') != 'zero_approach' + or row.get('cycle') == 3 or row['view'] != spec.view or row.get('input_is_rectified') is not True + or any(row.get(k) != current[0].get(k) for k in ('task_name', 'zero_joints', 'session_epoch')) + or row.get('command_vector') is None or row.get('feedback_vector') is None): + raise ValueError('preparation_transition_capture_identity_changed') + if any(any(r['command_vector'][i] != target[i] for i in held) for r in rows): + raise ValueError('preparation_transition_held_posture_changed') + commands = np.asarray([r['command_vector'][channel] for r in rows]) + if (commands[0] != before or commands[-1] != after + or np.any(np.diff(commands)*np.sign(after-before) < 0) + or np.any(commands < min(before, after)) or np.any(commands > max(before, after))): + raise ValueError('preparation_transition_path_changed') + feedback = np.asarray([r['feedback_vector'] for r in rows]) + old_feedback = np.asarray([s.feedback for s in old]) + tolerance = feedback_tolerances(profile.command.unit).stability + if np.ptp(feedback[:, channel]) < feedback_tolerances(profile.command.unit).minimum_travel: + raise ValueError('preparation_transition_feedback_did_not_move') + if (not np.all(np.isfinite(feedback)) or np.any(np.ptp(feedback[:, held], axis=0) > tolerance) + or np.any(np.abs(feedback[:, held]-np.median(old_feedback[:, held], axis=0)) > 2*tolerance)): + raise ValueError('preparation_transition_held_feedback_changed') + selected, starts, endings = select_transition_rows(profile, rows, channel, before, after) + if not starts or len(endings) < 10: + raise PreparationTransitionUnavailable('preparation_transition_endpoint_samples_missing') + if (endings[-1]['image_stamp_ns']-endings[0]['image_stamp_ns'] < 200_000_000 + or np.ptp([r['feedback_vector'][channel] for r in endings]) > tolerance + or any(abs(r['feedback_vector'][channel]-np.median(old_feedback[:, channel])) > 2*tolerance for r in starts)): + raise ValueError('preparation_transition_endpoints_unstable') + main_channel = channel_for_joint(profile, source.joint) + current_held = tuple(i for i in source.relevant_channels if i != main_channel) + ending_feedback = np.median([r['feedback_vector'] for r in endings], axis=0) + if any(r['command_vector'][i] != target[i] + or abs(r['feedback_vector'][i]-ending_feedback[i]) > 2*tolerance + for r in current for i in current_held): + raise ValueError('preparation_transition_current_posture_changed') + current_zeros = tuple(r['image_stamp_ns'] for r in current + if r['command_vector'][main_channel] == target[main_channel] + and abs(r['feedback_vector'][main_channel]-ending_feedback[main_channel]) <= tolerance) + relation = MotionRelation(source.transition_joint, spec.parent_role, spec.child_role) + if any(not all(role in r['tags'] for role in (spec.parent_role, spec.child_role)) for r in selected): + raise PreparationTransitionUnavailable('preparation_transition_pixels_missing') + frames = bridge_frames(selected, relation) + if any(f.camera_matrix != parent_model.camera_matrix or f.reference_frames != parent_model.reference_frames for f in frames): + raise ValueError('preparation_transition_camera_reference_changed') + rotation = Rotation.from_quat([s.relative_quaternion_xyzw for s in old]) + translation = np.asarray([s.relative_translation_xyz_m for s in old]) + if (np.max((rotation.mean().inv()*rotation).magnitude()) > math.radians(1) + or np.max(np.linalg.norm(translation-np.median(translation, axis=0), axis=1)) > .001): + raise ValueError('preparation_transition_source_zero_unstable') + point, orientation = np.median(translation, axis=0), rotation.mean() + # An old branch is rechecked on the actual, later shared starting posture. + # This does not authorize a new zero from these few stationary frames. + for frame in bridge_frames(starts, relation): + checked = select_image_motion_frame(parent_model, frame) + poses = {s.role: s.pose for s in checked.selections} + if not checked.resolved: + raise ValueError('preparation_transition_source_image_unresolved') + turn, position = _relative_pose(poses[spec.parent_role], poses[spec.child_role]) + if (orientation.inv()*turn).magnitude() > math.radians(2) or np.linalg.norm(position-point) > .005: + raise ValueError('preparation_transition_source_pose_changed') + transition = PreparationTransition(relation, frames, + tuple(0 if r['command_vector'][channel] == before else 1 if r['command_vector'][channel] == after else -1 for r in selected), + tuple(orientation.as_quat()), tuple(point), current_zeros) + record = dict(version='preparation_transition_v1', joint=source.joint, + transition_joint=source.transition_joint, channel=channel, relevant_channels=list(source.relevant_channels), + source_reference=source.reference.as_record(), source_evidence_id=identity, + source_model_sha256=source.source_report['image_model_sha256'], + source_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in rows}, + selected_image_stamps=[r['image_stamp_ns'] for r in selected], + current_zero_stamps=list(current_zeros)) + return transition, record diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_transition_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_transition_evidence.py new file mode 100644 index 0000000..b3b936e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_transition_evidence.py @@ -0,0 +1,123 @@ +"""Audit transition-conditioned preparation from immutable original records.""" + +from types import SimpleNamespace + +from ..core.domain.reference import JointZeroReference, JointZeroSample +from ..core.geometry.image_motion_replay import frozen_image_model, replay_image_models, validate_image_sample +from ..core.geometry.tag_pose.image_motion_model import image_model_payload +from ..core.geometry.tag_pose.transition_image_solver import TRANSITION_SELECTION_POLICY, resolve_transition_motion +from .motion_provenance import source_frame_sha256 +from .preparation_transition import TransitionSource, build_preparation_transition, transition_source +from .shared_tag_reference import bridge_frames + + +def check_transition_report(row): + transitions = row.get('preparation_transitions', ()) + if (row.get('image_model_selection_policy') == TRANSITION_SELECTION_POLICY) != bool(transitions): + raise ValueError('preparation_transition_selection_policy_changed') + if not transitions: + return + if len(transitions) != 1 or row.get('shared_tag_pose_bridges') or row.get('observer_pose_bridges'): + raise ValueError('preparation_transition_composition_changed') + selected = row.get('selected_hypothesis') + hypotheses = row.get('hypotheses', ()) + if type(selected) is not int or not 0 <= selected < len(hypotheses): + raise ValueError('preparation_transition_winner_missing') + winner = hypotheses[selected] + model = frozen_image_model(row) + if (winner.get('training_accepted') is not True or winner.get('converged') is not True + or winner.get('reason') or not winner.get('transition_branches') + or tuple(map(tuple, winner['branches'])) != model.branches + or row.get('geometry_uncertainty') != winner.get('child_frame_uncertainty') + or any(q['maximum_frame_rms_px'] > model.maximum_reprojection_error_px + for q in (*winner['training_quality'], *winner['validation_quality']))): + raise ValueError('preparation_transition_winner_changed') + + +def transition_inputs(records, evidence): + references = [r for r in records if r.get('kind') == 'joint_zero_reference'] + references.extend(r['current_reference'] for r in records if r.get('kind') == 'joint_zero_motion_reference_verified') + reference_hashes = {source_frame_sha256(r) for r in references} + observations = {(r['view'], str(r['image_stamp_ns'])): r for r in records + if r.get('kind') == 'motion_branch_observation'} + checked = set() + for payload in evidence.values(): + for record in payload.get('preparation_transitions', ()): + key = payload['image_model_sha256'], source_frame_sha256(record) + if key in checked: + continue + checked.add(key) + if record.get('version') != 'preparation_transition_v1': + raise ValueError('preparation_transition_version_changed') + ref = record.get('source_reference', {}) + if source_frame_sha256(ref) not in reference_hashes: + raise ValueError('preparation_transition_original_zero_missing') + reference = JointZeroReference.from_record(ref) + source = evidence.get(record.get('source_evidence_id')) + if (source is None or source.get('image_model_sha256') != record.get('source_model_sha256') + or source['view'] != payload['view'] or source['tag_role'] != payload['tag_role'] + or reference.joint not in source['zero_joints'] or record['joint'] not in payload['zero_joints']): + raise ValueError('preparation_transition_source_unbound') + rows = [] + for stamp, digest in record.get('source_frame_hashes', {}).items(): + row = observations.get((payload['view'], stamp)) + if row is None or source_frame_sha256(row) != digest: + raise ValueError('preparation_transition_source_pixels_changed') + rows.append(row) + rows.sort(key=lambda r: r['image_stamp_ns']) + if not rows: + raise ValueError('preparation_transition_sources_missing') + # Omitting inconvenient raw frames cannot change bin selection or + # hide a changed holding channel between selected observations. + complete = [r for r in observations.values() + if all(r.get(k) == rows[0].get(k) for k in ('task_name', 'view', 'zero_joints', 'session_epoch', 'motion_version')) + and r.get('command_vector') is not None and r.get('feedback_vector') is not None] + if {r['image_stamp_ns'] for r in complete} != {r['image_stamp_ns'] for r in rows}: + raise ValueError('preparation_transition_window_incomplete') + from .parent_reference_evidence import source_epoch_matches + if not source_epoch_matches(records, source, payload['session_epoch'], + record['source_evidence_id'], rows[0]['image_stamp_ns']): + raise ValueError('preparation_transition_source_epoch_changed') + report = dict(source, evidence_ids={payload['tag_role']: record['source_evidence_id']}) + prepared = TransitionSource(record['joint'], record['transition_joint'], record['channel'], + tuple(record['relevant_channels']), reference, report, tuple(rows)) + current = tuple(observations[(payload['view'], str(stamp))] for stamp in payload['source_image_stamps']) + yield payload, record, prepared, current + + +def validate_transition_topology(profile, records, evidence, source_model): + from ..profiles.observations import compile_tag_feedback_channels + channels = compile_tag_feedback_channels(profile, source_model) + for payload, record, prepared, _ in transition_inputs(records, evidence): + epoch = payload['session_epoch'] + registry = SimpleNamespace(zero_references={(epoch, payload['view'], prepared.reference.joint): prepared.reference}, + models={(epoch, payload['view'], prepared.reference.joint): + (SimpleNamespace(image_model=frozen_image_model(prepared.source_report)), prepared.source_report)}) + expected = transition_source(profile, record['joint'], epoch, registry, channels) + if (expected is None or (expected.channel, expected.transition_joint, expected.relevant_channels) + != (prepared.channel, prepared.transition_joint, prepared.relevant_channels)): + raise ValueError('preparation_transition_topology_changed') + + +def validate_preparation_transitions(profile, records, evidence): + samples = {(r['view'], r['image_stamp_ns']): r for r in records if r.get('kind') == 'joint_zero_sample'} + pixels = {(r['view'], r['image_stamp_ns']): r for r in records if r.get('kind') == 'pnp_candidate_frame'} + for payload, record, prepared, current in transition_inputs(records, evidence): + for sample in prepared.reference.samples: + row = samples.get((sample.view, sample.image_stamp_ns)) + frame = pixels.get((sample.view, sample.image_stamp_ns)) + if (row is None or frame is None or row.get('joint') != prepared.reference.joint + or JointZeroSample.from_row(row, profile.command.unit) != sample): + raise ValueError('preparation_transition_zero_pixels_missing') + validate_image_sample(row, frame, replay_image_models(frame)) + transition, reconstructed = build_preparation_transition(profile, prepared, current) + if source_frame_sha256(reconstructed) != source_frame_sha256(record): + raise ValueError('preparation_transition_sampling_changed') + model = frozen_image_model(payload) + frames = bridge_frames(current, model.relations[0]) + from ..core.geometry.tag_pose.production_image_motion import image_parameters_for_sampling + result = resolve_transition_motion(frames, model.relations, transition, + parameters=image_parameters_for_sampling(payload.get('image_sampling_policy'))) + if (not result.resolved + or source_frame_sha256(image_model_payload(result.model)) != payload['image_model_sha256']): + raise ValueError('preparation_transition_frozen_model_changed') diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_witness.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_witness.py new file mode 100644 index 0000000..4d311c8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_witness.py @@ -0,0 +1,350 @@ +"""Independent same-Tag pose witnesses at a task's declared avoidance posture. + +No commands, retries, SDK-to-angle conversion or validation-round samples live +here. Only the current finger is observed; other fingers retain their avoidance +commands. The source excitation is separate from the recipient preparation. +""" +from dataclasses import asdict, dataclass +import math + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.geometry.tag_pose.motion_evidence import MotionRelation +from ..core.geometry.tag_pose.pose_bridge import SharedTagPoseBridge +from ..core.geometry.tag_pose.production_image_motion import ImageMotionParameters, resolve_image_motion +from ..core.geometry.tag_pose.image_motion_projection import select_image_motion_frame +from ..core.geometry.tag_pose.image_motion_model import image_model_payload +from ..core.geometry.tag_pose.relative import _relative_pose +from .shared_tag_reference import bridge_frames +from .motion_execution import feedback_tolerances +from .motion_provenance import source_frame_sha256 + +WITNESS_POLICY = 'training_independent_preparation_witness_holm_v1' +CONDITIONED_WITNESS_POLICY = 'training_preparation_witness_shared_pose_holm_v1' +INDEPENDENT_WITNESS_POLICY = 'training_independent_witness_declined_v1' +MAXIMUM_WINDOW_FRAMES = 2048 + + +def witness_roles(profile, motion): + if motion.phase != 'zero_approach' or motion.reference_check or motion.reference_reuse: + return set() + donor = motion.preparation_witness_joint + if not donor: + return set() + specs = [profile.measurement.measurements[n] for n in (*motion.reference_joints, donor)] + return {role for spec in specs for role in (spec.parent_role, spec.child_role)} + + +@dataclass(frozen=True) +class WitnessInput: + joint: str + donor: str + rows: tuple + endpoint_rows: tuple + channels: tuple[int, ...] + + +class PreparationWitnessCapture: + """Bounded windows; sibling witnesses share the same immutable raw rows.""" + def __init__(self, owner): + self.owner = owner + self.clear() + + def clear(self): + self.windows = {} + self.paths = {} + + def observe(self, row): + profile = self.owner.profile + joints = tuple(row.get('zero_joints', ())) + if len(joints) != 1 or not row.get('preparation_witness_joint'): + return + witness = profile.motion.preparation_witnesses.get(joints[0]) + if (witness is None or witness.joint != row['preparation_witness_joint'] + or row.get('sample_phase') != 'zero_approach' or row.get('cycle') == 3 + or row['view'] != profile.measurement.measurements[joints[0]].view): + return + key = row['session_epoch'], row['task_name'], row['view'] + for previous in tuple(self.windows): + if previous[1:] == key[1:] and previous[0] < key[0]: + self.windows.pop(previous) + self.paths.pop(previous, None) + path = row.get('reference_path_index') + if path == 0 and self.paths.get(key, 0) > 0: + self.windows.pop(key, None) + if path is not None: + self.paths[key] = path + # Entering the first declared pose may move several holding channels. + if path is None or path < 1: + return + rows = self.windows.setdefault(key, []) + if len(rows) <= MAXIMUM_WINDOW_FRAMES: # One overflow marker, no unbounded growth. + rows.append(row) + + def inputs(self, view, joints, endpoints, arc_stamps, epoch): + result = [] + for joint in joints: + witness = self.owner.profile.motion.preparation_witnesses.get(joint) + spec = self.owner.profile.measurement.measurements[joint] + if witness is None or spec.view != view: + continue + task = self.owner.profile.motion.joint_zero_references[joint].task_key + windows = [(key, rows) for key, rows in self.windows.items() + if key[1:] == (task, view) and key[0] <= epoch] + rows = tuple(max(windows, key=lambda pair: pair[0][0])[1]) if windows else () + channels = self.owner.tag_feedback_channels + relevant = () if channels is None else tuple(sorted(channels[spec.parent_role] | channels[spec.child_role])) + result.append(WitnessInput(joint, witness.joint, rows, + tuple(r for r in endpoints if r['image_stamp_ns'] not in arc_stamps), relevant)) + return tuple(result) + + def endpoint_error(self, motion, epoch, now_ns): + """Gate departure using at most eleven images, never fit in a tick.""" + if not motion.preparation_witness_joint: + return '' + joint, = motion.reference_joints + witness = self.owner.profile.motion.preparation_witnesses[joint] + if motion.reference_path_index != len(witness.approach_commands): + return '' + view = self.owner.profile.measurement.measurements[joint].view + rows = self.windows.get((epoch, motion.task_key, view), ()) + try: + tail = stationary_witness_endpoint(self.owner.profile, joint, rows) + if not 0 <= now_ns-tail[-1]['image_stamp_ns'] <= self.owner.profile.acquisition.visual_stale_seconds*1e9: + raise ValueError('preparation_witness_stationary_endpoint_missing') + except ValueError as error: + return str(error) + return '' + + +def stationary_witness_endpoint(profile, joint, rows): + """The same uninterrupted terminal window gates live departure and replay.""" + from ..core.fitting.motion_fit import channel_for_joint + donor = profile.motion.preparation_witnesses[joint] + spec = profile.measurement.measurements[joint] + channel = channel_for_joint(profile, donor.joint) + relation = MotionRelation(donor.joint, spec.parent_role, spec.child_role) + tail = [] + for row in rows[-11:]: + try: + command, feedback = row.get('command_vector'), row.get('feedback_vector') + if (row.get('reference_path_index') != len(donor.approach_commands) + or command is None or feedback is None + or len(command) != profile.command.command_count or len(feedback) != len(command) + or not all(math.isfinite(v) for v in (*command, *feedback)) + or command[channel] != donor.command[channel]): + raise ValueError('incomplete endpoint observation') + bridge_frames((row,), relation) + except (KeyError, ValueError, TypeError): + tail.clear() + continue + tail.append(row) + stamps = [row['image_stamp_ns'] for row in tail] + if len(tail) < 10 or stamps != sorted(set(stamps)) or stamps[-1]-stamps[0] < 200_000_000: + raise ValueError('preparation_witness_stationary_endpoint_missing') + if np.ptp([r['feedback_vector'][channel] for r in tail]) > feedback_tolerances(profile.command.unit).stability: + raise ValueError('preparation_witness_endpoint_unstable') + return tuple(tail) + + +def select_witness_rows(profile, source, *, legacy=False, admission=None): + """Deterministic command bins and stationary tail, before any image fitting.""" + from ..core.fitting.motion_fit import channel_for_joint + spec = profile.measurement.measurements[source.joint] + donor = profile.motion.preparation_witnesses[source.joint] + if donor.joint != source.donor: + raise ValueError("preparation_witness_dependency_changed") + task_key = profile.motion.joint_zero_references[source.joint].task_key + channel = channel_for_joint(profile, source.donor) + rows = source.rows + if not 24 <= len(rows) <= MAXIMUM_WINDOW_FRAMES or not source.channels or channel not in source.channels: + raise ValueError('preparation_witness_source_missing_or_oversized') + stamps = [r['image_stamp_ns'] for r in rows] + if stamps != sorted(set(stamps)): + raise ValueError('preparation_witness_image_identity_changed') + first = rows[0] + for row in rows: + if (row.get('kind') != 'motion_branch_observation' or row.get('sample_phase') != 'zero_approach' + or row.get('input_is_rectified') is not True or row.get('cycle') == 3 + or row.get('task_name') != task_key or row.get('view') != spec.view + or row.get('session_epoch') != first['session_epoch'] + or tuple(row.get('zero_joints', ())) != (source.joint,) + or row.get('preparation_witness_joint') != source.donor + or type(row.get('reference_path_index')) is not int + or not 1 <= row['reference_path_index'] <= len(donor.approach_commands) + or legacy and (row.get('command_vector') is None or row.get('feedback_vector') is None)): + raise ValueError('preparation_witness_capture_identity_changed') + held = tuple(i for i in source.channels if i != channel) + target = profile.motion.joint_zero_references[source.joint].command + if any(donor.command[i] != target[i] for i in source.channels): + raise ValueError('preparation_witness_posture_not_shared') + raw_rows = rows + if not legacy: + if any(r['camera_matrix'] != first['camera_matrix'] for r in rows): + raise ValueError('preparation_witness_camera_reference_changed') + from .preparation_samples import ADMISSION_POLICY, admit_preparation_rows + rows, rejected = admit_preparation_rows(profile, rows, held_channels=held, + target=target, group_key='reference_path_index') + if admission is not None: + admission.update(policy=ADMISSION_POLICY, rejected_frames=list(rejected)) + feedback = np.asarray([r['feedback_vector'] for r in rows], dtype=float) + commands = np.asarray([r['command_vector'] for r in rows], dtype=float) + tolerance = feedback_tolerances(profile.command.unit).stability + if (feedback.shape != (len(rows), profile.command.command_count) or commands.shape != feedback.shape + or not np.all(np.isfinite(feedback)) or not np.all(np.isfinite(commands)) + or any(np.any(commands[:, i] != target[i]) for i in held) + or np.any(np.ptp(feedback[:, held], axis=0) > tolerance)): + raise ValueError('preparation_witness_held_posture_changed') + if np.ptp(feedback[:, channel]) < feedback_tolerances(profile.command.unit).minimum_travel: + raise ValueError('preparation_witness_feedback_did_not_move') + paths = [r['reference_path_index'] for r in raw_rows] + if paths != sorted(paths) or set(paths) != set(range(1, len(donor.approach_commands)+1)): + raise ValueError('preparation_witness_path_incomplete') + for index in sorted(set(paths)): + values = [r['command_vector'][channel] for r in rows if r['reference_path_index'] == index] + before = donor.approach_commands[index-1][channel] + after = (donor.approach_commands[index] if index < len(donor.approach_commands) else donor.command)[channel] + if np.any(np.diff(values)*np.sign(after-before) < 0): + raise ValueError('preparation_witness_path_changed') + bins = {} + lower, upper = profile.command.minimum_values[channel], profile.command.maximum_values[channel] + admitted_stamps = {r['image_stamp_ns'] for r in rows} + for row in raw_rows: + if row['image_stamp_ns'] not in admitted_stamps: + continue + index = row['reference_path_index'] + before = donor.approach_commands[index-1][channel] + after = (donor.approach_commands[index] if index < len(donor.approach_commands) else donor.command)[channel] + value = row['command_vector'][channel] + if not min(before, after) <= value <= max(before, after): + raise ValueError('preparation_witness_path_changed') + try: + bridge_frames((row,), MotionRelation(source.donor, spec.parent_role, spec.child_role)) + except (KeyError, ValueError, TypeError): + continue + bins[(index, round(128*(value-lower)/(upper-lower)))] = row + tail = stationary_witness_endpoint(profile, source.joint, raw_rows) + selected = {r['image_stamp_ns']: r for r in (*bins.values(), *tail)} + return tuple(selected[k] for k in sorted(selected)), tuple(tail) + + +def build_preparation_witness(profile, source, *, legacy=False, conditioned=None): + """Replayable source authorization and fresh same-posture verification.""" + from ..profiles.preparation import uses_declared_witness_path + if conditioned is None: + conditioned = not legacy and uses_declared_witness_path(profile, source.joint) + if conditioned and (legacy or not uses_declared_witness_path(profile, source.joint)): + raise ValueError('preparation_witness_conditioning_path_changed') + spec = profile.measurement.measurements[source.joint] + admission = {} + selected, old_endpoints = select_witness_rows(profile, source, legacy=legacy, admission=admission) + minimum = max(10, profile.acquisition.fixed_reference_minimum_frames) + endpoints = source.endpoint_rows[-minimum:] + if (len(endpoints) < minimum or max(r['image_stamp_ns'] for r in source.rows) >= endpoints[0]['image_stamp_ns'] + or endpoints[-1]['image_stamp_ns']-endpoints[0]['image_stamp_ns'] < 200_000_000 + or [r['image_stamp_ns'] for r in endpoints] != sorted({r['image_stamp_ns'] for r in endpoints})): + raise ValueError('preparation_witness_current_endpoint_missing') + target = profile.motion.joint_zero_references[source.joint] + for row in endpoints: + if (row.get('sample_phase') != 'zero_approach' or row.get('cycle') == 3 + or row.get('input_is_rectified') is not True or row.get('view') != spec.view + or row.get('task_name') != target.task_key or source.joint not in row.get('zero_joints', ()) + or any(row.get(k) != endpoints[0].get(k) for k in ('session_epoch', 'motion_version', 'zero_joints')) + or row.get('command_vector') is None or row.get('feedback_vector') is None + or any(row['command_vector'][i] != target.command[i] for i in source.channels)): + raise ValueError('preparation_witness_current_posture_changed') + old_feedback = np.asarray([r['feedback_vector'] for r in old_endpoints])[:, source.channels] + current_feedback = np.asarray([r['feedback_vector'] for r in endpoints])[:, source.channels] + from .revisit import revisit_feedback_limits + limits = revisit_feedback_limits(profile, 'staged_revisit_v2') + if (not np.all(np.isfinite(current_feedback)) or np.any(np.ptp(current_feedback, axis=0) > limits['within_hold_range']) + or np.any(np.abs(current_feedback-np.median(old_feedback, axis=0)) > limits['between_visit_difference'])): + raise ValueError('preparation_witness_reference_feedback_changed') + relation = MotionRelation(source.donor, spec.parent_role, spec.child_role) + frames = bridge_frames(selected, relation) + current_frames = bridge_frames(endpoints, MotionRelation(source.joint, spec.parent_role, spec.child_role)) + if any(f.camera_matrix != frames[0].camera_matrix or f.reference_frames != frames[0].reference_frames + for f in current_frames): + raise ValueError('preparation_witness_camera_reference_changed') + record = dict(version=('preparation_witness_v1' if legacy else + 'preparation_witness_v3' if conditioned else 'preparation_witness_v2'), + joint=source.joint, donor=source.donor, channels=list(source.channels), + source_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in source.rows}, + endpoint_frame_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in endpoints}, + selected_image_stamps=[r['image_stamp_ns'] for r in selected]) + if not legacy: + record['sample_admission'] = admission + if _insufficient_rotation_before_fit(frames, relation): + record.update(decision='independent_before_fit', reason='insufficient_rotation_evidence') + return None, record + result = resolve_image_motion(frames, (relation,), parameters=ImageMotionParameters(report_pose_uncertainty=True)) + if not result.resolved: + raise ValueError('preparation_witness_unobservable:'+result.reason) + winner = result.hypotheses[result.selected_hypothesis] + bounds = winner.preparation_pose_uncertainty + if len(bounds) != 2 or bounds[0] > math.radians(1) or bounds[1] > .001: + raise ValueError('preparation_witness_pose_uncertain') + source_endpoints = tuple(r for r in old_endpoints if r['image_stamp_ns'] in result.model.training_stamps_ns) + if not source_endpoints: + raise ValueError('preparation_witness_training_endpoint_missing') + poses = [] + for frame in bridge_frames(source_endpoints, relation): + checked = select_image_motion_frame(result.model, frame) + if not checked.resolved: + raise ValueError('preparation_witness_endpoint_unresolved') + by_role = {s.role: s.pose for s in checked.selections} + poses.append(_relative_pose(by_role[spec.parent_role], by_role[spec.child_role])) + rotations = Rotation.from_quat([r.as_quat() for r, _ in poses]) + points = np.asarray([t for _, t in poses]) + if (np.max((rotations.mean().inv()*rotations).magnitude()) > math.radians(1) + or np.max(np.linalg.norm(points-np.median(points, axis=0), axis=1)) > .001): + raise ValueError('preparation_witness_source_pose_unstable') + current_frames = bridge_frames(endpoints, MotionRelation(source.joint, spec.parent_role, spec.child_role)) + if any(f.camera_matrix != result.model.camera_matrix or f.reference_frames != result.model.reference_frames + for f in current_frames): + raise ValueError('preparation_witness_camera_reference_changed') + bridge = SharedTagPoseBridge(MotionRelation(source.joint, spec.parent_role, spec.child_role), + tuple(rotations.mean().as_quat()), tuple(np.median(points, axis=0)), current_frames, + rotation_uncertainty_rad=bounds[0], translation_uncertainty_m=bounds[1]) + # Independently validate the source on the *new* endpoint too. The + # recipient will still fit every family and keep its own arc holdout. + from ..core.geometry.tag_pose.pose_bridge import check_pose_bridge + from dataclasses import replace + if check_pose_bridge(result.model, replace(bridge, relation=relation)).status != 'consistent': + raise ValueError('preparation_witness_source_pose_changed') + if conditioned: + # The source has independently passed its arc holdout and explains + # the reserved current endpoint. Reuse the existing shared-zero fit; + # recipient arc/endpoint images remain independent of source training. + bridge = replace(bridge, source_model=result.model) + record['conditioning'] = bridge.conditioning + record.update( + source_model=image_model_payload(result.model), source_hypotheses=[asdict(h) for h in result.hypotheses], + selected_hypothesis=result.selected_hypothesis, pose_uncertainty=list(bounds), + quaternion_xyzw=list(bridge.quaternion_xyzw), translation_xyz_m=list(bridge.translation_xyz_m)) + from .branch_initialization import _finite_report + return bridge, _finite_report(record) + + +def _insufficient_rotation_before_fit(frames, relation): + """Decline only when every raw candidate fails the existing motion-span gate. + + No model is fitted or holdout loss inspected. Once auxiliary fitting starts, + its failure must veto; there is no second model choice based on its result. + """ + from itertools import product + from ..core.geometry.tag_pose.motion_image_diagnostics import _validate_frames, _pnp_diagnostics + paths, roles = _validate_frames(frames, (relation,), ImageMotionParameters()) + for indices in product(*(range(len(paths[role])) for role in roles)): + poses = {role: paths[role][index] for role, index in zip(roles, indices)} + if any(pose is None for path in poses.values() for pose in path): + return False # Missing candidates do not prove insufficient motion. + try: + _pnp_diagnostics(frames, (relation,), poses) + except ValueError as error: + if str(error) != 'insufficient_rotation_evidence': + return False + else: + return False + return True diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_witness_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_witness_evidence.py new file mode 100644 index 0000000..253dbc0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/preparation_witness_evidence.py @@ -0,0 +1,135 @@ +"""The live witness admission is also the publication and resume audit boundary.""" +from .preparation_witness import (WITNESS_POLICY, INDEPENDENT_WITNESS_POLICY, + CONDITIONED_WITNESS_POLICY, WitnessInput, build_preparation_witness) +from .motion_provenance import source_frame_sha256 + + +def check_witness_report(row): + records = row.get('preparation_witnesses', ()) + independent = row.get('image_model_selection_policy') == INDEPENDENT_WITNESS_POLICY + if bool(records) != (row.get('image_model_selection_policy') in { + WITNESS_POLICY, INDEPENDENT_WITNESS_POLICY, CONDITIONED_WITNESS_POLICY}): + raise ValueError('preparation_witness_selection_policy_changed') + if not records: + return + conditioned = any(r.get('conditioning') for r in records) + if conditioned != (row.get('image_model_selection_policy') == CONDITIONED_WITNESS_POLICY): + raise ValueError('preparation_witness_conditioning_policy_changed') + if any(r.get('conditioning') and (r.get('version') != 'preparation_witness_v3' + or r['conditioning'] != 'shared_zero_pose_v2') for r in records): + raise ValueError('preparation_witness_conditioning_policy_changed') + if any(row.get(k) for k in ('shared_tag_pose_bridges', 'observer_pose_bridges', 'preparation_transitions')): + raise ValueError('preparation_witness_composition_changed') + selected = row.get('selected_hypothesis') + hypotheses = row.get('hypotheses', ()) + if type(selected) is not int or not 0 <= selected < len(hypotheses): + raise ValueError('preparation_witness_winner_missing') + winner = hypotheses[selected] + if independent: + if (any(r.get('version') not in {'preparation_witness_v2', 'preparation_witness_v3'} or r.get('decision') != 'independent_before_fit' + or r.get('reason') != 'insufficient_rotation_evidence' for r in records) + or winner.get('pose_bridge_checks')): + raise ValueError('preparation_witness_independent_decision_changed') + if (not winner.get('training_accepted') or not winner.get('converged') or winner.get('reason') + or tuple(map(tuple, winner.get('branches', ()))) != tuple(map(tuple, row['frozen_image_model']['branches'])) + or winner.get('child_frame_uncertainty') != row.get('geometry_uncertainty') + or (not independent and not winner.get('pose_bridge_checks')) + or any(c['status'] != 'consistent' for c in winner['pose_bridge_checks'])): + raise ValueError('preparation_witness_winner_changed') + + +def witness_inputs(records, evidence): + observations = {(r['view'], str(r['image_stamp_ns'])): r for r in records + if r.get('kind') == 'motion_branch_observation'} + checked = set() + for payload in evidence.values(): + for record in payload.get('preparation_witnesses', ()): + key = payload['image_model_sha256'], source_frame_sha256(record) + if key in checked: + continue + checked.add(key) + if record.get('version') not in {'preparation_witness_v1', 'preparation_witness_v2', 'preparation_witness_v3'} or record.get('joint') not in payload['zero_joints']: + raise ValueError('preparation_witness_binding_changed') + groups = [] + for field in ('source_frame_hashes', 'endpoint_frame_hashes'): + rows = [] + for stamp, digest in record.get(field, {}).items(): + row = observations.get((payload['view'], stamp)) + if row is None or source_frame_sha256(row) != digest: + raise ValueError('preparation_witness_source_pixels_changed') + rows.append(row) + rows.sort(key=lambda r: r['image_stamp_ns']) + if not rows: + raise ValueError('preparation_witness_source_missing') + groups.append(tuple(rows)) + sources, endpoints = groups + first = sources[0] + visit = [r for r in observations.values() + if all(r.get(k) == first.get(k) for k in ('view', 'task_name', 'zero_joints', 'session_epoch')) + and r['image_stamp_ns'] < min(payload['source_image_stamps']) + and r.get('preparation_witness_joint') == record['donor']] + entered = max((r['image_stamp_ns'] for r in visit if r.get('reference_path_index') == 0), default=0) + complete = [r for r in visit if r.get('reference_path_index', 0) >= 1 and r['image_stamp_ns'] > entered] + if {r['image_stamp_ns'] for r in complete} != {r['image_stamp_ns'] for r in sources}: + raise ValueError('preparation_witness_window_incomplete') + if any(any(r.get(k) != payload.get(k) for k in ('view', 'task_name', 'zero_joints', 'session_epoch', 'motion_version')) + or r['image_stamp_ns'] in payload['source_image_stamps'] + or r['image_stamp_ns'] > max(payload['source_image_stamps']) for r in endpoints): + raise ValueError('preparation_witness_endpoint_binding_changed') + yield payload, record, WitnessInput(record['joint'], record['donor'], sources, endpoints, + tuple(record['channels'])) + + +def validate_witness_topology(profile, records, evidence, source_model): + from ..profiles.preparation import validate_preparation_witnesses + from ..profiles.observations import compile_tag_feedback_channels + validate_preparation_witnesses(profile, source_model) + channels = compile_tag_feedback_channels(profile, source_model) + for _, record, source in witness_inputs(records, evidence): + spec = profile.measurement.measurements[source.joint] + if (profile.motion.preparation_witnesses.get(source.joint) is None + or profile.motion.preparation_witnesses[source.joint].joint != source.donor + or tuple(sorted(channels[spec.parent_role] | channels[spec.child_role])) != source.channels): + raise ValueError('preparation_witness_topology_changed') + + +def validate_preparation_witnesses(profile, records, evidence): + from ..core.geometry.tag_pose.pose_bridge import check_pose_bridge + from ..core.geometry.tag_pose.production_image_motion import resolve_image_motion + from ..core.geometry.tag_pose.image_motion_model import image_model_payload + from ..core.geometry.image_motion_replay import frozen_image_model + from .shared_tag_reference import bridge_frames + observations = {(r['view'], r['image_stamp_ns']): r for r in records + if r.get('kind') == 'motion_branch_observation'} + for payload in evidence.values(): + expected = {joint for joint in payload['zero_joints'] if joint in profile.motion.preparation_witnesses + and profile.measurement.measurements[joint].view == payload['view']} + declared = [r.get('joint') for r in payload.get('preparation_witnesses', ())] + if set(declared) != expected or len(declared) != len(expected): + raise ValueError('preparation_witness_required_evidence_missing') + for payload, record, source in witness_inputs(records, evidence): + if (profile.motion.preparation_witnesses.get(source.joint) is None + or profile.motion.preparation_witnesses[source.joint].joint != source.donor): + raise ValueError('preparation_witness_dependency_changed') + bridge, reproduced = build_preparation_witness(profile, source, + legacy=record['version'] == 'preparation_witness_v1', + conditioned=record['version'] == 'preparation_witness_v3') + if record['version'] == 'preparation_witness_v1': + for old, new in zip(record.get('source_hypotheses', ()), reproduced.get('source_hypotheses', ())): + if 'training_solver_attempts' not in old: + new.pop('training_solver_attempts', None) + if source_frame_sha256(reproduced) != source_frame_sha256(record): + raise ValueError('preparation_witness_replay_changed') + model = frozen_image_model(payload) + if bridge is not None and check_pose_bridge(model, bridge).status != 'consistent': + raise ValueError('preparation_witness_current_model_inconsistent') + # Replay the recipient as well: an edited plausible model must not be + # published merely because its endpoint happens to match the witness. + frames = bridge_frames(tuple(observations[payload['view'], stamp] + for stamp in payload['source_image_stamps']), model.relations[0]) + from ..core.geometry.tag_pose.production_image_motion import image_parameters_for_sampling + result = resolve_image_motion(frames, model.relations, pose_bridges=() if bridge is None else (bridge,), + parameters=image_parameters_for_sampling(payload.get('image_sampling_policy'))) + if (not result.resolved + or source_frame_sha256(image_model_payload(result.model)) != payload['image_model_sha256']): + raise ValueError('preparation_witness_frozen_model_changed') diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/profile_contract.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/profile_contract.py new file mode 100644 index 0000000..97505dd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/profile_contract.py @@ -0,0 +1,50 @@ +"""Transfer session profile overrides and verify them before creating motion IO.""" + +from dataclasses import asdict, replace +import json +import math + +from ..core.domain.capture_plan import CapturePlan, configure_training +from ..core.domain.profile import ModelPreparation + + +def profile_launch_parameters(profile): + return { + "training_policy": profile.quality.training_policy, + "preparation_witnesses_json": json.dumps( + {name: asdict(value) for name, value in profile.motion.preparation_witnesses.items()}, + sort_keys=True, separators=(",", ":"), allow_nan=False), + "capture_plan_expected_sha256": CapturePlan.from_profile(profile).sha256, + } + + +def resolve_runtime_profile(profile, value): + """Legacy direct launches retain YAML values; runners send explicit overrides.""" + profile = configure_training(profile, value("training_policy")) + encoded = value("preparation_witnesses_json") + if encoded: + try: + payload = json.loads(encoded) + if not isinstance(payload, dict): + raise ValueError("expected an object") + witnesses = {} + for name, item in payload.items(): + if not isinstance(item, dict) or set(item) != {"joint", "command", "approach_commands"}: + raise ValueError("invalid preparation fields") + if not isinstance(item["joint"], str) or not isinstance(item["approach_commands"], list): + raise ValueError("invalid preparation identity or path") + poses = [item["command"], *item["approach_commands"]] + for pose in poses: + if (not isinstance(pose, list) or len(pose) != profile.command.command_count + or any(type(number) not in (int, float) or not math.isfinite(number) + for number in pose)): + raise ValueError("invalid preparation command") + witnesses[name] = ModelPreparation(item["joint"], tuple(item["command"]), + tuple(tuple(pose) for pose in item["approach_commands"])) + except (TypeError, ValueError) as error: + raise ValueError("invalid preparation_witnesses_json") from error + profile = replace(profile, motion=replace(profile.motion, preparation_witnesses=witnesses)) + expected = value("capture_plan_expected_sha256") + if expected and CapturePlan.from_profile(profile).sha256 != expected: + raise ValueError("runtime_capture_plan_mismatch: session overrides differ from runner") + return profile diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_completion.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_completion.py new file mode 100644 index 0000000..c68b589 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_completion.py @@ -0,0 +1,132 @@ +"""Seal acquisition independently from solving or publishing a calibration.""" +import hashlib +import json +from pathlib import Path + +from ..core.domain.capture_plan import (CapturePlan, RAW_PROTOCOL, FEEDBACK_RAW_PROTOCOL, + raw_feedback_capture) +from ..storage import atomic_write_json +from .engine import CalibrationEngine + + +POSE_PROTOCOL = 'measured_pose_samples_v1' + + +def file_digest(path): + with Path(path).open('rb') as stream: + return hashlib.file_digest(stream, 'sha256').hexdigest() + + +def implementation_digest(): + root = Path(__file__).resolve().parent.parent + digest = hashlib.sha256() + for path in sorted(root.rglob('*.py')): + digest.update(str(path.relative_to(root)).encode()) + digest.update(path.read_bytes()) + return digest.hexdigest() + + +def snapshot_capture_inputs(config, directory): + """Persist the effective product and protected files before any motion.""" + import yaml + directory = Path(directory) + product = yaml.safe_load(config.path.read_text()) + files = {} + for field, filename in (('source_urdf', 'capture_source.urdf'), + ('camera_extrinsics', 'capture_extrinsics.yaml'), + ('calibration_config', 'capture_calibration.yaml'), ('tag_config', 'capture_tags.yaml')): + source = Path(getattr(config, field)) + contents = source.read_bytes() + if hashlib.sha256(contents).hexdigest() != getattr(config, field+'_sha256'): + raise ValueError('capture_input_changed_before_start:' + field) + target = directory/filename + target.write_bytes(contents) + product['artifacts'][field] = str(target.resolve()) + files[filename] = file_digest(target) + from ..core.urdf.patch import materialize_relative_mesh_assets + import xml.etree.ElementTree as ET + for asset in materialize_relative_mesh_assets(source=config.source_urdf, output=directory.resolve(), + urdf_root=ET.parse(config.source_urdf).getroot()): + files[str(asset.relative_to(directory.resolve()))] = file_digest(asset) + profile = directory/'capture_profile.yaml' + if file_digest(profile) != config.profile_config_sha256: + raise ValueError('capture_profile_snapshot_changed') + product.update(profile_config=str(profile.resolve()), profile_config_sha256=config.profile_config_sha256, + output_root=str(config.output_root), resume_mode=config.resume_mode) + files[profile.name] = file_digest(profile) + for view, settings in config.cameras.items(): + target = directory/f'capture_intrinsics_{view}.yaml' + target.write_bytes(Path(settings['camera_info']).read_bytes()) + product['cameras'][view]['camera_info'] = str(target.resolve()) + files[target.name] = file_digest(target) + target = directory/'capture_product.yaml' + target.write_text(yaml.safe_dump(product, sort_keys=False, allow_unicode=True)) + files[target.name] = file_digest(target) + atomic_write_json(directory/'capture_inputs.json', dict(files=files, original_product=str(config.path))) + + +def _sealed_path(directory, name): + relative = Path(name) + path = (directory/relative).resolve() + if relative.is_absolute() or '..' in relative.parts or not path.is_relative_to(directory.resolve()): + raise ValueError('raw_capture_invalid_sealed_path:' + name) + return path + + +def save_capture_manifest(raw_path, *, profile, serial_number, protected_inputs, + completed_units, incomplete_units, retries, scheduled_units=None, + unobservable_tasks=None, incomplete_references=None): + from ..core.domain.capture_plan import raw_joint_capture + directory = raw_path.parent + files = {raw_path, *directory.glob(raw_path.stem + '.*'), + *directory.glob('imported_evidence_*.zlib'), *directory.glob('capture_*.yaml'), + *directory.glob('capture_source.urdf'), *directory.glob('capture_inputs.json')} + snapshot = directory/'capture_inputs.json' + if snapshot.exists(): + files.update(_sealed_path(directory, name) for name in json.loads(snapshot.read_text())['files']) + units = tuple(scheduled_units) if scheduled_units is not None else CalibrationEngine(profile).scan_units() + manifest = dict(protocol=(RAW_PROTOCOL if raw_joint_capture(profile) else + FEEDBACK_RAW_PROTOCOL if raw_feedback_capture(profile) else POSE_PROTOCOL), + capture_finished=True, returned_to_baseline=True, + raw_capture_complete=(len(completed_units) == len(units) and not incomplete_units + and not unobservable_tasks and not incomplete_references), + incomplete_references=[dict(task=task, cycle=cycle, **details) + for (task, cycle), details in sorted((incomplete_references or {}).items())], + unobservable_tasks=[dict(task=task, cycle=cycle, reason=reason) + for (task, cycle), reason in sorted((unobservable_tasks or {}).items())], + accuracy_passed=False, publication_allowed=False, automatic_geometry_recapture=False, + serial_number=serial_number, capture_plan=CapturePlan.from_profile(profile).as_dict(), + protected_inputs=dict(protected_inputs), implementation_sha256=implementation_digest(), + units=[dict(identity=list(unit.identity), attempts=1+retries.get(unit.identity, 0), + passed=unit.identity in completed_units, + failures=list(incomplete_units.get(unit.identity, {}).get('failures', ()))) for unit in units], + files={str(p.resolve().relative_to(directory.resolve())): file_digest(p) + for p in sorted(files) if p.is_file()}) + atomic_write_json(directory / 'raw_capture_manifest.json', manifest) + return manifest + + +def verify_capture_manifest(raw_path): + raw_path = Path(raw_path) + manifest = json.loads((raw_path.parent / 'raw_capture_manifest.json').read_text()) + if (manifest.get('protocol') not in {RAW_PROTOCOL, FEEDBACK_RAW_PROTOCOL, POSE_PROTOCOL} or manifest.get('capture_finished') is not True + or manifest.get('returned_to_baseline') is not True + or raw_path.name not in manifest.get('files', {})): + raise ValueError('raw_capture_manifest_invalid') + for name, digest in manifest['files'].items(): + if file_digest(_sealed_path(raw_path.parent, name)) != digest: + raise ValueError('raw_capture_sealed_file_changed:' + name) + return manifest + + +def finish_capture(session): + """Report sealed acquisition after shutdown; never import a solver.""" + session = Path(session) + manifest = verify_capture_manifest(session/'raw_samples.jsonl') + result = dict(capture_finished=True, raw_capture_complete=manifest['raw_capture_complete'], + control_closed=True, fit_started=False, accuracy_passed=False, publication_allowed=False, + automatic_recapture=False, raw_samples=str(session/'raw_samples.jsonl')) + atomic_write_json(session/'capture_result.json', result) + print(f"采集结束,控制栈已关闭;数据完整:{result['raw_capture_complete']}。" + f"原始数据:{result['raw_samples']};请使用 --offline-raw 单独拟合。", flush=True) + return 0 if result['raw_capture_complete'] else 3 diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_evidence.py new file mode 100644 index 0000000..428a09b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_evidence.py @@ -0,0 +1,114 @@ +"""Immutable, partitioned inputs for the raw-image calibration protocol.""" +from collections import defaultdict +from dataclasses import dataclass + +from ..core.domain.capture_plan import CapturePlan, RAW_PROTOCOL, raw_joint_capture, evidence_digest +from ..core.domain.motion_path import record_scan_identity +from ..core.geometry.frozen_evidence import freeze_evidence +from .engine import CalibrationEngine +from .raw_quality import evaluate_raw_unit + + +@dataclass(frozen=True) +class RawCalibrationEvidence: + training: tuple + validation: tuple + completed_units: tuple + sha256: str + missing_units: tuple = () + capture_plan: dict | None = None + reassessed_units: tuple = () + + +def partition_raw_capture(profile, records, *, require_complete=True, reassess_quality=False): + """Recompute image coverage; a persisted passed flag is never sufficient.""" + if not raw_joint_capture(profile): + raise ValueError('raw_capture_protocol_required') + headers = [r for r in records if r.get('kind') == 'session_start'] + plans = [CapturePlan.from_profile(profile).as_dict(legacy_raw=legacy) for legacy in (False, True)] + if len(headers) != 1 or headers[0].get('capture_plan') not in plans: + raise ValueError('raw_capture_plan_mismatch') + plan = headers[0]['capture_plan'] + protocol = plan['observation_protocol']['version'] + reassess_quality = reassess_quality and protocol == RAW_PROTOCOL + units = {u.identity: u for u in CalibrationEngine(profile).scan_units()} + completions, groups, identities = {}, defaultdict(list), set() + latest_attempts = {} + for row in records: + kind = row.get('kind') + if kind in {'joint_sample', 'joint_zero_sample', 'diagnostic_observation_frame'}: + raise ValueError('raw_capture_mixed_authorization_protocol') + if kind not in {'raw_observation_frame', 'scan_unit_complete'}: + continue + unit = record_scan_identity(row) + if unit not in units: + raise ValueError('raw_capture_unknown_unit') + attempt = row.get('attempt') + if type(attempt) is not int or attempt not in (1, 2): + raise ValueError('raw_capture_retry_budget_changed') + if attempt < latest_attempts.get(unit, 1): + raise ValueError('raw_capture_attempt_order_invalid') + latest_attempts[unit] = attempt + if kind == 'scan_unit_complete': + if attempt <= completions.get(unit, {}).get('attempt', 0): + raise ValueError('raw_capture_completion_order_invalid') + completions[unit] = row + continue + if row.get('observation_protocol', 'raw_joint_images_v1') != protocol: + raise ValueError('raw_capture_mixed_observation_protocol') + identity = row.get('view'), row.get('image_stamp_ns') + if (identity in identities or type(identity[1]) is not int or identity[1] <= 0 + or identity[0] not in profile.vision.view_names): + raise ValueError('raw_capture_image_identity_invalid') + identities.add(identity) + if row.get('is_accepted_joint_sample') is not False or row.get('input_is_rectified') is not True: + raise ValueError('raw_capture_image_contract_changed') + groups[unit, attempt].append(row) + accepted, selected, failures, spans, reassessed = [], [], {}, {}, [] + for identity, unit in units.items(): + completion = completions.get(identity) + if (completion is None or (completion.get('passed') is not True and not reassess_quality) + or 'interrupted_attempt' in completion.get('failures', ()) + or completion['attempt'] != latest_attempts[identity]): + failures[str(identity)] = ('scan_incomplete',) + continue + rows = groups[identity, completion['attempt']] + quality = evaluate_raw_unit(profile, unit, completion['attempt'], rows, first_cycle_spans=spans) + if not quality.passed: + failures[str(identity)] = quality.failures + continue + if completion.get('passed') is not True: + reassessed.append(dict(unit=list(identity), attempt=completion['attempt'], + recorded_failures=list(completion.get('failures', ())), + policy='sent_command_endpoints_and_declared_segment_feedback_density', + recomputed_metrics=dict(quality.metrics))) + accepted.append(identity) + selected.extend(rows) + if failures and require_complete: + raise ValueError('raw_capture_incomplete:' + str(failures)) + selected.sort(key=lambda r: (r['image_stamp_ns'], r['view'])) + frozen = tuple(freeze_evidence(r) for r in selected) + training = tuple(r for r in frozen if r['cycle'] in (0, 1)) + validation = tuple(r for r in frozen if r['cycle'] == profile.quality.holdout_cycle) + return RawCalibrationEvidence(training, validation, tuple(accepted), evidence_digest({ + 'plan': evidence_digest(plan), 'rows': frozen}), + tuple(dict(unit=key, failures=list(value)) for key, value in failures.items()), plan, tuple(reassessed)) + + +def fitting_frames(profile, rows): + """Select synchronized steady images; retain rejected frames in the journal.""" + from .raw_quality import synchronized_frame + from .observation_coverage import complete_vector, visible_roles + tags = {view.name: {tag.role: tag for tag in view.tags} for view in profile.vision.views} + result = [] + for row in rows: + if (row.get('sample_phase') != 'steady' or not row.get('accepted_sample_window_open') + or not synchronized_frame(row) + or not complete_vector(row.get('command_vector'), profile.command.command_count) + or not complete_vector(row.get('feedback_vector'), profile.command.command_count) + or not complete_vector(row.get('target_command_vector'), profile.command.command_count) + or tuple(row['command_vector']) != tuple(row['target_command_vector'])): + continue + visible = visible_roles(row, tags[row['view']]) + result.append({**row, 'tags': {role: row['tags'][role] for role in visible}}) + return tuple(result) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_quality.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_quality.py new file mode 100644 index 0000000..692e615 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_quality.py @@ -0,0 +1,67 @@ +"""Image coverage for deferred geometry, without manufacturing joint angles.""" + +import math + +from ..core.domain.motion_path import record_scan_identity, task_segment, segment_metadata +from ..core.fitting.motion_fit import channel_for_joint +from .observation_coverage import complete_vector, visible_roles +from .scan_quality import evaluate_capture_unit, observation_streams + + +def synchronized_frame(row): + """Retain the existing 50 ms upper bound also during journal replay.""" + command_ns = row.get('command_image_skew_ns') + state_ms = row.get('state_image_sync_error_ms') + return all(isinstance(value, (int, float)) and not isinstance(value, bool) + and math.isfinite(value) and 0 <= value <= bound + for value, bound in ((command_ns, 50_000_000), (state_ms, 50.))) + + +def coverage_records(profile, unit, attempt, records): + """Ephemeral scalar views are used only by the shared acquisition gates.""" + task = next(task for task in profile.motion.tasks if task.key == unit.task_key) + segment = task_segment(task, unit.segment_key) if unit.segment_key else None + tags = {v.name: {t.role: t for t in v.tags} for v in profile.vision.views} + for row in records: + if (row.get('kind') != 'raw_observation_frame' + or record_scan_identity(row) != unit.identity or row.get('attempt') != attempt + or row.get('sample_phase') not in {'steady', 'sweep'} + or not synchronized_frame(row)): + continue + command, feedback = row.get('command_vector'), row.get('feedback_vector') + if (row.get('command_unit') != profile.command.unit + or not complete_vector(command, profile.command.command_count) + or not complete_vector(feedback, profile.command.command_count)): + continue + if row['sample_phase'] == 'steady' and not row.get('accepted_sample_window_open'): + continue + visible = visible_roles(row, tags.get(row.get('view'), {})) + for field, joint, spec in observation_streams(profile, task): + if segment is not None and joint not in segment.joints: + continue + if row['view'] != spec.view or not {spec.parent_role, spec.child_role} <= visible: + continue + channel = channel_for_joint(profile, joint) + result = {field: joint, 'view': spec.view, 'task_name': unit.task_key, + 'cycle': unit.cycle, 'direction': unit.direction, 'attempt': attempt, + **segment_metadata(unit.segment_key), 'image_stamp_ns': row['image_stamp_ns'], + 'sample_phase': row['sample_phase'], + f'command_{profile.command.unit}': command[channel], + f'feedback_{profile.command.unit}': feedback[channel]} + if row['sample_phase'] == 'steady': + target = row.get('target_command_vector') + if not complete_vector(target, profile.command.command_count) or tuple(command) != tuple(target): + continue + result.update(steady_index=row['steady_index'], steady_target=target[channel]) + yield result + + +def evaluate_raw_unit(profile, unit, attempt, records, *, first_cycle_spans): + from ..core.domain.capture_plan import RAW_PROTOCOL + records = tuple(records) + current_protocol = any(r.get('observation_protocol') == RAW_PROTOCOL for r in records) + return evaluate_capture_unit(profile, unit, attempt, + tuple(coverage_records(profile, unit, attempt, records)), + first_cycle_spans=first_cycle_spans, + include_steady_endpoints=current_protocol, + scale_segment_feedback_coverage=current_protocol) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_remount.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_remount.py new file mode 100644 index 0000000..bb497f7 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_remount.py @@ -0,0 +1,143 @@ +"""Explicit, offline restart boundary after a moving tag is remounted. + +The source journal remains untouched. Only an already completed prefix can be +reused, and every old observation of the remounted tag is excluded. This is a +draft workflow: unseen baseline installations cannot certify a passed release. +""" +import json +import os +from pathlib import Path + +from ..core.domain.motion_path import record_scan_identity +from ..storage import append_jsonl_many, atomic_write_json, sync_jsonl +from .engine import CalibrationEngine +from .raw_completion import file_digest +from .raw_resume import RawCheckpoint +from .scan_quality import observation_streams + + +REMOUNT_RECORD = 'raw_tag_remount_checkpoint' + + +def remount_prefix(profile, checkpoint, tag_ids, model): + """Keep the finite schedule prefix, including its original retry budgets.""" + requested = frozenset(tag_ids) + tags = [tag for view in profile.vision.views for tag in view.tags + if tag.tag_id in requested] + if (not requested or {tag.tag_id for tag in tags} != requested + or any(tag.fixed_reference for tag in tags)): + raise ValueError('remount_requires_known_moving_tags') + from ..profiles.observations import compile_tag_links + links = compile_tag_links(profile, model) + def root(role): + link = links[role] + if link == model.root_link: + return None + return next((joint.name for joint in model._chain(model.parent_joint_by_child[link]) + if joint.kind != 'fixed'), None) + roots = {root(tag.role) for tag in tags} + if None in roots: + raise ValueError('remount_requires_a_movable_finger_branch') + # The affected finger is recaptured as one installation. Incidental old + # views of its other tags must not bind the new chain to an old rest pose. + roles = {role for role in links if root(role) in roots} + declarations = [(i, row) for i, row in enumerate(checkpoint.rows) if row.get('kind') == REMOUNT_RECORD] + previous = None + if declarations: + index, previous = declarations[-1] + if (len(declarations) != 1 or set(previous['remounted_tag_ids']) != requested + or not set(previous['excluded_old_roles']) < roles + or any(row.get('kind') in {'raw_observation_frame', 'scan_unit_complete'} + for row in checkpoint.rows[index+1:])): + raise ValueError('remount_already_declared_use_normal_resume') + # A prepared checkpoint can narrow its retained auxiliary evidence + # before scanning starts. No attempted direction may be rewound. + tasks = {task.key for task in profile.motion.tasks + if any(roles & {spec.parent_role, spec.child_role} + for _, _, spec in observation_streams(profile, task))} + units = CalibrationEngine(profile).scan_units() + boundary = next((i for i, unit in enumerate(units) if unit.task_key in tasks), None) + if boundary is None or boundary == 0: + raise ValueError('remount_has_no_unaffected_prefix') + prefix = {unit.identity for unit in units[:boundary]} + if checkpoint.completed_units != prefix: + # Do not silently discard good work after the boundary, or rewind a + # failed unrelated task and thereby grant it more attempts. + raise ValueError('remount_requires_exact_completed_prefix') + completions = [i for i, row in enumerate(checkpoint.rows) + if row.get('kind') == 'scan_unit_complete' and record_scan_identity(row) in prefix] + end = max(completions) + 1 + retained, excluded = [], previous['excluded_old_tag_observations'] if previous else 0 + for row in checkpoint.rows[:end]: + if row.get('kind') == 'raw_observation_frame': + old_tags = row.get('tags', {}) + removed = roles & old_tags.keys() + if removed: + excluded += len(removed) + row = {**row, 'tags': {key: value for key, value in old_tags.items() if key not in roles}, + 'excluded_remounted_tag_roles': sorted(removed | set(row.get('excluded_remounted_tag_roles', ())))} + elif row.get('kind') == 'session_start': + row = {**row, 'resume_checkpoint_requested': True, 'derived_remount_checkpoint': True} + retained.append(row) + report = dict(kind=REMOUNT_RECORD, version=1, remounted_tag_ids=sorted(requested), + excluded_old_roles=sorted(roles), affected_finger_roots=sorted(roots), + retained_units=[list(unit.identity) for unit in units[:boundary]], + restart_unit=list(units[boundary].identity), remaining_units=len(units)-boundary, + excluded_old_tag_observations=excluded, new_installation_attempt_limit=2, + replaced_attempts=[{key: row[key] for key in ('task_name', 'cycle', 'direction', 'attempt', 'passed', 'failures') + if key in row} for row in checkpoint.rows[end:] if row.get('kind') == 'scan_unit_complete'], + installation_verification='available_baseline_corners_and_fixed_reference', + publication_allowed=False) + if previous: + report['replaced_attempts'] = previous['replaced_attempts'] + report['refined_unstarted_checkpoint'] = True + return tuple(retained), report + + +def prepare_remount_checkpoint(config, source, output, tag_ids): + """Prepare a reviewable checkpoint without opening ROS or an SDK.""" + from .artifacts.capture_validation import validate_capture_provenance + from .runner_support import protected_inputs + source, output = Path(source).resolve(), Path(output).resolve() + source = source/'raw_samples.jsonl' if source.is_dir() else source + if output == source.parent or output.exists(): + raise ValueError('remount_output_must_be_new_directory') + receipt = source.parent/'remount_successor.json' + if receipt.exists(): + raise ValueError('remount_already_prepared_use_normal_resume:' + str(receipt)) + profile = config.calibration_contract.typed_profile + checkpoint = RawCheckpoint.load(profile, CalibrationEngine(profile), source, config.serial_number) + validate_capture_provenance(profile, config.serial_number, protected_inputs(config), checkpoint.rows, + allow_installation_draft=True) + from ..core.urdf.kinematics import UrdfKinematicModel + rows, report = remount_prefix(profile, checkpoint, tag_ids, UrdfKinematicModel(config.source_urdf)) + files = sorted({source, *source.parent.glob(source.stem+'.*'), + *source.parent.glob('imported_evidence_*.zlib'), source.parent/'capture_profile.yaml'}) + report['source_files'] = {str(path): file_digest(path) for path in files if path.is_file()} + report['source_session'] = str(source.parent) + output.mkdir(parents=True) + path = output/'raw_samples.jsonl' + append_jsonl_many(path, (*rows, report), durable=True) + sync_jsonl(path) + snapshot = source.parent/'capture_profile.yaml' + if snapshot.is_file(): + (output/snapshot.name).write_bytes(snapshot.read_bytes()) + # Recompute quality after filtering; the derived checkpoint must still + # restore exactly the same good prefix before it can be offered to motion. + verified = RawCheckpoint.load(profile, CalibrationEngine(profile), path, config.serial_number) + if verified.completed_units != checkpoint.completed_units: + raise ValueError('remount_changed_unaffected_quality') + for name, digest in report['source_files'].items(): + if file_digest(name) != digest: + raise ValueError('remount_source_changed_during_preparation') + report['checkpoint_files'] = {p.name: file_digest(p) for p in output.iterdir() if p.is_file()} + atomic_write_json(output/'remount_checkpoint.json', report) + # Exclusive receipt prevents repeated invocation on this old installation + # from resetting the new installation's attempts. Ordinary restarts resume + # the newest journal and keep the existing attempt counters. + with receipt.open('x', encoding='utf-8') as stream: + json.dump(dict(checkpoint=str(output), tag_ids=sorted(set(tag_ids))), stream, indent=2) + stream.write('\n') + stream.flush() + os.fsync(stream.fileno()) + return report diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_resume.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_resume.py new file mode 100644 index 0000000..ff781bc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/raw_resume.py @@ -0,0 +1,172 @@ +"""Reference-bound replay of the raw protocol's finite acquisition schedule.""" +from dataclasses import dataclass, replace +from collections import defaultdict, deque + +import numpy as np + +from ..core.domain.capture_plan import raw_joint_capture +from ..core.domain.motion_path import record_scan_identity, segment_metadata +from .raw_evidence import partition_raw_capture +from .resume import ResumeVerifier, fingerprint_from_mapping +from .session import CalibrationSession, CalibrationPhase, SweepQuality + + +class InstallationReference: + """Repeated baseline corners, independent of a unique PnP solution.""" + def __init__(self, profile): + self.profile = profile + self.frames = defaultdict(lambda: deque(maxlen=profile.acquisition.fixed_reference_minimum_frames)) + + def observe(self, frame): + if (frame.command is None or frame.feedback is None + or tuple(frame.command) != self.profile.command.baseline_values): + return + for role, points in frame.corners.items(): + key = f'{frame.view}:{role}' + if self.frames[key] and frame.stamp_ns <= self.frames[key][-1][0]: + continue + self.frames[key].append((frame.stamp_ns, np.asarray(points), tuple(frame.feedback))) + + def payload(self): + result = {} + for key, samples in self.frames.items(): + if len(samples) < self.profile.acquisition.fixed_reference_minimum_frames: + continue + corners = np.asarray([s[1] for s in samples]) + feedback = np.asarray([s[2] for s in samples]) + center = np.median(corners, axis=0) + if (np.max(np.linalg.norm(corners-center, axis=-1)) + > self.profile.acquisition.fixed_reference_maximum_drift_px + or np.max(np.ptp(feedback, axis=0)) > 2): + continue + result[key] = dict(corners_xy=center.tolist(), + feedback=np.median(feedback, axis=0).tolist(), + image_stamps_ns=[s[0] for s in samples]) + return result + + +@dataclass(frozen=True) +class RawCheckpoint: + header: dict + fixed_reference: dict + rows: tuple + completed_units: frozenset + + @classmethod + def load(cls, profile, engine, path, serial_number, **_): + from .acquisition import load_capture + if not raw_joint_capture(profile): + raise ValueError('raw_resume_protocol_required') + rows = tuple(load_capture(path)) + headers = [r for r in rows if r.get('kind') == 'session_start'] + references = [r for r in rows if r.get('kind') == 'fixed_base_reference_locked'] + if (len(headers) != 1 or len(references) != 1 + or headers[0].get('serial_number') != serial_number + or not engine.resume_compatible(headers[0])): + raise ValueError('raw_resume_identity_or_protocol_changed') + from ..core.domain.capture_plan import CapturePlan + if headers[0].get('capture_plan') != CapturePlan.from_profile(profile).as_dict(): + raise ValueError('raw_resume_identity_or_protocol_changed') + evidence = partition_raw_capture(profile, rows, require_complete=False) + checkpoint = cls(headers[0], references[0], rows, frozenset(evidence.completed_units)) + # Validate order and retry budgets before any live motor command. + checkpoint.restore(CalibrationSession(profile)) + return checkpoint + + def verify_reference(self, profile, current, *, require_installation=True): + """Check fixed references; audit moving baselines separately. + + Equal SDK commands do not prove equal physical poses after a restart. + Raw acquisition records that ambiguity without authorizing a measured + zero or a shared tag mount. Offline release keeps the strict default. + """ + previous = {**self.fixed_reference, + 'acquisition_policy_version': current['acquisition_policy_version']} + checker = ResumeVerifier(required_fixed_views=profile.vision.view_names, + required_fixed_poses=profile.vision.view_names, + required_hashes=current['protected_hashes']) + # Moving-tag installation is verified below from baseline pixels and + # feedback. A PnP branch is not an installation identity in this protocol. + decision = checker.compare( + replace(fingerprint_from_mapping(previous), moving_tag_poses={}), + replace(fingerprint_from_mapping(current), moving_tag_poses={})) + if not decision.reuse: + raise ValueError('raw_resume_reference_changed:' + str(decision.incompatible_fields)) + old = self.fixed_reference.get('raw_installation_reference', {}) + new = current.get('raw_installation_reference', {}) + fixed_roles = {f'{view.name}:{tag.role}' for view in profile.vision.views + for tag in view.tags if tag.fixed_reference} + roles = {f"{r['view']}:{role}" for r in self.rows + if r.get('kind') == 'raw_observation_frame' + for role in r.get('tags', {})} - fixed_roles + from .raw_remount import REMOUNT_RECORD + draft_remount = any(r.get('kind') == REMOUNT_RECORD for r in self.rows) + checked, unavailable, changed, diagnostics = [], [], [], {} + for role in sorted(roles): + if role not in old or role not in new: + if draft_remount or not require_installation: + unavailable.append(role) + continue + raise ValueError('raw_resume_installation_observation_missing:' + role) + drift = np.linalg.norm(np.asarray(old[role]['corners_xy']) + -np.asarray(new[role]['corners_xy']), axis=-1) + feedback = np.abs(np.asarray(old[role]['feedback'])-np.asarray(new[role]['feedback'])) + if not np.all(np.isfinite(drift)) or not np.all(np.isfinite(feedback)): + raise ValueError('raw_resume_installation_invalid:' + role) + diagnostics[role] = dict(maximum_corner_difference_px=float(np.max(drift)), + maximum_feedback_difference=float(np.max(feedback))) + if (np.max(drift) > profile.acquisition.fixed_reference_maximum_drift_px + or np.max(feedback) > 10): + if require_installation: + raise ValueError('raw_resume_installation_changed:' + role) + changed.append(role) + continue + checked.append(role) + verified = not (changed or unavailable) + return dict(checked_roles=checked, unavailable_roles=unavailable, + changed_roles=changed, baseline_diagnostics=diagnostics, + installation_verified=verified, requires_offline_review=not verified, + policy='moving_baseline_audit_v1', + draft_only=draft_remount or not verified, fixed_reference_verified=True) + + def restore(self, session): + """Replay journal transitions, including failed and interrupted attempts.""" + if session._unit_index or session._retry_by_unit: + raise ValueError('raw_resume_requires_fresh_schedule') + pending = set() + for row in self.rows: + kind = row.get('kind') + if kind not in {'raw_observation_frame', 'scan_unit_complete'}: + continue + unit = session.current_unit + if (unit is None or record_scan_identity(row) != unit.identity + or row['attempt'] != session.action().retry+1): + raise ValueError('raw_resume_schedule_order_changed') + pending.add(unit.identity) + if kind == 'scan_unit_complete': + if row['passed'] and unit.identity not in self.completed_units: + raise ValueError('raw_resume_passed_evidence_invalid') + session.phase = CalibrationPhase.EVALUATE + session.evaluation_complete(SweepQuality(row['passed'], + tuple(row.get('failures', ())), (), row.get('metrics', {}))) + pending.discard(unit.identity) + interrupted = () + if pending: + unit = session.current_unit + record = dict(kind='scan_unit_complete', task_name=unit.task_key, + cycle=unit.cycle, direction=unit.direction, **segment_metadata(unit.segment_key), + attempt=session.action().retry+1, passed=False, + failures=['interrupted_attempt'], metrics={}) + session.phase = CalibrationPhase.EVALUATE + session.evaluation_complete(SweepQuality(False, ('interrupted_attempt',), (), {})) + interrupted = (record,) + if session.current_unit is None: + session.phase = CalibrationPhase.RETURN_BASELINE + else: + session.phase = CalibrationPhase.PREPARE + return interrupted + + def import_rows(self): + return tuple(r for r in self.rows if r.get('kind') not in { + 'session_start', 'fixed_base_reference_locked', 'rectified_camera_model', + 'raw_capture_finished'}) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/reference_lock.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/reference_lock.py new file mode 100644 index 0000000..73b5d4a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/reference_lock.py @@ -0,0 +1,171 @@ +"""Session-scoped fixed-Tag locking shared by every hand profile.""" + +from __future__ import annotations + +from collections import deque +from dataclasses import dataclass +from typing import Mapping, Sequence + +import numpy as np + + +@dataclass(frozen=True) +class ReferenceObservation: + view: str + tag_id: int + corners_px: tuple[tuple[float, float], ...] + + +@dataclass(frozen=True) +class ReferenceMovement: + view: str + tag_id: int + drift_px: float + confirmation_frames: int + + +class ReferenceLock: + """Discard preview data, robustly lock once, then never rewrite it.""" + + def __init__( + self, + fixed_tag_by_view: Mapping[str, int], + *, + minimum_frames: int = 10, + maximum_corner_drift_px: float = 5.0, + confirmation_frames: int = 10, + ) -> None: + if minimum_frames < 3: + raise ValueError("reference lock requires at least three frames") + if maximum_corner_drift_px <= 0.0 or confirmation_frames < 1: + raise ValueError("reference movement limits are invalid") + self.fixed_tag_by_view = { + str(view): int(tag_id) for view, tag_id in fixed_tag_by_view.items() + } + if not self.fixed_tag_by_view: + raise ValueError("at least one fixed reference Tag is required") + self.minimum_frames = int(minimum_frames) + self.maximum_corner_drift_px = float(maximum_corner_drift_px) + self.confirmation_frames = int(confirmation_frames) + self.preview_corners: dict[str, np.ndarray] = {} + self._buffers = { + view: deque(maxlen=max(self.minimum_frames, 30)) + for view in self.fixed_tag_by_view + } + self._references: dict[str, np.ndarray] = {} + self._drift_counts = {view: 0 for view in self.fixed_tag_by_view} + self._latest_drift = {view: 0.0 for view in self.fixed_tag_by_view} + self.session_started = False + self.locking_enabled = False + + @property + def locked(self) -> bool: + return set(self._references) == set(self.fixed_tag_by_view) + + @property + def missing_views(self) -> tuple[str, ...]: + return tuple( + view for view in self.fixed_tag_by_view if view not in self._references + ) + + @property + def references(self) -> Mapping[str, np.ndarray]: + return {view: value.copy() for view, value in self._references.items()} + + @property + def latest_drift_px(self) -> Mapping[str, float]: + return dict(self._latest_drift) + + def begin_session(self) -> None: + """Make all observations collected before Start preview-only.""" + self.session_started = True + self.locking_enabled = False + self._references.clear() + for buffer in self._buffers.values(): + buffer.clear() + for view in self._drift_counts: + self._drift_counts[view] = 0 + self._latest_drift[view] = 0.0 + + def start_locking(self) -> None: + """Start formal collection only after the baseline trajectory ends.""" + if not self.session_started: + raise RuntimeError("the calibration session has not started") + self.locking_enabled = True + self._references.clear() + for buffer in self._buffers.values(): + buffer.clear() + for view in self._drift_counts: + self._drift_counts[view] = 0 + self._latest_drift[view] = 0.0 + + def observe( + self, + view: str, + tag_id: int, + corners_px: Sequence[Sequence[float]], + ) -> ReferenceMovement | None: + selected_view = str(view) + if self.fixed_tag_by_view.get(selected_view) != int(tag_id): + return None + corners = np.asarray(corners_px, dtype=float) + if corners.shape != (4, 2) or not np.all(np.isfinite(corners)): + return None + if not self.session_started: + self.preview_corners[selected_view] = corners.copy() + return None + if not self.locking_enabled: + return None + reference = self._references.get(selected_view) + if reference is None: + buffer = self._buffers[selected_view] + buffer.append(corners.copy()) + if len(buffer) >= self.minimum_frames: + self._references[selected_view] = np.median( + np.asarray(tuple(buffer), dtype=float), axis=0 + ) + buffer.clear() + return None + drift = float(np.max(np.linalg.norm(corners - reference, axis=1))) + self._latest_drift[selected_view] = drift + self._drift_counts[selected_view] = ( + self._drift_counts[selected_view] + 1 + if drift > self.maximum_corner_drift_px + else 0 + ) + if self._drift_counts[selected_view] < self.confirmation_frames: + return None + return ReferenceMovement( + selected_view, + int(tag_id), + drift, + self._drift_counts[selected_view], + ) + + def fingerprint(self) -> dict[str, list[list[float]]]: + if not self.locked: + raise ValueError("fixed references have not been locked") + return { + view: [[float(value) for value in point] for point in corners] + for view, corners in sorted(self._references.items()) + } + + def compatible_with( + self, + fingerprint: Mapping[str, Sequence[Sequence[float]]], + ) -> bool: + if not self.locked or set(fingerprint) != set(self._references): + return False + for view, reference in self._references.items(): + previous = np.asarray(fingerprint[view], dtype=float) + if previous.shape != (4, 2) or not np.all(np.isfinite(previous)): + return False + drift = float( + np.max(np.linalg.norm(reference - previous, axis=1)) + ) + if drift > self.maximum_corner_drift_px: + return False + return True + + +__all__ = ["ReferenceLock", "ReferenceMovement", "ReferenceObservation"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/__init__.py new file mode 100644 index 0000000..4c111bc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/__init__.py @@ -0,0 +1,6 @@ +"""Shared calibration progress and diagnostic messages.""" + +from .progress_zh import progress_fraction, render_progress_zh +from .reasons_zh import reason_zh + +__all__ = ["progress_fraction", "reason_zh", "render_progress_zh"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/progress_zh.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/progress_zh.py new file mode 100644 index 0000000..0a69021 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/progress_zh.py @@ -0,0 +1,204 @@ +"""Unified Chinese console progress renderer for every hand profile.""" + +from __future__ import annotations + +from typing import Any, Callable, Mapping + +from ...operator_report import ( + ProgressEstimator, + render_compact_progress_header_zh, +) + + +STATE_LABELS = { + "WAIT_DEVICES": "等待设备反馈和相机内参", + "READY": "设备就绪", + "RUNNING": "标定中", + "FINALIZING": "拟合、验证并生成 URDF", + "PASSED": "通过", + "PAUSED": "已暂停", + "ABORTED": "已中止", +} +PHASE_LABELS = { + "joint_zero": "采集并锁定当前关节零位", + "zero_approach": "准备关节零位观测姿态", + "baseline": "安全恢复基准形态", + "preflight": "任务运动预检", + "prepare": "扫描起点准备", + "retry_prepare": "自动重扫起点准备", + "resume_prepare": "断点恢复起点准备", + "sweep": "正式扫描", + "clearance": "手指避让", + "clearance_outer": "小指/无名指避让", + "clearance_splay": "侧摆避让", + "return_splay_zero": "侧摆回零", + "return_middle_open": "展开中指", + "return_outer_open": "展开小指/无名指", +} +DIRECTION_LABELS = {"decreasing": "递减", "increasing": "递增"} + + +def progress_fraction(status: Mapping[str, Any]) -> tuple[float, int, int]: + state = str(status.get("state", "")) + step_count = max(0, int(status.get("step_count", 0) or 0)) + step_index = int(status.get("step_index", -1) or 0) + step_fraction = float(status.get("step_fraction", 0.0) or 0.0) + if state == "PASSED": + overall = 1.0 + elif step_count and step_index >= 0: + overall = min(1.0, max(0.0, (step_index + step_fraction) / step_count)) + else: + overall = 0.0 + current = min(step_count, max(0, step_index + 1)) if step_count else 0 + return overall, current, step_count + + +def _duration_zh(seconds: float | None) -> str: + if seconds is None or seconds < 0.0: + return "计算中" + value = int(round(seconds)) + return f"{value // 60}分{value % 60:02d}秒" + + +def render_progress_zh( + status: Mapping[str, Any], + *, + task_labels: Mapping[str, str], + reason_renderer: Callable[ + [Mapping[str, Any]], tuple[str, str, str] + ], + estimator: ProgressEstimator | None = None, +) -> str: + """Render the shared progress/status contract with model labels injected.""" + state = str(status.get("state", "")) + overall, _current_step, _step_count = progress_fraction(status) + task = status.get("task_name") + phase = status.get("phase") + if task: + task_text = task_labels.get(str(task), str(task)) + elif phase == "baseline": + task_text = "全手基准姿态" + elif state == "WAIT_DEVICES": + task_text = "等待设备连接" + elif state == "READY": + task_text = "等待开始" + else: + task_text = "无" + eta = _duration_zh(estimator.remaining(overall) if estimator else None) + cycle = status.get("cycle") + cycle_text = "-" if cycle is None else str(int(cycle) + 1) + direction_text = DIRECTION_LABELS.get(str(status.get("direction")), "-") + command_unit = str(status.get("command_unit", "u8")) + target = ( + status.get("target_rad") + if command_unit == "rad" + else status.get("target_u8") + ) + requested = status.get("current_command_u8", target) + actual = status.get("actual_u8") + if command_unit == "rad": + requested = "未知" if requested is None else f"{float(requested):.3f} rad" + actual_text = "未知" if actual is None else f"{float(actual):.3f} rad" + else: + requested = "未知" if requested is None else f"{float(requested):.1f}" + actual_text = "未知" if actual is None else f"{float(actual):.1f}" + valid = int(status.get("valid_frames", 0) or 0) + total = int(status.get("total_frames", 0) or 0) + rate = float(status.get("tag_detection_rate", 0.0) or 0.0) + joint_rate = float( + status.get( + "joint_frame_rate", (float(valid) / total) if total else 0.0 + ) or 0.0 + ) + recognized = [int(value) for value in status.get("recognized_tag_ids", [])] + unrecognized = [ + int(value) for value in status.get("unrecognized_tag_ids", []) + ] + if str(status.get("reason", "")).startswith("locking_fixed_base_references"): + unrecognized = [ + int(value) + for value in status.get("reference_missing_tag_ids", unrecognized) + ] + recognized_text = "/".join(f"ID{value}" for value in recognized) or "无" + unrecognized_text = "/".join(f"ID{value}" for value in unrecognized) or "无" + attempt = int(status.get("attempt", 1) or 1) + lines = render_compact_progress_header_zh( + serial_number=str(status.get("serial_number", "?")), + progress=overall, + eta=eta, + stage=PHASE_LABELS.get(str(phase), STATE_LABELS.get(state, state)), + cycle=cycle_text, + repetitions=4, + task=task_text, + requested=requested, + actual=actual_text, + direction=direction_text, + tag_status=( + f"已识别 {recognized_text};未识别/不合格 {unrecognized_text};" + f"本方向各Tag最低 {rate:.1%};联合 {valid}/{total} 帧" + f"({joint_rate:.1%})" + ), + ready_cameras=3, + feedback_hz=float(status.get("feedback_hz", 0.0) or 0.0), + valid_frames=valid, + automatic_retry_count=max(0, attempt - 1), + ) + required_by_view = status.get("required_tag_ids_by_view", {}) + if isinstance(required_by_view, Mapping) and required_by_view: + lines.append( + "任务所需Tag:" + ";".join( + f"{view}=" + "/".join(f"ID{int(tag_id)}" for tag_id in ids) + for view, ids in required_by_view.items() + ) + ) + speed_u8 = status.get("speed_u8") + if speed_u8 is not None: + seconds = float( + status.get("command_trajectory_full_range_seconds", 0.0) or 0.0 + ) + lines.append(f"运动:速度档 {int(speed_u8)};全行程 {seconds:.1f} 秒余弦轨迹") + speed_rad_s = status.get("speed_rad_s") + if speed_rad_s is not None: + seconds = float( + status.get("command_trajectory_duration_seconds", 0.0) or 0.0 + ) + lines.append( + f"运动:峰值 {float(speed_rad_s):.3f} rad/s;" + f"本段 {seconds:.1f} 秒平滑限速轨迹" + ) + latest_state = status.get(f"latest_state_{command_unit}", []) + command_names = status.get("command_names", []) + if ( + isinstance(latest_state, (list, tuple)) + and isinstance(command_names, (list, tuple)) + and len(latest_state) == len(command_names) + and len(command_names) in {6, 12} + and (phase == "baseline" or state in {"PAUSED", "ABORTED"}) + ): + digits = 3 if command_unit == "rad" else 1 + suffix = " rad" if command_unit == "rad" else "" + feedback_text = ", ".join( + f"{name}={float(value):.{digits}f}{suffix}" + for name, value in zip(command_names, latest_state) + ) + error_channel = status.get("maximum_error_channel") + maximum_error = status.get(f"maximum_error_{command_unit}") + error_text = ( + "未知" + if error_channel is None or maximum_error is None + else f"{error_channel}={float(maximum_error):.{digits}f}{suffix}" + ) + channel_label = "六路" if len(command_names) == 6 else "十二路" + error_label = "最大命令/反馈差" if command_unit == "rad" else "最大偏差" + lines.append( + f"{channel_label}反馈:{feedback_text} {error_label}:{error_text}" + ) + if state in {"PAUSED", "ABORTED"}: + _code, problem, suggestion = reason_renderer(status) + lines.extend((f"原因:{problem}", f"建议:{suggestion}")) + if status.get("reference_locked"): + lines.append("基准已锁定:请勿移动手掌、相机、支架或Tag") + return "\n".join(lines) + + +__all__ = ["progress_fraction", "render_progress_zh"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/reasons_zh.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/reasons_zh.py new file mode 100644 index 0000000..2639b13 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/reporting/reasons_zh.py @@ -0,0 +1,242 @@ +"""Shared Chinese operator explanations for common calibration failures.""" + +from __future__ import annotations + +import re +from typing import Any, Mapping + + +def reason_zh( + status: Mapping[str, Any], *, model_name: str +) -> tuple[str, str, str]: + """Map a common runtime reason to a stable code, explanation and action.""" + reason = str(status.get("reason", "unknown")) + if 'o30_sdk_identity_mismatch' in reason or 'o30_sdk_device_changed' in reason: + return ('DEVICE-IDENTITY-203', 'SDK 报告的设备身份与当前 O30 配置不一致。', + '核对诊断中保存的型号、左右手、设备 UID 和通道名称,以及 SDK 信息话题是否存在其他发布者。') + if 'shared_pose_handoff_' in reason: + return ('OBS-HANDOFF-120', f'共享 Tag 的任务交接证据不完整或已发生变化:{reason}', + '核对上游回基准的完整原始图像窗口、反馈及时间顺序;交接不能借用验证轮、跨会话旧图或挑选低误差帧。原零位和已通过数据保持冻结。') + if "preparation_sync_" in reason or "preparation_state_vector_invalid" in reason: + return ("OBS-PREP-SYNC-119", "准备观测的指令/反馈同步证据不足或格式无效,不能确认完整运动过程。", + "查看原始帧和 sample_admission 记录中的缺失比例、间隙及端点;不要将此错误直接归因于 Tag 安装,也不放宽同步门限或填造指令。") + if any(code in reason for code in ("image_motion_solver_budget_exhausted", + "image_motion_optimizer_unresolved", "image_motion_solver_timeout")): + return ("OBS-SOLVER-118", "准备几何求解未能在计算预算内收敛,尚不能完成候选评估。", + "查看 motion_branch_initialization 中各候选的求解次数、终止状态与原始图像;先离线分析计算问题,不因这条错误反复运动或调整 Tag。") + if reason.startswith("training_quality_failed"): + return ("FIT-TRAINING-511", "第三轮训练后质量仍不合格,本任务已结束,未进入独立验证或发布。", + "查看 training_decision 的重复性、几何依赖和零位置信区间;保留原始日志,先分析原因。") + if reason.startswith("training_assessment_failed"): + return ("FIT-TRAINING-WORKER-512", "训练预检未能在规定时间内完成,会话已暂停。", + "查看原始异常和阶段耗时;已采数据保留,不会继续增加训练轮次或更换冻结模型。") + if "shared_pose" in reason: + return ("OBS-SHARED-POSE-116", f"共享标签在当前基准姿态下尚不能可靠继承已确认的姿态约束:{reason}", + "查看共享标签检查中的静止图像、相关通道反馈及各候选姿态差;已通过的关节数据保留。证据仍不充分时需要补充有效观测,原样重复扫描不保证消除歧义。") + if "parent_reference_" in reason: + return ("OBS-PARENT-REFERENCE-115", f"父标签的当前姿态或原安装证据未通过复核:{reason}", + "保留诊断,核对保持指令、反馈稳定性、当前图像与模型来源;不会额外转动父关节或替换原零位。若标签安装发生变化,需要重新采集相关关节。") + if "tag_installation_not_rigid:" in reason: + return ("FIT-RIGID-CHAIN-510", "采集已完成,但实测 Tag 轨迹与整条 URDF 运动链未通过刚性一致性验证。", + "查看 tag_installation_diagnostics.json 中全部 Tag 的角度和位置残差,核对坐标转换、视觉重建和模型几何;这不等于已确认硬件松动,不应直接重复整场采集。") + if "image_motion_families_not_distinguishable" in reason: + return ("OBS-POSE-AMBIGUOUS-117", "现有图像仍可由多个不同的三维姿态解释,无法可靠选择唯一结果。", + "补充当前关节的独立观测,或改善尚未通过关节标签的视角;已通过的数据保留。原样重复同一段运动不保证消除歧义,不能只取像素误差略小的解。") + if "image_motion_alternative_not_evaluable" in reason or "image_motion_alternative_angles_unresolved" in reason: + return ("OBS-POSE-ALTERNATIVE-122", "已有候选结果,但另一套姿态尚未得到可比较的图像结果。", + "查看 motion_branch_initialization 的 image_solve_diagnosis 和各候选求解状态;未算完不等于被排除,不要直接采用当前最低误差解。") + if "image_motion_no_observable_image_model" in reason: + return ("OBS-POSE-MODEL-121", "目前没有一套姿态能同时通过图像与几何检查。", + "查看 image_solve_diagnosis 中每套候选的失败原因和训练/留出像素误差;先分清图像对不齐、几何不确定或求解未完成。") + if reason.startswith("joint_zero_motion_unresolved:"): + return ("OBS-JOINT-BRANCH-111", f"归零准备运动未能可靠确认当前关节的姿态分支:{reason}", + "查看所列关节、机位及 motion_branch_initialization 记录;检查 Tag 刚性、完整可见性和运动几何证据。保持当前位置,不把分数较低的候选直接当作真值,不覆盖已冻结零位。") + if reason.startswith("fixed_reference_pose_inconsistent:"): + return ("OBS-BASE-POSE-110", f"固定基准的当前图像持续无法验证已冻结姿态:{reason}", + "已保持当前位置并禁止发布。检查所列固定 Tag 的遮挡、变形、成像及相机/支架是否移动;不重新定位基准来拼接旧样本。") + if reason.startswith(("pose_branch_conflict:", "pose_branch_recovery_required:")): + return ("OBS-POSE-BRANCH-109", f"当前所需 Tag 的姿态分支与已冻结参考无法可靠保持一致:{reason}", + "已保持当前位置并禁止发布。检查所列机位和 Tag 的刚性、视角与成像;不重置既有零位,不用镜像姿态继续拼接数据。") + if "joint_zero_unavailable" in reason: + return ("OBS-JOINT-ZERO-107", f"当前关节未取得稳定零位观测:{reason}", + "查看所列关节、机位和 Tag;排除持续遮挡或抖动后重新开始,已有零位不会被覆盖。") + if "joint_resume_reference_changed" in reason: + return ("OBS-JOINT-RESUME-108", f"当前关节的原零位或 Tag 安装验证失败:{reason}", + "旧样本不能与新零位拼接。检查安装,使用 --no-resume 开始新会话。") + if "independent_release_incomplete" in reason: + return ("FIT-INDEPENDENT-COVERAGE-509", f"独立实测或绝对几何依据不完整,已禁止发布:{reason}", + "查看相对运动诊断及缺失关节,补充实际 Tag 观测与有依据的几何条件;不能用 mimic、迁移或补零替代。") + if "compact_byte_requires_measured_full_command_domain" in reason: + return ("FIT-COMPACT-DOMAIN-507", "实测指令范围没有完整覆盖 0–255,不能生成完整的 256 项查表。", + "核对扫描范围和端点稳态数据;不得用反馈表、外推或裁剪补齐缺失指令。") + if "compact_command_table_holdout_failed" in reason: + return ("FIT-COMPACT-HOLDOUT-508", "精简单张指令查表未通过独立视觉验收,已禁止发布。", + "查看具体角度和空间误差;若回差过大,单张表不能准确表达实机,不自动回退或重新调参。") + if "steady_" in reason and ("failed" in reason or "incomplete" in reason or "missing" in reason): + return ("FIT-COMMAND-MAPPING-506", "稳态指令与独立视觉观测不足或不一致,已禁止发布指令映射。", + "查看具体关节、方向、稳态点及诊断;反馈曲线不能替代缺失的指令标定。") + live_failures = { + "waiting_for_visual_motion_tags": ("OBS-MOTION-112", "运动前缺少所需关节的新鲜 Tag 图像。", "保持当前指令,检查所列关节的运动 Tag 和基准 Tag 是否完整可见。"), + "visual_motion_unavailable": ("OBS-MOTION-112", "运动观测所需的 Tag 图像持续缺失或过期。", "已暂停;检查所列关节对应的 Tag 和相机。"), + "visual_motion_not_observed": ("OBS-MOTION-113", "已下发明显运动,但图像未观察到对应关节运动。", "检查实际机构、指令响应及 Tag;该判断不使用位置反馈数值,也不能单独确定硬件原因。"), + "visual_motion_target_unconfirmed": ("OBS-MOTION-114", "图像尚未确认稳定到位或回到已冻结零位。", "已暂停;检查图像抖动、遮挡与实际姿态,不跳过确认继续释放避让。"), + "duplicate_controller": ("DEVICE-COMMAND-CONFLICT-204", "检测到另一个命令控制节点。", "退出 GUI 或其他控制节点,只保留本次标定。"), + "fixed_reference_moved": ("OBS-BASE-DRIFT-105", "已锁定的固定基准连续 10 帧漂移超过 5 px。", "检查手掌、相机、支架和固定 Tag;重新固定后开始新采集。"), + "sdk_disconnected": ("DEVICE-COMMUNICATION-202", "SDK 通信或健康报告持续失效。", "检查供电、连接及 SDK 日志;不要直接重复强推动作。"), + "wrong_control_mode": ("DEVICE-MODE-205", "SDK 未确认位置控制模式。", "确认 POSITION 模式,退出竞争控制进程后重新开始。"), + "hardware_fault": ("DEVICE-ACTIVE-FAULT-201", "SDK 报告活动硬件故障。", "根据下方原始错误码检查机械阻挡、温度和通信。"), + "feedback_stale": ("DEVICE-FEEDBACK-203", "SDK 反馈连续超过 1 秒未更新。", "检查 SDK 回读和总线;终端进度不变不等于反馈失联。"), + "physical_range_exceeded": ("DEVICE-PHYSICAL-RANGE-204", "命令或反馈越过声明的物理范围。", "核对通道、单位、编码器范围;不要通过扩大边界掩盖异常。"), + "protected_camera_model_changed": ("OBS-CAMERA-MODEL-106", "开始后相机投影模型或图像尺寸发生变化。", "中止后重新确认相机参数;涉及机位关系变化时重标外参。"), + "finalization_protocol_error": ("FIT-PROTOCOL-502", "拟合与发布阶段顺序异常,已禁止发布。", "保留当前会话和日志,检查后台验收的完整诊断。"), + "invalid_motion_target": ("MOTION-CONTRACT-304", "运动段缺少有效的反馈推进目标。", "检查 Profile 和轨迹诊断;不要继续发送未经验证的运动。"), + } + if reason.split(":", 1)[0] in live_failures: + return live_failures[reason.split(":", 1)[0]] + runner_failures = { + "calibration_node_process_exited": "标定状态发布进程已退出,不能继续本次采集。", + "calibration_stack_exited": "标定 ROS 进程栈已退出。", + "calibration_node_initial_status_timeout": "启动后未收到标定节点状态;这不是机械堵转诊断。", + "calibration_checkpoint_preparation_timeout": "断点证据校验超过独立加载时限,尚未开始标定运动。", + "calibration_device_not_ready": "设备尚未满足启动条件,未自动开始任务运动。", + "calibration_start_service_unavailable": "设备报告就绪,但标定开始服务不可用。", + "calibration_start_response_timeout": "开始请求未收到确认,不能判断任务是否已启动;运行栈将退出。", + "calibration_start_rejected": "标定节点拒绝了开始请求。", + "ros_context_shutdown": "ROS 通信上下文已关闭。", + "independent_release_evidence_missing": "本次数据已通过旧格式会话校验,但缺少该格式要求的独立发布证据。", + "existing_calibration_publishers": "检测到已有 SDK 或控制进程,不能重复启动当前标定栈。", + } + if reason.split(":", 1)[0] in runner_failures: + return ( + "RUNTIME-LIFECYCLE-500", runner_failures[reason.split(":", 1)[0]], + "查看原始原因、runner_diagnostic.json 和 calibration.log;确认进程及设备状态后再启动。", + ) + # Legacy transport spellings are decoded here, not in a product runner. + if reason.startswith(("o12_feedback_stream_timeout", "feedback_stream_timeout")): + return ("DEVICE-FEEDBACK-203", "SDK 反馈连续超过 1 秒未更新。", + "检查供电、SDK 和实际总线连接;不要把终端进度不变当成反馈失联。") + if reason.startswith("o12_active_motor_fault"): + return ("DEVICE-ACTIVE-FAULT-201", f"SDK 返回活动电机故障:{status.get('error_faults', reason)}。", + "检查对应电机错误码、机械阻挡和温度;排除活动故障后再恢复。") + if reason.startswith("o12_new_communication_fault"): + return ("DEVICE-COMMUNICATION-202", f"SDK 运行中报告新的通信故障:{status.get('error_faults', reason)}。", + "检查 HCAN 连接、供电和相关电机通信。") + if reason.startswith(("feedback_outside_registered_feedback_domain", "command_outside_physical_range")): + return ("DEVICE-PHYSICAL-RANGE-204", f"命令或反馈超出登记的物理范围:{reason}。", + "核对通道、单位和硬件限位;不得扩大软件边界来掩盖异常。") + if reason.startswith(("mapping_preflight_no_target_motion", "mapping_preflight_wrong_feedback_direction")): + return ("DEVICE-MAPPING-301", f"固定通道点动未证实要求的目标反馈运动或方向:{reason}。", + "检查 SDK 通道与机械运动;不要自动交换映射或增加强推幅度。") + if "standard_urdf_mimic_not_expressive" in reason: + return ( + "FIT-STANDARD-MIMIC-504", + "独立视觉数据不能由同一条标准 URDF 线性 mimic 在规定精度内解释,已禁止发布。", + "检查 Tag 刚性和重复性;若机构确为非线性,应明确报告标准 URDF 表达能力不足,不能用 JSON 或端点比例补偿。", + ) + if "corrected range exceeds source mechanical range" in reason or "URDF mimic reachable range exceeds limits" in reason: + return ( + "URDF-PHYSICAL-RANGE-505", + f"修正范围或递归 mimic 与原始 CAD 机械限位不一致:{reason}。", + "保留原始 CAD 和测量数据,核实限位及坐标定义;不要扩大限位或裁剪曲线来制造通过结果。", + ) + if reason.startswith("fixed_base_tag_moved:"): + fields = reason.split(":") + view = fields[1] if len(fields) > 1 else "unknown" + view_label = str(status.get("view_label", view)) + match = re.search(r"drift_px=([0-9.]+)", reason) + drift = match.group(1) if match else "未知" + limit = float(status.get("base_corner_drift_limit_px", 5.0) or 5.0) + return ( + "OBS-BASE-DRIFT-105", + f"{view_label}机位的固定基准 Tag 连续漂移,最大角点位移 " + f"{drift} px,超过 {limit:g} px。", + "检查手掌支架、相机和固定基准 Tag 是否松动或被碰触;" + "固定后重新开始。程序已禁止发布本次结果。", + ) + if reason.startswith("sweep_quality_failed:"): + details = reason.split(":", 2)[-1] + return ( + "OBS-SWEEP-QUALITY-104", + "当前方向经过自动重扫后仍未满足采集门限;具体未通过项:" + f"{details}。", + "查看会话诊断中的有效样本、覆盖、分箱和数据空白;" + "处理持续遮挡或同步问题后从断点继续。", + ) + if reason.startswith("multiple_state_publishers:"): + count = status.get("state_publisher_count", "?") + return ( + "DEVICE-DUPLICATE-SDK-203", + f"检测到 {count} 个 {model_name} 状态发布者,可能已有 SDK/GUI 未退出。", + "停止单独启动的 SDK 和 GUI,只保留本次标定自动拉起的进程。", + ) + if reason.startswith("multiple_command_publishers:"): + count = status.get("command_publisher_count", "?") + return ( + "DEVICE-COMMAND-CONFLICT-204", + f"检测到 {count} 个 {model_name} 命令发布者。", + "停止 GUI、手动控制节点或其他标定进程,只保留当前标定命令。", + ) + if reason.startswith("mechanical_stall:"): + timeout = re.search(r"(?:[:,])timeout_seconds=([0-9]+(?:\.[0-9]+)?)(?:,|$)", reason) + duration = f" {timeout.group(1)} 秒" if timeout else "两秒" + if 'consecutive_failures=2' in reason: + return ('MOTION-STALL-303', + f'停滞后已等待 3 秒并重试一次,仍未获得有效反馈推进(预算{duration}),已停止。', + '本次硬件重试已用尽;检查执行器、反馈和机械阻挡。') + if 'active_no_progress_seconds=' in reason: + return ('MOTION-STALL-303', + f'当前扫描方向缺少有效反馈推进,运动时间预算为{duration}(不计计划内静止采样),已保持当前位置。', + '检查机械阻挡、执行器和反馈;硬件重试预算由采集记录独立保存。') + if 'consecutive_failures=3' in reason: + return ('MOTION-STALL-303', + f'同一运动连续 3 次失败,每次反馈{duration}未推进;两次重发前均等待 3 秒,已停止。', + '检查机械阻挡、执行器和实际行程;本次重试预算已用尽。') + return ( + "MOTION-STALL-303", + f"目标电机连续{duration}没有向目标推进,程序已保持当前位置。", + "检查碰撞、摩擦和机械端点;不要连续重启强推。", + ) + if reason.startswith("motion_timeout:"): + return ( + "MOTION-TIMEOUT-302", + "当前运动在规定时间内没有完成。", + "检查 SDK 反馈、电机状态和机械阻挡后重新开始。", + ) + if reason.startswith("fit_or_publication_failed:"): + if "mimic_residual_exceeds:" in reason or "coupling_residual_exceeds:" in reason: + joint = re.search(r"joint=([^:]+)", reason) + model = re.search(r"model=([^:]+)", reason) + multiplier = re.search(r"(?:multiplier|linear_term)=([0-9.]+)", reason) + p95 = re.search(r"p95_deg=([0-9.]+)", reason) + maximum = re.search(r"maximum_deg=([0-9.]+)", reason) + return ( + "FIT-MIMIC-503", + f"{joint.group(1) if joint else '未知关节'} 的 " + f"{model.group(1) if model else 'linear_mimic'} " + "耦合模型未达到精度门限:" + f"线性项 {multiplier.group(1) if multiplier else '未知'}," + f"P95={p95.group(1) if p95 else '未知'}°、" + f"最大={maximum.group(1) if maximum else '未知'}°。", + "原始视觉曲线已保留;请检查 Tag 刚性、遮挡与机械重复性," + "不要放宽门限或发布错误 URDF。", + ) + detail = reason.split(":", 1)[1] if ":" in reason else "未知" + return ( + "FIT-PUBLISH-501", + f"拟合、holdout 或 URDF 安全写回失败:{detail}。", + "保留本会话和源 URDF;查看诊断日志。", + ) + if reason.startswith("operator_abort"): + return ( + "OPERATOR-ABORT-001", + "操作员主动中止了本次标定。", + "排除现场问题后重新开始。", + ) + return ( + "CALIBRATION-500", + f"{model_name} 标定停止,原始原因:{reason}。", + "保留会话目录和运行日志,并复制诊断信息给开发者。", + ) + + +__all__ = ["reason_zh"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/resume.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/resume.py new file mode 100644 index 0000000..887528e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/resume.py @@ -0,0 +1,375 @@ +"""Reference- and input-bound checkpoint compatibility for every model.""" + +from __future__ import annotations + +from dataclasses import dataclass, field +import json +import math +from pathlib import Path +import re +from typing import Any, Mapping, Sequence + +import numpy as np + +from ..core.geometry.pnp import POSE_TRACKING_POLICY_VERSION +from .engine import ACQUISITION_POLICY_VERSION, SUPPORTED_CAPTURE_SCHEDULE_VERSIONS +from .diagnostic_capture import reject_diagnostic_capture +from ..core.domain.motion_path import record_scan_identity + + +def _compatible_header(header, profile_id, serial_number, serial_fallback, protected_hashes): + model, side, layout, _revision = profile_id.split("/") + recorded_id = header.get("profile_id") + if recorded_id is None: + # Read-only legacy journal spelling; the profile hash remains + # mandatory and identifies the exact YAML contract. + if (header.get("model"), header.get("hand_type"), header.get("tag_layout")) != (model, side, layout): + return False + elif recorded_id != profile_id: + return False + if header.get("serial_number", serial_fallback) != serial_number: + return False + if header.get("acquisition_policy_version") != ACQUISITION_POLICY_VERSION: + return False + if header.get("capture_schedule_version") not in SUPPORTED_CAPTURE_SCHEDULE_VERSIONS: + return False + if header.get("pose_tracking_policy_version") != POSE_TRACKING_POLICY_VERSION: + return False + recorded = header.get("protected_hashes", header) + if not isinstance(recorded, Mapping) or any(recorded.get(key) != value for key, value in protected_hashes.items()): + return False + return True + + +def discover_resume_candidate( + session_root: Path, *, profile_id: str, serial_number: str, + protected_hashes: Mapping[str, str], + training_policy: str = "fixed", + preparation_contract: Mapping[str, Any] | None = None, + rejected_candidates: list | None = None, +) -> Path | None: + """Locate evidence, never authorize its reuse or publish from a checkpoint. + + The online owner applies the product's declared reuse policy. A newer + empty/truncated attempt cannot shadow an + older complete capture. Old source files are never modified. + """ + if not protected_hashes or any(re.fullmatch(r"[0-9a-f]{64}", value) is None + for value in protected_hashes.values()): + raise ValueError("resume discovery requires valid protected hashes") + root = session_root.resolve() + if not root.is_dir(): + return None + released = { + pointer.resolve() for pointer in root.iterdir() + if pointer.name.startswith("latest_") and "passed" in pointer.name and pointer.is_symlink() + } + best, best_completed = None, -1 + for candidate in sorted(root.iterdir(), key=lambda path: path.name, reverse=True): + if candidate.is_symlink() or not candidate.is_dir() or candidate.name.startswith("latest_"): + continue + if candidate in released or any(candidate.name <= path.name for path in released if path.parent == root): + continue + start = None + reference_found = False + completed_found = False + raw_capture_found = False + completed = {} + try: + summary_path = candidate / "calibration_summary_zh.json" + if summary_path.exists(): + summary = json.loads(summary_path.read_text(encoding="utf-8")) + if not isinstance(summary, Mapping) or summary.get("result") != "FAIL": + # A successful capture awaiting a separate release proof + # is not a failed checkpoint. Reusing it cannot create an + # independent second calibration session. + continue + with (candidate / "raw_samples.jsonl").open(encoding="utf-8") as stream: + for line in stream: + if not line.strip(): + continue + row = json.loads(line) + if not isinstance(row, dict): + raise ValueError("invalid checkpoint record") + reject_diagnostic_capture((row,)) + kind = str(row.get("kind", "")) + if training_policy == 'raw_joint_2_plus_1' and kind in {'raw_observation_frame', 'scan_unit_complete'}: + raw_capture_found = True + if kind == "session_start": + from ..core.artifacts.evidence_journal import REFERENCE_KEY, decode_envelope + if REFERENCE_KEY in row: + from ..core.geometry.frozen_evidence import EvidenceDecoder + row = decode_envelope(candidate / "raw_samples.jsonl", row, + EvidenceDecoder(verify_hashes=False)) + if start is not None: + raise ValueError("multiple checkpoint session headers") + start = row + plan = start.get("capture_plan", {}) + if not isinstance(plan, Mapping) or plan.get("policy", "fixed") != training_policy: + raise ValueError("checkpoint training policy differs") + if not _compatible_header(start, profile_id, serial_number, root.name, protected_hashes): + raise ValueError("checkpoint header incompatible") + if start.get("preparation_contract") != preparation_contract: + raise ValueError("checkpoint preparation contract changed") + if kind == "fixed_base_reference_locked": + reference_found = True + if kind == "scan_unit_complete" or kind.endswith("sweep_observation_quality"): + # Old direction records used an explicit empty failure + # list instead of a boolean. This merely finds a source; + # the node applies the selected checkpoint reuse policy. + passed = row.get("passed") is True or ( + "passed" not in row and row.get("failures") == [] + and int(row.get("valid_frames", 0)) >= 40 + and int(row.get("feedback_bins", 0)) >= 32 + ) + completed_found = completed_found or passed + identity = record_scan_identity(row) + attempt = int(row.get("attempt", 1)) + previous = completed.get(identity) + if previous is None or attempt >= previous[0]: + completed[identity] = (attempt, passed) + except (OSError, ValueError) as error: + if rejected_candidates is not None: + rejected_candidates.append(dict(session=candidate.name, reason=str(error))) + # An explicit fresh run is a lineage boundary even if its header + # cannot be reused. Do not resurrect evidence from before it. + if start is not None and start.get("resume_checkpoint_requested") is False: + break + continue + if start is None or not reference_found or not (completed_found or raw_capture_found): + continue + count = sum(passed for _attempt, passed in completed.values()) + if count > best_completed: + best, best_completed = candidate, count + # A resumed process may stop after importing only its first task. + # Prefer the most complete checkpoint in the same restart lineage; + # equal coverage keeps the newest record. Never reach across an + # explicit fresh capture to resurrect superseded physical evidence. + if start.get("resume_checkpoint_requested") is False: + break + return best + + +@dataclass(frozen=True) +class TagPoseFingerprint: + rotation_xyzw: tuple[float, float, float, float] + translation_xyz_m: tuple[float, float, float] + + +@dataclass(frozen=True) +class ResumeFingerprint: + profile_id: str + protected_hashes: Mapping[str, str] + fixed_corners_by_view: Mapping[str, tuple[tuple[float, float], ...]] + fixed_poses: Mapping[str, TagPoseFingerprint] = field(default_factory=dict) + moving_tag_poses: Mapping[str, TagPoseFingerprint] = field(default_factory=dict) + acquisition_policy_version: str = ACQUISITION_POLICY_VERSION + + +@dataclass(frozen=True) +class ResumeDecision: + reuse: bool + reason: str + incompatible_fields: tuple[str, ...] = () + completed_units: tuple[tuple[str, int, str], ...] = () + + +def select_installation_evidence(previous, current, required_roles): + """Compare a reused Tag at the SAME baseline or named verification pose. + + Unrelated Tags do not authorize reuse, and a missing fingerprint cannot be + replaced with another pose's installation. Do not mutate either journal. + """ + from dataclasses import replace + old, new = {}, {} + shared = previous.moving_tag_poses.keys() & current.moving_tag_poses.keys() + for role in required_roles: + candidates = sorted(key for key in shared if key == role or key.endswith("/"+role)) + if not candidates: + continue # ResumeVerifier will reject the missing required role. + key = role if role in candidates else candidates[0] + old[role], new[role] = previous.moving_tag_poses[key], current.moving_tag_poses[key] + return replace(previous, moving_tag_poses=old), replace(current, moving_tag_poses=new) + + +class ResumeVerifier: + """A mismatch starts fresh; it is never a live safety pause.""" + + def __init__( + self, + *, + maximum_corner_drift_px: float = 5.0, + maximum_rotation_rad: float = math.radians(2.0), + maximum_translation_m: float = 0.005, + required_fixed_views: Sequence[str] = (), + required_fixed_poses: Sequence[str] = (), + required_moving_poses: Sequence[str] = (), + required_hashes: Sequence[str] = (), + ) -> None: + self.maximum_corner_drift_px = float(maximum_corner_drift_px) + self.maximum_rotation_rad = float(maximum_rotation_rad) + self.maximum_translation_m = float(maximum_translation_m) + if not all(math.isfinite(value) and value > 0 for value in ( + self.maximum_corner_drift_px, self.maximum_rotation_rad, self.maximum_translation_m + )): + raise ValueError("resume tolerances must be finite and positive") + self.required_fixed_views = frozenset(required_fixed_views) + self.required_fixed_poses = frozenset(required_fixed_poses) + self.required_moving_poses = frozenset(required_moving_poses) + self.required_hashes = frozenset(required_hashes) + + def compare( + self, previous: ResumeFingerprint, current: ResumeFingerprint + ) -> ResumeDecision: + failures: list[str] = [] + for label, fingerprint in (("previous", previous), ("current", current)): + if not fingerprint.profile_id: + failures.append(f"{label}.profile_id") + if not fingerprint.protected_hashes or not self.required_hashes <= fingerprint.protected_hashes.keys(): + failures.append(f"{label}.required_hashes") + if any(re.fullmatch(r"[0-9a-f]{64}", str(value)) is None for value in fingerprint.protected_hashes.values()): + failures.append(f"{label}.invalid_hash") + if not fingerprint.fixed_corners_by_view or not self.required_fixed_views <= fingerprint.fixed_corners_by_view.keys(): + failures.append(f"{label}.required_fixed_views") + if not fingerprint.fixed_poses or not self.required_fixed_poses <= fingerprint.fixed_poses.keys(): + failures.append(f"{label}.required_fixed_poses") + if not self.required_moving_poses <= fingerprint.moving_tag_poses.keys(): + failures.append(f"{label}.required_moving_poses") + if previous.acquisition_policy_version != ACQUISITION_POLICY_VERSION: + failures.append("acquisition_policy_version") + if current.acquisition_policy_version != ACQUISITION_POLICY_VERSION: + failures.append("current_acquisition_policy_version") + if previous.profile_id != current.profile_id: + failures.append("profile_id") + if dict(previous.protected_hashes) != dict(current.protected_hashes): + failures.append("protected_hashes") + self._compare_corners(previous, current, failures) + self._compare_poses( + "fixed_pose", previous.fixed_poses, current.fixed_poses, failures + ) + self._compare_poses( + "moving_tag_pose", + previous.moving_tag_poses, + current.moving_tag_poses, + failures, + ) + if failures: + return ResumeDecision( + False, + "基准变化,已放弃旧断点并重新采集", + tuple(sorted(set(failures))), + ) + return ResumeDecision(True, "断点基准和 Tag 安装关系验证通过") + + def _compare_corners( + self, + previous: ResumeFingerprint, + current: ResumeFingerprint, + failures: list[str], + ) -> None: + if set(previous.fixed_corners_by_view) != set( + current.fixed_corners_by_view + ): + failures.append("fixed_reference_views") + return + for view, previous_corners in previous.fixed_corners_by_view.items(): + old = np.asarray(previous_corners, dtype=float) + new = np.asarray(current.fixed_corners_by_view[view], dtype=float) + if old.shape != (4, 2) or new.shape != (4, 2): + failures.append(f"fixed_corners[{view}]") + continue + drift = float(np.max(np.linalg.norm(old - new, axis=1))) + if not math.isfinite(drift) or drift > self.maximum_corner_drift_px: + failures.append(f"fixed_corners[{view}]") + + def _compare_poses( + self, + prefix: str, + previous: Mapping[str, TagPoseFingerprint], + current: Mapping[str, TagPoseFingerprint], + failures: list[str], + ) -> None: + if set(previous) != set(current): + failures.append(f"{prefix}s") + return + for name, old in previous.items(): + new = current[name] + old_translation = np.asarray(old.translation_xyz_m, dtype=float) + new_translation = np.asarray(new.translation_xyz_m, dtype=float) + if (old_translation.shape != (3,) or new_translation.shape != (3,) + or not np.all(np.isfinite(old_translation)) or not np.all(np.isfinite(new_translation))): + failures.append(f"{prefix}[{name}].translation") + continue + translation = float( + np.linalg.norm( + old_translation - new_translation + ) + ) + rotation = _quaternion_distance_rad( + old.rotation_xyzw, new.rotation_xyzw + ) + if translation > self.maximum_translation_m: + failures.append(f"{prefix}[{name}].translation") + if rotation > self.maximum_rotation_rad: + failures.append(f"{prefix}[{name}].rotation") + + +def _quaternion_distance_rad( + left: Sequence[float], right: Sequence[float] +) -> float: + first = np.asarray(tuple(left), dtype=float) + second = np.asarray(tuple(right), dtype=float) + if first.shape != (4,) or second.shape != (4,): + return math.inf + if not np.all(np.isfinite(first)) or not np.all(np.isfinite(second)): + return math.inf + first_norm = float(np.linalg.norm(first)) + second_norm = float(np.linalg.norm(second)) + if first_norm <= 0.0 or second_norm <= 0.0: + return math.inf + dot = abs(float(np.dot(first / first_norm, second / second_norm))) + return 2.0 * math.acos(min(1.0, max(-1.0, dot))) + + +def fingerprint_from_mapping(payload: Mapping[str, Any]) -> ResumeFingerprint: + """Strictly decode persisted v2 data; incomplete v1 data cannot be reused.""" + + def poses(key: str) -> dict[str, TagPoseFingerprint]: + return { + str(name): TagPoseFingerprint( + tuple(float(value) for value in value["rotation_xyzw"]), + tuple(float(value) for value in value["translation_xyz_m"]), + ) + for name, value in dict(payload.get(key, {})).items() + } + + return ResumeFingerprint( + profile_id=str(payload.get("profile_id", "")), + protected_hashes={ + str(key): str(value) + for key, value in dict(payload.get("protected_hashes", {})).items() + }, + fixed_corners_by_view={ + str(view): tuple( + tuple(float(coordinate) for coordinate in point) + for point in corners + ) + for view, corners in dict( + payload.get("fixed_corners_by_view", {}) + ).items() + }, + fixed_poses=poses("fixed_poses"), + moving_tag_poses=poses("moving_tag_poses"), + acquisition_policy_version=str( + payload.get("acquisition_policy_version", "") + ), + ) + + +__all__ = [ + "ResumeDecision", + "ResumeFingerprint", + "ResumeVerifier", + "TagPoseFingerprint", + "fingerprint_from_mapping", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/resume_storage.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/resume_storage.py new file mode 100644 index 0000000..c80549d --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/resume_storage.py @@ -0,0 +1,137 @@ +"""Bounded memory for passed-task imports; original image bytes stay on disk. + +Startup needs scan identities, persisted passes and reference provenance. Large +per-image payloads are only needed when a bounded import batch is written. Each +deferred row is bound to the exact bytes read during indexing, so replacing or +editing a checkpoint cannot silently change an import after it was prepared. +""" + +from collections.abc import Mapping +import hashlib +import json +from pathlib import Path +from functools import lru_cache + +from ..core.geometry.frozen_evidence import EvidenceDecoder + + +@lru_cache(maxsize=256) +def _shared_field_names(fields): + return fields + + +class DeferredCaptureRecord(Mapping): + __slots__ = ("path", "offset", "length", "digest", "metadata", "field_names", "decoder", "reference", "canonical_sha256") + + def __init__(self, path, offset, line, row, decoder): + self.path, self.offset, self.length = path, offset, len(line) + self.digest = hashlib.sha256(line).digest() + self.metadata = {k: v for k, v in row.items() + if v is None or isinstance(v, (str, int, float, bool))} + self.field_names = tuple(row) + self.decoder = decoder + self.reference = None + self.canonical_sha256 = None + + @classmethod + def from_envelope(cls, path, envelope, decoder): + from ..core.artifacts.evidence_journal import ( + CANONICAL_SHA256_KEY, FIELDS_KEY, REFERENCE_KEY, SCHEMA_KEY, _schema_fields, + ) + value = object.__new__(cls) + value.path, value.offset, value.length = path, 0, 0 + from ..core.artifacts.evidence_journal import EvidenceRecordReference + value.reference = EvidenceRecordReference.from_mapping(envelope[REFERENCE_KEY]) + value.digest = bytes.fromhex(value.reference.record_sha256) + value.canonical_sha256 = envelope.get(CANONICAL_SHA256_KEY) + value.metadata = {key: item for key, item in envelope.items() + if key not in {REFERENCE_KEY, FIELDS_KEY, SCHEMA_KEY, CANONICAL_SHA256_KEY}} + fields = envelope.get(FIELDS_KEY) + if fields is None and SCHEMA_KEY in envelope: + fields = _schema_fields(path, envelope[SCHEMA_KEY]) + value.field_names = None if fields is None else _shared_field_names(tuple(fields)) + value.decoder = decoder + return value + + def materialize(self): + return self.decoder.loads(self._record_bytes()) + + def materialize_plain(self): + """Decode one integrity-checked row without building shared models.""" + return json.loads(self._record_bytes()) + + def _record_bytes(self): + if self.reference is not None: + from ..core.artifacts.evidence_journal import evidence_record_bytes + return evidence_record_bytes(self.path, self.reference) + with self.path.open("rb") as stream: + stream.seek(self.offset) + line = stream.read(self.length) + if hashlib.sha256(line).digest() != self.digest: + raise ValueError("resume_source_record_changed") + return line + + def __getitem__(self, key): + if key in self.metadata: + return self.metadata[key] + if self.field_names is not None and key not in self.field_names: + raise KeyError(key) + return self.materialize()[key] + + def __iter__(self): + return iter(self.materialize() if self.field_names is None else self.field_names) + + def __len__(self): + return len(self.materialize()) if self.field_names is None else len(self.field_names) + + +def materialize_record(row): + return row.materialize() if isinstance(row, DeferredCaptureRecord) else row + + +def materialize_plain_record(row): + return row.materialize_plain() if isinstance(row, DeferredCaptureRecord) else row + + +def load_passed_capture(path): + """Read once without retaining every scan's expanded image dictionaries. + + No historical image fitting or hash verification is introduced. Provenance + remains eager, while per-image records retain their full field interface. + Final artifact replay still reads and verifies the complete journal. + """ + path = Path(path).resolve() + decoder = EvidenceDecoder(verify_hashes=False) + rows = [] + deferred_kinds = {"joint_sample", "secondary_joint_sample", "pnp_candidate_frame"} + from ..core.artifacts.evidence_journal import REFERENCE_KEY + with path.open("rb") as stream: + number = 0 + while True: + offset = stream.tell() + line = stream.readline() + if not line: + break + number += 1 + if not line.strip(): + continue + try: + # Indexed envelopes contain only scalar lookup fields and an + # evidence reference. Running the recursive evidence decoder + # over tens of thousands of these small rows dominated resume + # startup even though there is no model to intern. Preserve + # the decoder for the few inline records that carry shared + # frozen objects. + needs_evidence_decoder = (b'"frozen_image_model"' in line + or b'"reference_frame"' in line) + row = decoder.loads(line) if needs_evidence_decoder else json.loads(line) + except json.JSONDecodeError as error: + raise ValueError(f"invalid calibration JSONL at line {number}") from error + if not isinstance(row, dict): + raise ValueError(f"calibration JSONL record is not an object at line {number}") + if REFERENCE_KEY in row: + row = DeferredCaptureRecord.from_envelope(path, row, decoder) + elif row.get("kind") in deferred_kinds: + row = DeferredCaptureRecord(path, offset, line, row, decoder) + rows.append(row) + return rows diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/revisit.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/revisit.py new file mode 100644 index 0000000..a661d27 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/revisit.py @@ -0,0 +1,75 @@ +"""Fresh evidence checks that preserve the original zero and installation.""" + +import numpy as np + +from .joint_resume import reference_pose_failures +from .motion_execution import feedback_tolerances + + +LEGACY_REVISIT_POLICY = "staged_revisit_v1" +REVISIT_POLICY = "staged_revisit_v2" + + +def validated_feedback_limits(profile, verification, feedback_limits): + """Replay the declared feedback contract, without upgrading old evidence.""" + limits = revisit_feedback_limits(profile, verification) + if ((verification == REVISIT_POLICY and feedback_limits != limits) + or (verification == LEGACY_REVISIT_POLICY and feedback_limits is not None)): + raise ValueError("reference_feedback_policy_changed") + return limits + + +def revisit_feedback_limits(profile, verification=REVISIT_POLICY): + """Separate within-hold stability from between-visit repeatability. + + O30's operator-reported repeatability is 10 native SDK units. This does + not change motion settling, image precision, or another hand's limits. + Historical records retain their original feedback acceptance semantics. + """ + if verification not in {LEGACY_REVISIT_POLICY, REVISIT_POLICY}: + raise ValueError("staged_revisit_policy_unknown") + stability = feedback_tolerances(profile.command.unit).stability + repeatability = 2*stability + if verification == REVISIT_POLICY and profile.key.model.upper() == "O30" and profile.command.unit == "u8": + repeatability = 10.0 + return dict(unit=profile.command.unit, within_hold_range=stability, + between_visit_difference=repeatability) + + +def verify_revisit(profile, previous, current, *, verification=LEGACY_REVISIT_POLICY, + feedback_limits=None): + limits = revisit_feedback_limits(profile, verification) + if ((verification == REVISIT_POLICY and feedback_limits != limits) + or (verification == LEGACY_REVISIT_POLICY and feedback_limits is not None)): + raise ValueError("staged_revisit_feedback_policy_changed") + failures = reference_pose_failures(previous, current) + identities = lambda ref: {(b.view, b.tag_role, b.motion_evidence_id) for b in ref.branch_references} + if not previous.branch_references or identities(previous) != identities(current): + failures.append("installation_evidence_changed") + for view in {s.view for s in previous.samples}: + old = [s for s in previous.samples if s.view == view] + new = [s for s in current.samples if s.view == view] + if not new or min(s.image_stamp_ns for s in new) <= max(s.image_stamp_ns for s in old): + failures.append("fresh_images_missing") + continue + if not profile.vision_motion: + before, after = np.asarray([s.feedback for s in old]), np.asarray([s.feedback for s in new]) + if (before.shape != (len(old), profile.command.command_count) + or after.shape != (len(new), profile.command.command_count) + or not np.all(np.isfinite(before)) or not np.all(np.isfinite(after))): + failures.append("feedback_missing") + else: + if (np.any(np.ptp(after, axis=0) > limits["within_hold_range"]) + or np.any(np.abs(after-np.median(before, axis=0)) > limits["between_visit_difference"])): + failures.append("held_feedback_changed") + if failures: + raise ValueError(f"revisit_reference_changed:{previous.joint}:{','.join(failures)}") + + +def revisit_record(profile, previous, current, cycle): + limits = revisit_feedback_limits(profile) + verify_revisit(profile, previous, current, verification=REVISIT_POLICY, feedback_limits=limits) + return {"kind": "joint_zero_motion_reference_verified", "verification": REVISIT_POLICY, + "feedback_limits": limits, + "joint": previous.joint, "task_name": previous.task_key, "cycle": cycle, + "current_reference": current.as_record(), "preserved_reference": previous.as_record()} diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/__init__.py new file mode 100644 index 0000000..aa55c25 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/__init__.py @@ -0,0 +1 @@ +"""Thin ROS interfaces for the single calibration session engine.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/calibration_node.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/calibration_node.py new file mode 100644 index 0000000..4c94422 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/calibration_node.py @@ -0,0 +1,175 @@ +"""ROS identity, parameters and callback wiring for the shared coordinator.""" + +from contextlib import contextmanager +import gc +import time + +from rclpy.executors import SingleThreadedExecutor +from rclpy.node import Node +from rclpy.qos import qos_profile_sensor_data +from sensor_msgs.msg import CameraInfo, JointState +from std_msgs.msg import String +from std_srvs.srv import Trigger + +from ..adapters.ros_binding import SdkBindingPorts, bind_ros_sdk +from ..coordinator import CalibrationCoordinator +from ..branch_worker import IsolatedBranchSolver +from ...core.geometry.tag_pose.image_projection_worker import ImageProjectionWorker +from ..inputs import RuntimePorts +from ..profile_contract import resolve_runtime_profile +from .io import RosCalibrationIO, _stamp_ns, camera_input, checked_detection_input +from .parameters import load_runtime_parameters, parameter_defaults + + +class UnifiedCalibrationNode(Node): + def __init__(self, profile): + super().__init__(f"{profile.key.model.lower()}_calibration") + for name, default in parameter_defaults(profile).items(): + self.declare_parameter(name, default) + profile = resolve_runtime_profile(profile, lambda name: self.get_parameter(name).value) + parameters = load_runtime_parameters(profile, lambda name: self.get_parameter(name).value) + self.io = RosCalibrationIO(self, profile, parameters) + from ..timing_diagnostics import RuntimeTimingDiagnostics + self.timing_diagnostics = RuntimeTimingDiagnostics(parameters.session_dir / "runtime_timing_diagnostic.jsonl") + ports = RuntimePorts(lambda: int(self.get_clock().now().nanoseconds), time.monotonic, + lambda: self.count_publishers(parameters.command_topic), + self.io.publish_position, self.io.publish_setting) + + def subscribe_health(receive): + from ..adapters.ros_topics import sdk_topics + topic = sdk_topics(profile).health or parameters.command_topic.rsplit("/", 1)[0]+"/calibration_health" + self.create_subscription(String, + topic, + lambda message: receive(message.data), 10) + + def adapter_factory(publish, set_speed, feedback_fresh): + return bind_ros_sdk(profile, SdkBindingPorts(feedback_fresh, ports.monotonic, subscribe_health), + publish=publish, set_speed=set_speed) + + self.branch_solver = IsolatedBranchSolver(parameters.session_dir / "motion_solver_diagnostic.jsonl") + self.projection_worker = ImageProjectionWorker() + from ..artifacts.controller import FinalizationController + from ..startup import checkpoint_heartbeat + with checkpoint_heartbeat(self.io.publish_status, + enabled=parameters.resume_raw_samples_path is not None): + self.coordinator = CalibrationCoordinator(profile, parameters, ports, adapter_factory, + finalization=FinalizationController(profile, parameters.session_dir, isolated=True), + initialization_solver=self.branch_solver, projection_worker=self.projection_worker) + from ..detection_dispatch import DetectionDispatcher + self.detection_dispatch = DetectionDispatcher(self.coordinator.required_observation_views, + self.coordinator.receive_detections, + maximum_wait_seconds=parameters.maximum_state_image_skew_ns/1e9, + failed=lambda error: self.get_logger().error(f"image processing failed: {error}")) + self.fixed_ids = {view.name: frozenset(t.tag_id for t in view.tags if t.fixed_reference) + for view in profile.vision.views} + if profile.sdk_adapter == "legacy_byte_sdk": + self.create_subscription(String, parameters.state_topic+"_timed", self._timed_state_callback, 30) + else: + self.create_subscription(JointState, parameters.state_topic, self._state_callback, 30) + for view in self.coordinator.required_observation_views: + self.create_subscription(CameraInfo, parameters.camera_info_topics[view], + lambda message, selected=view: self._camera_info_callback(selected, message), + qos_profile_sensor_data) + self.create_subscription(String, parameters.detection_topics[view]+"_checked", + lambda message, selected=view: self._detections_callback(selected, message), + qos_profile_sensor_data) + self.create_service(Trigger, f"{profile.namespace}/start", self._start) + self.create_service(Trigger, f"{profile.namespace}/abort", self._abort) + self.create_timer(1.0/parameters.command_rate_hz, self._tick) + self.create_timer(0.5, self._publish_status) + + def _start(self, _request, response): + self.detection_dispatch.clear() + result = self.coordinator.start() + response.success, response.message = result.success, result.message + return response + + def _abort(self, _request, response): + self.detection_dispatch.clear() + result = self.coordinator.abort() + response.success, response.message = result.success, result.message + return response + + def _state_callback(self, message): + self._receive_feedback(tuple(message.name), tuple(message.position), _stamp_ns(message.header.stamp)) + + def _timed_state_callback(self, message): + from ..feedback import decode_timed_feedback + try: + names, positions, stamp, channel_stamps = decode_timed_feedback(message.data) + except (ValueError, TypeError) as error: + self.get_logger().error(str(error)) + return # Invalid data cannot refresh the independent feedback watchdog. + self._receive_feedback(names, positions, stamp, channel_stamps_ns=channel_stamps) + + def _receive_feedback(self, names, positions, stamp, *, channel_stamps_ns=()): + sample = self.coordinator.receive_feedback(names, positions, stamp, channel_stamps_ns=channel_stamps_ns) + if sample is not None: + self.detection_dispatch.feedback_available(min(sample.channel_stamps_ns or (sample.stamp_ns,))) + + def _camera_info_callback(self, view, message): + self.coordinator.receive_camera_info(view, camera_input(message)) + + def _detections_callback(self, view, message): + self.detection_dispatch.submit(checked_detection_input(view, message, + fixed_ids=self.fixed_ids[view])) + + def _tick(self): + self.detection_dispatch.raise_if_failed() + started = time.perf_counter() + try: + self.coordinator.tick() + finally: + self.timing_diagnostics.record("control_tick", started) + + def _publish_status(self): + self.io.publish_status(self.coordinator.snapshot()) + self.timing_diagnostics.flush() + + def destroy_node(self): + self.detection_dispatch.close() + self.branch_solver.close() + self.projection_worker.close() + self.coordinator.close() + self.timing_diagnostics.close() + return super().destroy_node() + + +@contextmanager +def _frozen_startup_graph(): + """Exclude the resident checkpoint from cyclic scans during live callbacks. + + This dedicated process owns its collector lifecycle. Preparation can load + hundreds of MB of validated, long-lived records; revisiting that graph in + generation 2 can block feedback for seconds. New live objects still receive + normal cyclic collection, and ordinary reference counting stays enabled. + Restore the startup graph only after the executor and node have stopped. + """ + gc.collect() + gc.freeze() + try: + yield + finally: + gc.unfreeze() + + +def run_profile_node(profile, args=None): + import rclpy + rclpy.init(args=args) + node = UnifiedCalibrationNode(profile) + # ROS callbacks only decode messages and advance the control state. Heavy + # image work has its own bounded workers. Parallel ROS callbacks would + # compete for the same session lock and delay feedback and command ticks. + executor = SingleThreadedExecutor() + executor.add_node(node) + with _frozen_startup_graph(): + try: + executor.spin() + finally: + try: + executor.shutdown() + finally: + try: + node.destroy_node() + finally: + rclpy.shutdown() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/entrypoint.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/entrypoint.py new file mode 100644 index 0000000..62c11bd --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/entrypoint.py @@ -0,0 +1,38 @@ +"""Protected Profile handoff to the online execution implementation.""" + +from __future__ import annotations + +import argparse +import hashlib +from pathlib import Path +import sys + +from ...core import ProfileKey +from ...profiles import load_hand_profile + + +def run_profile_node(profile, args): + from .calibration_node import run_profile_node as run + return run(profile, args) + + +def main(args: list[str] | None = None) -> None: + arguments = list(sys.argv[1:] if args is None else args) + selector = argparse.ArgumentParser(add_help=False) + selector.add_argument("--profile-id", default=None) + selector.add_argument("--profile-config", default=None) + selector.add_argument("--profile-sha256", default=None) + selected, remaining = selector.parse_known_args(arguments) + if not all((selected.profile_id, selected.profile_config, selected.profile_sha256)): + raise ValueError("online calibration requires a protected YAML Profile; use calibrate_hand --config") + key = ProfileKey.parse(selected.profile_id) + path = Path(selected.profile_config) + def verify_hash(): + if hashlib.sha256(path.read_bytes()).hexdigest() != selected.profile_sha256: + raise ValueError("Profile changed between launch and calibration-node startup") + verify_hash() + declared = load_hand_profile(path) + verify_hash() + if declared.key != key: + raise ValueError("protected YAML Profile identity differs from --profile-id") + return run_profile_node(declared, remaining) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/io.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/io.py new file mode 100644 index 0000000..dfa52a1 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/io.py @@ -0,0 +1,78 @@ +"""ROS message conversion and publication; no calibration business state.""" + +from __future__ import annotations + +import json + +from sensor_msgs.msg import JointState +from std_msgs.msg import String + +from ..inputs import CameraModelInput, DetectionInput, TagDetection +from ..status import normalize_status + + +def _stamp_ns(stamp) -> int: + return int(stamp.sec)*1_000_000_000 + int(stamp.nanosec) + + +def camera_input(message) -> CameraModelInput: + return CameraModelInput(int(message.width), int(message.height), + tuple(message.k), tuple(message.d), tuple(message.r), tuple(message.p)) + + +def detection_input(view: str, message, *, gray=None, fixed_ids=()) -> DetectionInput: + from ...core.geometry.tag_border import inspect_tag_border + def convert(tag): + corners = tuple((float(p.x), float(p.y)) for p in tag.corners) + border = None + if int(tag.id) in fixed_ids: + border = ({"passed": False, "reason": "border_image_missing"} if gray is None + else inspect_tag_border(gray, corners)) + return TagDetection(int(tag.id), corners, int(tag.hamming), float(tag.decision_margin), border) + return DetectionInput(view, _stamp_ns(message.header.stamp), tuple( + convert(tag) for tag in message.detections)) + + +def checked_detection_input(view, message, *, fixed_ids): + data = json.loads(message.data) + if data.get("policy") != "image_border_checked_v1" or data.get("view") != view: + raise ValueError("checked detection provenance differs from subscribed view") + detections = tuple(TagDetection(int(tag["tag_id"]), tuple(map(tuple, tag["corners"])), + int(tag["hamming"]), float(tag["decision_margin"]), tag.get("border_quality")) + for tag in data["detections"]) + if any(tag.tag_id in fixed_ids and not isinstance(tag.border_quality, dict) for tag in detections): + raise ValueError("fixed Tag is missing its current-image border check") + return DetectionInput(view, int(data["stamp_ns"]), detections) + + +class RosCalibrationIO: + """Explicit transport object composed by UnifiedCalibrationNode.""" + + def __init__(self, node, profile, parameters): + self.profile = profile + self.serial_number = parameters.serial_number + self.clock = node.get_clock() + self.command_publisher = node.create_publisher(JointState, parameters.command_topic, 10) + self.setting_publisher = node.create_publisher(String, parameters.setting_topic, 10) + self.status_publisher = node.create_publisher(String, f"{profile.namespace}/status", 10) + + def publish_position(self, values) -> None: + message = JointState() + message.header.stamp = self.clock.now().to_msg() + message.name = [] if self.profile.command.feedback_by_index else list(self.profile.command.names) + message.position = list(values) + self.command_publisher.publish(message) + + def publish_setting(self, payload) -> None: + message = String() + message.data = json.dumps(payload) + self.setting_publisher.publish(message) + + def publish_status(self, snapshot) -> None: + message = String() + message.data = json.dumps(normalize_status(snapshot.as_dict(), + profile=self.profile, serial_number=self.serial_number), ensure_ascii=False) + self.status_publisher.publish(message) + + +__all__ = ["RosCalibrationIO"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/parameters.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/parameters.py new file mode 100644 index 0000000..6bb5964 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/parameters.py @@ -0,0 +1,197 @@ +"""Declare and convert ROS parameters into explicit coordinator inputs.""" + +from __future__ import annotations + +import math +from pathlib import Path +from typing import Any, Callable + +from ...core.geometry.extrinsics import load_camera_extrinsics +from ...core.geometry.pnp import DEFAULT_POSE_TRACKING_PARAMETERS, PoseTrackingParameters +from ..parameters import DetectionPolicy, RuntimeParameters + + +def parameter_defaults(profile) -> dict[str, Any]: + model = profile.key.model.lower() + namespace = profile.namespace + speed_parameters = profile.motion.speed_parameters + defaults: dict[str, Any] = { + "serial_number": "UNSET", + "session_dir": "", + "source_urdf_path": "", + "source_urdf_expected_sha256": "", + "camera_extrinsics_file": "", + "camera_extrinsics_expected_sha256": "", + "calibration_config_expected_sha256": "", + "tag_config_expected_sha256": "", + "sdk_config_expected_sha256": "", + "sdk_package_expected_sha256": "", + "profile_config_expected_sha256": "", + "resume_raw_samples_path": "", + "resume_mode": "verify", + "training_policy": profile.quality.training_policy, + "preparation_witnesses_json": "", + "capture_plan_expected_sha256": "", + "initial_command_file": "", + "reuse_camera_calibration": False, + "camera_optical_observations_file": "", + "command_topic": f"/{model}/cb_right_hand_control_cmd", + "state_topic": f"/{model}/cb_right_hand_state", + "setting_topic": f"/{model}/cb_hand_setting_cmd", + "commands_enabled": True, + "diagnostic_capture": "", + "speed_settle_seconds": float( + speed_parameters.get("speed_settle_seconds", 0.2) + ), + "torque_u8": int(speed_parameters.get("torque_u8", 80)), + "maximum_state_image_skew_ms": 50.0, + "maximum_hamming": 0, + "minimum_decision_margin": 30.0, + "minimum_edge_pixels": 30.0, + "tag_size_m": 0.016, + "pnp_maximum_reprojection_error_px": DEFAULT_POSE_TRACKING_PARAMETERS.maximum_reprojection_error_px, + "pnp_reprojection_tie_px": DEFAULT_POSE_TRACKING_PARAMETERS.reprojection_tie_px, + "pnp_maximum_pose_jump_deg": math.degrees(DEFAULT_POSE_TRACKING_PARAMETERS.maximum_pose_jump_rad), + "pnp_maximum_translation_jump_m": DEFAULT_POSE_TRACKING_PARAMETERS.maximum_translation_jump_m, + "pnp_maximum_tag_tilt_deg": math.degrees(DEFAULT_POSE_TRACKING_PARAMETERS.maximum_tag_tilt_rad), + "pnp_tracker_reset_seconds": DEFAULT_POSE_TRACKING_PARAMETERS.reset_after_seconds, + "pnp_branch_confirmation_frames": DEFAULT_POSE_TRACKING_PARAMETERS.branch_confirmation_frames, + "pnp_branch_confirmation_minimum_seconds": DEFAULT_POSE_TRACKING_PARAMETERS.branch_confirmation_minimum_seconds, + "pnp_branch_equivalence_deg": math.degrees(DEFAULT_POSE_TRACKING_PARAMETERS.branch_equivalence_rad), + "command_rate_hz": float(speed_parameters.get("command_rate_hz", 100.0)), + } + for view in profile.vision.view_names: + defaults[f"{view}_camera_info_topic"] = ( + f"{namespace}/{view}/camera/camera_info" + ) + defaults[f"{view}_detections_topic"] = ( + f"{namespace}/{view}/apriltag/detections" + ) + if profile.sdk_adapter == "o30_ros": + from ..adapters.ros_topics import sdk_topics + topics = sdk_topics(profile) + defaults.update(command_topic=topics.command, state_topic=topics.feedback, setting_topic=topics.setting) + return defaults + + +def load_runtime_parameters(profile, value: Callable[[str], Any]) -> RuntimeParameters: + from ..diagnostic_capture import resolve_diagnostic_capture + + diagnostic_capture = str(value("diagnostic_capture")).strip() + diagnostic = resolve_diagnostic_capture(profile, diagnostic_capture) + if diagnostic is not None and not bool(value("commands_enabled")): + raise ValueError("diagnostic_capture requires commands_enabled") + serial_number = str(value("serial_number")) + session_dir = Path(str(value("session_dir"))).expanduser().resolve() + source_urdf = Path(str(value("source_urdf_path"))).expanduser().resolve() + camera_extrinsics_file = Path( + str(value("camera_extrinsics_file")) + ).expanduser().resolve() + if serial_number in {"", "UNSET"}: + raise ValueError("serial_number is required") + if not str(value("session_dir")) or not source_urdf.is_file(): + raise ValueError("session_dir and immutable source_urdf_path are required") + if not camera_extrinsics_file.is_file(): + raise ValueError( + f"camera_extrinsics_file is required for {profile.key.model} zero solve" + ) + extrinsics = load_camera_extrinsics( + camera_extrinsics_file, + required_views=profile.vision.view_names, + reference_view=profile.vision.extrinsic_reference_view, + quality_limits=profile.vision.extrinsics_quality_limits, + minimum_capture_counts=profile.vision.minimum_capture_counts, + ) + protected_inputs = { + "source_urdf_sha256": str(value("source_urdf_expected_sha256")), + "camera_extrinsics_sha256": str( + value("camera_extrinsics_expected_sha256") + ), + "calibration_config_sha256": str( + value("calibration_config_expected_sha256") + ), + "tag_config_sha256": str(value("tag_config_expected_sha256")), + } + if "sdk_config_sha256" in profile.artifacts.protected_input_fields: + protected_inputs["sdk_config_sha256"] = str( + value("sdk_config_expected_sha256") + ) + if "sdk_package_sha256" in profile.artifacts.protected_input_fields: + protected_inputs["sdk_package_sha256"] = str(value("sdk_package_expected_sha256")) + if "profile_config_sha256" in profile.artifacts.protected_input_fields: + protected_inputs["profile_config_sha256"] = str( + value("profile_config_expected_sha256") + ) + resume_value = str(value("resume_raw_samples_path")).strip() + if diagnostic is not None and resume_value: + raise ValueError("diagnostic_capture does not support resuming prior samples") + resume_raw_samples_path = ( + None + if not resume_value + else Path(resume_value).expanduser().resolve() + ) + if ( + set(protected_inputs) + != profile.artifacts.protected_input_fields + or any(len(item) != 64 for item in protected_inputs.values()) + ): + raise ValueError("all profile-protected SHA-256 values are required") + command_topic = str(value("command_topic")) + state_topic = str(value("state_topic")) + setting_topic = str(value("setting_topic")) + camera_info_topics = { + view: str(value(f"{view}_camera_info_topic")) + for view in profile.vision.view_names + } + detection_topics = { + view: str(value(f"{view}_detections_topic")) + for view in profile.vision.view_names + } + skew_ns = int(float(value("maximum_state_image_skew_ms"))*1_000_000) + rate = float(value("command_rate_hz")) + settle = float(value("speed_settle_seconds")) + if not 0 < skew_ns <= 50_000_000: + raise ValueError("image/feedback synchronization bound must be within 50 ms") + if not 0 < rate <= 200: + raise ValueError("command_rate_hz must be in (0, 200]") + if not 0 <= settle <= 5: + raise ValueError("speed_settle_seconds must be in [0, 5]") + from ..adapters.command_seed import load_command_seed + initial_command, device_uid = load_command_seed(str(value("initial_command_file")), profile) + resume_mode = str(value("resume_mode")) + if resume_mode not in {"verify", "passed"}: + raise ValueError("resume_mode must be verify or passed") + return RuntimeParameters( + serial_number=serial_number, session_dir=session_dir, source_urdf=source_urdf, + camera_extrinsics_file=camera_extrinsics_file, extrinsics=extrinsics, + protected_inputs=protected_inputs, resume_raw_samples_path=resume_raw_samples_path, + command_topic=command_topic, state_topic=state_topic, setting_topic=setting_topic, + camera_info_topics=camera_info_topics, detection_topics=detection_topics, + commands_enabled=bool(value("commands_enabled")), speed_settle_seconds=settle, + torque_u8=int(value("torque_u8")), maximum_state_image_skew_ns=skew_ns, + command_rate_hz=rate, tag_size_m=float(value("tag_size_m")), + detection=DetectionPolicy(int(value("maximum_hamming")), + float(value("minimum_decision_margin")), float(value("minimum_edge_pixels"))), + tracking=tracking_parameters(value), + diagnostic_capture=diagnostic_capture, + initial_command=initial_command, initial_device_uid=device_uid, + resume_mode=resume_mode, + reuse_camera_calibration=bool(value("reuse_camera_calibration")), + camera_optical_observations_file=(Path(str(value("camera_optical_observations_file"))).expanduser().resolve() + if value("camera_optical_observations_file") else None), + ) + + +def tracking_parameters(value: Callable[[str], Any]) -> PoseTrackingParameters: + """ROS exposes degrees; the shared pose core receives radians.""" + return PoseTrackingParameters( + maximum_reprojection_error_px=float(value("pnp_maximum_reprojection_error_px")), + reprojection_tie_px=float(value("pnp_reprojection_tie_px")), + maximum_pose_jump_rad=math.radians(float(value("pnp_maximum_pose_jump_deg"))), + maximum_translation_jump_m=float(value("pnp_maximum_translation_jump_m")), + maximum_tag_tilt_rad=math.radians(float(value("pnp_maximum_tag_tilt_deg"))), + reset_after_seconds=float(value("pnp_tracker_reset_seconds")), + branch_confirmation_frames=int(value("pnp_branch_confirmation_frames")), + branch_confirmation_minimum_seconds=float(value("pnp_branch_confirmation_minimum_seconds")), + branch_equivalence_rad=math.radians(float(value("pnp_branch_equivalence_deg"))), + ) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/tag_border_filter.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/tag_border_filter.py new file mode 100644 index 0000000..fa715f5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/ros/tag_border_filter.py @@ -0,0 +1,71 @@ +"""Image preprocessing in its own process, isolated from SDK/control callbacks.""" + +import argparse +from dataclasses import asdict +import hashlib +import json +from pathlib import Path + +from apriltag_msgs.msg import AprilTagDetectionArray +from cv_bridge import CvBridge +import rclpy +from rclpy.node import Node +from rclpy.qos import qos_profile_sensor_data +from sensor_msgs.msg import Image +from std_msgs.msg import String + +from ...profiles import load_hand_profile +from ..image_pairing import ExactImagePairing +from .io import detection_input + + +class TagBorderFilter(Node): + def __init__(self, profile, views): + super().__init__("tag_border_filter") + self.bridge = CvBridge() + self.pairing = {view: ExactImagePairing() for view in views} + self.fixed_ids = {v.name: frozenset(t.tag_id for t in v.tags if t.fixed_reference) + for v in profile.vision.views} + self.publishers_by_view = {} + for view in views: + raw = f"{profile.namespace}/{view}/apriltag/detections" + self.publishers_by_view[view] = self.create_publisher(String, raw+"_checked", 10) + self.create_subscription(Image, f"{profile.namespace}/{view}/camera/image_rect", + lambda msg, v=view: self.receive(v, "image", msg), qos_profile_sensor_data) + self.create_subscription(AprilTagDetectionArray, raw, + lambda msg, v=view: self.receive(v, "detections", msg), qos_profile_sensor_data) + + def receive(self, view, kind, message): + stamp = message.header.stamp.sec*1_000_000_000+message.header.stamp.nanosec + pair = self.pairing[view].add(kind, stamp, message) + if pair is None: + return + image, detections = pair + gray = self.bridge.imgmsg_to_cv2(image, desired_encoding="mono8") + observation = detection_input(view, detections, gray=gray, fixed_ids=self.fixed_ids[view]) + output = String() + output.data = json.dumps({"policy": "image_border_checked_v1", **asdict(observation)}, + separators=(",", ":"), allow_nan=False) + self.publishers_by_view[view].publish(output) + + +def main(args=None): + parser = argparse.ArgumentParser() + parser.add_argument("--profile-config", required=True) + parser.add_argument("--profile-sha256", required=True) + parser.add_argument("--views", nargs="+", required=True) + selected, ros_args = parser.parse_known_args(args) + path = Path(selected.profile_config) + if hashlib.sha256(path.read_bytes()).hexdigest() != selected.profile_sha256: + raise ValueError("border filter Profile hash differs from launch") + profile = load_hand_profile(path) + if not set(selected.views) <= set(profile.vision.view_names): + raise ValueError("border filter view is not declared by Profile") + rclpy.init(args=ros_args) + node = TagBorderFilter(profile, selected.views) + try: + rclpy.spin(node) + finally: + node.destroy_node() + if rclpy.ok(): + rclpy.shutdown() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/runner.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/runner.py new file mode 100644 index 0000000..8ef9991 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/runner.py @@ -0,0 +1,515 @@ +"""One process lifecycle for every product; no delegation to model runners. + +ROS imports are lazy, allowing tests of the actual CLI and lifecycle without +hardware. Pending legacy status/artifact contracts are isolated in compat. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +from pathlib import Path +import subprocess +import sys +import time +from typing import Any, Callable, Mapping + +from ..compat import default_product_config_path +from ..product import ProductConfig, load_product_config +from ..storage import atomic_write_json +from .status import normalize_status, render_status_zh + + +TERMINAL_STATES = frozenset({"COMPLETE", "CAPTURE_COMPLETE", "DIAGNOSTIC_COMPLETE", "PAUSED", "ABORTED", "FAILED"}) + + +def drive_session( + monitor: Any, process: Any, *, spin: Callable[[], None], + ok: Callable[[], bool], request_start: Callable[[], Any], + clock: Callable[[], float] = time.monotonic, auto_start: bool = True, + startup_timeout: float = 120.0, service_timeout: float = 10.0, + checkpoint_timeout: float = 900.0, +) -> dict[str, Any]: + """Send Start once; never infer an SDK fault from console/status age. + + Missing references after Start may wait indefinitely. Only startup/service + discovery have runner deadlines; hardware safety belongs to the node. + """ + launched = clock() + checkpoint_started = None + device_wait_started = launched + ready_since: float | None = None + requested_at: float | None = None + future = None + start_acknowledged = False + latest: dict[str, Any] = {} + + def failed(reason: str) -> dict[str, Any]: + return {**latest, "state": "FAILED", "reason": reason} + + while ok(): + spin() + latest = dict(monitor.status) + state = normalize_status(latest)["state"] + if state in TERMINAL_STATES: + return latest + if process.poll() is not None: + return failed(f"calibration_stack_exited:exit_code={process.returncode}") + now = clock() + if latest and now - monitor.last_status_at > 10.0: + if monitor.count_publishers(monitor.status_topic) == 0: + return failed("calibration_node_process_exited") + if not latest and now - launched > startup_timeout: + return failed("calibration_node_initial_status_timeout") + if state == "PREPARING_CHECKPOINT" and requested_at is None: + if checkpoint_started is None: + checkpoint_started = now + if now - checkpoint_started > max(checkpoint_timeout, startup_timeout): + return failed("calibration_checkpoint_preparation_timeout") + device_wait_started = now + continue + + if state == "READY" and auto_start and requested_at is None: + if ready_since is None: + ready_since = now + if monitor.start_client.service_is_ready(): + future = request_start() + requested_at = now + elif now - ready_since > service_timeout: + return failed("calibration_start_service_unavailable") + elif ready_since is None and requested_at is None: + if auto_start and now - device_wait_started > startup_timeout: + return failed("calibration_device_not_ready:" + str(latest.get("reason", state))) + + if future is not None and not start_acknowledged: + if future.done(): + response = future.result() + if response is None or not response.success: + return failed("calibration_start_rejected:" + str(getattr(response, "message", ""))) + start_acknowledged = True + elif now - float(requested_at) > service_timeout: + return failed("calibration_start_response_timeout") + return failed("ros_context_shutdown") + + +def _write_failure(config: ProductConfig, session: Path, status: Mapping[str, Any]) -> None: + from .runner_support import log_exception_summary, protected_inputs + + report = normalize_status(status, profile=config.calibration_contract.typed_profile) + report.update( + serial_number=config.serial_number, result="FAIL", + log_path=str(session / "calibration.log"), + protected_inputs=protected_inputs(config), + child_exception=log_exception_summary(session / "calibration.log"), + raw_node_status=dict(status), + ) + atomic_write_json(session / "runner_diagnostic.json", report) + print(render_status_zh(report), flush=True) + if report["child_exception"]: + print(f"节点异常:{report['child_exception']}", flush=True) + print(f"诊断日志:{report['log_path']}", flush=True) + + +def run_online( + config: ProductConfig, *, record_bag: bool = False, + commands_enabled: bool = True, allow_resume: bool = True, + diagnostic_capture: str = "", startup_timeout: float = 120.0, + reuse_camera_calibration: bool = False, + camera_optical_observations_file: Path | None = None, +) -> int: + import rclpy + from rclpy.signals import SignalHandlerOptions + from std_srvs.srv import Trigger + + from .artifacts.completion import finish_online_artifacts + from ..hikrobot_camera import configure_fastdds_large_image_transport + from .resume import discover_resume_candidate + from .diagnostic_capture import diagnostic_capture_label, resolve_diagnostic_capture + from .adapters.ros_topics import sdk_topics + from .runner_support import ( + CalibrationMonitor, ProgressConsole, create_session_directory, + launch_command, overlay_environment, protected_inputs, stop_stack, + ) + + profile = config.calibration_contract.typed_profile + diagnostic = resolve_diagnostic_capture(profile, diagnostic_capture) + if diagnostic is not None and not commands_enabled: + raise ValueError("diagnostic_capture requires commands_enabled") + session = create_session_directory(config.session_root) + # A CLI-selected preparation policy is a real protected profile, not an + # in-process hint. Materialize its canonical bytes so the launched node, + # resume selector and journal all bind the identical effective contract. + from ..profiles.export import dump_hand_profile + effective_profile = dump_hand_profile(profile).encode() + effective_digest = hashlib.sha256(effective_profile).hexdigest() + from ..profiles import load_hand_profile + runtime_profile_changed = (config.profile_config is None + or load_hand_profile(config.profile_config) != profile) + if runtime_profile_changed: + effective_path = session / "effective_profile.yaml" + effective_path.write_bytes(effective_profile) + from dataclasses import replace + config = replace(config, profile_config=effective_path, + profile_config_sha256=effective_digest) + if config.profile_config is not None: + captured_profile = Path(config.profile_config).read_bytes() + if hashlib.sha256(captured_profile).hexdigest() != config.profile_config_sha256: + raise ValueError('capture_profile_changed_before_start') + (session/'capture_profile.yaml').write_bytes(captured_profile) + if diagnostic is None: + from .raw_completion import snapshot_capture_inputs + snapshot_capture_inputs(config, session) + from ..profiles.validator import validate_executable_profile, require_release_geometry + contract_report = validate_executable_profile(profile, config.source_urdf) + atomic_write_json(session/"measurement_contract.json", contract_report) + if profile.artifacts.output_schema_version >= 3 and commands_enabled and diagnostic is None: + require_release_geometry(contract_report) + from ..profiles.preparation import preparation_contract + from ..core.domain.capture_plan import raw_feedback_capture + if raw_feedback_capture(profile): + allow_resume = False # No raw-feedback checkpoint verifier exists yet. + rejected_checkpoints = [] + preparation = preparation_contract(profile) + resume = discover_resume_candidate( + config.session_root, profile_id=profile.key.profile_id, + serial_number=config.serial_number, protected_hashes=protected_inputs(config), + training_policy=profile.quality.training_policy, + preparation_contract=preparation, rejected_candidates=rejected_checkpoints, + ) if allow_resume and commands_enabled and diagnostic is None else None + atomic_write_json(session/"resume_selection.json", dict( + selected_session=resume.name if resume else None, + preparation_contract=preparation, rejected_candidates=rejected_checkpoints)) + if resume is not None: + installation_note = resume/'operator_installation_clarification.json' + if installation_note.is_file(): + (session/installation_note.name).write_bytes(installation_note.read_bytes()) + from ..core.domain.capture_plan import raw_joint_capture + if raw_joint_capture(profile) and allow_resume and rejected_checkpoints and resume is None: + raise ValueError("raw_resume_incompatible:no_automatic_recapture; 首次使用新协议请明确指定 --no-resume") + if any(row['reason'] == 'checkpoint preparation contract changed' for row in rejected_checkpoints): + print("旧断点的准备策略或父子模型预算与当前版本不同,已排除复用;" + + ("将使用兼容断点。" if resume else "本轮重新采集整条准备链,历史记录保留。"), flush=True) + if contract_report["cad_constraint_conflicts"]: + print("原始 CAD 存在限位/mimic 冲突,未修改原文件;详见 measurement_contract.json。最终范围验证不通过时禁止发布。", flush=True) + log_path = session / "calibration.log" + configure_fastdds_large_image_transport() + process = None + monitor = None + capture_complete = False + owns_context = not rclpy.ok() + with log_path.open("a", encoding="utf-8", buffering=1) as log_stream: + try: + environment = overlay_environment(config.sdk_setup) if config.sdk_setup else dict(os.environ) + environment.setdefault("ROS_LOG_DIR", str(session / "ros_logs")) + if owns_context: + # Keep Python's SIGINT handler: Ctrl+C must request a hold + # while ROS is still alive, before tearing down the stack. + # SIGTERM still uses rclpy's orderly context shutdown. + rclpy.init(signal_handler_options=SignalHandlerOptions.SIGTERM) + progress = ProgressConsole(lambda status, estimator: render_status_zh( + normalize_status(status, profile=profile, serial_number=config.serial_number), + estimator, + )) + monitor = CalibrationMonitor( + node_name="calibration_product_runner", namespace=profile.namespace, + progress=progress, + ) + # This runner owns and launches its SDK process. Do not open the + # same device a second time or accept another session's READY. + topics = sdk_topics(profile) + discovery_deadline = time.monotonic() + 1.5 + while rclpy.ok() and time.monotonic() < discovery_deadline: + rclpy.spin_once(monitor, timeout_sec=0.1) + occupied = {topic: monitor.count_publishers(topic) for topic in + (topics.command, topics.feedback, monitor.status_topic)} + if any(occupied.values()): + raise RuntimeError(f"existing_calibration_publishers:{occupied}") + print(f"{config.serial_number} 标定环境正在启动;日志:{log_path}", flush=True) + if resume is not None: + if getattr(config, "resume_mode", "verify") == "passed": + print(f"发现断点:{resume.name};按已通过记录续采,跳过已完成访问的运动和零位复核。", flush=True) + else: + print(f"发现候选断点:{resume.name};尚未复用,启动后验证基准和 Tag 安装关系。", flush=True) + if not commands_enabled: + print("仅预览:不自动开始、不发送标定运动;Ctrl+C 退出。", flush=True) + if diagnostic is not None: + if diagnostic.chain_joints: + print(f"{diagnostic_capture_label(diagnostic.mode)}:整手基准恢复后,每任务连续两轮训练+一轮留出;" + "沿原路径停点采集,复用原 MCP/PIP 模型检查父参考;曲线与产物待离线验收,不发布产物。", flush=True) + elif diagnostic.hold_command_values: + values = "/".join(f"{value:g}" for value in diagnostic.hold_command_values) + print(f"{diagnostic_capture_label(diagnostic.mode)}:仅执行 yaw 一次往返;" + f"每个方向扫描后回到该方向起点,按方向依次到达 {values},各保持 {diagnostic.hold_seconds:g} 秒;" + "不复用断点、不拟合或发布标定产物。", flush=True) + else: + print(f"{diagnostic_capture_label(diagnostic.mode)}:仅执行声明任务各一次往返,保留准备和零位采集;不复用断点、不拟合或发布标定产物。", flush=True) + launch_options = {"diagnostic_capture": diagnostic_capture} if diagnostic is not None else {} + if reuse_camera_calibration: + launch_options["reuse_camera_calibration"] = True + if camera_optical_observations_file is not None: + launch_options["camera_optical_observations_file"] = camera_optical_observations_file + if commands_enabled and profile.vision_motion: + if profile.sdk_adapter != "o30_ros": + raise ValueError("visual_motion_requires_native_command_seed_adapter") + seed = session / "initial_command.json" + subprocess.run([sys.executable, "-m", "linkerhand_calibration.runtime.adapters.command_seed", + "--side", profile.key.side, "--output", str(seed)], + cwd=config.workspace, env=environment, stdout=log_stream, + stderr=subprocess.STDOUT, check=True, timeout=20) + launch_options["initial_command_file"] = seed + process = subprocess.Popen( + launch_command(config, session, record_bag=record_bag, + commands_enabled=commands_enabled, resume_from=resume, + **launch_options), + cwd=config.workspace, env=environment, stdout=log_stream, + stderr=subprocess.STDOUT, text=True, start_new_session=True, + ) + status = drive_session( + monitor, process, spin=lambda: rclpy.spin_once(monitor, timeout_sec=0.1), + ok=rclpy.ok, request_start=lambda: monitor.start_client.call_async(Trigger.Request()), + auto_start=commands_enabled, + startup_timeout=startup_timeout, + ) + atomic_write_json(session / "node_status.json", status) + if normalize_status(status)["state"] == "CAPTURE_COMPLETE": + capture_complete = True + stop_stack(process) + process = None + monitor.destroy_node() + monitor = None + if owns_context and rclpy.ok(): + rclpy.shutdown() + log_stream.flush() + os.fsync(log_stream.fileno()) + from .raw_completion import finish_capture + return finish_capture(session) + if diagnostic is not None: + if normalize_status(status)["state"] != "DIAGNOSTIC_COMPLETE": + _write_failure(config, session, status) + return 3 + report_path = session / "diagnostic_capture.json" + report = json.loads(report_path.read_text(encoding="utf-8")) + if (not isinstance(report, dict) + or report.get("mode") != diagnostic_capture + or report.get("result") != "DIAGNOSTIC_COMPLETE" + or report.get("publication_allowed") is not False): + raise ValueError("diagnostic_capture_completion_report_invalid") + capture_complete = True + capture_label = diagnostic_capture_label(diagnostic.mode) + print(f"{capture_label}数据已采完;本次未进行精度验收,未发布 JSON 或修正 URDF。\n诊断报告:{report_path}\n原始样本:{session / 'raw_samples.jsonl'}", flush=True) + pose_gaps = report.get("accepted_pose_quality_incomplete_attempts", 0) + unresolved = report.get("missing_joint_zero_references", ()) + if unresolved: + print("零位未确认,仅保留原始观测:" + ", ".join(unresolved) + + ";未生成这些关节的零位或角度样本。", flush=True) + if pose_gaps: + print(f"其中 {pose_gaps} 次方向采集的可信姿态覆盖不足;已保留原始候选供诊断,不能据此确认标定精度。", flush=True) + # The expensive diagnostic is independent of live sampling. + # Stop camera/SDK processes first; it can never delay feedback + # or change a reference after the capture has completed. + stop_stack(process) + process = None + from .diagnostic_analysis import finish_diagnostic_analysis + finish_diagnostic_analysis(profile, session) + return 0 + if normalize_status(status)["state"] != "COMPLETE": + _write_failure(config, session, status) + return 3 + if not commands_enabled: + raise RuntimeError("preview session cannot publish calibration artifacts") + outputs = finish_online_artifacts(config, session, status) + print("标定会话完成;结果已通过当前发布链的校验。", flush=True) + for name, path in outputs.items(): + print(f"{name}:{path}", flush=True) + return 0 + except KeyboardInterrupt: + if (not capture_complete and process is not None and monitor is not None + and rclpy.ok() and monitor.abort_client.service_is_ready()): + aborted = monitor.abort_client.call_async(Trigger.Request()) + deadline = time.monotonic() + 1.0 + while rclpy.ok() and not aborted.done() and time.monotonic() < deadline: + rclpy.spin_once(monitor, timeout_sec=0.1) + message = "采集已完成;已取消后续分析" if capture_complete else "已请求中止" + print(f"{message};本次数据保留在 {session}。", flush=True) + return 130 + except Exception as error: + import traceback + traceback.print_exc(file=log_stream) + _write_failure(config, session, {"state": "FAILED", "reason": str(error)}) + return 2 + finally: + # No unsolicited fast opening is commanded by a CLI failure. + try: + if process is not None: + stop_stack(process) + finally: + if monitor is not None: + monitor.destroy_node() + if owns_context and rclpy.ok(): + rclpy.shutdown() + log_stream.flush() + os.fsync(log_stream.fileno()) + + +def main(args: list[str] | None = None) -> None: + parser = argparse.ArgumentParser(description="配置驱动的多型号统一标定") + parser.add_argument("--config", default=None) + parser.add_argument("--workspace", default=None) + parser.add_argument("--validate-only", "--preflight-only", action="store_true") + parser.add_argument("--record-bag", action="store_true") + parser.add_argument("--commands-disabled", action="store_true") + parser.add_argument("--no-resume", action="store_true") + parser.add_argument("--prepare-remount-from", type=Path, + help="仅离线:保留未受影响的已完成前缀,为调整标签后的低精度草稿采集建立新断点") + parser.add_argument("--remounted-tag-id", type=int, action="append", default=[], + help="与 --prepare-remount-from 一起显式声明本次重新安装的移动标签,可重复指定") + parser.add_argument("--training-policy", choices=("fixed", "adaptive_2_to_3", "staged_2_to_3", + "taskwise_staged_2_to_3", "taskwise_2_plus_1", "raw_joint_2_plus_1", + "raw_feedback_3_plus_1"), default=None, + help="taskwise_2_plus_1:每任务连续两轮训练加一轮验证、不补轮;其他策略保留原语义,默认沿用配置") + parser.add_argument("--startup-timeout-seconds", type=float, default=None, + help="等待节点初始化及设备就绪的秒数(默认 120);大断点逐帧校验可显式延长,不改变运动保护") + diagnostic_options = parser.add_mutually_exclusive_group() + diagnostic_options.add_argument("--diagnostic-thumb", action="store_true", + help="仅 O6 右手:拇指任务各采一次往返,只保存诊断数据") + diagnostic_options.add_argument("--diagnostic-yaw-hold", action="store_true", + help="仅 O6 右手:yaw 两方向扫描后各在 64/128/192 保持 10 秒,只保存诊断数据") + from ..profiles.diagnostics import DIAGNOSTIC_CAPTURE_PRESETS + diagnostic_options.add_argument("--diagnostic-capture", choices=sorted(DIAGNOSTIC_CAPTURE_PRESETS), + default="", help="执行已声明的诊断任务,只保存诊断数据,不发布标定产物") + parser.add_argument("--offline-raw", default="") + parser.add_argument("--reuse-camera-calibration", action="store_true", + help="明确复用已验收相机标定,不执行新的棋盘格核验;记录本次未复核光学状态") + parser.add_argument("--camera-optical-observations", type=Path, + help="当前安装下的多姿态同步标定板角点 JSON;新 O30 协议启动前重新计算光学核验") + parser.add_argument("--offline-output", default="") + parser.add_argument("--publish-offline", action="store_true") + parser.add_argument("--offline-draft", action="store_true", + help="仅离线:用已完成任务生成未认证的零位/行程修正 URDF,报告误差而不要求精度通过") + parser.add_argument("--capture-profile", type=Path, + help="草稿读取旧配置数据时提供原 Profile;仅允许离线修正标签安装连杆") + parser.add_argument("--draft-initialization-from", type=Path, + help="仅离线草稿:使用同一批数据的已有训练草稿作为初值,全部参数仍重新联合拟合") + parser.add_argument("--draft-upright-splay-zero", action="store_true", + help="仅离线草稿:按用户确认,将四指基准指令下的侧摆零位定义为 CAD 竖直;不作为独立实测零位") + parser.add_argument("--preparation-policy", nargs='?', const='occlusion_aware_trajectory_v3', + choices=("occlusion_aware_witness_v1", "occlusion_aware_witness_v2", + "occlusion_aware_trajectory_v3"), + help="O30 staged 准备策略;省略取值使用 v3 整段轨迹消歧和有界自动观察;v1/v2 仅保留历史兼容") + selected = parser.parse_args(args) + if bool(selected.prepare_remount_from) != bool(selected.remounted_tag_id): + parser.error("--prepare-remount-from and --remounted-tag-id must be specified together") + if selected.prepare_remount_from and (selected.offline_raw or selected.offline_draft + or selected.publish_offline or selected.commands_disabled or selected.no_resume + or selected.validate_only or selected.diagnostic_capture or selected.diagnostic_thumb + or selected.diagnostic_yaw_hold): + parser.error("--prepare-remount-from is a separate offline operation") + if selected.offline_draft and (not selected.offline_raw or selected.publish_offline): + parser.error("--offline-draft requires --offline-raw and cannot publish a passed release") + if selected.capture_profile and not selected.offline_draft: + parser.error("--capture-profile requires --offline-draft") + if selected.draft_initialization_from and not selected.offline_draft: + parser.error("--draft-initialization-from requires --offline-draft") + if selected.draft_upright_splay_zero and not selected.offline_draft: + parser.error("--draft-upright-splay-zero requires --offline-draft") + if selected.startup_timeout_seconds is not None and ( + not math.isfinite(selected.startup_timeout_seconds) or selected.startup_timeout_seconds <= 0 + ): + parser.error("--startup-timeout-seconds must be finite and positive") + diagnostic_flag = ("--diagnostic-thumb" if selected.diagnostic_thumb else + "--diagnostic-yaw-hold" if selected.diagnostic_yaw_hold else + "--diagnostic-capture" if selected.diagnostic_capture else "") + if diagnostic_flag and (selected.offline_raw or selected.offline_output + or selected.publish_offline or selected.commands_disabled): + parser.error(f"{diagnostic_flag} cannot be combined with --offline-raw, --offline-output, --publish-offline or --commands-disabled") + config = load_product_config( + selected.config or str(default_product_config_path()), workspace=selected.workspace, + check_can=not (selected.validate_only or selected.offline_raw or selected.commands_disabled + or selected.prepare_remount_from), + ) + if selected.training_policy is not None: + from dataclasses import replace + from ..product import ProductCalibrationContract + from ..core.domain.capture_plan import configure_training + try: + profile = configure_training(config.calibration_contract.typed_profile, selected.training_policy) + config = replace(config, calibration_contract=ProductCalibrationContract(declarative=profile)) + except ValueError as error: + parser.error(str(error)) + diagnostic_capture = ("o6_thumb" if selected.diagnostic_thumb else + "o6_yaw_hold" if selected.diagnostic_yaw_hold else selected.diagnostic_capture) + if selected.preparation_policy is not None: + from dataclasses import replace + from ..product import ProductCalibrationContract + from ..profiles.preparation import configure_preparation + try: + profile = configure_preparation(config.calibration_contract.typed_profile, selected.preparation_policy) + if selected.preparation_policy == 'occlusion_aware_trajectory_v3': + from ..core.urdf.kinematics import UrdfKinematicModel + from ..profiles.observer_preparation import configure_observer_preparations + profile = configure_observer_preparations(profile, UrdfKinematicModel(config.source_urdf)) + config = replace(config, calibration_contract=ProductCalibrationContract(declarative=profile)) + except ValueError as error: + parser.error(str(error)) + diagnostic = None + if diagnostic_capture: + if (config.calibration_contract.typed_profile.quality.training_policy != "fixed" + and not DIAGNOSTIC_CAPTURE_PRESETS[diagnostic_capture].chain_joints): + parser.error("adaptive training cannot be combined with diagnostic capture") + from .diagnostic_capture import resolve_diagnostic_capture + try: + diagnostic = resolve_diagnostic_capture(config.calibration_contract.typed_profile, diagnostic_capture) + except ValueError as error: + parser.error(str(error)) + if selected.validate_only: + from ..profiles.validator import validate_executable_profile + report = validate_executable_profile(config.calibration_contract.typed_profile, config.source_urdf) + from ..core.domain.capture_plan import CapturePlan + report["capture_plan"] = CapturePlan.from_profile(config.calibration_contract.typed_profile).as_dict() + if config.profile_key.model == 'O30': + from ..core.fitting.raw_joint_draft import draft_targets + report['draft_correction_targets'] = draft_targets(config.calibration_contract.typed_profile) + if diagnostic is not None: + report["diagnostic_capture"] = {**diagnostic.as_dict(), "publication_allowed": False} + print(json.dumps(report, ensure_ascii=False, indent=2)) + print(f"配置与受保护输入一致:{config.profile_key.profile_id}。此检查不代表 URDF 精度或硬件验收通过。") + return + if selected.prepare_remount_from: + from datetime import datetime + from .raw_remount import prepare_remount_checkpoint + output = (Path(selected.offline_output) if selected.offline_output else + config.session_root/(datetime.now().strftime('%Y%m%d_%H%M%S')+'_remount')) + report = prepare_remount_checkpoint(config, selected.prepare_remount_from, output, + selected.remounted_tag_id) + print(f"标签调整后的草稿断点已保存:{output};复用 {len(report['retained_units'])} 个方向," + f"剩余 {report['remaining_units']} 个方向。原始记录未修改;后续使用普通断点恢复。") + return + if selected.offline_raw: + if selected.offline_draft: + from .artifacts.raw_joint_draft import replay_draft + replay_draft(config, Path(selected.offline_raw), + output=Path(selected.offline_output) if selected.offline_output else None, + capture_profile=selected.capture_profile, initialization_from=selected.draft_initialization_from, + upright_splay_zero=selected.draft_upright_splay_zero) + return + from .artifacts.replay import replay_capture + replay_capture(config, Path(selected.offline_raw), + output=Path(selected.offline_output) if selected.offline_output else None, + publish=selected.publish_offline) + return + if selected.offline_output or selected.publish_offline: + parser.error("--offline-output/--publish-offline require --offline-raw") + online_options = {"diagnostic_capture": diagnostic_capture} if diagnostic is not None else {} + if selected.reuse_camera_calibration: + online_options["reuse_camera_calibration"] = True + if selected.camera_optical_observations is not None: + online_options["camera_optical_observations_file"] = selected.camera_optical_observations + if selected.startup_timeout_seconds is not None: + online_options["startup_timeout"] = selected.startup_timeout_seconds + raise SystemExit(run_online(config, record_bag=selected.record_bag, + commands_enabled=not selected.commands_disabled, + allow_resume=not selected.no_resume and diagnostic is None, + **online_options)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/runner_support.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/runner_support.py new file mode 100644 index 0000000..aecc395 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/runner_support.py @@ -0,0 +1,286 @@ +"""Model-independent process, status and session support for CLI runners.""" + +from __future__ import annotations + +from datetime import datetime +import json +import os +from pathlib import Path +import re +import signal +import subprocess +import sys +import time +from typing import Any, Callable, Mapping + +import rclpy +from rclpy.node import Node +from std_msgs.msg import String +from std_srvs.srv import Trigger + +from ..operator_report import ProgressEstimator +from ..product import ProductConfig +from .profile_contract import profile_launch_parameters + + +class ProgressConsole: + """Render only changed status snapshots on either a TTY or a log stream.""" + + def __init__(self, renderer: Callable[..., str]) -> None: + self.last_text = "" + self.estimator = ProgressEstimator.start() + self.renderer = renderer + + def update(self, status: Mapping[str, Any]) -> None: + text = self.renderer(status, self.estimator) + if text == self.last_text: + return + self.last_text = text + if sys.stdout.isatty(): + sys.stdout.write("\x1b[2J\x1b[H" + text + "\n") + sys.stdout.flush() + else: + print(text, flush=True) + + +class CalibrationMonitor(Node): + """Observe the common status topic and expose common control services.""" + + def __init__( + self, + *, + node_name: str, + namespace: str, + progress: ProgressConsole, + ) -> None: + super().__init__(node_name) + base = namespace.rstrip("/") + self.status_topic = f"{base}/status" + self.status: dict[str, Any] = {} + self.last_status_at = 0.0 + self.progress = progress + self.create_subscription(String, self.status_topic, self._on_status, 10) + self.start_client = self.create_client(Trigger, f"{base}/start") + self.abort_client = self.create_client(Trigger, f"{base}/abort") + + def _on_status(self, message: String) -> None: + try: + value = json.loads(message.data) + except json.JSONDecodeError: + return + if isinstance(value, dict): + self.status = value + self.last_status_at = time.monotonic() + self.progress.update(value) + + +def create_session_directory(root: Path) -> Path: + """Create a unique timestamped session without overwriting prior evidence.""" + root.mkdir(parents=True, exist_ok=True) + stamp = datetime.now().strftime("%Y%m%d_%H%M%S") + for number in range(10000): + session = root / (stamp if number == 0 else f"{stamp}_{number:04d}") + try: + session.mkdir() + except FileExistsError: + continue + return session + raise RuntimeError("cannot allocate a new calibration session") + + +def launch_command( + config: ProductConfig, + session: Path, + *, + record_bag: bool, + commands_enabled: bool, + sdk_startup_speed_u8: int | None = None, + resume_from: Path | None = None, + diagnostic_capture: str = "", + initial_command_file: Path | None = None, + reuse_camera_calibration: bool = False, + camera_optical_observations_file: Path | None = None, +) -> list[str]: + """Build the single launch invocation entirely from the product contract.""" + arguments = { + "reuse_camera_calibration": str(reuse_camera_calibration).lower(), + "camera_optical_observations_file": str(camera_optical_observations_file or ""), + "model": config.model, + "hand_type": config.side, + "tag_layout": config.tag_layout, + "serial_number": config.serial_number, + "source_urdf_path": str(config.source_urdf), + "source_urdf_expected_sha256": config.source_urdf_sha256, + "camera_extrinsics_file": str(config.camera_extrinsics), + "camera_extrinsics_expected_sha256": config.camera_extrinsics_sha256, + "calibration_config": str(config.calibration_config), + "calibration_config_expected_sha256": config.calibration_config_sha256, + "tag_config": str(config.tag_config), + "tag_config_expected_sha256": config.tag_config_sha256, + "vendor_sdk_config": "" if config.sdk_config is None else str(config.sdk_config), + "sdk_config_expected_sha256": config.sdk_config_sha256, + "profile_config_expected_sha256": getattr( + config, "profile_config_sha256", "" + ), + "profile_config": str(getattr(config, "profile_config", None) or ""), + "output_root": str(config.output_root), + "session_dir": str(session), + "commands_enabled": str(commands_enabled).lower(), + "vendor_sdk_python_package": str(getattr(config, "sdk_python_package", None) or ""), + "sdk_package_expected_sha256": getattr(config, "sdk_package_sha256", ""), + "record_bag": str(record_bag).lower(), + "diagnostic_capture": diagnostic_capture, + "resume_mode": getattr(config, "resume_mode", "verify"), + **profile_launch_parameters(config.calibration_contract.typed_profile), + } + startup_speed = sdk_startup_speed_u8 + if startup_speed is None: + startup_speed = config.calibration_contract.typed_profile.motion.speed_parameters.get("baseline_u8") + if startup_speed is not None: + arguments["calibration_speed"] = str(int(startup_speed)) + if resume_from is not None and not diagnostic_capture: + arguments["resume_raw_samples_path"] = str( + resume_from / "raw_samples.jsonl" + ) + if initial_command_file is not None: + arguments["initial_command_file"] = str(initial_command_file) + if config.can_interface: + arguments["can_interface"] = config.can_interface + for view, camera in config.cameras.items(): + arguments[f"{view}_camera_serial"] = camera["serial_number"] + arguments[f"{view}_camera_name"] = camera["camera_name"] + arguments[f"{view}_camera_info_url"] = camera["camera_info"] + arguments[f"{view}_camera_gain_db"] = camera["gain_db"] + return [ + "ros2", + "launch", + "linkerhand_calibration", + "unified_calibration.launch.py", + # ros2 launch rejects name:= with no value. Unused optional SDK + # arguments already have empty defaults in the launch description. + *(f"{name}:={value}" for name, value in arguments.items() if value != ""), + ] + + +def wait_until( + monitor: CalibrationMonitor, + process: subprocess.Popen[Any], + predicate: Callable[[Mapping[str, Any]], bool], + *, + timeout: float | None, + status_stale_after: float | None = None, + finalizing_stale_after: float = 180.0, +) -> bool: + """Wait for a status predicate while detecting process and status loss.""" + started = time.monotonic() + while rclpy.ok(): + if process.poll() is not None: + return False + rclpy.spin_once(monitor, timeout_sec=0.2) + if predicate(monitor.status): + return True + now = time.monotonic() + if status_stale_after is not None and monitor.last_status_at > 0.0: + stale_limit = ( + finalizing_stale_after + if monitor.status.get("state") == "FINALIZING" + else float(status_stale_after) + ) + if now - monitor.last_status_at > stale_limit: + status_publishers = monitor.count_publishers( + monitor.status_topic + ) + # A busy fit or a delayed console message is not loss of SDK + # feedback. The motion owner monitors feedback independently. + # Stop only when ROS discovery also says that owner is gone. + if status_publishers == 0: + monitor.status = { + **monitor.status, + "state": "FAILED", + "reason": "calibration_node_process_exited", + } + return False + if timeout is not None and now - started > timeout: + return False + return False + + +def stop_stack(process: subprocess.Popen[Any]) -> None: + """Stop the launch process group without leaking child processes.""" + try: + # The launch parent may have exited while its SDK/camera children still + # own this process group. The caller created it with start_new_session. + os.killpg(process.pid, signal.SIGINT) + except ProcessLookupError: + return + for timeout, stop_signal in ((15.0, signal.SIGTERM), (5.0, signal.SIGKILL)): + try: + process.wait(timeout=timeout) + return + except subprocess.TimeoutExpired: + try: + os.killpg(process.pid, stop_signal) + except ProcessLookupError: + return + process.wait(timeout=5.0) + + +def overlay_environment(setup: Path) -> dict[str, str]: + """Load a reviewed vendor overlay into a child-process environment.""" + completed = subprocess.run( + ["bash", "-c", 'source "$1" >/dev/null 2>&1 && env -0', "bash", str(setup)], + check=True, + stdout=subprocess.PIPE, + ) + environment = dict(os.environ) + for item in completed.stdout.split(b"\0"): + if b"=" in item: + key, value = item.split(b"=", 1) + environment[key.decode()] = value.decode(errors="surrogateescape") + return environment + + +def log_exception_summary(log_path: Path) -> str: + """Return the final child exception without flooding the operator view.""" + try: + lines = log_path.read_text(encoding="utf-8", errors="replace").splitlines() + except OSError: + return "" + prefixes = ( + "AttributeError:", "AssertionError:", "ImportError:", + "IndexError:", "KeyError:", "ModuleNotFoundError:", + "OSError:", "RuntimeError:", "TypeError:", "ValueError:", + ) + ansi = re.compile(r"\x1b\[[0-9;]*m") + for raw in reversed(lines[-300:]): + payload = ansi.sub("", raw).strip().rsplit("] ", 1)[-1].strip() + if payload.startswith(prefixes): + return payload + return "" + + +def protected_inputs(config: ProductConfig) -> dict[str, str]: + """Return exactly the immutable inputs available on a product contract.""" + values = { + "source_urdf_sha256": config.source_urdf_sha256, + "camera_extrinsics_sha256": config.camera_extrinsics_sha256, + "calibration_config_sha256": config.calibration_config_sha256, + "tag_config_sha256": config.tag_config_sha256, + "sdk_config_sha256": config.sdk_config_sha256, + "sdk_package_sha256": getattr(config, "sdk_package_sha256", ""), + "profile_config_sha256": getattr(config, "profile_config_sha256", ""), + } + return {key: value for key, value in values.items() if value} + + +__all__ = [ + "CalibrationMonitor", + "ProgressConsole", + "create_session_directory", + "launch_command", + "log_exception_summary", + "overlay_environment", + "protected_inputs", + "stop_stack", + "wait_until", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/safety.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/safety.py new file mode 100644 index 0000000..d1bb45c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/safety.py @@ -0,0 +1,199 @@ +"""Minimal, model-independent live safety policy. + +Only conditions that can damage hardware, corrupt the coordinate reference, or +make command ownership ambiguous are stops. Vision quality and normal tendon +coupling deliberately do not enter this module. +""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Sequence + +from ..core import CalibrationProfile +from .adapters import HardwareHealth + + +@dataclass(frozen=True) +class MotionGoal: + """One axis of a whole segment, in the Adapter's feedback coordinates.""" + + channel: int + start_feedback: float + end_feedback: float + completion_tolerance: float + progress_resolution: float + + +@dataclass(frozen=True) +class SafetySample: + now_seconds: float + feedback_timestamp_seconds: float | None + command: tuple[float, ...] + feedback: tuple[float, ...] | None + health: HardwareHealth + competing_controller: bool = False + reference_moved: bool = False + operator_abort: bool = False + motion_expected: bool = False + target_channel: int | None = None + target_value: float | None = None + motion_id: str = "" + motion_goals: tuple[MotionGoal, ...] = () + + +@dataclass(frozen=True) +class SafetyDecision: + safe: bool + code: str = "" + reason: str = "" + details: str = "" + + +class SafetyPolicy: + """Evaluate the complete and intentionally small list of live stops.""" + + def __init__(self, profile: CalibrationProfile) -> None: + self.profile = profile + self._motion_id: str | None = None + self._axis_progress: dict[int, tuple[float, float, float]] = {} + + def evaluate(self, sample: SafetySample) -> SafetyDecision: + if not math.isfinite(float(sample.now_seconds)): + return self._stop("invalid_control_clock", "控制时钟无效") + if sample.operator_abort: + return self._stop("operator_abort", "操作者已中止标定") + if sample.competing_controller: + return self._stop( + "duplicate_controller", "检测到另一个命令控制节点" + ) + if sample.reference_moved: + return self._stop( + "fixed_reference_moved", + "已锁定的手掌、相机、支架或固定基准 Tag 发生移动", + ) + health = sample.health + if not health.connected: + return self._stop("sdk_disconnected", "SDK 连接或身份检查未通过", health.diagnostic) + if not health.position_mode: + return self._stop("wrong_control_mode", "机械手不在位置控制模式") + if health.active_faults: + return self._stop( + "hardware_fault", + "SDK 报告活动硬件故障", + ",".join(health.active_faults), + ) + if not self.profile.vision_motion and (sample.feedback is None or not health.feedback_fresh + or sample.feedback_timestamp_seconds is None + or not math.isfinite(float(sample.now_seconds)) + or not math.isfinite(float(sample.feedback_timestamp_seconds)) + or float(sample.feedback_timestamp_seconds) > float(sample.now_seconds) + 1e-6 + or float(sample.now_seconds) - float(sample.feedback_timestamp_seconds) + > self.profile.acquisition.feedback_stale_seconds): + return self._stop("feedback_stale", "反馈连续超过允许时间未更新") + try: + self._validate_vector(sample.command, feedback=False) + if sample.feedback is not None and not self.profile.vision_motion: + self._validate_vector(sample.feedback, feedback=True) + except ValueError as error: + return self._stop("physical_range_exceeded", str(error)) + stall = None if self.profile.vision_motion else self._evaluate_progress(sample) + if stall is not None: + return stall + return SafetyDecision(True) + + def _evaluate_progress( + self, sample: SafetySample + ) -> SafetyDecision | None: + """Track signed feedback advance, not a moving set-point's distance. + + Each segment has a stable identity and may move several avoidance axes. + Updating a streaming position command cannot reset its stall clock. + """ + if not sample.motion_expected or sample.feedback is None: + self._reset_progress() + return None + goals = sample.motion_goals + if not goals and sample.target_channel is not None and sample.target_value is not None: + # Compatibility for existing scalar callers. Live execution supplies + # explicit whole-segment goals, including feedback zero conventions. + index = int(sample.target_channel) + if not 0 <= index < self.profile.command.command_count: + return self._stop("invalid_motion_target", "运动目标通道不在 Profile 中") + span = self.profile.command.maximum_values[index] - self.profile.command.minimum_values[index] + tolerance = max(1e-4, 0.002*span) + goals = (MotionGoal(index, sample.feedback[index], float(sample.target_value), tolerance, tolerance),) + if not goals: + return self._stop("invalid_motion_target", "运动段缺少反馈推进目标") + motion_id = sample.motion_id or "legacy_scalar_motion" + if self._motion_id != motion_id: + self._axis_progress.clear() + self._motion_id = motion_id + now = float(sample.now_seconds) + seen: set[int] = set() + for goal in goals: + index = goal.channel + if (index in seen or not 0 <= index < self.profile.command.command_count + or not all(math.isfinite(v) for v in (goal.start_feedback, goal.end_feedback, goal.completion_tolerance, goal.progress_resolution)) + or goal.completion_tolerance < 0 or goal.progress_resolution <= 0): + return self._stop("invalid_motion_target", "运动段推进目标无效") + seen.add(index) + feedback = float(sample.feedback[index]) + if abs(goal.end_feedback - goal.start_feedback) <= goal.completion_tolerance: + continue + direction = math.copysign(1.0, goal.end_feedback - goal.start_feedback) + projected = direction * feedback + previous = self._axis_progress.get(index) + if previous is None or previous[2] != direction: + self._axis_progress[index] = (projected, now, direction) + continue + best, last_advance, _ = previous + # Passing the requested travel is completion, not a new stall + # while holding slightly beyond an encoder-biased endpoint. + if direction * (goal.end_feedback - feedback) <= goal.completion_tolerance or projected >= best + goal.progress_resolution: + self._axis_progress[index] = (projected, now, direction) + continue + timeout = self.profile.acquisition.stall_timeout_seconds + if now - last_advance >= timeout: + return self._stop("mechanical_stall", + f"已要求明显运动,但目标反馈连续 {timeout:g} 秒没有向目标推进", + f"segment={motion_id},channel={index},command={sample.command[index]:.9g}," + f"feedback={feedback:.9g},feedback_progress_goal={goal.end_feedback:.9g}," + f"timeout_seconds={timeout:g},no_progress_seconds={now-last_advance:.9g}") + return None + + def _reset_progress(self) -> None: + self._motion_id = None + self._axis_progress.clear() + + def _validate_vector( + self, values: Sequence[float], *, feedback: bool + ) -> None: + layout = self.profile.command + if len(values) != layout.command_count: + raise ValueError("命令或反馈通道数量与 Profile 不一致") + lower = ( + layout.minimum_feedback_values if feedback else layout.minimum_values + ) + upper = ( + layout.maximum_feedback_values if feedback else layout.maximum_values + ) + kind = "反馈" if feedback else "命令" + for index, value in enumerate(values): + numeric = float(value) + if ( + not math.isfinite(numeric) + or numeric < lower[index] + or numeric > upper[index] + ): + raise ValueError( + f"{kind}越过物理范围: channel={index}:value={numeric}" + ) + + @staticmethod + def _stop(code: str, reason: str, details: str = "") -> SafetyDecision: + return SafetyDecision(False, code, reason, details) + + +__all__ = ["MotionGoal", "SafetyDecision", "SafetyPolicy", "SafetySample"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/scan_quality.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/scan_quality.py new file mode 100644 index 0000000..f8936a6 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/scan_quality.py @@ -0,0 +1,186 @@ +"""One post-direction data policy for primary and secondary observations.""" + +from __future__ import annotations + +import math +from typing import Mapping, Sequence + +from .engine import CalibrationEngine, ScanUnit, SweepQuality, evaluate_observability +from .motion_execution import feedback_tolerances +from ..core.domain.motion_path import task_segment, record_scan_identity +from ..core.fitting.motion_fit import channel_for_joint + + +from ..core.domain.profile import observation_streams as observation_streams + + +def evaluate_capture_unit(profile, unit: ScanUnit, attempt: int, + records: Sequence[Mapping], *, first_cycle_spans: dict[str, float], + include_steady: bool = True, + include_steady_endpoints: bool = False, + scale_segment_feedback_coverage: bool = False, +) -> SweepQuality: + """No rates, coupling, endpoint tracking error or Tag percentages stop a scan. + + Count unique images separately for EVERY required joint/view. A good + proximal Tag cannot hide missing distal or secondary-camera observations. + Reference travel is learned only from an accepted first training cycle. + """ + engine = CalibrationEngine(profile) + if hasattr(records, "task_records"): + records = records.task_records(unit.task_key) + task = next(task for task in profile.motion.tasks if task.key == unit.task_key) + segment = task_segment(task, unit.segment_key) if unit.segment_key else None + streams = [s for s in observation_streams(profile, task) if segment is None or s[1] in segment.joints] + native = profile.command.unit + command_coverage = profile.command_based_release and ( + profile.vision_motion or not profile.acquisition.feedback_travel_matches_command) + lower, upper = sorted((task.start_value, task.end_value)) + span = upper - lower + if span <= 0: + raise ValueError("a scan needs a nonzero declared range") + failures, warnings, metrics, references = [], [], {}, {} + if unit.sample_phase == "steady": + from .steady import steady_failures, steady_targets + failures = steady_failures(profile, unit, attempt, records) + targets = steady_targets(profile, unit, records=records) + for field, name, spec in streams: + rows = [r for r in records if r.get(field) == name and r.get("view") == spec.view + and r.get("sample_phase") == "steady" and r.get("task_name") == unit.task_key + and r.get("cycle") == unit.cycle and r.get("direction") == unit.direction + and record_scan_identity(r) == unit.identity and int(r.get("attempt", 1)) == attempt] + covered = {r["steady_index"] for r in rows} + metrics[f"{field}:{name}:{spec.view}:{unit.direction}"] = { + "quality_scope": "steady_command_nodes", "valid_frames": len({r["image_stamp_ns"] for r in rows}), + "feedback_span": len(covered) / len(targets), "feedback_bins": len(covered), + "maximum_bin_gap": 0, "required_nodes": len(targets)} + if command_coverage: + metrics = {key: _command_coverage(value, native) for key, value in metrics.items()} + return SweepQuality(not failures, tuple(failures), (), metrics) + for field, name, spec in streams: + if segment: + channel = channel_for_joint(profile, name) + lower, upper = sorted((dict(segment.start_commands)[channel], dict(segment.end_commands)[channel])) + span = upper-lower + identity = f"{field}:{name}:{spec.view}:{unit.direction}" + if segment: + identity += f":{segment.key}" + samples, command_samples, feedback_samples = {}, {}, {} + channel = channel_for_joint(profile, name) + for row in records: + sample_phase = row.get("sample_phase", "sweep") + if sample_phase != "sweep" and not (include_steady_endpoints and sample_phase == "steady"): + continue + if (row.get(field) != name or row.get("view") != spec.view + or row.get("task_name") != unit.task_key + or row.get("cycle") != unit.cycle or row.get("direction") != unit.direction + or record_scan_identity(row) != unit.identity or int(row.get("attempt", 1)) != attempt): + continue + stamp = row.get("image_stamp_ns") + if stamp is None or not isinstance(stamp, int) or stamp <= 0: + continue + feedback = row.get(f"feedback_{native}") + if not profile.vision_motion: + if (feedback is None or not math.isfinite(float(feedback)) or not + profile.command.minimum_feedback_values[channel] <= float(feedback) + <= profile.command.maximum_feedback_values[channel]): + continue + if sample_phase == "sweep": + feedback_samples[(spec.view, stamp)] = float(feedback) + value = row.get(f"{'command' if command_coverage else 'feedback'}_{native}") + if value is None or not math.isfinite(float(value)): + continue + limits = ((profile.command.minimum_values, profile.command.maximum_values) if command_coverage + else (profile.command.minimum_feedback_values, profile.command.maximum_feedback_values)) + if not (limits[0][channel] <= float(value) <= limits[1][channel]): + continue + commanded = row.get(f"command_{native}") + if commanded is not None and math.isfinite(float(commanded)): + command_progress = (float(commanded) - lower) / span + if 0 <= command_progress <= 1: + command_samples[(spec.view, stamp)] = command_progress + if sample_phase == "steady": + # A synchronized held image proves the actual sent endpoint + # command. It does not become a moving coverage sample. + continue + progress = (float(value) - lower) / span + # Physical encoder bounds are distinct from the requested sweep. + # Samples outside it are not clipped into fake endpoint bins. + if 0 <= progress <= 1: + samples[(spec.view, stamp)] = progress + policy = profile.acquisition + minimum = policy.legacy_minimum_span_01 if native == "u8" else ( + policy.physical_first_cycle_minimum_span_01 if unit.cycle == 0 else + policy.physical_repeat_minimum_fraction * first_cycle_spans.get(identity, 1.0)) + if native != "u8" and unit.cycle > 0 and identity not in first_cycle_spans: + failures.append(f"{identity}:missing_training_travel") + decision = engine.evaluate_sweep(tuple(samples.values()), minimum_span=minimum, + total_frames=len(samples), joint_frame_rate=1.0, feedback_hz=0.0, + detection_rate=1.0, bin_count=256, + observed_command_progress_01=tuple(command_samples.values())) + failures.extend(f"{identity}:{'command_span' if command_coverage and reason == 'feedback_span' else reason}" + for reason in decision.failures) + warnings.extend(f"{identity}:{reason}" for reason in decision.warnings) + metrics[identity] = dict(decision.metrics) + if command_coverage: + metrics[identity] = _command_coverage(metrics[identity], native) + if not profile.vision_motion: + fraction = (span/(profile.command.maximum_values[channel]-profile.command.minimum_values[channel]) + if segment is not None and scale_segment_feedback_coverage else 1.) + motion_quality, motion_metrics = _feedback_motion_coverage(profile, feedback_samples.values(), + command_span_fraction=fraction) + failures.extend(f"{identity}:feedback_motion_{reason}" for reason in motion_quality.failures) + metrics[identity]["feedback_motion"] = motion_metrics + references[identity] = float(decision.metrics["feedback_span"]) + if include_steady and profile.acquisition.command_capture_mode == "interleaved": + from .steady import steady_failures + failures.extend(steady_failures(profile, unit, attempt, records)) + if not failures and unit.cycle == 0: + first_cycle_spans.update(references) + return SweepQuality(not failures, tuple(failures), tuple(warnings), metrics) + + +def _feedback_motion_coverage(profile, values, *, command_span_fraction=1.): + """Check actual encoder travel without interpreting commands as encoders. + + Runtime checks direction, progress, and stability. The recorded direction + must also contain enough independent, distributed feedback observations. + Its observed interval is explicit: it is not a claim that an encoder has + reached command 0/255 or a grouped segment's command boundary. + """ + values = tuple(values) + lower, upper = (min(values), max(values)) if values else (None, None) + span = upper-lower if values else 0. + normalized = tuple((value-lower)/span if span > 0 else 0. for value in values) + policy = profile.acquisition + if not 0 < command_span_fraction <= 1: + raise ValueError('feedback_coverage_invalid_declared_segment_span') + # A short declared segment cannot resolve as many native encoder bins as + # a full sweep. Scaling its sample-density check avoids amplifying byte + # quantization when the observed travel is normalized back to 256 bins. + minimum_bins = max(2, math.ceil(policy.minimum_bins*command_span_fraction)) + maximum_gap_fraction = min(1., policy.maximum_unobserved_fraction/command_span_fraction) + quality = evaluate_observability(normalized, minimum_span=1., + minimum_valid_samples=policy.minimum_valid_samples, minimum_bins=minimum_bins, + maximum_unobserved_fraction=maximum_gap_fraction, + total_frames=len(values), joint_frame_rate=1., feedback_hz=0., detection_rate=1.) + if span < feedback_tolerances(profile.command.unit).minimum_travel: + quality = SweepQuality(False, (*quality.failures, "below_motion_resolution"), + quality.warnings, quality.metrics) + return quality, dict(observed_minimum=lower, observed_maximum=upper, observed_span=span, + unit=profile.command.unit, normalized_to="observed_feedback_interval", + declared_command_span_fraction=command_span_fraction, required_bins=minimum_bins, + allowed_maximum_bin_gap=quality.metrics['allowed_maximum_bin_gap'], + valid_frames=quality.metrics["valid_frames"], bins=quality.metrics["feedback_bins"], + maximum_bin_gap=quality.metrics["maximum_bin_gap"]) + + +def _command_coverage(metrics, native): + """Do not label image-associated command coverage as measured encoders.""" + result = dict(metrics) + result["input_span"] = result.pop("feedback_span") + result["input_bins"] = result.pop("feedback_bins") + result["coverage_input_domain"] = f"command_{native}" + if result.get("gap_scope") == "observed_feedback_span": + result["gap_scope"] = "observed_command_span" + return result diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/session.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/session.py new file mode 100644 index 0000000..25a2196 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/session.py @@ -0,0 +1,547 @@ +"""The single online calibration state machine. + +ROS and SDK adapters execute requested actions. This object owns ordering, +retry policy, pause semantics, progress and resume fallback for every profile. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +from typing import Mapping + +from ..core import CalibrationProfile, CalibrationStatus, PauseStatus, TaskStatus +from .diagnostic_capture import DiagnosticCapturePlan +from .engine import CalibrationEngine, ScanUnit, SweepQuality +from ..core.domain.motion_path import task_segment +from .observation_scope import required_observation_views +from .resume import ResumeDecision + + +class CalibrationPhase(str, Enum): + WAIT_DEVICE = "WAIT_DEVICE" + READY = "READY" + BASELINE = "BASELINE" + REFERENCE_LOCKING = "REFERENCE_LOCKING" + REFERENCE_POSES = "REFERENCE_POSES" + RESUME_VERIFY = "RESUME_VERIFY" + PREPARE = "PREPARE" + MAPPING_PROBE = "MAPPING_PROBE" + SWEEP = "SWEEP" + EVALUATE = "EVALUATE" + RESCAN = "RESCAN" + RETURN_BASELINE = "RETURN_BASELINE" + FIT = "FIT" + HOLDOUT_VALIDATE = "HOLDOUT_VALIDATE" + BUILD_ARTIFACTS = "BUILD_ARTIFACTS" + VALIDATE_URDF = "VALIDATE_URDF" + PUBLISH = "PUBLISH" + COMPLETE = "COMPLETE" + DIAGNOSTIC_COMPLETE = "DIAGNOSTIC_COMPLETE" + CAPTURE_COMPLETE = "CAPTURE_COMPLETE" + PAUSED = "PAUSED" + ABORTED = "ABORTED" + FAILED = "FAILED" + + +@dataclass(frozen=True) +class SessionAction: + phase: CalibrationPhase + scan_unit: ScanUnit | None = None + retry: int = 0 + + +class CalibrationSession: + """Deterministic orchestration kernel with no model-specific branches.""" + + def __init__( + self, profile: CalibrationProfile, *, + diagnostic_capture: DiagnosticCapturePlan | None = None, + ) -> None: + self.profile = profile + self.diagnostic_capture = diagnostic_capture + self.required_observation_views = required_observation_views(profile, diagnostic_capture) + self.engine = CalibrationEngine(profile, diagnostic_capture=diagnostic_capture) + self.phase = CalibrationPhase.WAIT_DEVICE + self._units = list(self.engine.scan_units()) + self._unit_index = 0 + self._retry_by_unit: dict[tuple[str, int, str], int] = {} + self._mapping_probed_channels: set[int] = set() + self._reused_units: set[tuple[str, int, str]] = set() + self._resume_requested = False + self._resume_message = "" + self._pause = PauseStatus() + self._reference_locked = False + self._rescan_pending = False + self.incomplete_units = {} + self.incomplete_references = {} + from .task_deferral import TaskDeferralQueue + self.task_deferrals = TaskDeferralQueue(profile) + + @property + def current_unit(self) -> ScanUnit | None: + if self._unit_index >= len(self._units): + return None + return self._units[self._unit_index] + + @property + def scheduled_units(self): + return tuple(self._units) + + def select_training(self, task_key, cycles): + """Replace only future optional units; evidence IDs never change.""" + from ..core.domain.capture_plan import select_task_training + current = self.current_unit + self.profile = select_task_training(self.profile, task_key, cycles) + self.engine.profile = self.profile + self._units = list(self.engine.scan_units()) + if current is not None: + self._unit_index = next(i for i, unit in enumerate(self._units) if unit.identity == current.identity) + + def supplement_training(self, task_keys): + for task_key in task_keys: + self.select_training(task_key, (0, 1, 2)) + + def device_ready(self) -> None: + self._require(CalibrationPhase.WAIT_DEVICE) + self.phase = CalibrationPhase.READY + + def devices_unavailable(self) -> None: + """Revoke readiness before Start without pausing a running scan.""" + self._require_any(CalibrationPhase.WAIT_DEVICE, CalibrationPhase.READY) + self.phase = CalibrationPhase.WAIT_DEVICE + + def start(self, *, resume_requested: bool = False) -> None: + self._require(CalibrationPhase.READY) + if self.diagnostic_capture is not None and resume_requested: + raise ValueError("diagnostic capture cannot resume previous data") + self._resume_requested = bool(resume_requested) + self._reference_locked = False + self.phase = CalibrationPhase.BASELINE + + def baseline_complete(self) -> None: + self._require(CalibrationPhase.BASELINE) + self.phase = CalibrationPhase.REFERENCE_LOCKING + + def reference_locked(self) -> None: + self._require(CalibrationPhase.REFERENCE_LOCKING) + self._reference_locked = True + if self.profile.motion.resume_verification_waypoints and self.profile.artifacts.output_schema_version < 3: + self.phase = CalibrationPhase.REFERENCE_POSES + return + self._after_reference_poses() + + def reference_poses_complete(self): + self._require(CalibrationPhase.REFERENCE_POSES) + self._after_reference_poses() + + def _after_reference_poses(self): + self.phase = ( + CalibrationPhase.RESUME_VERIFY + if self._resume_requested + else CalibrationPhase.PREPARE + ) + + def resume_checked(self, decision: ResumeDecision) -> None: + self._require_formal_resume() + self._require(CalibrationPhase.RESUME_VERIFY) + if self.profile.artifacts.output_schema_version >= 3 and decision.completed_units: + raise ValueError("v3 resume requires per-joint zero verification before skipping units") + self._resume_message = decision.reason + if not decision.reuse: + self._unit_index = 0 + self._retry_by_unit.clear() + self._reused_units.clear() + else: + valid = { + unit.identity + for unit in self._units + } + requested = { + tuple(key) for key in decision.completed_units + } + if not requested.issubset(valid): + raise ValueError("resume contains an unknown scan unit") + self._reused_units = requested + self._advance_reused_units() + self.phase = CalibrationPhase.PREPARE + + def preparation_complete(self) -> None: + self._require(CalibrationPhase.PREPARE) + unit = self.current_unit + if unit is None: + self._finish_capture_schedule() + return + task = self._task(unit.task_key) + if ( + self.engine.mapping_probe_delta(task) is not None + and task.command_index not in self._mapping_probed_channels + ): + self.phase = CalibrationPhase.MAPPING_PROBE + else: + self.phase = CalibrationPhase.RESCAN if self._rescan_pending else CalibrationPhase.SWEEP + self._rescan_pending = False + + def authorize_task_reuse(self, units): + """The coordinator must apply the reuse policy and durably import evidence.""" + self._require_formal_resume() + self._require_any(CalibrationPhase.PREPARE, CalibrationPhase.MAPPING_PROBE) + current = self.current_unit + valid = {u.identity for u in self._units} + requested = set(units) + if current is None or not requested <= valid or any(key[0] != current.task_key for key in requested): + raise ValueError("deferred resume must belong to the current task") + self._reused_units.update(requested) + self._advance_reused_units() + self.phase = CalibrationPhase.PREPARE + + def mapping_probe_complete(self) -> None: + self._require(CalibrationPhase.MAPPING_PROBE) + unit = self.current_unit + if unit is None: + raise RuntimeError("mapping probe has no current task") + self._mapping_probed_channels.add(self._task(unit.task_key).command_index) + self.phase = CalibrationPhase.SWEEP + + def sweep_complete(self) -> None: + self._require_any(CalibrationPhase.SWEEP, CalibrationPhase.RESCAN) + self.phase = CalibrationPhase.EVALUATE + + def evaluation_complete(self, quality: SweepQuality) -> None: + self._require(CalibrationPhase.EVALUATE) + unit = self.current_unit + if unit is None: + self.fail("missing_scan_unit", "扫描单元状态丢失") + return + key = unit.identity + retries = self._retry_by_unit.get(key, 0) + from ..core.domain.capture_plan import raw_joint_capture + if raw_joint_capture(self.profile) and not quality.passed: + if self.engine.permits_retry("sweep_acquisition", retries): + self._retry_by_unit[key] = retries + 1 + self.phase = CalibrationPhase.PREPARE + else: + self.incomplete_units[key] = {"failures": quality.failures, + "metrics": dict(quality.metrics)} + self._unit_index += 1 + if self.current_unit is None: + self._finish_capture_schedule() + else: + self.phase = CalibrationPhase.PREPARE + return + if not quality.passed: + if self.engine.permits_retry("sweep_acquisition", retries): + self._retry_by_unit[key] = retries + 1 + self._rescan_pending = True + # Never reverse a failed direction by jumping straight back to + # its first set-point. Re-execute the ordinary safe preparation. + self.phase = CalibrationPhase.PREPARE + return + # This is an observation shortfall, not a motion safety failure. + # Preserve the failed unit and finish other independent collection. + self.incomplete_units[key] = {"failures": quality.failures, + "metrics": dict(quality.metrics)} + self._rescan_pending = False + self._unit_index += 1 + if self.current_unit is None: + self._finish_capture_schedule() + else: + self.phase = CalibrationPhase.PREPARE + return + self._unit_index += 1 + self._advance_reused_units() + if self._unit_index < len(self._units): + # A skipped checkpoint may leave a gap even within the same task. + # The executor elides already-satisfied waypoints without motion. + self.phase = CalibrationPhase.PREPARE + return + self._finish_capture_schedule() + + def can_defer_current_task(self): + """Taskwise recovery cannot interrupt an already started scan task.""" + from .task_deferral import taskwise_deferral + unit = self.current_unit + return (self.phase == CalibrationPhase.PREPARE and unit is not None + and (not taskwise_deferral(self.profile) or (unit.cycle == 0 + and not any(previous.task_key == unit.task_key + for previous in self._units[:self._unit_index])))) + + def defer_current_task(self, reason: str): + """Move a visual visit, or an entire task, within its retry budget. + + A second failure records the visit as unobservable and removes only + its still-uncompleted units. Finalization is then blocked explicitly. + """ + self._require(CalibrationPhase.PREPARE) + unit = self.current_unit + if unit is None: + raise ValueError("task_deferral_without_current_unit") + from .task_deferral import dependency_closure, TaskObservationState + if not self.can_defer_current_task(): + raise ValueError("task_deferral_requires_unstarted_task") + affected = dependency_closure(self.profile, unit.task_key) + # Decide before mutating the schedule: an exhausted budget leaves it intact. + decision = self.task_deferrals.decide(unit.task_key, unit.cycle, reason, 0) + moved = self._move_visit_to_stage_end(unit.cycle, affected) + from dataclasses import replace + decision = replace(decision, moved_units=len(moved)) + if decision.state == TaskObservationState.PENDING: + self._insert_at_stage_end(unit.cycle, moved) + else: + # Descendants cannot be accepted without the missing parent + # geometry. Remove their future visits from every later cycle. + self._units = self._units[:self._unit_index] + [candidate + for candidate in self._units[self._unit_index:] + if candidate.task_key not in set(decision.affected_tasks)] + self._rescan_pending = False + if self.current_unit is None: + self._finish_capture_schedule() + else: + self.phase = CalibrationPhase.PREPARE + return decision + + def restore_task_deferrals(self, records): + """Restore retry budgets and the exact pending order.""" + self.task_deferrals.restore(records) + from .task_deferral import TaskObservationState, unresolved_observation_records, taskwise_deferral + for row in unresolved_observation_records(self.profile, records): + if taskwise_deferral(self.profile) and row.get("state") == TaskObservationState.UNOBSERVABLE.value: + affected = set(row["affected_tasks"]) + self._units = self._units[:self._unit_index] + [unit + for unit in self._units[self._unit_index:] if unit.task_key not in affected] + continue + if row.get("state") != TaskObservationState.PENDING.value: + continue + moved = self._move_visit_to_stage_end( + int(row["cycle"]), frozenset(row["affected_tasks"])) + self._insert_at_stage_end(int(row["cycle"]), moved) + + def _stage_index(self, cycle): + from ..core.domain.capture_plan import TASKWISE_STAGED + if self.profile.quality.training_policy == TASKWISE_STAGED: + return 0 if cycle == 0 else 1 if cycle in {1, 2} else 2 + return cycle + + def _move_visit_to_stage_end(self, cycle, affected_tasks): + from .task_deferral import taskwise_deferral + indices = [index for index in range(self._unit_index, len(self._units)) + if (taskwise_deferral(self.profile) or self._units[index].cycle == cycle) + and self._units[index].task_key in affected_tasks] + if not indices: + raise ValueError("task_deferral_has_no_pending_units") + moved = [self._units[index] for index in indices] + for index in reversed(indices): + del self._units[index] + return moved + + def _insert_at_stage_end(self, cycle, moved): + from .task_deferral import taskwise_deferral + if taskwise_deferral(self.profile): + self._units.extend(moved) + return + stage = self._stage_index(cycle) + insertion = next((index for index in range(self._unit_index, len(self._units)) + if self._stage_index(self._units[index].cycle) > stage), len(self._units)) + self._units[insertion:insertion] = moved + + def _finish_capture_schedule(self): + # Finish the safe return even when a bounded observation revisit failed. + # The capture manifest records unresolved tasks and blocks offline fitting. + self.phase = CalibrationPhase.RETURN_BASELINE + + def return_complete(self) -> None: + self._require(CalibrationPhase.RETURN_BASELINE) + from ..core.domain.capture_plan import raw_joint_capture + if raw_joint_capture(self.profile) and self.diagnostic_capture is None: + self.phase = CalibrationPhase.CAPTURE_COMPLETE + return + if self.diagnostic_capture is not None: + if self.incomplete_units or self.task_deferrals.unobservable: + self.fail("diagnostic_capture_incomplete", "诊断采集已归位,但有未完成任务") + else: + self.phase = CalibrationPhase.DIAGNOSTIC_COMPLETE + return + # Capture completion is independent of fit eligibility. Incomplete + # units and unresolved tasks are sealed as incomplete, never published. + self.phase = CalibrationPhase.CAPTURE_COMPLETE + + def fit_complete(self) -> None: + self._require(CalibrationPhase.FIT) + self.phase = CalibrationPhase.HOLDOUT_VALIDATE + + def holdout_complete(self, *, passed: bool, reason: str = "") -> None: + self._require(CalibrationPhase.HOLDOUT_VALIDATE) + if not passed: + self.fail("holdout_failed", reason or "独立验证未通过") + return + self.phase = CalibrationPhase.BUILD_ARTIFACTS + + def artifacts_built(self) -> None: + self._require(CalibrationPhase.BUILD_ARTIFACTS) + self.phase = CalibrationPhase.VALIDATE_URDF + + def urdf_validated(self, *, passed: bool, reason: str = "") -> None: + self._require(CalibrationPhase.VALIDATE_URDF) + if not passed: + self.fail("urdf_validation_failed", reason or "URDF 校验失败") + return + self.phase = CalibrationPhase.PUBLISH + + def published(self) -> None: + self._require(CalibrationPhase.PUBLISH) + self.phase = CalibrationPhase.COMPLETE + + def pause( + self, code: str, reason: str, details: Mapping[str, object] | None = None, + *, suggestion: str = "排除原因后从安全基准恢复", + ) -> None: + self._pause = PauseStatus(code, reason, suggestion, details or {}) + self.phase = CalibrationPhase.PAUSED + + def abort(self) -> None: + self._pause = PauseStatus("operator_abort", "操作者已中止标定") + self.phase = CalibrationPhase.ABORTED + + def fail(self, code: str, reason: str, details: Mapping[str, object] | None = None, + *, suggestion: str = "") -> None: + self._pause = PauseStatus(code, reason, suggestion, details or {}) + self.phase = CalibrationPhase.FAILED + + def action(self) -> SessionAction: + unit = self.current_unit + retries = 0 + if unit is not None: + retries = self._retry_by_unit.get( + unit.identity, 0 + ) + return SessionAction(self.phase, unit, retries) + + def status(self) -> CalibrationStatus: + unit = self.current_unit + task_phases = {CalibrationPhase.PREPARE, CalibrationPhase.MAPPING_PROBE, + CalibrationPhase.SWEEP, CalibrationPhase.EVALUATE, CalibrationPhase.RESCAN, + CalibrationPhase.PAUSED, CalibrationPhase.ABORTED} + if self.phase not in task_phases: + unit = None + task = next( + ( + value + for value in self.profile.motion.tasks + if unit is not None and value.key == unit.task_key + ), + None, + ) + segment = task_segment(task, unit.segment_key) if task is not None and unit.segment_key else None + progress = ( + 1.0 + if self.phase in {CalibrationPhase.COMPLETE, CalibrationPhase.DIAGNOSTIC_COMPLETE, CalibrationPhase.CAPTURE_COMPLETE} + else 0.90*self._unit_index / max(1, len(self._units)) + ) + required: dict[str, tuple[int, ...]] = {} + if self.phase in {CalibrationPhase.REFERENCE_LOCKING, CalibrationPhase.RESUME_VERIFY}: + required = {view.name: tuple(tag.tag_id for tag in view.tags if tag.fixed_reference) + for view in self.profile.vision.views if view.name in self.required_observation_views} + if task is not None: + measurement_names = set(segment.joints if segment else task.joints) + measurement_names.update( + self.profile.measurement.cross_view_sources[name] + for name in tuple(measurement_names) + if name in self.profile.measurement.cross_view_sources + ) + measurements = [ + self.profile.measurement.measurements[name] + for name in measurement_names + ] + for view in self.profile.vision.views: + roles = { + role for measurement in measurements if measurement.view == view.name + for role in (measurement.parent_role, measurement.child_role) if role is not None + } + ids = tuple(tag.tag_id for tag in view.tags if tag.role in roles) + if ids: + required[view.name] = ids + from ..core.domain.capture_plan import TASKWISE_STAGED, raw_joint_capture, raw_feedback_capture + taskwise = self.profile.quality.training_policy == TASKWISE_STAGED + displayed_cycle = (None if unit is None or unit.sample_phase == "steady" else + ({0: 1, 1: 2, 2: 2, 3: 3}[unit.cycle] if taskwise else + list(dict.fromkeys(u.cycle for u in self._units if u.task_key == unit.task_key + and u.sample_phase == "sweep")).index(unit.cycle) + 1)) + displayed_cycle_count = (3 if taskwise else + len(self.diagnostic_capture.cycles) if self.diagnostic_capture is not None else + len({u.cycle for u in self._units if unit is not None and u.task_key == unit.task_key + and u.sample_phase == "sweep"}) or len({u.cycle for u in self.engine.scan_units() + if u.sample_phase == "sweep"})) + capture_stage = ("training_supplement" if taskwise and unit is not None and unit.cycle == 2 + else "command_validation" if unit is not None and unit.sample_phase == "steady" + and unit.cycle == self.profile.quality.holdout_cycle + 2 + else "command_training" if unit is not None and unit.sample_phase == "steady" + else "motion") + return CalibrationStatus( + state=self.phase.value, + phase=self.phase.value, + overall_progress_01=progress, + reference_locked=self._reference_locked, + reference_message=( + "基准已锁定:请勿移动手掌、相机、支架或Tag" + if self._reference_locked + else "" + ), + task=TaskStatus( + key="" if task is None else task.key, + label="" if task is None else " / ".join(segment.joints if segment else task.joints), + cycle=displayed_cycle, + cycle_count=displayed_cycle_count, + direction="" if unit is None else unit.direction, + capture_stage=capture_stage, + required_tag_ids_by_view=required, + segment_key="" if segment is None else segment.key, + segment_commands={} if segment is None else { + self.profile.command.names[index]: (start, dict(segment.end_commands)[index]) + for index, start in sorted(segment.start_commands)}, + ), + resume={"message": self._resume_message, + **({"pending_unit_recaptures": [list(candidate.identity) + for candidate in self._units[self._unit_index:] + if self._retry_by_unit.get(candidate.identity, 0)], + "incomplete_units": {str(key): value + for key, value in self.incomplete_units.items()}, + "incomplete_references": {str(key): value + for key, value in self.incomplete_references.items()}} + if raw_joint_capture(self.profile) or raw_feedback_capture(self.profile) else {}), + "deferred_tasks": {f"{task}:{cycle}": attempt + for (task, cycle), attempt in self.task_deferrals.attempts.items()}, + "unobservable_tasks": [f"{task}:{cycle}" + for task, cycle in self.task_deferrals.unobservable]}, + pause=self._pause, + ) + + def _require(self, expected: CalibrationPhase) -> None: + if self.phase != expected: + raise RuntimeError( + f"invalid transition from {self.phase.value}; " + f"expected {expected.value}" + ) + + def _require_formal_resume(self) -> None: + if self.diagnostic_capture is not None: + raise ValueError("diagnostic capture cannot reuse previous data") + + def _require_any(self, *expected: CalibrationPhase) -> None: + if self.phase not in expected: + allowed = ",".join(value.value for value in expected) + raise RuntimeError( + f"invalid transition from {self.phase.value}; expected {allowed}" + ) + + def _task(self, key: str): + return next(task for task in self.profile.motion.tasks if task.key == key) + + def _advance_reused_units(self) -> None: + while self._unit_index < len(self._units): + unit = self._units[self._unit_index] + if unit.identity not in self._reused_units: + break + self._unit_index += 1 + + +__all__ = ["CalibrationPhase", "CalibrationSession", "SessionAction"] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_pose_handoff.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_pose_handoff.py new file mode 100644 index 0000000..f9f68c8 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_pose_handoff.py @@ -0,0 +1,117 @@ +"""Two-sided, immutable evidence for handing a shared Tag to another joint. + +The source is checked on its last baseline images BEFORE recipient motion. +The recipient is checked on its own return images AFTER that motion. Neither +window is selected by pixel loss, and neither model nor zero is rewritten. +""" +from collections import deque + +import numpy as np + +from ..core.geometry.tag_pose.ippe import solve_square_tag_ippe +from ..core.geometry.tag_pose.motion_evidence import MotionEvidenceFrame, RoleCandidates +from ..core.geometry.tag_pose.motion_image_types import ImageMotionFrame, ImageRoleObservation +from .revisit import LEGACY_REVISIT_POLICY, validated_feedback_limits + +HANDOFF_POLICY = 'two_sided_shared_pose_v1' +SOURCE_PHASES = frozenset({'sweep', 'steady', 'joint_zero'}) + + +def enabled(profile): + from ..core.domain.capture_plan import STAGED_POLICIES + return (profile.quality.training_policy in STAGED_POLICIES + and bool(profile.motion.preparation_witnesses)) + + +class SharedPoseHandoff: + """Bounded raw-image tails, owned by the existing reference registry.""" + + def __init__(self, profile): + self.profile = profile + self.windows = {} + + def observe(self, row): + if not enabled(self.profile) or row.get('kind') != 'image_observation_frame': + return + if row.get('sample_phase') not in SOURCE_PHASES: + return + key = (row.get('session_epoch'), row.get('task_name'), row.get('view')) + window = self.windows.setdefault(key, deque(maxlen=max(10, + self.profile.acquisition.fixed_reference_minimum_frames))) + if window and window[-1]['session_epoch'] != row['session_epoch']: + window.clear() + if not window or row['image_stamp_ns'] > window[-1]['image_stamp_ns']: + window.append(row) + + def rows(self, epoch, reference, view): + return tuple(self.windows.get((epoch, reference.task_key, view), ())) + + def advance_recovery_epoch(self, previous, current): + # Called only by the registry's journalled internal recovery. Raw rows + # keep their original epoch; a restart cannot copy this in-memory grant. + self.windows.update({(current, task, view): deque(rows, maxlen=rows.maxlen) + for (epoch, task, view), rows in tuple(self.windows.items()) if epoch == previous}) + + +def source_window(profile, rows, reference, channels, model, *, epoch, before_stamp, + verification=LEGACY_REVISIT_POLICY, feedback_limits=None): + """Validate the entire predetermined tail, then reconstruct all IPPE seeds. + + A bad/missing frame vetoes this window. Current-image root verification, + the 1.5 px gate and the source-zero pose bounds still run in check_source_pose. + """ + limits = validated_feedback_limits(profile, verification, feedback_limits) + minimum = max(10, profile.acquisition.fixed_reference_minimum_frames) + if len(rows) != minimum: + raise ValueError('shared_pose_handoff_source_missing') + stamps = [r['image_stamp_ns'] for r in rows] + spec = profile.measurement.measurements[reference.joint] + old = [s for s in reference.samples if s.view == spec.view] + if (not old or stamps != sorted(set(stamps)) or stamps[-1] >= before_stamp + or stamps[0] < min(s.image_stamp_ns for s in old) + or not 200_000_000 <= stamps[-1]-stamps[0] + <= profile.acquisition.joint_zero_timeout_seconds*1e9): + raise ValueError('shared_pose_handoff_window_invalid') + target = profile.motion.joint_zero_references[reference.joint].command + for row in rows: + if (row.get('kind') != 'image_observation_frame' or row.get('session_epoch') != epoch + or row.get('task_name') != reference.task_key or row.get('view') != spec.view + or row.get('sample_phase') not in SOURCE_PHASES + or row.get('cycle') == profile.quality.holdout_cycle + or row.get('command_unit') != profile.command.unit + or row.get('input_is_rectified') is not True + or row.get('camera_matrix_source') != 'CameraInfo.P[:3,:3]' + or tuple(map(tuple, row['camera_matrix'])) != model.camera_matrix): + raise ValueError('shared_pose_handoff_identity_changed') + for field in ('command_vector', 'feedback_vector'): + values = row.get(field) + if (values is None or np.shape(values) != (profile.command.command_count,) + or not np.all(np.isfinite(values))): + raise ValueError('shared_pose_handoff_state_missing') + if any(row['command_vector'][i] != target[i] for i in channels): + raise ValueError('shared_pose_handoff_posture_changed') + feedback = np.asarray([r['feedback_vector'] for r in rows])[:, channels] + previous = np.asarray([s.feedback for s in old])[:, channels] + if (np.any(np.ptp(feedback, axis=0) > limits['within_hold_range']) + or np.any(np.abs(feedback-np.median(previous, axis=0)) > limits['between_visit_difference'])): + raise ValueError('shared_pose_handoff_feedback_changed') + references = {ref.role: ref for ref in model.reference_frames} + if set(references) != {spec.parent_role}: + raise ValueError('shared_pose_handoff_fixed_root_required') + frames = [] + tags = {tag.role:tag for view in profile.vision.views if view.name == spec.view for tag in view.tags} + for row in rows: + roles, observations = [], [] + for role, size in model.tag_sizes: + item = row['tags'].get(role) + if (item is None or item.get('tag_size_m') != size + or item.get('tag_id') != tags[role].tag_id): + raise ValueError('shared_pose_handoff_pixels_missing') + corners = tuple(map(tuple, item['corners_xy'])) + candidates = ((references[role].pose,) if role in references else + tuple(solve_square_tag_ippe(corners, tag_size_m=size, camera_matrix=model.camera_matrix))) + roles.append(RoleCandidates(role, candidates, role in references)) + observations.append(ImageRoleObservation(role, size, corners)) + frames.append(ImageMotionFrame(MotionEvidenceFrame(row['image_stamp_ns'], tuple(roles)), + model.camera_matrix, tuple(observations), model.reference_frames)) + return tuple(frames) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_tag_evidence.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_tag_evidence.py new file mode 100644 index 0000000..6500ebc --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_tag_evidence.py @@ -0,0 +1,147 @@ +"""Read back shared-Tag posture constraints without re-fitting old sweeps.""" + +from ..core.domain.reference import JointZeroReference, JointZeroSample +from ..core.geometry.image_motion_replay import frozen_image_model, replay_image_models, validate_image_sample +from dataclasses import replace + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.geometry.tag_pose.pose_bridge import ( + check_pose_bridge, check_source_pose, SHARED_ZERO_CONDITIONING, SHARED_POSE_CONDITIONING, + is_handoff_policy, +) +from .parent_reference_evidence import source_epoch_matches +from .shared_tag_reference import build_pose_bridge, shared_zero_source +from .revisit import LEGACY_REVISIT_POLICY + + +def validate_shared_tag_references(profile, records, evidence, *, source_model=None): + from .motion_provenance import source_frame_sha256 + from ..profiles.observations import compile_tag_feedback_channels + + source_references = [r for r in records if r.get('kind')=='joint_zero_reference'] + source_references.extend(r['current_reference'] for r in records + if r.get('kind')=='joint_zero_motion_reference_verified') + sources = {source_frame_sha256(r): r for r in source_references} + observations = {(r['view'], str(r['image_stamp_ns'])): r for r in records + if r.get('kind')=='motion_branch_observation'} + # A resumed scan and its dependency import may both carry the same raw + # exposure. Count it once, and reject conflicting copies of that identity. + raw_images = {} + for row in records: + if row.get('kind') != 'image_observation_frame': + continue + identity = (row.get('session_epoch'), row.get('task_name'), row.get('view'), row['image_stamp_ns']) + previous = raw_images.get(identity) + if previous is not None and previous != row: + raise ValueError('shared_pose_handoff_duplicate_image_changed') + raw_images[identity] = row + samples = {(r['view'], r['image_stamp_ns']): r for r in records if r.get('kind')=='joint_zero_sample'} + pixels = {(r['view'], r['image_stamp_ns']): r for r in records if r.get('kind')=='pnp_candidate_frame'} + channels = None if source_model is None else compile_tag_feedback_channels(profile, source_model) + checked = set() + for payload in evidence.values(): + for record in payload.get('shared_tag_pose_bridges', ()): + key = (payload.get('image_model_sha256'), source_frame_sha256(record)) + if key in checked: + continue + checked.add(key) + joint = record.get('joint') + source_record = record.get('source_reference', {}) + if source_frame_sha256(source_record) not in sources: + raise ValueError('shared_pose_original_zero_missing_or_changed') + reference = JointZeroReference.from_record(source_record) + source = evidence.get(record.get('source_evidence_id')) + spec = profile.measurement.measurements.get(joint) + if (spec is None or joint not in payload['zero_joints'] or source is None + or payload['task_name'] != profile.motion.joint_zero_references[joint].task_key + or source['view'] != spec.view or payload['view'] != spec.view + or source['tag_role'] != spec.child_role + or source['image_model_sha256'] != record.get('source_model_sha256') + or reference.joint not in source['zero_joints'] + or not any(b.view==spec.view and b.tag_role==spec.child_role + and b.motion_evidence_id==record['source_evidence_id'] for b in reference.branch_references)): + raise ValueError('shared_pose_source_model_unbound') + held = record.get('held_channels') + if (not isinstance(held, (list, tuple)) or not held or list(held)!=sorted(set(held)) + or any(type(i) is not int or not 0<=imax(payload['source_image_stamps'])): + raise ValueError('shared_pose_current_image_missing_or_changed') + rows.append(row) + rows.sort(key=lambda r:r['image_stamp_ns']) + if (not rows or not source_epoch_matches(records, source, payload['session_epoch'], + record['source_evidence_id'], rows[0]['image_stamp_ns'])): + raise ValueError('shared_pose_source_epoch_changed') + for sample in reference.samples: + row = samples.get((sample.view, sample.image_stamp_ns)) + frame = pixels.get((sample.view, sample.image_stamp_ns)) + if (row is None or frame is None or row.get('joint')!=reference.joint + or JointZeroSample.from_row(row, profile.command.unit)!=sample): + raise ValueError('shared_pose_zero_pixels_missing_or_changed') + validate_image_sample(row, frame, replay_image_models(frame)) + feedback_contract = dict(verification=record.get('verification', LEGACY_REVISIT_POLICY), + feedback_limits=record.get('feedback_limits')) + bridge = build_pose_bridge(profile, joint, reference, rows, tuple(held), **feedback_contract) + current_model, source_image_model = frozen_image_model(payload), frozen_image_model(source) + if is_handoff_policy(payload.get('image_model_selection_policy')): + from .shared_pose_handoff import HANDOFF_POLICY, SOURCE_PHASES, source_window + from .parent_reference_evidence import same_capture_epoch + if record.get('handoff_policy') != HANDOFF_POLICY: + raise ValueError('shared_pose_handoff_policy_changed') + # Recompute the chronological tail from ALL recorded images; + # hashes of a hand-picked set are not sufficient evidence. + before = min(payload['source_image_stamps']) + available = sorted((r for r in raw_images.values() + if r.get('session_epoch') == record.get('source_window_epoch') + and r.get('task_name') == reference.task_key and r.get('view') == spec.view + and r.get('sample_phase') in SOURCE_PHASES and r['image_stamp_ns'] < before), + key=lambda r:r['image_stamp_ns']) + minimum = max(10, profile.acquisition.fixed_reference_minimum_frames) + window = available[-minimum:] + if record.get('source_window_hashes') != { + str(r['image_stamp_ns']): source_frame_sha256(r) for r in window}: + raise ValueError('shared_pose_handoff_window_changed') + if not window or not same_capture_epoch(records, record.get('source_window_epoch'), + payload['session_epoch'], window[-1]['image_stamp_ns'], before): + raise ValueError('shared_pose_handoff_epoch_changed') + bridge = replace(bridge, source_frames=source_window(profile, window, + reference, tuple(held), source_image_model, + epoch=record['source_window_epoch'], before_stamp=before, **feedback_contract)) + elif 'handoff_policy' in record or 'source_window_hashes' in record: + raise ValueError('shared_pose_handoff_policy_changed') + conditioning = record.get('conditioning') + if conditioning is not None: + if conditioning not in {SHARED_ZERO_CONDITIONING, SHARED_POSE_CONDITIONING}: + raise ValueError('shared_pose_conditioning_policy_changed') + bridge = replace(bridge, source_model=source_image_model, conditioning=conditioning) + if check_source_pose(bridge).status != 'consistent': + raise ValueError('shared_pose_source_current_image_changed') + geometry = next(g for g in current_model.geometry if g.relation.joint == joint) + if (Rotation.from_quat(geometry.reference_quaternion_xyzw).inv() + * Rotation.from_quat(bridge.quaternion_xyzw)).magnitude() > 1e-10: + raise ValueError('shared_pose_conditioned_orientation_changed') + if conditioning == SHARED_POSE_CONDITIONING: + zero_point = (np.asarray(geometry.pivot_parent_xyz_m) + + Rotation.from_quat(geometry.reference_quaternion_xyzw).apply(geometry.mount_child_xyz_m)) + if np.linalg.norm(zero_point-np.asarray(bridge.translation_xyz_m)) > 1e-10: + raise ValueError('shared_pose_conditioned_translation_changed') + if (current_model.camera_matrix!=source_image_model.camera_matrix + or any(f.camera_matrix!=current_model.camera_matrix for f in bridge.frames) + or check_pose_bridge(current_model, bridge).status!='consistent'): + raise ValueError('shared_pose_current_model_inconsistent') diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_tag_reference.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_tag_reference.py new file mode 100644 index 0000000..fe21783 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/shared_tag_reference.py @@ -0,0 +1,163 @@ +"""Build a bounded posture bridge from passed zeros and new approach images. + +This consumes immutable references already available to the session. It never +replays an old sweep, moves hardware, or changes a frozen joint reference. +""" + +import math +from dataclasses import replace + +import numpy as np +from scipy.spatial.transform import Rotation + +from ..core.geometry.tag_pose.motion_evidence import MotionEvidenceFrame, MotionRelation, RoleCandidates +from ..core.geometry.tag_pose.motion_image_types import ImageMotionFrame, ImageRoleObservation +from ..core.geometry.tag_pose.pose_bridge import SharedTagPoseBridge +from ..core.geometry.tag_pose.types import SquareTagPose +from ..core.geometry.tag_pose.image_reference import IMAGE_REFERENCE_SOURCE, reference_from_evidence +from .revisit import LEGACY_REVISIT_POLICY, REVISIT_POLICY, revisit_feedback_limits, validated_feedback_limits + + +def shared_zero_source(profile, joint, view, references, channels): + """Nearest earlier task observing the same rigid roles at the same posture.""" + spec = profile.measurement.measurements[joint] + if spec.view != view or channels is None or profile.vision_motion: + return None + # A changing parent needs its own authorization path; this bridge is for + # two single hinges measured against the same stationary camera reference. + if not any(tag.role == spec.parent_role and tag.fixed_reference + for v in profile.vision.views if v.name == view for tag in v.tags): + return None + target = profile.motion.joint_zero_references[joint].command + relevant = sorted(channels[spec.child_role] | channels[spec.parent_role]) + previous = [] + for task in profile.motion.tasks: + if joint in task.joints: + break + for name in task.joints: + old = profile.measurement.measurements[name] + reference = references.get(name) + if (reference is not None and (old.view, old.parent_role, old.child_role) == + (view, spec.parent_role, spec.child_role)): + samples = [s for s in reference.samples if s.view == view] + if samples and all(s.command[i] == target[i] for s in samples for i in relevant): + previous.append(reference) + return (previous[-1], tuple(relevant)) if previous else None + + +def bridge_frames(rows, relation): + """Use actual same-image pixels; never obtain a moving pose from continuity.""" + frames = [] + for row in rows: + roles, observations, references = [], [], [] + for role in (relation.parent_role, relation.child_role): + item = row['tags'][role] + if item['candidate_diagnostics']['observation_stamp_ns'] != row['image_stamp_ns']: + raise ValueError('shared_pose_image_identity_changed') + root = role == relation.parent_role + payloads = ([item['selected_pose']] if root else item['reprojection_valid_candidates']) + if not payloads or any(p is None for p in payloads): + raise ValueError('shared_pose_candidates_missing') + if root and item['candidate_diagnostics'].get('branch_frozen') is not True: + raise ValueError('shared_pose_parent_not_frozen') + poses = tuple(SquareTagPose(tuple(p['quaternion_xyzw']), tuple(p['translation_xyz_m']), + float(p['reprojection_error_px'])) for p in payloads) + roles.append(RoleCandidates(role, poses, root)) + observations.append(ImageRoleObservation(role, item['tag_size_m'], tuple(map(tuple, item['corners_xy'])))) + if item.get('pose_source') == IMAGE_REFERENCE_SOURCE: + references.append(reference_from_evidence(item, stamp_ns=row['image_stamp_ns'], camera_matrix=row['camera_matrix'])) + frames.append(ImageMotionFrame(MotionEvidenceFrame(row['image_stamp_ns'], tuple(roles)), + tuple(map(tuple, row['camera_matrix'])), tuple(observations), tuple(references))) + return tuple(frames) + + +def build_pose_bridge(profile, joint, reference, rows, channels, *, + verification=LEGACY_REVISIT_POLICY, feedback_limits=None): + """The same physical checks serve live construction and journal read-back.""" + limits = validated_feedback_limits(profile, verification, feedback_limits) + spec = profile.measurement.measurements[joint] + old_spec = profile.measurement.measurements[reference.joint] + if (spec.view, spec.parent_role, spec.child_role) != (old_spec.view, old_spec.parent_role, old_spec.child_role): + raise ValueError('shared_pose_physical_roles_changed') + samples = [s for s in reference.samples if s.view == spec.view] + minimum = max(10, profile.acquisition.fixed_reference_minimum_frames) + if len(samples) < minimum or len(rows) < minimum: + raise ValueError('shared_pose_stationary_images_missing') + stamps = [row['image_stamp_ns'] for row in rows] + if (stamps != sorted(set(stamps)) or min(stamps) <= max(s.image_stamp_ns for s in samples) + or stamps[-1]-stamps[0] < 200_000_000): + raise ValueError('shared_pose_stationary_window_invalid') + target = profile.motion.joint_zero_references[joint].command + if (any(s.command[i] != target[i] for s in samples for i in channels) + or any(row.get('command_vector') is None or row.get('feedback_vector') is None + or row['view'] != spec.view or row['sample_phase'] != 'zero_approach' + or any(row['command_vector'][i] != target[i] for i in channels) for row in rows)): + raise ValueError('shared_pose_posture_changed') + old_feedback = np.asarray([s.feedback for s in samples])[:, channels] + current_feedback = np.asarray([r['feedback_vector'] for r in rows])[:, channels] + if (not np.all(np.isfinite(current_feedback)) or not np.all(np.isfinite(old_feedback)) + or np.any(np.ptp(current_feedback, axis=0) > limits['within_hold_range']) + or np.any(np.abs(current_feedback-np.median(old_feedback, axis=0)) > limits['between_visit_difference'])): + raise ValueError('shared_pose_feedback_changed') + rotations = Rotation.from_quat([s.relative_quaternion_xyzw for s in samples]) + points = np.asarray([s.relative_translation_xyz_m for s in samples]) + if (np.max((rotations.mean().inv()*rotations).magnitude()) > math.radians(1.) + or np.max(np.linalg.norm(points-np.median(points, axis=0), axis=1)) > .001): + raise ValueError('shared_pose_source_not_stable') + relation = MotionRelation(joint, spec.parent_role, spec.child_role) + return SharedTagPoseBridge(relation, tuple(rotations.mean().as_quat()), + tuple(np.median(points, axis=0)), bridge_frames(rows, relation)) + + +def prepare_pose_bridges(owner, view, references, sources, arc_stamps, epoch): + from .motion_provenance import source_frame_sha256 + + bridges, records = [], [] + for joint in owner.zero_joints: + # Verify-mode resume preserves historical curve zeros, but also has a + # freshly verified pose attached to the current image model. Use that + # pose for new geometry; never relabel the historical zero's identity. + pose_references = {name: owner.parent_references.zero_references.get((epoch, view, name), ref) + for name, ref in references.items()} + selected = shared_zero_source(owner.profile, joint, view, pose_references, owner.tag_feedback_channels) + if selected is None: + continue + reference, channels = selected + source = owner.parent_references.models.get((epoch, view, reference.joint)) + if source is None: + raise ValueError('shared_pose_source_model_missing') + model, report = source + spec = owner.profile.measurement.measurements[joint] + identity = dict(model.evidence_ids).get(spec.child_role) + if not any(b.view == view and b.tag_role == spec.child_role and b.motion_evidence_id == identity + for b in reference.branch_references): + raise ValueError('shared_pose_source_model_changed') + minimum = max(10, owner.profile.acquisition.fixed_reference_minimum_frames) + rows = tuple(row for row in sources if row['image_stamp_ns'] not in arc_stamps)[-minimum:] + feedback_contract = dict(verification=REVISIT_POLICY, + feedback_limits=revisit_feedback_limits(owner.profile)) + bridge = replace(build_pose_bridge(owner.profile, joint, reference, rows, channels, + **feedback_contract), + source_model=model.image_model) + from .shared_pose_handoff import enabled, source_window, HANDOFF_POLICY + handoff_record = {} + if enabled(owner.profile): + source_rows = owner.parent_references.handoff.rows(epoch, reference, view) + source_epoch = source_rows[0]['session_epoch'] if source_rows else epoch + source_frames = source_window(owner.profile, source_rows, reference, channels, + model.image_model, epoch=source_epoch, before_stamp=min(arc_stamps), **feedback_contract) + bridge = replace(bridge, source_frames=source_frames) + handoff_record = dict(handoff_policy=HANDOFF_POLICY, + source_window_epoch=source_epoch, + source_window_hashes={str(r['image_stamp_ns']): source_frame_sha256(r) for r in source_rows}) + if any(f.camera_matrix != model.image_model.camera_matrix for f in bridge.frames): + raise ValueError('shared_pose_camera_changed') + bridges.append(bridge) + records.append(dict(joint=joint, source_reference=reference.as_record(), + **feedback_contract, + **handoff_record, + conditioning=bridge.conditioning, + source_evidence_id=identity, source_model_sha256=report['image_model_sha256'], + held_channels=list(channels), + source_frame_hashes={str(row['image_stamp_ns']): source_frame_sha256(row) for row in rows})) + return tuple(bridges), tuple(records) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/snapshot.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/snapshot.py new file mode 100644 index 0000000..5406fed --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/snapshot.py @@ -0,0 +1,203 @@ +"""Typed live status assembly; wire dictionaries are created only at the edge.""" + +from __future__ import annotations + +from dataclasses import asdict, dataclass, replace +from typing import TYPE_CHECKING, Mapping + +from ..core.domain.status import CalibrationStatus, MotionStatus +from .camera_preflight import CameraPreflight +from .diagnostic_quality import evaluate_diagnostic_unit +from .scan_quality import evaluate_capture_unit +from .session import CalibrationPhase as Phase + +if TYPE_CHECKING: + from .coordinator import CalibrationCoordinator + + +_LEGACY_STATES = { + Phase.WAIT_DEVICE: "WAIT_DEVICES", Phase.READY: "READY", + Phase.COMPLETE: "PASSED", Phase.PAUSED: "PAUSED", + Phase.CAPTURE_COMPLETE: "CAPTURE_COMPLETE", + Phase.DIAGNOSTIC_COMPLETE: "DIAGNOSTIC_COMPLETE", + Phase.ABORTED: "ABORTED", Phase.FAILED: "FAILED", + **{phase: "FINALIZING" for phase in ( + Phase.FIT, Phase.HOLDOUT_VALIDATE, Phase.BUILD_ARTIFACTS, + Phase.VALIDATE_URDF, Phase.PUBLISH, + )}, +} + + +def legacy_state(phase: Phase) -> str: + return _LEGACY_STATES.get(phase, "RUNNING") + + +@dataclass(frozen=True) +class CameraReadiness: + camera_info_ready: bool + detections_ready: bool + error: str + + +@dataclass(frozen=True) +class DeviceReadiness: + ready: bool + waiting_for: tuple[str, ...] + cameras: Mapping[str, CameraReadiness] + + +@dataclass(frozen=True) +class RuntimeSnapshot: + calibration: CalibrationStatus + model: str + side: str + profile_id: str + serial_number: str + reason: str + session_dir: str + latest_base_drift_px: Mapping[str, float] + devices: DeviceReadiness | None + steady: bool = False + steady_node: int | None = None + camera_preflight: CameraPreflight | None = None + diagnostic_capture: Mapping | None = None + raw_protocol_progress: Mapping | None = None + + def as_dict(self) -> dict: + value = self.calibration.as_dict() + value.update(model=self.model, side=self.side, profile_id=self.profile_id, + serial_number=self.serial_number, reason=self.reason, + session_dir=self.session_dir, latest_base_drift_px=dict(self.latest_base_drift_px)) + if self.devices is not None: + value["devices"] = asdict(self.devices) + if self.camera_preflight is not None: + value["camera_preflight"] = self.camera_preflight.as_dict() + if self.diagnostic_capture is not None: + value["diagnostic_capture"] = dict(self.diagnostic_capture) + if self.raw_protocol_progress is not None: + value['raw_protocol_progress'] = dict(self.raw_protocol_progress) + if self.steady: + value["acquisition"]["steady_node"] = self.steady_node + return value + + +def build_snapshot(host: CalibrationCoordinator) -> RuntimeSnapshot: + """Called under the coordinator lock; retains the public status fields.""" + session, profile, parameters = host.execution.session, host.profile, host.parameters + status = session.status() + task, motion = status.task, host._motion + if motion is not None and motion.phase == "joint_zero": + required = {} + for view in profile.vision.views: + roles = {role for name in motion.zero_joints + for key in (name, profile.measurement.cross_view_sources.get(name)) if key is not None + for spec in (profile.measurement.measurements[key],) if spec.view == view.name + for role in (spec.parent_role, spec.child_role)} + ids = tuple(tag.tag_id for tag in view.tags if tag.role in roles) + if ids: + required[view.name] = ids + label = "确认父标签保持姿态:" if motion.reference_reuse else "采集关节零位:" + task = replace(task, label=label+", ".join(motion.zero_joints), + required_tag_ids_by_view=required) + elif motion is not None and motion.phase in {'observer_preflight', 'observer_probe'}: + joint = motion.reference_joints[0] + label = '检查观测充分性:'+joint + if motion.phase == 'observer_probe': + decision = host.branch_initialization.observer_preparation.decisions[joint] + action = decision.get('action_index', 0)+1 + total = decision.get('action_limit', 1) + stage = ('起始保持', '改变观察方向', '回位保持')[motion.reference_path_index] + label = f'补采观测:{joint}(第 {action}/{total} 步,{stage})' + task = replace(task, label=label) + if session.phase == Phase.REFERENCE_POSES and motion is not None: + waypoint = next((w for w in profile.motion.resume_verification_waypoints + if w.key == motion.task_key), None) + if waypoint is not None: + task = replace(task, required_tag_ids_by_view=waypoint.tag_ids_by_view, + label="Tag 安装验证姿态:"+waypoint.key) + required = task.required_tag_ids_by_view + required_ids = {tag for ids in required.values() for tag in ids} + missing = {tag for view, ids in required.items() + for tag in host.capture.last_missing.get(view, ids)} & required_ids + filtered = {tag for ids in host.capture.last_filtered.values() for tag in ids} & required_ids + interrupted = session.phase in {Phase.PAUSED, Phase.ABORTED, Phase.FAILED} + steady = not interrupted and motion is not None and motion.phase in {"steady", "steady_prepare"} + steady_node = None + if steady and motion.steady_index is not None: + steady_node = motion.steady_index+1 + task = replace(task, label=task.label+f"(稳态点 {steady_node})") + index = None if motion is None else motion.command_index + health = host.sdk_adapter.health() + # A pause can interrupt a new task before its first evaluation. The last + # completed quality result may belong to another task/direction; scope + # paused statistics to the current unit just like live scan statistics. + quality = None + diagnostic_quality = None + if session.current_unit is not None and session.phase in {Phase.SWEEP, Phase.RESCAN, Phase.EVALUATE, Phase.PAUSED}: + from ..core.domain.capture_plan import raw_joint_capture + if raw_joint_capture(profile): + from .raw_quality import evaluate_raw_unit + quality = evaluate_raw_unit(profile, session.current_unit, + host.execution.action.retry+1, tuple(host._unit_rows), + first_cycle_spans=dict(host.execution.first_cycle_spans)) + elif host.diagnostic_capture is not None: + diagnostic_quality = evaluate_diagnostic_unit(profile, session.current_unit, + host.execution.action.retry+1, tuple(host._unit_rows)) + quality = diagnostic_quality.observations + else: + quality = evaluate_capture_unit(profile, session.current_unit, + host.execution.action.retry+1, tuple(host._unit_rows), + first_cycle_spans=dict(host.execution.first_cycle_spans), include_steady=True) + acquisition = replace(status.acquisition, retry_count=host.execution.action.retry) + if quality is not None and quality.metrics: + metrics = tuple(quality.metrics.values()) + acquisition = replace(acquisition, + valid_samples=min(m["valid_frames"] for m in metrics), + coverage_01=min(m.get("input_span", m.get("feedback_span")) for m in metrics), + bins=min(m.get("input_bins", m.get("feedback_bins")) for m in metrics), + maximum_gap=max(m["maximum_bin_gap"] for m in metrics)) + status = replace(status, task=task, acquisition=acquisition, + phase=motion.phase if not interrupted and motion is not None and motion.phase in + {"steady", "steady_prepare", "joint_zero", "zero_approach"} else status.phase, + recognized_tag_ids=tuple(sorted(required_ids-missing-filtered)), + missing_tag_ids=tuple(sorted(missing)), rejected_tag_ids=tuple(sorted(filtered)), + log_path=str(parameters.session_dir/"calibration.log"), + hardware={"feedback_hz": round(host._feedback_hz(), 2), "mode_verified": health.position_mode, + "faults": health.active_faults, "feedback_fresh": health.feedback_fresh, "diagnostic": health.diagnostic}, + motion=MotionStatus(channel="" if index is None else host.command_names[index], + unit=host.command_unit, speed=None if motion is None else motion.speed, + command=None if index is None or host.last_command is None else host.last_command[index], + feedback=None if index is None or not host.latest_feedback else host.latest_feedback[index]), + resume={**status.resume, "message": host._resume_message, "completed_unit_count": host._resumed_count, + "source_session": "" if parameters.resume_raw_samples_path is None + else parameters.resume_raw_samples_path.parent.name}, + outputs={"json": host.final_json, "urdf": host.final_urdf, + "raw_samples": str(host.raw_path), + "failure_diagnostic": str(parameters.session_dir / "failure_diagnostic.json") + if session.phase == Phase.FAILED and host.finalization.started else "", + "publication_pointer": str(parameters.session_dir.parent/profile.artifacts.publication_pointer) + if session.phase == Phase.COMPLETE else "", + **({"diagnostic_report": + str(parameters.session_dir / "diagnostic_capture.json") + if session.phase == Phase.DIAGNOSTIC_COMPLETE else ""} if host.diagnostic_capture else {})}) + devices = None if host.started else host._device_status(host.ports.monotonic()) + preflight = host._camera_preflight if devices is None else CameraPreflight.from_readiness(devices.cameras) + diagnostic = None + if host.diagnostic_capture is not None: + diagnostic = {**host.diagnostic_capture.as_dict(), "publication_allowed": False, + "accuracy_validated": False, "coverage_scope": "raw_observations", + "unresolved_joint_zero_references": sorted(host.execution.diagnostic_zero_attempts), + "confirmed_joint_zero_references": sorted(host.execution.zero_references)} + if diagnostic_quality is not None: + diagnostic["accepted_pose_quality"] = diagnostic_quality.accepted_pose_report() + return RuntimeSnapshot(status, profile.key.model, profile.key.side, profile.key.profile_id, + parameters.serial_number, host.reason, str(parameters.session_dir), + dict(host.reference_lock.latest_drift_px), + devices, steady, steady_node, preflight, + diagnostic, (dict(protocol='raw_joint_images_v2', capture_finished=session.phase == Phase.CAPTURE_COMPLETE, formal_rounds_per_task=3, + actual_commands_sent=host._actual_command_count, + actual_direction_changes_by_channel=list(host._actual_direction_changes), + command_count_scope='all_sent_commands_including_approach_avoidance_return_and_retries', + raw_capture_complete=(len(host.execution.completed_units) == len(session.engine.scan_units()) + and not session.incomplete_units), + acceptance_report=str(parameters.session_dir/'raw_joint_result.json')) if host.raw_joint else None)) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/staged_resume.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/staged_resume.py new file mode 100644 index 0000000..c111b9b --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/staged_resume.py @@ -0,0 +1,225 @@ +"""Resume complete visits without crossing a frozen training boundary.""" + +from collections import OrderedDict +from pathlib import Path +import json + +from ..core.domain.capture_plan import evidence_digest +from ..core.domain.motion_path import record_scan_identity +from ..core.domain.reference import read_joint_zero_references +from .motion_provenance import validate_motion_provenance +from .scan_quality import evaluate_capture_unit + + +def stage_visits(resume, engine, rows): + from .task_deferral import deferred_visit_keys + deferred = deferred_visit_keys(resume.profile, rows) + references = read_joint_zero_references(resume.profile, rows) + validate_motion_provenance(resume.profile, rows, references=references, + image_replay_workers=resume.image_replay_workers) + visits, latest = OrderedDict(), {} + for unit in engine.scan_units(): + visits.setdefault((unit.task_key, unit.cycle), []).append(unit) + for row in rows: + if row.get('kind') == 'scan_unit_complete': + latest[record_scan_identity(row)] = row + spans, valid = {}, set() + for (key, cycle), units in visits.items(): + task = next(t for t in resume.profile.motion.tasks if t.key == key) + if not set(task.joints) <= references.keys(): + if (key, cycle) in deferred: + continue + break + if any(latest.get(u.identity, {}).get('passed') is not True for u in units): + if (key, cycle) in deferred: + continue + break + if not all(evaluate_capture_unit(resume.profile, u, latest[u.identity].get('attempt', 1), rows, + first_cycle_spans=spans).passed for u in units): + raise ValueError('staged_resume_completed_visit_invalid') + valid.update(u.identity for u in units) + decisions = [r for r in rows if r.get('kind') == 'staged_training_decision'] + if any(r['decision'] == 'fail' for r in decisions): + raise ValueError('staged_failed_training_cannot_resume') + if any(r['decision'] == 'freeze' for r in decisions): + if not {u.identity for u in engine.scan_units() if u.cycle != 3} <= valid: + raise ValueError('staged_frozen_training_prefix_incomplete') + resume.references, resume.rows, resume.units = references, tuple(rows), valid + resume.first_cycle_spans = spans + + +def stage_passed_visits(resume, engine, rows): + """Restore durable visit decisions without replaying historical images. + + This is only used by the explicit unchanged-installation ``passed`` mode. + Every imported evidence record remains content-bound and finalization still + performs the complete image/provenance replay before publication. + """ + from .task_deferral import deferred_visit_keys + deferred = deferred_visit_keys(resume.profile, rows) + references = read_joint_zero_references(resume.profile, rows) + visits, latest = OrderedDict(), {} + for unit in engine.scan_units(): + visits.setdefault((unit.task_key, unit.cycle), []).append(unit) + for row in rows: + if row.get("kind") == "scan_unit_complete": + key = record_scan_identity(row) + previous = latest.get(key) + if previous is None or int(row.get("attempt", 1)) >= int(previous.get("attempt", 1)): + latest[key] = row + spans, valid = {}, set() + for (task_key, cycle), units in visits.items(): + task = next(task for task in resume.profile.motion.tasks if task.key == task_key) + if not set(task.joints) <= references.keys(): + if (task_key, cycle) in deferred: + continue + break + completions = [latest.get(unit.identity) for unit in units] + if any(row is None or row.get("passed") is not True for row in completions): + if (task_key, cycle) in deferred: + continue + break + valid.update(unit.identity for unit in units) + if cycle == 0: + for row in completions: + for identity, metrics in row.get("metrics", {}).items(): + span = metrics.get("feedback_span", metrics.get("input_span")) + if isinstance(span, (int, float)): + spans[identity] = float(span) + decisions = [row for row in rows if row.get("kind") == "staged_training_decision"] + if any(row.get("decision") == "fail" for row in decisions): + raise ValueError("staged_failed_training_cannot_resume") + if any(row.get("decision") == "freeze" for row in decisions): + if not {unit.identity for unit in engine.scan_units() if unit.cycle != 3} <= valid: + raise ValueError("staged_frozen_training_prefix_incomplete") + resume.references, resume.rows, resume.units = references, tuple(rows), valid + resume.first_cycle_spans = spans + + +def load_frozen_checkpoint(profile, rows, path, source): + from .staged_training import read_frozen_training, staged_snapshot + freezes = [r for r in rows if r.get('kind') == 'staged_training_decision' and r['decision'] == 'freeze'] + if not freezes: + return None + payload = json.loads((Path(path).parent/'frozen_training.json').read_text()) + if len(freezes) != 1 or evidence_digest(payload) != freezes[0]['frozen_training_sha256']: + raise ValueError('staged_resume_frozen_model_changed') + read_frozen_training(profile, staged_snapshot(profile, rows), read_joint_zero_references(profile, rows), source, payload) + return payload + + +def reference_import(resume, *, reuse_passed_visits=False): + from .joint_resume import _index_motion_provenance + from .passed_resume import PassedReferenceImport, coherent_observer_preparation_rows + provenance = tuple(_index_motion_provenance(resume.rows).values()) + if reuse_passed_visits: + reused_tasks = {identity[0] for identity in resume.units} + reused_joints = {joint for task in resume.profile.motion.tasks + if task.key in reused_tasks for joint in task.joints} + references = {joint: reference for joint, reference in resume.references.items() + if joint in reused_joints} + # A visit that did not pass is restarted with a fresh preparation + # model in the current image epoch. Reusing its old candidate path is + # neither a passed-unit optimization nor valid cross-session evidence. + provenance = tuple(row for row in provenance + if row.get("task_name") is None or row.get("task_name") in reused_tasks) + provenance = _essential_indexed_provenance(provenance) + provenance = coherent_observer_preparation_rows(provenance) + else: + references = resume.references + models = tuple(r for r in provenance if r.get('kind') == 'motion_branch_initialization' and r.get('status') == 'resolved') + audit = () + if reuse_passed_visits: + # Authorize only visits whose complete unit set passed stage_visits. + # Future training/holdout visits retain their normal zero checks. + visits = {(key[0], key[1]) for key in resume.units} + resume.verified_visits.update((name, cycle) for task in resume.profile.motion.tasks + for key, cycle in visits if key == task.key for name in task.joints) + audit = ({'kind': 'passed_tasks_reused', 'resume_mode': 'passed', + 'unchanged_installation_declared': True, + 'training_policy': resume.profile.quality.training_policy, + 'completed_units': [list(key) for key in sorted(resume.units)], + 'historical_replay_performed': False, 'physical_zero_reverification_performed': False, + 'full_replay_required_before_publication': True},) + return PassedReferenceImport(rows=(*(r.as_record() for r in references.values()), *provenance, *audit), + references=references, model_records=models) + + +def _essential_indexed_provenance(rows): + """Keep source frames actually named by accepted models in compact journals.""" + import re + from collections.abc import Mapping + from .resume_storage import DeferredCaptureRecord, materialize_record + + if not any(isinstance(row, DeferredCaptureRecord) and row.canonical_sha256 for row in rows): + return rows + hashes = set() + + def collect(value, key=""): + if isinstance(value, Mapping): + for name, item in value.items(): + # Digest maps are keyed by image stamp. Preserve the parent + # field name while descending into them; replacing it with the + # numeric stamp made every digest invisible to this filter. + collect(item, key if "hash" in key.lower() else str(name)) + elif isinstance(value, (list, tuple)): + for item in value: + collect(item, key) + elif (isinstance(value, str) and "hash" in key.lower() + and re.fullmatch(r"[0-9a-f]{64}", value)): + hashes.add(value) + + evidence_kinds = {"motion_branch_initialization", "parent_reference_verified", + "parent_reference_model_refreshed", + "observer_preparation_decision", "observer_preparation_segment_complete", + "joint_zero_motion_reference_verified"} + for row in rows: + if row.get("kind") in evidence_kinds: + collect(materialize_record(row)) + if not hashes: + return rows + return tuple(row for row in rows if row.get("kind") != "motion_branch_observation" + or getattr(row, "canonical_sha256", None) in hashes) + + +def restore_recovery(session, recovery, rows): + session.restore_task_deferrals(rows) + for row in rows: + if row.get('kind') == 'joint_zero_recovery': + recovery.restore(row['task_name'], row['joints']) + elif row.get('kind') == 'scan_unit_complete': + if row.get('passed') is False and int(row.get('attempt', 1)) >= 2: + raise ValueError('staged_resume_recovery_exhausted') + key = record_scan_identity(row) + consumed = max(0, int(row.get('attempt', 1))-1) + (row.get('passed') is False) + session._retry_by_unit[key] = max(session._retry_by_unit.get(key, 0), min(1, consumed)) + + +def visit_rows(resume, task_key, cycle): + task = next(t for t in resume.profile.motion.tasks if t.key == task_key) + if not all((name, cycle) in resume.verified_visits for name in task.joints): + return (), () + units = {key for key in resume.units if key[0] == task_key and key[1] == cycle} + rows = [r for r in resume.rows if record_scan_identity(r) in units + and r.get('kind') not in {'joint_zero_reference', 'joint_zero_sample'}] + if units: + from ..core.domain.capture_plan import TASKWISE_STAGED + from .engine import CalibrationEngine + if resume.profile.quality.training_policy == TASKWISE_STAGED and cycle in {1, 2}: + # Persist the causal decision beside the visit that produced it. + # This lets a later restart reconstruct an optional cycle 2 from + # the new journal without depending on in-memory profile state. + assessed = list(range(cycle + 1)) + decisions = [r for r in resume.rows if r.get('kind') == 'training_decision' + and r.get('task_name') == task_key and r.get('assessed_cycles') == assessed] + if len(decisions) != 1: + raise ValueError('taskwise_resume_training_decision_missing') + rows.extend(decisions) + stage = [u for u in CalibrationEngine(resume.profile).scan_units() if u.cycle == cycle] + if (resume.profile.quality.training_policy != TASKWISE_STAGED + and cycle in {1, 2} and stage[-1].task_key == task_key): + decisions = [r for r in resume.rows if r.get('kind') == 'staged_training_decision'] + candidates = decisions[:1] if cycle == 1 else decisions[1:] + rows.extend(candidates) + resume.units.difference_update(units) + return tuple(sorted(units)), tuple(rows) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/staged_training.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/staged_training.py new file mode 100644 index 0000000..b6836b5 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/staged_training.py @@ -0,0 +1,275 @@ +"""Whole-hand training checkpoints and one dependency-complete supplement.""" + +from dataclasses import dataclass, replace +import hashlib +import math +from pathlib import Path + +from ..core.domain.capture_plan import CapturePlan, evidence_digest, select_task_training, training_cycles +from ..core.urdf.kinematics import UrdfKinematicModel +from ..core.fitting.command_motion import fit_command_training, CommandMotionFit +from ..core.fitting.frozen import encode, decode +from ..core.fitting.session import compile_spatial_profile, build_axis_observations +from ..core.fitting.spatial_solver.solve import fit_urdf_zero_training +from ..core.fitting.training_quality import _by_joint, _curve_repeatability + + +STAGED_DECISION_VERSION = "staged_training_decision_v1" +FROZEN_VERSION = "frozen_hand_training_v1" +SOLVER_VERSION = "staged_command_spatial_tag_v1" + + +@dataclass(frozen=True) +class TrainingIssue: + code: str + scope: str + parameters: tuple[str, ...] + tasks: tuple[str, ...] + + +def dependency_tasks(profile, parameter): + """Same-cycle observation closure; shared/global failures use all tasks.""" + graph = profile.zero.spatial + if graph.get('base_pose_strategy') == 'full_hand' and parameter in graph.get('root_anchor_joints', ()): + return tuple(t.key for t in profile.motion.tasks) + observer = graph.get("offset_observer_joint", {}).get(parameter) + if observer is None: + return tuple(t.key for t in profile.motion.tasks) + pending, joints = [parameter, observer], set() + while pending: + joint = pending.pop() + if joint in joints: + continue + joints.add(joint) + for key in ("axis_parent_joint", "phase_parent_joint"): + parent = graph.get(key, {}).get(joint) + if parent is not None: + pending.append(parent) + return tuple(t.key for t in profile.motion.tasks if set(t.joints) & joints) + + +def training_input_sha256(profile, rows, references, source_urdf): + return evidence_digest({"plan": CapturePlan.from_profile(profile).as_dict(), "rows": rows, + "configuration": encode(profile), "solver_version": SOLVER_VERSION, + "references": {name: ref.as_record() for name, ref in sorted(references.items())}, + "source_urdf_sha256": hashlib.sha256(Path(source_urdf).read_bytes()).hexdigest()}) + + +def spatial_inputs(profile, source_urdf, model, steady, motion, *, include_holdout): + zero_profile = compile_spatial_profile(profile) + axes = build_axis_observations(profile, model, steady, motion, zero_profile, include_holdout=include_holdout) + baselines = {**{n: v.cad_angle_rad for n, v in profile.zero.known_baseline_geometry.items()}, + **{n: 0. for n in profile.zero.cad_zero_assumptions}} + curves = {n: replace(c, circle={**c.circle, "known_cad_baseline_rad": baselines[n]}) + if n in baselines and n not in zero_profile.direct_zero_joints else c + for n, c in motion.coordinate_curves.items()} + from ..core.fitting.motion_fit import channel_for_joint + return dict(source_urdf=source_urdf, measurements=axes, + curves=curves, motor_by_joint={n: channel_for_joint(profile, n) for n in curves}, + zero_profile=zero_profile, + training_cycles=tuple(sorted({c for t in profile.motion.tasks for c in training_cycles(profile, t)})), + allow_partial_training_cycles=True, maximum_offset_rad=math.radians(20), + finger_maximum_offset_rad=math.radians(20), maximum_validation_mae_rad=math.radians(1), + maximum_validation_p95_rad=math.radians(2), maximum_validation_error_rad=math.radians(3), + maximum_confidence_half_width_rad=math.radians(1), maximum_pose_axis_line_rms_m=.0015) + + +def assess_staged_training(*, profile, rows, references, source_urdf, cache=None, **_): + """Only current training rows enter; cache keys include every local input.""" + if any(r["cycle"] not in training_cycles(profile, r["task_name"]) for r in rows): + raise ValueError("staged_training_received_holdout") + cache = {} if cache is None else cache + model = UrdfKinematicModel(source_urdf) + sweep, steady = _by_joint(rows, "sweep"), _by_joint(rows, "steady") + source_hash = hashlib.sha256(Path(source_urdf).read_bytes()).hexdigest() + parts, issues, metrics = [], [], {} + profile_contract = encode(replace(profile, quality=replace(profile.quality, task_training_cycles={}))) + for task in profile.motion.tasks: + names = task.joints + try: + part_sweep, part_steady = ({n: sweep[n] for n in names}, {n: steady[n] for n in names}) + refs = {n: references[n] for n in names} + key = evidence_digest({"source": source_hash, "task": task.key, + "profile": profile_contract, "cycles": training_cycles(profile, task), + "sweep": part_sweep, "steady": part_steady, + "references": {n: r.as_record() for n, r in refs.items()}}) + cached = cache.get(task.key) + local = cached[1] if cached and cached[0] == key else fit_command_training( + profile, model, part_sweep, part_steady, refs) + cache[task.key] = (key, local) + failures, observed = _curve_repeatability(profile, task, local, steady, training_cycles(profile, task)) + metrics.update(observed) + if failures: + issues.append(TrainingIssue("training_repeatability", "task", tuple(names), (task.key,))) + parts.append(local) + except (ValueError, KeyError) as error: + issues.append(TrainingIssue("local_training_invalid", "task", tuple(names), (task.key,))) + metrics[task.key] = {"reason": str(error)} + motion, zero, frozen = None, None, None + if len(parts) == len(profile.motion.tasks): + motion = CommandMotionFit(**{field: {k: v for part in parts for k, v in getattr(part, field).items()} + for field in CommandMotionFit.__dataclass_fields__}) + try: + zero = fit_urdf_zero_training(**spatial_inputs(profile, source_urdf, model, steady, motion, include_holdout=False)) + metrics['spatial'] = {'zero_confidence_half_width_rad': { + n: v if math.isfinite(v) else None for n, v in zero.confidence_half_widths.items()}, + 'independent_cycles_by_joint': {name: len(values) for name, values in zero.cycle_values.items()}} + for name, code in zero.failure_reasons.items(): + tasks = dependency_tasks(profile, name) + issues.append(TrainingIssue(code, "parameter" if name in profile.zero.direct_zero_joints else "global", + (name,), tasks)) + except (ValueError, KeyError) as error: + issues.append(TrainingIssue("spatial_training_invalid", "global", (), tuple(t.key for t in profile.motion.tasks))) + metrics["spatial_failure"] = str(error) + if not issues and motion is not None and zero is not None: + try: + frozen = _freeze(profile, rows, references, source_urdf, model, motion, zero) + except ValueError as error: + issues.append(TrainingIssue("tag_training_invalid", "global", (), tuple(t.key for t in profile.motion.tasks))) + metrics["tag_failure"] = str(error) + supplemented = any(2 in training_cycles(profile, t) for t in profile.motion.tasks) + decision = "fail" if issues and supplemented else "supplement" if issues else "freeze" + tasks = tuple(t.key for t in profile.motion.tasks if any(t.key in issue.tasks for issue in issues)) + record = {"kind": "staged_training_decision", "version": STAGED_DECISION_VERSION, + "decision": decision, "supplement_tasks": list(tasks) if decision == "supplement" else [], + "issues": [{"code": i.code, "scope": i.scope, "parameters": list(i.parameters), + "tasks": list(i.tasks)} for i in issues], "metrics": metrics, + "failures": [i.code for i in issues], + "source_sha256": training_input_sha256(profile, rows, references, source_urdf), + "input_plan_sha256": CapturePlan.from_profile(profile).sha256, + "frozen_training_sha256": None if frozen is None else evidence_digest(frozen)} + record["decision_sha256"] = evidence_digest(record) + return {"decision": record, "frozen_training": frozen} + + +def _freeze(profile, rows, references, source, model, motion, zero): + from .artifacts.evidence import prepare_tag_replay + from ..core.urdf.plan import StandardUrdfPlan + from ..core.urdf.patch import UrdfPatchSet + from ..core.geometry.extrinsics import transform_matrix + offsets = {**zero.frozen.applied_offsets, **{n: 0. for n in profile.zero.cad_zero_assumptions}} + if any(j.mimic_joint for j in model.joints.values()): + raise ValueError("staged_tag_training_requires_independent_joint_model") + plan = StandardUrdfPlan(hashlib.sha256(Path(source).read_bytes()).hexdigest(), offsets, {}, {}, + UrdfPatchSet({}), profile.urdf_authorized_fields) + pose = zero.frozen.fit + replay = prepare_tag_replay(profile=profile, source_model=model, plan=plan, + output_mappings=motion.mappings, + common_from_base=transform_matrix(pose.base_translation, pose.base_rotation.as_quat()), + records=[r for r in rows if r.get("sample_phase") == "steady"]) + return {"version": FROZEN_VERSION, "solver_version": SOLVER_VERSION, + "input_sha256": training_input_sha256(profile, rows, references, source), + "capture_plan": CapturePlan.from_profile(profile).as_dict(), "motion": encode(motion), + "zero": encode(zero.frozen), "tag_installations": encode(dict(replay.installations)), + "common_from_base": encode(replay.common_from_base), "required_roles": list(replay.required_roles)} + + +def read_frozen_training(profile, rows, references, source, payload): + if (payload.get("version") != FROZEN_VERSION or payload.get("solver_version") != SOLVER_VERSION + or payload.get("capture_plan") != CapturePlan.from_profile(profile).as_dict() + or payload.get("input_sha256") != training_input_sha256(profile, rows, references, source)): + raise ValueError("frozen_hand_training_inputs_changed") + return {key: decode(payload[key]) for key in ("motion", "zero", "tag_installations", "common_from_base")} + + +def staged_snapshot(profile, records): + from .capture_index import task_training_snapshot + if hasattr(records, 'training_task_snapshot'): + return tuple(row for task in profile.motion.tasks for row in + records.training_task_snapshot(task.key, training_cycles(profile, task))) + groups = {} + for row in records: + groups.setdefault(row.get('task_name'), []).append(row) + return tuple(row for task in profile.motion.tasks for row in + task_training_snapshot(groups.get(task.key, ()), training_cycles(profile, task))) + + +def resolve_staged_plan(profile, records, *, source_urdf=None, verify_decisions=False, require_complete=False): + """Replay phase transitions before trusting any partition or frozen file.""" + from ..core.domain.capture_plan import STAGED, configure_training + from ..core.domain.reference import JointZeroReference + from ..core.domain.motion_path import record_scan_identity + from .engine import CalibrationEngine + current = configure_training(profile, STAGED) + headers = [r for r in records if r.get("kind") == "session_start"] + if len(headers) != 1 or headers[0].get("capture_plan") != CapturePlan.from_profile(current).as_dict(): + raise ValueError("staged_capture_requires_matching_plan_header") + phase, supplemented, frozen, failed = 0, False, False, False + completed, prefix, references, revisits = set(), [], {}, {} + units = CalibrationEngine(current).scan_units() + allowed = {u.identity for u in units} + first_round = {u.identity for u in units if u.cycle == 0} + for row in records: + kind = row.get("kind") + if kind == "joint_zero_reference": + reference = JointZeroReference.from_record(row) + old = references.get(reference.joint) + if old is not None and old.as_record() != reference.as_record(): + raise ValueError("staged_frozen_reference_replaced") + references[reference.joint] = reference + if kind == "scan_unit_complete": + identity = record_scan_identity(row) + if row.get("passed"): + completed.add(identity) + else: + completed.discard(identity) + elif kind == "joint_zero_motion_reference_verified" and str(row.get("verification", "")).startswith("staged_revisit"): + from .revisit import verify_revisit + original = JointZeroReference.from_record(row["preserved_reference"]) + current_reference = JointZeroReference.from_record(row["current_reference"]) + if (original.joint not in references or row.get("joint") != original.joint + or row.get("task_name") != original.task_key + or evidence_digest(original.as_record()) != evidence_digest(references[original.joint].as_record())): + raise ValueError("staged_revisit_zero_binding_changed") + verify_revisit(current, original, current_reference, verification=row["verification"], + feedback_limits=row.get("feedback_limits")) + visit = revisits.setdefault((original.task_key, row.get("cycle")), {}) + # Imported scans retain their original, already verified visit. + # A later physical recheck must not erase that historical proof. + visit[original.joint] = min(visit.get(original.joint, math.inf), + max(s.image_stamp_ns for s in current_reference.samples)) + elif kind == "staged_training_decision": + expected = {u.identity for u in units if u.cycle != 3} + if (failed or frozen or not expected <= completed + or row.get("version") != STAGED_DECISION_VERSION + or row.get("input_plan_sha256") != CapturePlan.from_profile(current).sha256 + or row.get("decision_sha256") != evidence_digest({k: v for k, v in row.items() if k != "decision_sha256"})): + raise ValueError("staged_training_decision_invalid") + if verify_decisions: + result = assess_staged_training(profile=current, rows=staged_snapshot(current, prefix), + references=references, source_urdf=source_urdf) + if evidence_digest(result["decision"]) != evidence_digest(row): + raise ValueError("staged_training_decision_evidence_changed") + decision = row.get("decision") + if decision == "supplement" and not supplemented: + keys = row.get("supplement_tasks", []) + if not keys or len(set(keys)) != len(keys): + raise ValueError("staged_supplement_tasks_invalid") + for key in keys: + current = select_task_training(current, key, (0, 1, 2)) + units = CalibrationEngine(current).scan_units() + allowed = {u.identity for u in units} + supplemented, phase = True, 2 + elif decision == "freeze" and row.get("frozen_training_sha256"): + frozen, phase = True, 3 + elif decision == "fail": + failed = True + else: + raise ValueError("staged_training_transition_invalid") + elif kind in {"joint_sample", "secondary_joint_sample"}: + cycle = row.get("cycle") + if cycle == 1 and phase == 0 and first_round <= completed: + phase = 1 + if failed or cycle != phase or record_scan_identity(row) not in allowed: + raise ValueError("staged_observation_outside_current_phase") + task = next(t for t in current.motion.tasks if t.key == row["task_name"]) + if cycle > 0: + visit = revisits.get((task.key, cycle), {}) + if not set(task.joints) <= visit.keys(): + raise ValueError("staged_visit_reference_not_verified") + if row['image_stamp_ns'] <= max(visit[name] for name in task.joints): + raise ValueError("staged_visit_images_precede_reference_check") + prefix.append(row) + if require_complete and (not frozen or failed): + raise ValueError("staged_training_not_frozen") + return current diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/stall_retry.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/stall_retry.py new file mode 100644 index 0000000..dca9291 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/stall_retry.py @@ -0,0 +1,32 @@ +"""Bounded, clock-driven retries of the same motion after a progress timeout.""" +from dataclasses import dataclass + + +@dataclass +class StallRetry: + maximum_failures: int = 3 + delay_seconds: float = 3.0 + motion_id: str = '' + failures: int = 0 + waiting_since: float | None = None + + @property + def waiting(self): + return self.waiting_since is not None + + def failed(self, motion_id, now): + if self.motion_id != motion_id: + self.motion_id, self.failures = motion_id, 0 + self.failures += 1 + self.waiting_since = now if self.failures < self.maximum_failures else None + return self.waiting + + def remaining(self, now): + return max(0., self.delay_seconds-(now-self.waiting_since)) if self.waiting else 0. + + def resume(self, now): + if not self.waiting or self.remaining(now) > 0: + return None + elapsed = now-self.waiting_since + self.waiting_since = None + return elapsed diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/startup.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/startup.py new file mode 100644 index 0000000..d8ffbd9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/startup.py @@ -0,0 +1,37 @@ +"""Publish initialization liveness before the ROS executor can start. + +The publisher owns no coordinator state, SDK ports or start service. Its +lifetime ends before normal status callbacks begin, including on exceptions. +""" +from contextlib import contextmanager +from threading import Event, Thread + +from ..core.domain.status import CalibrationStatus + + +@contextmanager +def checkpoint_heartbeat(publish, *, enabled, interval=1.0): + if not enabled: + yield + return + status = CalibrationStatus(state='PREPARING_CHECKPOINT', phase='PREPARING_CHECKPOINT', + resume={'message': '正在加载并校验断点原始证据,尚未开始标定运动'}) + stopped = Event() + errors = [] + def heartbeat(): + while not stopped.wait(interval): + try: + publish(status) + except Exception as error: + errors.append(error) + return + publish(status) + worker = Thread(target=heartbeat, name='checkpoint-status', daemon=True) + worker.start() + try: + yield + finally: + stopped.set() + worker.join() + if errors: + raise RuntimeError('checkpoint_status_publication_failed') from errors[0] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/status.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/status.py new file mode 100644 index 0000000..681ee17 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/status.py @@ -0,0 +1,222 @@ +"""One console/status contract, with a read-only bridge for legacy messages.""" + +from __future__ import annotations + +from typing import Any, Mapping + +from ..core.domain.profile import CalibrationProfile +from ..core.domain.status import CalibrationStatus +from .diagnostic_capture import diagnostic_capture_label +from .reporting.reasons_zh import reason_zh + + +_STATES = {"WAIT_START": "READY", "WAIT_DEVICES": "WAIT_DEVICE", "PASSED": "COMPLETE"} +_SEGMENTS = { + "linked_increasing": "四指正向联动", "linked_decreasing": "四指反向联动", + "middle_lower_increasing": "中指向上补段", "middle_lower_decreasing": "中指向下补段", +} +_PHASES = { + "PREPARING_CHECKPOINT": "加载并校验断点证据(未开始运动)", + "WAIT_DEVICE": "等待设备", "READY": "设备就绪", "BASELINE": "安全恢复基准", + "REFERENCE_LOCKING": "锁定基准(等待所需 Tag)", "RESUME_VERIFY": "验证断点基准", + "REFERENCE_POSES": "采集 Tag 安装验证姿态", + "PREPARE": "扫描起点准备", "MAPPING_PROBE": "固定通道映射点动", + "SWEEP": "正式扫描", "EVALUATE": "方向数据检查", "RESCAN": "同速重扫", + "RETURN_BASELINE": "按避让顺序安全收尾", + "FIT": "训练数据拟合", "HOLDOUT_VALIDATE": "独立验证", + "BUILD_ARTIFACTS": "生成产物", "VALIDATE_URDF": "校验导出 URDF", + "PUBLISH": "发布", "COMPLETE": "会话完成", "PAUSED": "已暂停", + "CAPTURE_COMPLETE": "采集已结束(URDF 尚未验收)", + "DIAGNOSTIC_COMPLETE": "诊断采集完成(未进行精度验收)", + "ABORTED": "已中止", "FAILED": "失败", "RUNNING": "标定中", + "FINALIZING": "拟合与产物校验", "FITTING": "拟合与验证", + "baseline": "安全恢复基准", "preflight": "固定通道映射点动", + "prepare": "扫描起点准备", "retry_prepare": "同速重扫起点准备", "sweep": "正式扫描", + "steady_prepare": "稳态指令采样起点准备", "steady": "稳态指令→rad 采样", + "joint_zero": "采集并冻结关节零位", "zero_approach": "关节零位到达准备", +} + + +def required_tags(profile: CalibrationProfile, task_key: str) -> dict[str, list[int]]: + task = next((task for task in profile.motion.tasks if task.key == task_key), None) + if task is None: + return {} + names = set(task.joints) + names.update(profile.measurement.cross_view_sources[name] for name in task.joints + if name in profile.measurement.cross_view_sources) + measurements = [profile.measurement.measurements[name] for name in names] + result = {} + for view in profile.vision.views: + roles = {role for item in measurements if item.view == view.name + for role in (item.parent_role, item.child_role) if role is not None} + ids = [tag.tag_id for tag in view.tags if tag.role in roles] + if ids: + result[view.name] = ids + return result + + +def normalize_status( + value: Mapping[str, Any], *, profile: CalibrationProfile | None = None, + serial_number: str = "", +) -> dict[str, Any]: + """Normalize transport fields only; never invent quality or motion evidence.""" + result = CalibrationStatus().as_dict() + result.update(value) + state = _STATES.get(str(value.get("state", "WAIT_DEVICE")), str(value.get("state", "WAIT_DEVICE"))) + result["state"] = state + result["serial_number"] = serial_number or value.get("serial_number", "?") + if profile is not None: + result.update(model=profile.key.model, side=profile.key.side, + profile_id=profile.key.profile_id) + if isinstance(value.get("task"), Mapping) and "overall_progress_01" in value: + return result + active = value.get("active", {}) + active = active if isinstance(active, Mapping) else {} + row = {**value, **active} + key = str(row.get("task_name") or "") + selected = next((task for task in profile.motion.tasks if task.key == key), None) if profile else None + cycle = row.get("cycle") + # The old nested active contract is already one-based; old flat nodes are + # zero-based. The public v1 status uses one-based cycles everywhere. + cycle = None if cycle is None else int(cycle) + (0 if active else 1) + result["task"] = { + "key": key, "label": " / ".join(selected.joints) if selected else key, + "cycle": cycle, "cycle_count": 4, "direction": row.get("direction", ""), + "required_tag_ids_by_view": required_tags(profile, key) if profile and key + else value.get("required_tag_ids_by_view", {}), + } + unit = str(value.get("command_unit", profile.command.unit if profile else "u8")) + result["motion"] = { + "command": row.get("current_command_u8", row.get("current_motion_target_u8", row.get("target_rad", row.get("target_u8")))), + "feedback": row.get("actual_u8"), "unit": unit, + "speed": row.get("speed_rad_s", row.get("speed_u8")), + } + sample = row.get("sample", {}) + sample = sample if isinstance(sample, Mapping) else {} + result["acquisition"] = { + "valid_samples": row.get("valid_frames", 0), + "coverage_01": row.get("feedback_span_01", float(sample.get("span_u8", 0)) / 255.0 if unit == "u8" else 0.0), + "bins": row.get("feedback_bins", sample.get("bin_count", 0)), + "maximum_gap": row.get("maximum_bin_gap", sample.get("maximum_gap", 0)), + "retry_count": row.get("automatic_retry_count", max(0, int(row.get("attempt", 1) or 1) - 1)), + } + progress = value.get("progress") + if progress is None: + count = int(value.get("step_count", 0) or 0) + progress = (int(value.get("step_index", 0) or 0) + float(value.get("step_fraction", 0) or 0)) / count if count else 0.0 + result["overall_progress_01"] = 1.0 if state in {"COMPLETE", "DIAGNOSTIC_COMPLETE"} else min(1.0, max(0.0, float(progress))) + result["phase"] = str(row.get("phase") or state) + result["missing_tag_ids"] = value.get("missing_tag_ids", value.get("unrecognized_tag_ids", ())) + result["hardware"] = { + "feedback_hz": value.get("feedback_hz"), + "mode_verified": value.get("position_mode_verified"), + "faults": value.get("error_faults", value.get("error_codes")), + "feedback_fresh": value.get("hand_state_fresh"), + } + if state in {"PAUSED", "ABORTED", "FAILED"}: + code, reason, suggestion = reason_zh(value, model_name=profile.key.model if profile else "机械手") + result["pause"] = {"code": code, "reason": reason, "suggestion": suggestion, + "details": {"raw_reason": str(value.get("reason", ""))}} + return result + + +def render_status_zh(value: Mapping[str, Any], estimator=None) -> str: + """Render v1 without assumptions about channel, task, or camera counts.""" + progress = float(value.get("overall_progress_01", 0.0)) + eta = value.get("estimated_remaining_seconds") + if eta is None and estimator is not None: + eta = estimator.remaining(progress) + eta_text = "计算中" if eta is None else f"{int(eta) // 60}分{int(eta) % 60:02d}秒" + task, motion, acquisition = (value.get(name, {}) for name in ("task", "motion", "acquisition")) + unit = motion.get("unit", "") + def angle(item): + return "未知" if item is None else f"{float(item):.3f} {unit}" + def tags(ids): + return "/".join(f"ID{int(item)}" for item in ids) or "无" + phase = str(value.get("phase")) + phase_label = _PHASES.get(phase, value.get("phase")) + if value.get("raw_protocol_progress") and phase == "steady": + phase_label = "稳态角点采集" + diagnostic_info = value.get("diagnostic_capture") or {} + diagnostic = bool(diagnostic_info) + sample_label = "原始观测" if diagnostic_info.get("coverage_scope") == "raw_observations" else "有效样本" + if diagnostic and phase in {"SWEEP", "sweep"}: + phase_label = "诊断扫描" + if diagnostic_info.get("hold_command_values"): + if phase == "steady_prepare": + phase_label = "方向差保持采集起点准备" + elif phase == "steady": + phase_label = f"方向差保持采集(每点至少 {diagnostic_info['hold_seconds']:g} 秒)" + capture_stage = task.get("capture_stage", "motion") + stage_line = f"阶段:{phase_label}(第 {task.get('cycle') or '-'}/{task.get('cycle_count', 4)} 轮)" + if capture_stage in {"command_training", "command_validation"}: + stage_line = "阶段:" + ("稳态指令映射训练" if capture_stage == "command_training" else "稳态指令映射独立验证") + elif capture_stage == "training_supplement": + stage_line = f"阶段:{phase_label}(当前任务训练补采 1/1)" + lines = [ + f"[{value.get('model', '未知型号')} / {value.get('side', '?')} / {value.get('serial_number', '?')}] {progress:6.1%} 预计剩余 {eta_text}", + stage_line, + f"任务:{task.get('label') or task.get('key') or '无'};方向:{task.get('direction') or '-'}", + f"命令/反馈{'('+motion['channel']+')' if motion.get('channel') else ''}:" + f"{angle(motion.get('command'))}/{angle(motion.get('feedback'))}", + "任务所需 Tag:" + (";".join(f"{view}={tags(ids)}" for view, ids in task.get("required_tag_ids_by_view", {}).items()) or "无"), + f"Tag:已识别 {tags(value.get('recognized_tag_ids', ()))};缺失 {tags(value.get('missing_tag_ids', ()))};过滤 {tags(value.get('rejected_tag_ids', ()))}", + f"{sample_label} {acquisition.get('valid_samples', 0)};覆盖 {float(acquisition.get('coverage_01', 0)):.1%};分箱 {acquisition.get('bins', 0)};内部空白 {acquisition.get('maximum_gap', 0)};重扫 {acquisition.get('retry_count', 0)} 次", + ] + if task.get('segment_key'): + key = task['segment_key'] + path = ';'.join(f'{channel} {start:g}→{end:g}' + for channel, (start, end) in task.get('segment_commands', {}).items()) + lines.insert(3, f"子段:{_SEGMENTS.get(key, key)};计划指令:{path} {unit}") + if diagnostic: + label = diagnostic_capture_label(diagnostic_info.get("mode", "o6_thumb")) + lines.insert(1, f"模式:{label};仅采集观测,不发布标定 JSON/URDF") + accepted = diagnostic_info.get("accepted_pose_quality", {}) + metrics = tuple(accepted.get("metrics", {}).values()) + if metrics: + lines.append(f"可信姿态样本 {min(m['valid_frames'] for m in metrics)};" + f"覆盖 {min(m.get('input_span', m.get('feedback_span')) for m in metrics):.1%}(未进行精度验收)") + unresolved = diagnostic_info.get("unresolved_joint_zero_references", ()) + if unresolved: + lines.append("零位未确认,仅保留原始观测:" + ", ".join(unresolved)) + waiting = value.get("devices", {}).get("waiting_for", ()) + if waiting: + lines.append("等待项:" + ";".join(waiting)) + preflight = value.get("camera_preflight") + if preflight: + labels = {"passed": "通过", "failed": "失败", "unverified": "未验证"} + configuration = preflight.get("configuration", {}) + lines.append("启动前相机配置:" + ";".join( + f"{view}={labels.get(check['status'], check['status'])}" + for view, check in configuration.items())) + lines.append("启动前实测:" + ";".join( + f"{label}={labels.get(preflight[key]['status'], preflight[key]['status'])}" + for key, label in (("intrinsics", "光学内参"), ("extrinsics", "相对外参")))) + if value.get("state") in {"READY", "WAIT_DEVICE", "WAIT_DEVICES"}: + for view, check in configuration.items(): + if check["status"] != "passed": + lines.append(f"{view}:{check['reason']};{check['suggestion']}") + for key in ("intrinsics", "extrinsics"): + check = preflight[key] + if check["status"] != "passed": + lines.append(f"检查依据:{check['reason']};{check['suggestion']}") + lines.append("提示:设备就绪不代表内外参实测通过;缺少依据时无法判断是否需重新标定。") + if motion.get("speed") is not None: + lines.append(f"运动速度:{motion['speed']} {'rad/s' if unit == 'rad' else 'SDK速度档'}") + if value.get("reference_locked"): + lines.append("基准已锁定:请勿移动手掌、相机、支架或Tag") + resume = value.get("resume", {}) + if resume: + message = resume.get('message', resume.get('reason', '')) + message = {"not_requested": "本次完整重采,未请求恢复", + "waiting_for_reference_verification": "已请求断点恢复,等待基准和逐关节零位复核", + "diagnostic_capture_no_resume": "诊断采集,不复用断点"}.get(message, message) + lines.append(f"断点:{message};复用 {resume.get('completed_unit_count', 0)} 单元;来源 {resume.get('source_session') or '-'}") + hardware = value.get("hardware", {}) + lines.append(f"SDK:反馈 {hardware.get('feedback_hz', '未知')} Hz;模式确认 {hardware.get('mode_verified', '未知')};故障 {hardware.get('faults', '未知')}") + pause = value.get("pause", {}) + if pause.get("reason"): + lines.extend((f"原因 [{pause.get('code', '')}]:{pause['reason']}", f"建议:{pause.get('suggestion', '')}")) + if pause.get("details"): + lines.append(f"诊断:{pause['details']}") + return "\n".join(lines) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/steady.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/steady.py new file mode 100644 index 0000000..cc64e77 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/steady.py @@ -0,0 +1,51 @@ +"""Bounded, direction-specific command observations, separate from sweeps.""" + +import math +from ..core.domain.motion_path import task_segment, record_scan_identity + + +def steady_targets(profile, unit, *, records=(), training_nodes=None): + from ..core.domain.sampling import command_nodes, command_holdout_cycle + task = next(t for t in profile.motion.tasks if t.key == unit.task_key) + from ..core.fitting.command_sampling import declared_training_nodes + values = (command_nodes(profile, task, holdout=True) if unit.cycle == command_holdout_cycle(profile) + else training_nodes if training_nodes is not None else declared_training_nodes(profile, task, records)) + if unit.segment_key: + segment = task_segment(task, unit.segment_key) + starts, ends = dict(segment.start_commands), dict(segment.end_commands) + fractions = {0.0, 1.0} + for channel in segment.moving_channels: + lo, hi = sorted((starts[channel], ends[channel])) + fractions.update((value-starts[channel])/(ends[channel]-starts[channel]) + for value in values if lo <= value <= hi) + return tuple(segment.start+(segment.end-segment.start)*f for f in sorted(fractions)) + return tuple(values if unit.direction == "increasing" else reversed(values)) + + +def steady_failures(profile, unit, attempt, records): + from .scan_quality import observation_streams + task = next(t for t in profile.motion.tasks if t.key == unit.task_key) + failures = [] + selected = [r for r in records if r.get("sample_phase") == "steady" + and r.get("task_name") == unit.task_key and r.get("cycle") == unit.cycle + and record_scan_identity(r) == unit.identity and int(r.get("attempt", 1)) == attempt] + segment = task_segment(task, unit.segment_key) if unit.segment_key else None + for field, name, spec in observation_streams(profile, task): + if segment and name not in segment.joints: + continue + for index, target in enumerate(steady_targets(profile, unit, records=records)): + if segment: + from ..core.fitting.motion_fit import channel_for_joint + expected = segment.commands_at(target, quantize=profile.command.unit == "u8")[channel_for_joint(profile, name)] + else: + expected = target + images = {r.get("image_stamp_ns") for r in selected + if r.get("sample_phase") == "steady" and r.get(field) == name + and r.get("view") == spec.view and r.get("task_name") == unit.task_key + and r.get("cycle") == unit.cycle and r.get("direction") == unit.direction + and int(r.get("attempt", 1)) == attempt and r.get("steady_index") == index + and math.isclose(float(r.get("steady_target", float("nan"))), expected, abs_tol=1e-9) + and r.get("image_stamp_ns", 0) > 0} + if len(images) < profile.acquisition.steady_minimum_samples: + failures.append(f"steady:{field}:{name}:{spec.view}:node={index}:samples={len(images)}") + return tuple(failures) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/task_deferral.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/task_deferral.py new file mode 100644 index 0000000..abfc4eb --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/task_deferral.py @@ -0,0 +1,298 @@ +"""Bounded task deferral for recoverable visual observability failures. + +The queue reorders uncompleted visits, or whole tasks for taskwise capture. It +never changes accepted units, reference models, quality limits or holdout +semantics. Safety failures are deliberately outside this module. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum + + +POLICY = "dependency_ordered_observation_deferral_v1" +TASKWISE_POLICY = "dependency_ordered_task_deferral_v2" + + +def taskwise_deferral(profile): + from ..core.domain.capture_plan import TASKWISE_TWO_ROUND + return profile.quality.training_policy == TASKWISE_TWO_ROUND + + +def deferral_policy(profile): + return TASKWISE_POLICY if taskwise_deferral(profile) else POLICY + + +RECOVERABLE_REASONS = frozenset({ + "rigid_pair_candidates_unresolved", + "rigid_pair_pose_uncertain", + "rigid_pair_viewpoint_span_insufficient", + "rigid_pair_source_missing", + "observer_images_missing", + "observer_preparation_candidates_missing", + "motion_candidates_missing", + "motion_candidate_assignment_ambiguous", + "motion_candidate_family_discontinuous", + "motion_candidate_family_interrupted", + "motion_geometry_ambiguous", + "motion_geometry_unresolved", + "image_motion_alternative_angles_unresolved", + "image_motion_families_not_distinguishable", + "image_motion_frame_angles_ambiguous", + "image_motion_frame_angles_uncertain", + "image_motion_frame_angles_unobservable", + "image_motion_insufficient_independent_frames", + "image_motion_no_observable_image_model", + "image_motion_shared_pose_unresolved", + "parent_reference_samples_missing", + "image_reference_current_image_moved", + "pose_image_motion_root_missing", +}) + + +class TaskObservationState(str, Enum): + PASSED = "passed" + PENDING = "pending" + DEPENDENCY_PENDING = "dependency_pending" + UNOBSERVABLE = "unobservable" + + +def task_dependencies(profile): + """Compile parent task -> descendant tasks from observed Tag roles.""" + task_by_joint = {joint: task.key for task in profile.motion.tasks for joint in task.joints} + owners = {} + for joint, spec in profile.measurement.measurements.items(): + task = task_by_joint.get(joint) + if task is not None and spec.child_role: + owners.setdefault((spec.view, spec.child_role), set()).add(task) + graph = {task.key: set() for task in profile.motion.tasks} + for joint, spec in profile.measurement.measurements.items(): + child_task = task_by_joint.get(joint) + if child_task is None or not spec.parent_role: + continue + for parent_task in owners.get((spec.view, spec.parent_role), ()): + if parent_task != child_task: + graph[parent_task].add(child_task) + if taskwise_deferral(profile): + # A parent pose and its hinge geometry can come from different tasks. + # Shared stationary tags also hand their reference to the next hinge. + previous_roles = {} + for task in profile.motion.tasks: + reference = task.parent_reference + if reference is not None: + for joint in (reference.pose_joint, reference.geometry_joint): + parent = task_by_joint.get(joint) + if parent is not None and parent != task.key: + graph[parent].add(task.key) + for joint in task.joints: + spec = profile.measurement.measurements[joint] + roles = (spec.view, spec.parent_role, spec.child_role) + previous = previous_roles.get(roles) + if previous is not None and previous != task.key: + graph[previous].add(task.key) + previous_roles[roles] = task.key + return {key: frozenset(value) for key, value in graph.items()} + + +def dependency_closure(profile, task_key): + graph = task_dependencies(profile) + pending, result = [task_key], set() + while pending: + current = pending.pop() + if current in result: + continue + result.add(current) + pending.extend(graph.get(current, ())) + return frozenset(result) + + +def recoverable_observation_reason(reason): + text = str(reason) + return any(code in text for code in RECOVERABLE_REASONS) + + +def recoverable_task_observation(reason, reports): + """Require all failed views to be recoverable, not a message substring.""" + text = str(reason) + if text.startswith("view="): + fields = text.split(":", 2) + if len(fields) != 3 or not fields[1].startswith("joints="): + return False + text = fields[2] + reasons = [text, *(report.get("reason", "") for report in reports.values() + if report.get("status") != "resolved")] + allowed = RECOVERABLE_REASONS - {"image_reference_current_image_moved"} + return all(value.split(":", 1)[0] in allowed for value in reasons) + + +@dataclass(frozen=True) +class DeferralDecision: + task_name: str + cycle: int + attempt: int + state: TaskObservationState + affected_tasks: tuple[str, ...] + reason: str + moved_units: int + policy: str = POLICY + + def as_record(self, *, stamp_ns, corner_evidence_sha256=""): + dependency_state = (TaskObservationState.DEPENDENCY_PENDING.value + if self.state == TaskObservationState.PENDING + else TaskObservationState.UNOBSERVABLE.value) + return { + "kind": "task_observation_state", + "schema_version": 1, + "policy": self.policy, + "task_name": self.task_name, + "cycle": self.cycle, + "attempt": self.attempt, + "state": self.state.value, + "affected_tasks": list(self.affected_tasks), + "dependency_states": ({task: dependency_state + for task in self.affected_tasks if task != self.task_name} + if self.state != TaskObservationState.PASSED else {}), + "reason": self.reason, + "moved_units": self.moved_units, + "corner_evidence_sha256": corner_evidence_sha256, + "stamp_ns": int(stamp_ns), + } + + +class TaskDeferralQueue: + """Own the finite retry state independently of motion execution.""" + + def __init__(self, profile, *, revisit_limit=1): + if revisit_limit != 1: + raise ValueError("task_deferral_revisit_limit_must_be_one") + self.profile = profile + self.revisit_limit = revisit_limit + self.attempts = {} + self.unobservable = {} + self.resolved = set() + self.inferred_resolutions = set() + + def decide(self, task_name, cycle, reason, moved_units): + key = (str(task_name), int(cycle)) + if key in self.resolved and not taskwise_deferral(self.profile): + raise ValueError("task_deferral_already_resolved") + attempt = self.attempts.get(key, 0) + 1 + if attempt > self.revisit_limit + 1: + raise ValueError("task_deferral_budget_exhausted") + self.resolved.discard(key) + self.attempts[key] = attempt + affected = tuple(task.key for task in self.profile.motion.tasks + if task.key in dependency_closure(self.profile, task_name)) + state = (TaskObservationState.PENDING if attempt <= self.revisit_limit + else TaskObservationState.UNOBSERVABLE) + if state == TaskObservationState.UNOBSERVABLE: + self.unobservable[key] = str(reason) + return DeferralDecision(str(task_name), int(cycle), attempt, state, + affected, str(reason), int(moved_units), deferral_policy(self.profile)) + + def resolve(self, task_name, cycle): + key = (str(task_name), int(cycle)) + attempt = self.attempts.get(key) + if attempt is None or key in self.resolved: + return None + self.resolved.add(key) + self.unobservable.pop(key, None) + affected = tuple(task.key for task in self.profile.motion.tasks + if task.key in dependency_closure(self.profile, task_name)) + return DeferralDecision(key[0], key[1], attempt, TaskObservationState.PASSED, + affected, "trajectory_observation_resolved", 0, deferral_policy(self.profile)) + + def restore(self, records): + records = tuple(records) + state_positions = {} + for position, row in enumerate(records): + if row.get("kind") != "task_observation_state": + continue + if row.get("policy") != deferral_policy(self.profile) or row.get("state") not in { + state.value for state in TaskObservationState}: + raise ValueError("task_deferral_checkpoint_policy_changed") + key = (str(row["task_name"]), int(row["cycle"])) + if key[0] not in {task.key for task in self.profile.motion.tasks} or ( + taskwise_deferral(self.profile) and key[1] != 0): + raise ValueError("task_deferral_checkpoint_visit_changed") + state_positions[key] = position + attempt = int(row["attempt"]) + expected_affected = tuple(task.key for task in self.profile.motion.tasks + if task.key in dependency_closure(self.profile, key[0])) + # Historical v1 resolution records named only the resolved task. + historical_resolution = (row.get("policy") == POLICY + and row["state"] == TaskObservationState.PASSED.value + and tuple(row.get("affected_tasks", ())) == (key[0],)) + if tuple(row.get("affected_tasks", ())) != expected_affected and not historical_resolution: + raise ValueError("task_deferral_checkpoint_dependencies_changed") + if row["state"] == TaskObservationState.PASSED.value: + if self.attempts.get(key) != attempt or key in self.resolved: + raise ValueError("task_deferral_checkpoint_resolution_changed") + self.resolved.add(key) + self.unobservable.pop(key, None) + continue + if attempt != self.attempts.get(key, 0)+1 or attempt not in (1, 2): + raise ValueError("task_deferral_checkpoint_budget_changed") + expected_state = (TaskObservationState.PENDING if attempt == 1 + else TaskObservationState.UNOBSERVABLE) + if row["state"] != expected_state.value: + raise ValueError("task_deferral_checkpoint_state_changed") + self.resolved.discard(key) + self.attempts[key] = attempt + if row["state"] == TaskObservationState.UNOBSERVABLE.value: + self.unobservable[key] = str(row.get("reason", "")) + # If a crash happened after the final scan-unit commit but before the + # adjacent PASSED state record, the complete visit itself closes the + # pending state. A partial direction can never do so. + from .engine import CalibrationEngine + from ..core.domain.motion_path import record_scan_identity + completion_positions = {} + for position, row in enumerate(records): + if row.get("kind") == "scan_unit_complete" and row.get("passed") is True: + completion_positions[record_scan_identity(row)] = position + units = CalibrationEngine(self.profile).scan_units() + for key in set(self.attempts) - self.resolved - set(self.unobservable): + required = {unit.identity for unit in units + if (unit.task_key, unit.cycle) == key} + boundary = state_positions[key] + if required and all(completion_positions.get(identity, -1) > boundary + for identity in required): + self.resolved.add(key) + self.inferred_resolutions.add(key) + + +def deferred_visit_keys(profile, records): + """Return incomplete visits that may be followed by durable later visits. + + A non-contiguous resume prefix is legal only when a versioned deferral + record explains the gap. Replaying the queue also validates retry order, + dependency closure and terminal state before the gap is trusted. + """ + rows = [row for row in records if row.get("kind") == "task_observation_state"] + if not rows: + return frozenset() + queue = TaskDeferralQueue(profile) + queue.restore(records) + latest = {} + for row in rows: + latest[(str(row["task_name"]), int(row["cycle"]))] = row + blocked = set() + for key, row in latest.items(): + if row["state"] == TaskObservationState.PASSED.value or key in queue.resolved: + continue + blocked.update((task, key[1]) for task in row["affected_tasks"]) + return frozenset(blocked) + + +def unresolved_observation_records(profile, records): + """Return latest states that are not closed by a full durable visit.""" + rows = [row for row in records if row.get("kind") == "task_observation_state"] + if not rows: + return () + queue = TaskDeferralQueue(profile) + queue.restore(records) + latest = {} + for row in rows: + latest[(str(row["task_name"]), int(row["cycle"]))] = row + return tuple(row for key, row in latest.items() if key not in queue.resolved) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/task_quality.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/task_quality.py new file mode 100644 index 0000000..b69dd71 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/task_quality.py @@ -0,0 +1,57 @@ +"""Reject unsupported independent inputs after their capture phase completes. + +The protected release policy selects steady command support or native feedback +support. This never extends a curve domain or changes a recorded endpoint. +Final numerical and artifact validation still run. +""" + +import math + +from ..core.domain.motion_path import record_scan_identity +from ..core.domain.profile import observation_streams +from ..core.domain.capture_plan import CapturePlan +from ..core.fitting.rotation_curve import common_directional_input_support +from .engine import SweepQuality + + +def evaluate_task_input_support(profile, task, records): + rows = (records.task_records(task.key) if hasattr(records, "task_records") else + [row for row in records if row.get("task_name") == task.key]) + latest = {} + for row in rows: + if all(key in row for key in ("cycle", "direction")): + key = record_scan_identity(row) + latest[key] = max(latest.get(key, 0), int(row.get("attempt", 1))) + phase = "steady" if profile.command_based_release else "sweep" + partition = CapturePlan.from_profile(profile).task(task.key) + training_cycles = partition.command_training if phase == "steady" else partition.training + holdout_cycle = partition.command_holdout if phase == "steady" else partition.holdout + selected = [row for row in rows if row.get("sample_phase", "sweep") == phase + and row.get("cycle") in (*training_cycles, holdout_cycle) + and row.get("direction") in {"increasing", "decreasing"} + and int(row.get("attempt", 1)) == latest.get(record_scan_identity(row))] + field = f"command_{profile.command.unit}" if profile.command_based_release else profile.curve_input_domain + failures, metrics = [], {} + for kind, joint, spec in observation_streams(profile, task): + stream = [row for row in selected if row.get(kind) == joint and row.get("view") == spec.view] + identity = f"{kind}:{joint}:{spec.view}" + training = [row for row in stream if row["cycle"] in training_cycles] + holdout = [row for row in stream if row["cycle"] == holdout_cycle] + if (not training or not holdout or any(row.get(field) is None + or not math.isfinite(float(row[field])) for row in stream)): + failures.append(f"{identity}:missing_native_input_evidence") + continue + try: + lower, upper = common_directional_input_support( + [row[field] for row in training], [row["direction"] for row in training]) + except ValueError as error: + failures.append(f"{identity}:{error}") + continue + outside = [row for row in holdout if not lower <= float(row[field]) <= upper] + metrics[identity] = {"input_domain": field, "training_support": [lower, upper], + "holdout_span": [min(float(row[field]) for row in holdout), max(float(row[field]) for row in holdout)], + "holdout_samples": len(holdout), "outside_training_support": len(outside), + "outside_image_ids": [f"{row['view']}:{row['image_stamp_ns']}" for row in outside]} + if outside: + failures.append(f"{identity}:holdout_outside_training_support") + return SweepQuality(not failures, tuple(failures), (), metrics) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/timing_diagnostics.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/timing_diagnostics.py new file mode 100644 index 0000000..dd32be0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/timing_diagnostics.py @@ -0,0 +1,102 @@ +"""Observe control-loop and garbage-collector pauses without changing guards.""" +from collections import deque +import gc +from pathlib import Path +import time + +from ..core.artifacts.storage import append_jsonl_many + + +class StageTiming: + """Exclusive wall-time buckets; repeated polls do not write to disk.""" + + def __init__(self, now): + self.started = self.previous = float(now) + self.stage = "startup" + self.seconds = {} + self.transitions = {} + self.capture_started = self.terminal_started = None + + def mark_start(self, now): + self.capture_started = float(now) + self.terminal_started = None + + def enter(self, stage, now): + now = float(now) + self.seconds[self.stage] = self.seconds.get(self.stage, 0.) + max(0., now - self.previous) + self.previous = now + if stage != self.stage: + self.transitions[stage] = self.transitions.get(stage, 0) + 1 + self.stage = stage + if stage == 'terminal' and self.terminal_started is None: + self.terminal_started = now + + def as_dict(self, now): + self.enter(self.stage, now) + return {"schema_version": 1, "elapsed_seconds": max(0., float(now) - self.started), + "start_to_terminal_seconds": (None if self.capture_started is None or self.terminal_started is None + else max(0., self.terminal_started-self.capture_started)), + "checkpoint_preload_seconds": self.seconds.get('resume_loading', 0.), + "stage_seconds": dict(self.seconds), "stage_entries": dict(self.transitions), + "clock": "monotonic", "resolution": "control_tick_boundaries"} + + +def acquisition_stage(host): + if host.state in {"PASSED", "FAILED", "ABORTED", "PAUSED", "DIAGNOSTIC_COMPLETE"}: + return "terminal" + if host.finalization.started: + return ("final_acceptance" if host.execution.session.phase.value in { + "HOLDOUT_VALIDATE", "BUILD_ARTIFACTS", "VALIDATE_URDF", "PUBLISH"} else "finalization_fit") + if host._training_request is not None: + return "training_assessment" + if host.branch_initialization.pending(): + return "geometry_solving" + if host._resume_import is not None or host._passed_reference_import is not None or host._reference_import is not None: + return "resume_import" + if host.execution.action.retry: + return "recovery" + motion = host._motion + if motion is None: + return "initialization" if not host.started else "coordination" + if motion.phase == "sweep": + return "scan_motion" + if motion.phase in {"steady", "joint_zero"}: + now = host.ports.monotonic() + if host.segment is not None and host.segment.steady_ready(now): + return "zero_sampling" if motion.phase == "joint_zero" else "steady_sampling" + return "stable_wait" + return "preparation_motion" + + +class RuntimeTimingDiagnostics: + def __init__(self, path, threshold_seconds=.05): + self.path = Path(path) + self.threshold_seconds = threshold_seconds + self.pending = deque(maxlen=256) + self._gc_started = None + gc.callbacks.append(self._gc_event) + + def record(self, operation, started, **details): + elapsed = time.perf_counter()-started + if elapsed >= self.threshold_seconds: + self.pending.append(dict(kind='runtime_processing_delay', operation=operation, + elapsed_seconds=elapsed, stamp_ns=time.time_ns(), **details)) + + def _gc_event(self, phase, info): + if phase == 'start': + self._gc_started = time.perf_counter() + elif self._gc_started is not None: + self.record('garbage_collection', self._gc_started, generation=info['generation'], + collected=info.get('collected',0)) + self._gc_started = None + + def flush(self): + rows = [] + while self.pending: + rows.append(self.pending.popleft()) + if rows: + append_jsonl_many(self.path, rows, durable=False) + + def close(self): + gc.callbacks.remove(self._gc_event) + self.flush() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/training.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/training.py new file mode 100644 index 0000000..3021518 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/training.py @@ -0,0 +1,186 @@ +"""Causal training-plan replay and isolated live assessment.""" + +from concurrent.futures import Future, ThreadPoolExecutor +import multiprocessing +import threading +import time +import traceback + +from ..core.domain.capture_plan import (ADAPTIVE, STAGED, TASKWISE_STAGED, TASKWISE_TWO_ROUND, RAW_JOINT, + CapturePlan, LEGACY_HOLDOUT, configure_training, evidence_digest, select_task_training) +from ..core.domain.reference import JointZeroReference +from ..core.fitting.training_quality import (TRAINING_DECISION_VERSION, assess_training, + training_snapshot) + + +def resolve_capture_plan(profile, records, *, source_urdf=None, verify_decisions=False, require_complete=False): + """Replay decisions in journal order, never from future or held-out rows.""" + if profile.quality.training_policy == STAGED: + from .staged_training import resolve_staged_plan + return resolve_staged_plan(profile, records, source_urdf=source_urdf, + verify_decisions=verify_decisions, require_complete=require_complete) + base = configure_training(profile, profile.quality.training_policy) + headers = [row for row in records if row.get("kind") == "session_start"] + plan = CapturePlan.from_profile(base) + if base.quality.training_policy not in {ADAPTIVE, TASKWISE_STAGED}: + if any(row.get("kind") in {"training_decision", "staged_training_decision"} for row in records): + raise ValueError("adaptive_decisions_in_fixed_capture") + if headers and "capture_plan" in headers[0] and headers[0]["capture_plan"] != plan.as_dict(): + raise ValueError("capture_plan_header_changed") + if base.quality.training_policy in {TASKWISE_TWO_ROUND, RAW_JOINT} and any( + row.get("kind") in {"joint_sample", "secondary_joint_sample", "scan_unit_complete", "raw_observation_frame"} + and row.get("cycle") not in (0, 1, LEGACY_HOLDOUT) + for row in records): + raise ValueError("taskwise_two_round_unexpected_cycle") + return base + if len(headers) != 1 or headers[0].get("capture_plan") != plan.as_dict(): + raise ValueError("adaptive_capture_requires_matching_plan_header") + current, previous, frozen, prefix, references = base, {}, set(), [], {} + for row in records: + kind = row.get("kind") + if kind == "joint_zero_reference": + reference = JointZeroReference.from_record(row) + references[reference.joint] = reference + if kind == "training_decision": + key = row.get("task_name") + cycles = tuple(row.get("assessed_cycles", ())) + decision = row.get("decision") + expected_cycles = (0, 1, 2) if previous.get(key) == "add_training" else (0, 1) + if (key not in {task.key for task in profile.motion.tasks} or key in frozen + or previous.get(key) == "fail" + or cycles != expected_cycles or row.get("version") != TRAINING_DECISION_VERSION + or decision not in {"add_training", "freeze", "fail"} + or (decision == "add_training" and len(cycles) != 2) + or row.get("input_plan_sha256") != CapturePlan.from_profile(current).sha256 + or row.get("decision_sha256") != evidence_digest({k: v for k, v in row.items() + if k != "decision_sha256"})): + raise ValueError(f"training_decision_invalid:{key}") + if verify_decisions: + expected = assess_training(current, key, cycles, + training_snapshot(current, prefix, key, cycles), references, source_urdf) + if row != expected: + raise ValueError(f"training_decision_evidence_changed:{key}") + previous[key] = decision + if decision == "freeze": + current = select_task_training(current, key, cycles) + frozen.add(key) + elif decision == "fail" and require_complete: + raise ValueError(f"training_failed:{key}") + elif kind in {"joint_sample", "secondary_joint_sample"}: + key = row.get("task_name") + if row.get("cycle") == 2 and previous.get(key) != "add_training": + raise ValueError(f"third_training_without_decision:{key}") + if row.get("cycle") == profile.quality.holdout_cycle and key not in frozen: + raise ValueError(f"holdout_before_training_freeze:{key}") + if key in frozen and row.get("cycle") in profile.quality.training_cycles: + raise ValueError(f"training_observation_after_freeze:{key}") + prefix.append(row) + if require_complete and frozen != {task.key for task in profile.motion.tasks}: + raise ValueError("training_plan_incomplete") + return current + + +def _assess_child(connection): + cache = {} + try: + while True: + kwargs = connection.recv() + if kwargs is None: + return + try: + if kwargs["profile"].quality.training_policy == STAGED: + from .staged_training import assess_staged_training + result = assess_staged_training(**kwargs, cache=cache) + else: + result = assess_training(**kwargs) + connection.send((result, None)) + except Exception: + connection.send((None, traceback.format_exc())) + except (EOFError, BrokenPipeError): + return + finally: + connection.close() + + +class TrainingWorker: + """One reusable isolated worker; serialization and fitting stay off the loop.""" + + def __init__(self, timeout_seconds=120.): + self.timeout_seconds = timeout_seconds + self._closed = threading.Event() + self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="training-check") + self._future = None + self._process = self._connection = None + + def _stop(self): + process, connection = self._process, self._connection + self._process = self._connection = None + if connection is not None: + connection.close() + if process is not None and process.pid is not None: + if process.is_alive(): + process.terminate() + process.join(timeout=1.) + if process.is_alive(): + process.kill() + process.join(timeout=1.) + process.close() + + def _run(self, kwargs): + started = time.monotonic() + try: + if self._process is None: + context = multiprocessing.get_context("spawn") + self._connection, child = context.Pipe(duplex=True) + self._process = context.Process(target=_assess_child, args=(child,), daemon=True) + try: + self._process.start() + finally: + child.close() + # A large serialization/write or reply must also obey cancellation + # and the deadline. Killing the child closes the peer and releases IO. + reply = Future() + connection = self._connection + def exchange(): + try: + connection.send(kwargs) + reply.set_result(connection.recv()) + except BaseException as error: + reply.set_exception(error) + threading.Thread(target=exchange, name="training-transport", daemon=True).start() + while not self._closed.is_set(): + remaining = self.timeout_seconds - (time.monotonic()-started) + if remaining <= 0: + raise TimeoutError("training_assessment_timeout") + if reply.done(): + result, error = reply.result() + if error is not None: + raise RuntimeError(error) + return result + if not self._process.is_alive(): + raise RuntimeError(f"training_assessment_process_exited:{self._process.exitcode}") + self._closed.wait(min(.05, remaining)) + raise RuntimeError("training_assessment_cancelled") + except BaseException: + self._stop() + raise + finally: + if self._closed.is_set(): + self._stop() + + def poll(self, **kwargs): + if self._closed.is_set(): + raise RuntimeError("training_assessment_cancelled") + if self._future is None: + self._future = self._executor.submit(self._run, kwargs) + if not self._future.done(): + return None + future, self._future = self._future, None + return future.result() + + def close(self): + if self._closed.is_set(): + return + self._closed.set() + self._executor.submit(self._stop) + self._executor.shutdown(wait=False) diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/training_replay.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/training_replay.py new file mode 100644 index 0000000..c8a96ec --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/training_replay.py @@ -0,0 +1,120 @@ +"""Read-only two/three-cycle comparison against the unchanged holdout. + +This diagnostic uses the live compact index. It does not publish, change the +recorded policy, or replace motion/image provenance and final-file acceptance. +""" + +import argparse +import hashlib +import json +from pathlib import Path +import time + +from ..core.domain.capture_plan import ADAPTIVE, configure_training, select_task_training +from ..core.domain.reference import read_joint_zero_references +from ..core.domain.motion_path import record_scan_identity +from ..core.fitting.command_motion import fit_command_motion +from ..core.fitting.training_quality import assess_training, training_snapshot +from ..core.geometry.frozen_evidence import EvidenceDecoder +from ..core.urdf.kinematics import UrdfKinematicModel +from ..profiles import load_bundled_hand_profile +from .acquisition import accepted_joint_records +from .capture_index import CaptureRecordIndex +from .engine import CalibrationEngine + + +def load_training_index(path): + started, digest = time.perf_counter(), hashlib.sha256() + index = CaptureRecordIndex(retain_complete=False, retain_training_geometry=True) + # Final release replays and verifies full evidence. This comparison never + # claims a provenance pass and only needs the recorded poses/scalars. + decoder = EvidenceDecoder(verify_hashes=False) + with Path(path).open("rb") as stream: + for line in stream: + digest.update(line) + if line.strip(): + index.append(decoder.loads(line)) + return index, {"load_seconds": time.perf_counter()-started, + "raw_bytes": Path(path).stat().st_size, "raw_sha256": digest.hexdigest(), "indexed_records": len(index)} + + +def compare_training(profile, source, records, *, task_keys=()): + selected = set(task_keys) or {t.key for t in profile.motion.tasks} + if not selected <= {t.key for t in profile.motion.tasks}: + raise ValueError("unknown comparison task") + adaptive = configure_training(profile, ADAPTIVE) + model = UrdfKinematicModel(source) + references = read_joint_zero_references(profile, records) + sweep = accepted_joint_records(profile, records) + steady = accepted_joint_records(profile, records, sample_phase="steady") + completions, attempts = {}, {} + for row in records: + if all(key in row for key in ("task_name", "cycle", "direction")): + key = record_scan_identity(row) + attempts[key] = max(attempts.get(key, 0), int(row.get("attempt", 1))) + if row.get("kind") == "scan_unit_complete": + completions[(key, int(row.get("attempt", 1)))] = row.get("passed") is True + units = CalibrationEngine(profile).scan_units() + tasks = {} + for task in profile.motion.tasks: + if task.key not in selected: + continue + variants = {} + if any(completions.get((u.identity, attempts.get(u.identity))) is not True + for u in units if u.task_key == task.key): + tasks[task.key] = {"status": "task_capture_incomplete"} + continue + holdout_rows = [r for name in task.joints for r in steady[name] if r["cycle"] == profile.quality.holdout_cycle] + if not holdout_rows: + tasks[task.key] = {"status": "no_independent_holdout"} + continue + cutoff = next(i for i, r in enumerate(records) if r.get("task_name") == task.key + and r.get("cycle") == profile.quality.holdout_cycle and r.get("kind") == "joint_sample") + prefix = records[:cutoff] + for cycles in ((0, 1), (0, 1, 2)): + began = time.perf_counter() + current = select_task_training(adaptive, task.key, cycles) + decision = assess_training(adaptive, task.key, cycles, + training_snapshot(adaptive, prefix, task.key, cycles), references, source) + result = {"training_decision": decision, "holdout_cycle": profile.quality.holdout_cycle} + try: + part = {name: [r for r in sweep[name] if r["cycle"] in (*cycles, profile.quality.holdout_cycle)] + for name in task.joints} + fixed = {name: [r for r in steady[name] if r["cycle"] in (*cycles, profile.quality.holdout_cycle)] + for name in task.joints} + fit = fit_command_motion(current, model, part, fixed, {name: references[name] for name in task.joints}) + result.update(holdout_passed=True, holdout_metrics={name: {key: metric[key] + for key in ("count", "mae_deg", "p95_deg", "maximum_deg", "by_direction")} + for name, metric in fit.command_metrics.items()}) + except (ValueError, KeyError) as error: + result.update(holdout_passed=False, reason=str(error)) + result["assessment_seconds"] = time.perf_counter()-began + variants[str(len(cycles))] = result + tasks[task.key] = {"status": "compared", "holdout_image_ids": sorted({r["sample_id"] for r in holdout_rows}), + "variants": variants} + return {"schema_version": 1, "publication_allowed": False, + "scope": "software_training_comparison_only; motion/image provenance and full-hand release not certified", + "profile_id": profile.key.profile_id, "tasks": tasks} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--profile", default="o30_right_18") + parser.add_argument("--source-urdf", required=True, type=Path) + parser.add_argument("--raw-samples", required=True, type=Path) + parser.add_argument("--task", action="append", default=[]) + parser.add_argument("--output", required=True, type=Path) + args = parser.parse_args() + if args.output.resolve() == args.raw_samples.resolve(): + parser.error("comparison output must not replace the source journal") + records, timing = load_training_index(args.raw_samples) + report = compare_training(load_bundled_hand_profile(args.profile), args.source_urdf, records, task_keys=args.task) + report["input"] = {"raw_samples": str(args.raw_samples.resolve()), **timing} + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(json.dumps(report, ensure_ascii=False, indent=2, allow_nan=False)+"\n") + print(json.dumps({"output": str(args.output), **timing, + "compared_tasks": sum(t["status"] == "compared" for t in report["tasks"].values())}, ensure_ascii=False)) + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/trajectory.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/trajectory.py new file mode 100644 index 0000000..3c34898 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/trajectory.py @@ -0,0 +1,292 @@ +"""Profile-driven trajectory and avoidance completion rules.""" + +from __future__ import annotations + +from dataclasses import dataclass +import math +from typing import Sequence + +import numpy as np + +from ..core import CalibrationProfile, TaskSpec +from ..core.domain.motion_path import task_segment, task_channels + + +@dataclass(frozen=True) +class AvoidanceArrival: + arrived: bool + progress_01: float + direction_correct: bool + stable: bool + + +def smoothstep_position(start: float, end: float, progress_01: float) -> float: + """Endpoint-zero-velocity cosine interpolation.""" + if not all(math.isfinite(float(value)) for value in (start, end, progress_01)): + raise ValueError("trajectory inputs must be finite") + phase = min(1.0, max(0.0, float(progress_01))) + blend = 0.5 - 0.5 * math.cos(math.pi * phase) + return float(start) + blend * (float(end) - float(start)) + + +def cosine_position_trajectory_u8( + start_u8: float, + target_u8: float, + elapsed_seconds: float, + full_range_duration_seconds: float, +) -> tuple[float, float, float]: + """Return a bounded byte-command trajectory with zero endpoint speed.""" + if full_range_duration_seconds <= 0.0: + raise ValueError("full_range_duration_seconds must be positive") + duration = ( + float(full_range_duration_seconds) + * abs(float(target_u8) - float(start_u8)) + / 255.0 + ) + if duration <= 0.0: + return float(target_u8), 1.0, 0.0 + phase = min(1.0, max(0.0, float(elapsed_seconds) / duration)) + return smoothstep_position(start_u8, target_u8, phase), phase, duration + + +def cosine_position_trajectory( + start_value: float, + target_value: float, + elapsed_seconds: float, + maximum_speed: float, +) -> tuple[float, float, float]: + """Cosine trajectory whose peak velocity does not exceed the limit.""" + if not all(math.isfinite(float(value)) for value in (start_value, target_value, elapsed_seconds)): + raise ValueError("trajectory values and clock must be finite") + speed = float(maximum_speed) + if not math.isfinite(speed) or speed <= 0.0: + raise ValueError("maximum_speed must be positive") + distance = abs(float(target_value) - float(start_value)) + if distance <= 0.0: + return float(target_value), 1.0, 0.0 + duration = math.pi * distance / (2.0 * speed) + phase = min(1.0, max(0.0, float(elapsed_seconds) / duration)) + blend = 0.5 - 0.5 * math.cos(math.pi * phase) + return ( + float(start_value) + (float(target_value) - float(start_value)) * blend, + phase, + duration, + ) + + +def cosine_ramp_velocity_trajectory( + start_value: float, + target_value: float, + elapsed_seconds: float, + maximum_speed: float, + ramp_seconds: float, +) -> tuple[float, float, float]: + """Velocity-limited trajectory with cosine ramps and a constant-speed core.""" + if not all(math.isfinite(float(value)) for value in (start_value, target_value, elapsed_seconds)): + raise ValueError("trajectory values and clock must be finite") + speed = float(maximum_speed) + ramp = float(ramp_seconds) + if not math.isfinite(speed) or speed <= 0.0: + raise ValueError("maximum_speed must be positive") + if not math.isfinite(ramp) or ramp <= 0.0: + raise ValueError("ramp_seconds must be positive") + start = float(start_value) + target = float(target_value) + distance = abs(target - start) + if distance <= 0.0: + return target, 1.0, 0.0 + + # For very short moves there is no room for a constant-speed section; + # retain the bounded position-cosine trajectory. + if distance <= speed * ramp: + return cosine_position_trajectory( + start, target, elapsed_seconds, speed + ) + + cruise_seconds = distance / speed - ramp + duration = 2.0 * ramp + cruise_seconds + elapsed = min(duration, max(0.0, float(elapsed_seconds))) + ramp_distance = 0.5 * speed * ramp + if elapsed < ramp: + travelled = speed * ( + 0.5 * elapsed + - ramp * math.sin(math.pi * elapsed / ramp) / (2.0 * math.pi) + ) + elif elapsed < ramp + cruise_seconds: + travelled = ramp_distance + speed * (elapsed - ramp) + else: + down = elapsed - ramp - cruise_seconds + travelled = ( + ramp_distance + + speed * cruise_seconds + + speed * ( + 0.5 * down + + ramp * math.sin(math.pi * down / ramp) / (2.0 * math.pi) + ) + ) + fraction = min(1.0, max(0.0, travelled / distance)) + return ( + start + (target - start) * fraction, + min(1.0, max(0.0, elapsed / duration)), + duration, + ) + + +def build_calibration_motion_command( + task: TaskSpec, + command_value: float, + *, + profile: CalibrationProfile, + segment_key: str = "", +) -> list[float]: + """Build one task command from the profile baseline and avoidance values.""" + values = list(profile.command.baseline_values) + for index, value in task.auxiliary_commands: + values[int(index)] = float(value) + if segment_key: + for index, value in task_segment(task, segment_key).commands_at(command_value, + quantize=profile.command.unit == "u8").items(): + values[index] = value + else: + values[int(task.command_index)] = float(command_value) + if profile.command.unit == "u8": + return [int(value) for value in values] + return values + + +def build_calibration_preparation_waypoints( + task: TaskSpec, + *, + profile: CalibrationProfile, + current_command: Sequence[float] | None = None, + start_value: float | None = None, + segment_key: str = "", +) -> tuple[tuple[float, ...], ...]: + """Execute declarative avoidance groups, then the measured channel.""" + # A return sweep or its retry starts at the opposite endpoint. Never + # silently substitute the task's first endpoint and reverse/jump the hand. + start = task.start_value if start_value is None else float(start_value) + segment = task_segment(task, segment_key) if segment_key else None + if start not in ((segment.start, segment.end) if segment else (task.start_value, task.end_value)): + raise ValueError("scan preparation must target a declared sweep endpoint") + final = tuple(build_calibration_motion_command(task, start, profile=profile, segment_key=segment_key)) + return _grouped_waypoints(current_command, final, task.preparation_groups, + profile=profile, measured_channel=task.command_index) + + +def build_calibration_return_waypoints( + target_command: Sequence[float] | None = None, + *, + profile: CalibrationProfile, + current_command: Sequence[float] | None = None, + **_: object, +) -> tuple[tuple[float, ...], ...]: + """Return in the profile's reviewed channel-group order.""" + target = ( + tuple(float(value) for value in target_command) + if target_command is not None + else tuple(profile.command.baseline_values) + ) + if len(target) != profile.command.command_count: + raise ValueError("return command has the wrong channel count") + return _grouped_waypoints(current_command, target, profile.motion.return_groups, profile=profile) + + +def build_joint_reference_waypoints(task, target, *, profile, current_command): + """Visit an explicitly declared reference pose, which may be inside a scan.""" + declared = {pose for spec in profile.motion.joint_zero_references.values() if spec.task_key == task.key + for pose in (spec.command, *spec.approach_commands)} + declared.update(pose for preparation in task.model_preparations + for pose in (preparation.command, *preparation.approach_commands)) + if tuple(target) not in declared: + raise ValueError("undeclared joint zero reference pose") + return _grouped_waypoints(current_command, target, task.preparation_groups, + profile=profile, measured_channel=task.command_index) + + +def _grouped_waypoints(current_command, target, groups, *, profile, measured_channel=None): + current = list(profile.command.baseline_values if current_command is None else current_command) + final = list(target) + count = profile.command.command_count + if len(current) != count or len(final) != count: + raise ValueError("waypoint command count differs from profile") + for vector in (current, final): + if any(not math.isfinite(float(v)) or not lo <= v <= hi for v, lo, hi in zip(vector, profile.command.minimum_values, profile.command.maximum_values)): + raise ValueError("waypoint is outside command coordinates") + for index in profile.command.disabled_indices: + final[index] = current[index] + declared = [tuple(group) for group in groups] + if not declared: + return (tuple(final),) + handled = {index for group in declared for index in group} + remaining = tuple(index for index in range(count) if index not in handled and index != measured_channel and index not in profile.command.disabled_indices) + if remaining: + # Undeclared auxiliaries precede the target, never follow it. + if declared and measured_channel in declared[-1]: + declared.insert(len(declared)-1, remaining) + else: + declared.append(remaining) + if measured_channel is not None and measured_channel not in handled: + declared.append((measured_channel,)) + output = [] + for group in declared: + changed = False + for index in group: + if current[index] != final[index]: + current[index] = final[index] + changed = True + if changed: + output.append(tuple(current)) + return tuple(output or [tuple(final)]) + + +def avoidance_arrival( + *, + start_feedback: float, + requested_target: float, + feedback_history: Sequence[float], + trajectory_complete: bool, + minimum_requested_fraction: float = 0.80, + stability_tolerance: float = 0.02, +) -> AvoidanceArrival: + """Accept a safely reached waypoint without exact servo equality.""" + values = np.asarray(tuple(feedback_history), dtype=float) + requested = float(requested_target) - float(start_feedback) + if values.ndim != 1 or values.size == 0 or not np.all(np.isfinite(values)) or not math.isfinite(requested): + return AvoidanceArrival(False, 0.0, False, False) + if not 0 < minimum_requested_fraction <= 1 or not math.isfinite(stability_tolerance) or stability_tolerance <= 0: + raise ValueError("invalid avoidance completion policy") + stable = bool(values.size >= 3 and float(np.ptp(values[-min(10, values.size):])) <= float(stability_tolerance)) + if abs(requested) < 1e-9: + close = abs(float(values[-1]) - float(requested_target)) <= stability_tolerance + return AvoidanceArrival(bool(trajectory_complete and stable and close), 1.0 if close else 0.0, close, stable) + measured = float(values[-1]) - float(start_feedback) + progress = measured / requested + direction_correct = progress >= 0.0 + stable = bool( + values.size >= 3 + and float(np.ptp(values[-min(10, values.size):])) + <= float(stability_tolerance) + ) + return AvoidanceArrival( + bool( + trajectory_complete + and direction_correct + and progress >= float(minimum_requested_fraction) + and stable + ), + float(progress), + direction_correct, + stable, + ) + + +__all__ = [ + "AvoidanceArrival", + "avoidance_arrival", + "build_calibration_motion_command", + "build_calibration_preparation_waypoints", + "build_calibration_return_waypoints", + "cosine_position_trajectory_u8", + "smoothstep_position", +] diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/visual_motion.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/visual_motion.py new file mode 100644 index 0000000..ccac374 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/visual_motion.py @@ -0,0 +1,307 @@ +"""Physical motion witnesses from current Tag corners, independent of encoders. + +The feature is the child's four corners in its parent's projective frame. It +does not choose a planar-PnP branch, infer a motor angle, or feed fitted values +back into capture. Angular accuracy still belongs to the independent image +and URDF validation. Every moved channel needs its own visible Tag pair. +""" + +from collections import deque +from dataclasses import dataclass +import hashlib +import json + +import cv2 +import numpy as np + +from ..core.fitting.motion_fit import channel_for_joint + + +VISUAL_MOTION_POLICY = "relative_tag_corners_v1" + + +def relative_corners(parent, child): + parent, child = np.asarray(parent, dtype=float), np.asarray(child, dtype=float) + if (parent.shape != (4, 2) or child.shape != (4, 2) + or not np.all(np.isfinite(parent)) or not np.all(np.isfinite(child))): + raise ValueError("visual_motion_invalid_corners") + canonical = np.array([[0, 0], [1, 0], [1, 1], [0, 1]], dtype=np.float32) + if abs(cv2.contourArea(parent.astype(np.float32))) < 1: + raise ValueError("visual_motion_degenerate_projection") + matrix = cv2.getPerspectiveTransform(parent.astype(np.float32), canonical) + points = np.column_stack((child, np.ones(4))) @ matrix.T + if np.min(np.abs(points[:, 2])) < 1e-8: + raise ValueError("visual_motion_degenerate_projection") + return points[:, :2]/points[:, 2, None] + + +def corner_distance(a, b, scale): + return float(np.sqrt(np.mean(np.sum((np.asarray(a)-np.asarray(b))**2, axis=1)))*scale) + + +def witness_hash(record): + return hashlib.sha256(json.dumps(record, sort_keys=True, + separators=(",", ":"), allow_nan=False).encode()).hexdigest() + + +@dataclass(frozen=True) +class VisualSample: + stamp_ns: int + received_at: float + points: tuple + scale_px: float + record: dict + + +class VisualMotionObserver: + def __init__(self, profile): + self.profile = profile + self.specs = {name: spec for name, spec in profile.measurement.measurements.items() + if name in profile.command.command_index_by_joint and spec.view is not None} + self.channels = {name: channel_for_joint(profile, name) for name in self.specs} + self.latest = {} + self.zeros = {} + self.pending_records = [] + self.motion = None + self.required = () + self.initial = {} + self.history = {} + self.requested_at = {} + self.window_id = "" + + def observe(self, view, stamp_ns, corners, *, now, epoch, version, command=None): + for name, spec in self.specs.items(): + if spec.view != view or spec.parent_role not in corners or spec.child_role not in corners: + continue + previous = self.latest.get(name) + if previous is not None and stamp_ns <= previous.stamp_ns: + continue + parent, child = corners[spec.parent_role], corners[spec.child_role] + try: + points = relative_corners(parent, child) + except (ValueError, cv2.error): + continue + scale = float(np.mean(np.linalg.norm(np.asarray(parent)-np.roll(parent, -1, axis=0), axis=1))) + record = dict(kind="visual_motion_observation", policy=VISUAL_MOTION_POLICY, + joint=name, view=view, image_stamp_ns=stamp_ns, + session_epoch=epoch, motion_version=version, + command_vector=None if command is None else list(command), + parent_role=spec.parent_role, child_role=spec.child_role, + parent_corners_xy=np.asarray(parent).tolist(), child_corners_xy=np.asarray(child).tolist()) + sample = VisualSample(stamp_ns, now, tuple(map(tuple, points)), scale, record) + self.latest[name] = sample + if name in self.history: + self.history[name].append(sample) + if self.motion is not None and name in self.required: + self.pending_records.append(record) + + def names_for(self, motion, initial): + moved = {i for i, (a, b) in enumerate(zip(initial, motion.target)) if abs(a-b) > 1e-9} + names = {name for name, channel in self.channels.items() if channel in moved} + names.update(motion.visual_return_joints) + names.update(motion.zero_joints or motion.reference_joints or motion.observed_joints) + if motion.recording and not names and motion.task_key: + task = next(task for task in self.profile.motion.tasks if task.key == motion.task_key) + names.update(task.joints) + if moved - {self.channels[name] for name in names}: + raise ValueError("visual_motion_channel_without_observer") + return tuple(sorted(names)) + + def available(self, names, now): + return all(name in self.latest and 0 <= now-self.latest[name].received_at <= + self.profile.acquisition.visual_stale_seconds for name in names) + + def begin(self, motion, initial, *, now, version): + names = self.names_for(motion, initial) + if not self.available(names, now): + return False + self.motion, self.required = motion, names + self.initial_command = tuple(initial) + self.version = version + self.initial = {name: self.latest[name] for name in names} + self.history = {name: deque((self.latest[name],), maxlen=120) for name in names} + self.deltas = {name: motion.target[self.channels[name]]-initial[self.channels[name]] for name in names} + self.requested_at = {} + self.maximum_travel = {name: 0.0 for name in names} + self.progress_sources = dict(self.initial) + self.window_id = "" + self.pending_records.extend(sample.record for sample in self.initial.values()) + return True + + def check(self, segment, now): + """Return a stop reason, while never deriving a goal from feedback.""" + policy = self.profile.acquisition + if not self.available(self.required, now): + missing = [name for name in self.required if not self.available((name,), now)] + return "visual_motion_unavailable:" + ",".join(missing) + for name in self.required: + start = self.initial[name] + distance = corner_distance(start.points, self.latest[name].points, start.scale_px) + if distance > self.maximum_travel[name]: + self.maximum_travel[name] = distance + self.progress_sources[name] = self.latest[name] + channel = self.channels[name] + span = self.profile.command.maximum_values[channel]-self.profile.command.minimum_values[channel] + if abs(self.deltas[name])*segment.fraction <= .05*span: + continue + self.requested_at.setdefault(name, now) + if (self.maximum_travel[name] < policy.visual_minimum_motion_px + and now-self.requested_at[name] >= policy.stall_timeout_seconds): + return f"visual_motion_not_observed:{name}" + if (segment.finished_at is not None + and now-segment.finished_at > max(policy.steady_timeout_seconds, policy.stall_timeout_seconds) + and (not self.motion_complete() or self.stable_window(segment.finished_at, now) is None)): + return "visual_motion_target_unconfirmed:" + ",".join(self.required) + return "" + + def motion_complete(self): + policy = self.profile.acquisition + for name, delta in self.deltas.items(): + channel = self.channels[name] + span = self.profile.command.maximum_values[channel]-self.profile.command.minimum_values[channel] + if abs(delta) > .05*span and self.maximum_travel[name] < policy.visual_minimum_motion_px: + return False + for name in self.motion.visual_return_joints: + target = self.zeros.get((name, tuple(self.motion.target))) + if target is None or corner_distance(target.points, self.latest[name].points, + target.scale_px) > policy.visual_zero_tolerance_px: + return False + return True + + def stable_window(self, finished_at, now): + if finished_at is None or not self.available(self.required, now) or not self.motion_complete(): + return None + selected = {} + for name in self.required: + rows = [sample for sample in self.history[name] if sample.received_at >= finished_at + and tuple(sample.record.get("command_vector") or ()) == tuple(self.motion.target)] + if len(rows) < 3: + return None + end = rows[-1].stamp_ns + boundary = next((i for i in range(len(rows)-1, -1, -1) + if (end-rows[i].stamp_ns)/1e9 >= self.profile.acquisition.steady_window_seconds), None) + if boundary is None: + return None + rows = rows[boundary:] + if len(rows) < 3: + return None + center = np.median([row.points for row in rows], axis=0) + if max(corner_distance(row.points, center, self.initial[name].scale_px) + for row in rows) > self.profile.acquisition.visual_stability_px: + return None + selected[name] = rows + return selected + + def settle_record(self, finished_at, now, *, epoch): + windows = self.stable_window(finished_at, now) + if windows is None: + self.window_id = "" + return None + record = dict(kind="visual_motion_settled", policy=VISUAL_MOTION_POLICY, + session_epoch=epoch, motion_version=self.version, + required_joints=list(self.required), + sources={name: [witness_hash(row.record) for row in rows] for name, rows in windows.items()}, + initial_sources={name: witness_hash(row.record) for name, row in self.initial.items()}, + initial_command=list(self.initial_command), + progress_sources={name: witness_hash(row.record) for name, row in self.progress_sources.items()}, + return_sources={name: witness_hash(self.zeros[(name, tuple(self.motion.target))].record) + for name in self.motion.visual_return_joints}, + target_command=list(self.motion.target)) + identity = witness_hash(record) + if identity == self.window_id: + return self.window_id + self.window_id = identity + record["evidence_id"] = self.window_id + self.pending_records.append(record) + return self.window_id + + def freeze_zeros(self, references): + for name, reference in references.items(): + if (name not in self.latest or not self.window_id + or tuple(self.latest[name].record.get("command_vector") or ()) != tuple(reference.samples[0].command)): + raise ValueError(f"visual_zero_observation_missing:{name}") + pose = tuple(reference.samples[0].command) + self.zeros[(name, pose)] = self.latest[name] + + def drain(self): + result, self.pending_records = self.pending_records, [] + return result + + +def validate_visual_motion_evidence(profile, records): + """Recompute accepted zero/static windows from original image corners.""" + if not profile.vision_motion: + return + samples, windows = {}, {} + policy = profile.acquisition + for row in records: + if row.get("kind") == "visual_motion_observation": + if row.get("policy") != VISUAL_MOTION_POLICY: + raise ValueError("visual_motion_policy_changed") + spec = profile.measurement.measurements.get(row.get("joint")) + if spec is None or (row.get("view"), row.get("parent_role"), row.get("child_role")) != ( + spec.view, spec.parent_role, spec.child_role): + raise ValueError("visual_motion_observer_changed") + relative_corners(row["parent_corners_xy"], row["child_corners_xy"]) + samples[witness_hash(row)] = row + elif row.get("kind") == "visual_motion_settled": + if row.get("policy") != VISUAL_MOTION_POLICY: + raise ValueError("visual_motion_policy_changed") + identity = row.get("evidence_id") + if identity != witness_hash({key: value for key, value in row.items() if key != "evidence_id"}): + raise ValueError("visual_settled_identity_changed") + if set(row["sources"]) != set(row["required_joints"]): + raise ValueError("visual_settled_observers_missing") + for name, ids in row["sources"].items(): + if len(set(ids)) != len(ids) or len(ids) < 3: + raise ValueError("visual_settled_independent_frames_missing") + try: + sources = [samples[key] for key in ids] + initial = samples[row["initial_sources"][name]] + except KeyError as error: + raise ValueError("visual_settled_source_missing") from error + if initial["joint"] != name: + raise ValueError("visual_settled_motion_identity_changed") + stamps = [r["image_stamp_ns"] for r in sources] + if stamps != sorted(set(stamps)) or (stamps[-1]-stamps[0])/1e9 < policy.steady_window_seconds: + raise ValueError("visual_settled_window_incomplete") + if any(r["joint"] != name or r["session_epoch"] != row["session_epoch"] + or r["motion_version"] != row["motion_version"] + or r.get("command_vector") != row["target_command"] for r in sources): + raise ValueError("visual_settled_motion_identity_changed") + scale = float(np.mean(np.linalg.norm(np.asarray(initial["parent_corners_xy"]) + - np.roll(initial["parent_corners_xy"], -1, axis=0), axis=1))) + points = [relative_corners(r["parent_corners_xy"], r["child_corners_xy"]) for r in sources] + center = np.median(points, axis=0) + if max(corner_distance(p, center, scale) for p in points) > policy.visual_stability_px: + raise ValueError("visual_settled_pose_not_stable") + channel = channel_for_joint(profile, name) + span = profile.command.maximum_values[channel]-profile.command.minimum_values[channel] + if abs(row["target_command"][channel]-row["initial_command"][channel]) > .05*span: + progress = samples.get(row.get("progress_sources", {}).get(name)) + if (progress is None or progress["joint"] != name + or progress["session_epoch"] != row["session_epoch"] + or progress["motion_version"] != row["motion_version"] + or corner_distance(relative_corners(initial["parent_corners_xy"], initial["child_corners_xy"]), + relative_corners(progress["parent_corners_xy"], progress["child_corners_xy"]), scale) + < policy.visual_minimum_motion_px): + raise ValueError("visual_settled_motion_not_observed") + if name in row.get("return_sources", {}): + zero = samples.get(row["return_sources"][name]) + if zero is None or zero["joint"] != name or zero.get("command_vector") != row["target_command"]: + raise ValueError("visual_return_source_missing") + reference = relative_corners(zero["parent_corners_xy"], zero["child_corners_xy"]) + if corner_distance(reference, points[-1], scale) > policy.visual_zero_tolerance_px: + raise ValueError("visual_return_pose_not_confirmed") + windows[identity] = row + elif row.get("kind") in {"joint_zero_sample", "joint_sample", "secondary_joint_sample"} and ( + row.get("kind") == "joint_zero_sample" or row.get("sample_phase") == "steady"): + window = windows.get(row.get("visual_settled_evidence_id")) + name = row.get("joint", row.get("observation_joint")) + if window is None or name not in window["required_joints"]: + raise ValueError("visual_sample_settled_evidence_missing") + if row.get(f"command_vector_{profile.command.unit}") != window["target_command"]: + raise ValueError("visual_sample_command_changed") + sources = [samples[key] for key in window["sources"][name]] + if row.get("image_stamp_ns") != sources[-1]["image_stamp_ns"]: + raise ValueError("visual_sample_image_changed") diff --git a/src/linkerhand_calibration/linkerhand_calibration/runtime/zero_recovery.py b/src/linkerhand_calibration/linkerhand_calibration/runtime/zero_recovery.py new file mode 100644 index 0000000..7446d42 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/runtime/zero_recovery.py @@ -0,0 +1,105 @@ +"""Shared failure categories and bounded acquisition recovery.""" + +from enum import Enum + + +class FailureCategory(str, Enum): + MISSING_SAMPLES = "missing_samples" + UNOBSERVABLE = "unobservable" + REFERENCE_CHANGED = "reference_changed" + DEVICE_FAULT = "device_fault" + NUMERICAL_SOLVER = "numerical_solver" + EVIDENCE_GAP = "evidence_gap" + UNKNOWN = "unknown" + + +RETRYABLE_PREPARATION_FAILURES = frozenset({ + # The frame validator can fail before the model solver is entered. + # Both stages must consume the same bounded local recovery allowance. + "insufficient_image_frames", + "motion_candidates_missing_or_invalid", + "image_motion_insufficient_independent_frames", + "image_motion_validation_frame_unresolved", + "image_motion_incomplete_candidate_family", +}) + + +def failure_category(reason): + code = str(reason).split(":", 1)[0] + if code in {"preparation_sync_coverage_missing", "preparation_sync_endpoint_missing", + "preparation_sync_gap_too_long", "preparation_state_vector_invalid"}: + return FailureCategory.EVIDENCE_GAP + if code in {"image_motion_solver_budget_exhausted", "image_motion_optimizer_unresolved", + "image_motion_solver_timeout", "image_motion_frame_optimizer_unresolved"}: + return FailureCategory.NUMERICAL_SOLVER + if code in {"image_motion_no_observable_image_model", "motion_geometry_unresolved", + "image_motion_families_not_distinguishable", "image_motion_shared_pose_unresolved", + "preparation_witness_unobservable", "preparation_witness_pose_uncertain", + "preparation_witness_endpoint_unresolved"}: + return FailureCategory.UNOBSERVABLE + if code in RETRYABLE_PREPARATION_FAILURES or code in {"sweep_acquisition", "joint_zero_samples_missing"}: + return FailureCategory.MISSING_SAMPLES + if code in {"motion_held_feedback_changed", "fixed_reference_moved", "joint_resume_reference_changed", + "parent_reference_pose_changed", "camera_extrinsics_changed", + "preparation_witness_held_posture_changed", "preparation_witness_current_posture_changed", + "preparation_witness_reference_feedback_changed", "preparation_witness_camera_reference_changed", + "preparation_witness_source_pose_changed"}: + return FailureCategory.REFERENCE_CHANGED + if code in {"mechanical_stall", "sdk_disconnected", "hardware_fault", "feedback_stale", "duplicate_controller"}: + return FailureCategory.DEVICE_FAULT + return FailureCategory.UNKNOWN + + +def permits_recovery(reasons, completed_retries): + reasons = tuple(reasons) + return completed_retries == 0 and bool(reasons) and all( + failure_category(reason) == FailureCategory.MISSING_SAMPLES for reason in reasons) + + +class ZeroRecovery: + def __init__(self): + self._used = set() + + def restore(self, task_key, joints): + self._used.add((task_key, tuple(joints))) + + def take_parent_model_refresh(self, motion, *, stale_image_anchor): + """Spend one fresh-model allowance for a resumed parent reference. + + This does not reacquire its joint zero or scan. It only permits the + already declared safe approach to rebuild the image-domain model in + the current session's stationary camera coordinate frame. + """ + if (not motion.reference_reuse or not stale_image_anchor + or len(motion.zero_joints) != 1): + return None + key = (motion.task_key, tuple(motion.zero_joints)) + if key in self._used: + return None + self._used.add(key) + return "refresh_parent_model" + + def take(self, motion, *, geometry_error, reports, referenced_joints): + if motion.reference_reuse: + return None + if not motion.zero_joints or (set(motion.zero_joints) & set(referenced_joints) + and not getattr(motion, 'reference_check', False)): + return None + if getattr(motion, 'reference_check', False) and geometry_error: + return None + if geometry_error: + # A partially installed multi-view model must not be refitted. + # Faults, changed holding poses and corrupt input are not retries. + if any(report.get("status") == "resolved" for report in reports.values()): + return None + reasons = {report.get("reason", "") for report in reports.values()} + if not permits_recovery(reasons, 0): + return None + action = "repeat_approach" + else: + action = "retry_zero_images" + key = (motion.task_key, tuple(motion.zero_joints)) + if key in self._used: + return None + self._used.add(key) + return action diff --git a/src/linkerhand_calibration/linkerhand_calibration/sample_schema.py b/src/linkerhand_calibration/linkerhand_calibration/sample_schema.py new file mode 100644 index 0000000..3fdbbf9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/sample_schema.py @@ -0,0 +1,3 @@ +"""Compatibility import for the canonical sample data contract.""" + +from .core.domain.sample_schema import * # noqa: F401,F403 diff --git a/src/linkerhand_calibration/linkerhand_calibration/storage.py b/src/linkerhand_calibration/linkerhand_calibration/storage.py new file mode 100644 index 0000000..e403f72 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/storage.py @@ -0,0 +1,3 @@ +"""Compatibility import for crash-safe artifact storage.""" + +from .core.artifacts.storage import * # noqa: F401,F403 diff --git a/src/linkerhand_calibration/linkerhand_calibration/three_camera_diagnostics.py b/src/linkerhand_calibration/linkerhand_calibration/three_camera_diagnostics.py new file mode 100644 index 0000000..b423b81 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/three_camera_diagnostics.py @@ -0,0 +1,4 @@ +"""Compatibility import for the installed Chinese model diagnostics.""" + +from linkerhand_calibration.models.g20.reporting_zh import * # noqa: F401,F403 +from linkerhand_calibration.models.g20.reporting_zh import _task_text diff --git a/src/linkerhand_calibration/linkerhand_calibration/three_camera_node.py b/src/linkerhand_calibration/linkerhand_calibration/three_camera_node.py new file mode 100644 index 0000000..f23027c --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/three_camera_node.py @@ -0,0 +1,7 @@ +"""Legacy module spelling of the only online calibration entry.""" + +import sys + +from .runtime.ros import entrypoint as _implementation + +sys.modules[__name__] = _implementation diff --git a/src/linkerhand_calibration/linkerhand_calibration/tools/__init__.py b/src/linkerhand_calibration/linkerhand_calibration/tools/__init__.py new file mode 100644 index 0000000..1782dc0 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/tools/__init__.py @@ -0,0 +1 @@ +"""Operator tools for extrinsics, alignment, and runtime bridges.""" diff --git a/src/linkerhand_calibration/linkerhand_calibration/tools/feedback_image_report.py b/src/linkerhand_calibration/linkerhand_calibration/tools/feedback_image_report.py new file mode 100644 index 0000000..4c805c9 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/tools/feedback_image_report.py @@ -0,0 +1,105 @@ +"""Read-only offline candidate inventory for feedback-based hand profiles.""" +import argparse +import json +from collections import Counter +from pathlib import Path + +from ..profiles import load_bundled_hand_profile +from ..runtime.acquisition import load_capture +from ..runtime.feedback_image_candidates import solve_feedback_image_candidates +from ..runtime.feedback_image_dataset import partition_feedback_images +from ..core.domain.capture_plan import FIXED, RAW_FEEDBACK, configure_training, raw_feedback_capture + + +def analyze(profile_name, journal, *, joint=None, task=None, view=None, coverage=False): + profile = load_bundled_hand_profile(profile_name) + records = load_capture(Path(journal)) + header = next((row for row in records if row.get('kind') == 'session_start'), {}) + recorded_policy = header.get('capture_plan', {}).get('policy') + if recorded_policy in {FIXED, RAW_FEEDBACK}: + profile = configure_training(profile, recorded_policy) + evidence = None + if raw_feedback_capture(profile): + from ..runtime.feedback_raw_evidence import partition_feedback_raw_capture + evidence = partition_feedback_raw_capture(profile, records, require_complete=False) + dataset = evidence.images + else: + dataset = partition_feedback_images(profile, records) + candidates = solve_feedback_image_candidates(dataset) + partitions = {} + for name, frames in candidates.partitions.items(): + counts = Counter(len(poses) for frame in frames + for poses in frame['candidates_by_role'].values()) + partitions[name] = dict(frames=len(frames), + tags_with_zero_candidates=counts[0], tags_with_one_candidate=counts[1], + tags_with_two_candidates=counts[2], + tags_with_other_candidate_count=sum(value for key, value in counts.items() if key > 2)) + result = dict(profile_id=profile.key.profile_id, input_sha256=dataset.sha256, + candidates_sha256=candidates.sha256, partitions=partitions, + fit_started=False, reference_motion_started=joint is not None, + task_motion_started=task is not None, publication_allowed=False) + if evidence is not None: + result['raw_capture_evidence'] = dict(completed_units=len(evidence.completed_units), + missing_units=list(evidence.missing_units), + selected_attempts=list(evidence.selected_attempts), sha256=evidence.sha256) + if coverage: + from ..runtime.engine import CalibrationEngine + from ..runtime.feedback_image_coverage import evaluate_feedback_image_unit + spans = {} + units = [] + if evidence is not None: + records_for_coverage = (*dataset.motion_training, *dataset.motion_holdout, + *dataset.command_training, *dataset.command_holdout) + chosen_attempts = {tuple(row['unit']): row['attempt'] + for row in evidence.selected_attempts} + else: + records_for_coverage = records + chosen_attempts = {} + for unit in CalibrationEngine(profile).scan_units(): + attempts = [int(row.get('attempt', 1)) for row in records_for_coverage + if row.get('kind') == 'image_observation_frame' + and row.get('task_name') == unit.task_key + and row.get('cycle') == unit.cycle + and row.get('direction') == unit.direction + and row.get('segment_key', '') == unit.segment_key + and row.get('sample_phase') == unit.sample_phase] + attempt = chosen_attempts.get(unit.identity, max(attempts, default=1)) + quality = evaluate_feedback_image_unit(profile, unit, attempt, records_for_coverage, + first_cycle_spans=spans) + units.append(dict(task_name=unit.task_key, cycle=unit.cycle, + direction=unit.direction, sample_phase=unit.sample_phase, + segment_key=unit.segment_key, attempt=attempt, + passed=quality.passed, failures=list(quality.failures), + metrics=dict(quality.metrics))) + result['raw_image_coverage'] = dict(units=units, + all_passed=all(unit['passed'] for unit in units), + joint_angles_authorized=False, publication_allowed=False) + if task is not None: + if view is None: + raise ValueError('feedback_task_graph_view_required') + from ..runtime.feedback_image_graph import feedback_task_image_graph + result['task_image_motion'] = feedback_task_image_graph( + profile, records, dataset, task, view).report() + if joint is not None: + from ..runtime.feedback_image_motion import solve_feedback_reference_motion + if joint not in profile.measurement.measurements: + raise ValueError('feedback_reference_unknown_joint:' + joint) + result['reference_motion'] = solve_feedback_reference_motion( + profile, records, joint, dataset=dataset).report() + return result + + +def main(argv=None): + parser = argparse.ArgumentParser(description='只读检查普通型号原始图像的离线双解与训练/验证分区') + parser.add_argument('profile', help='例如 o6_right_8') + parser.add_argument('journal', type=Path, help='raw_samples.jsonl') + parser.add_argument('--joint', help='离线求一个固定父标签关节的零位前运动几何;只出诊断,不写零位') + parser.add_argument('--task', help='按任务联合检查多个关节的图像运动;只出诊断') + parser.add_argument('--view', help='与 --task 一起指定相机视角') + parser.add_argument('--coverage', action='store_true', help='用原始角点和反馈重算每个扫描单元的覆盖率') + args = parser.parse_args(argv) + print(json.dumps(analyze(args.profile, args.journal, joint=args.joint, task=args.task, view=args.view, coverage=args.coverage), ensure_ascii=False, indent=2, allow_nan=False)) + + +if __name__ == '__main__': + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/tools/image_solve_report.py b/src/linkerhand_calibration/linkerhand_calibration/tools/image_solve_report.py new file mode 100644 index 0000000..0346065 --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/tools/image_solve_report.py @@ -0,0 +1,35 @@ +"""Read-only summary of saved zero-geometry candidate results.""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path + +from ..core.geometry.tag_pose.image_solve_diagnosis import diagnose_image_solve_record + + +def analyze_journal(path: Path) -> list[dict]: + reports = [] + with path.open(encoding="utf-8") as stream: + for number, line in enumerate(stream, 1): + if not line.strip(): + continue + try: + row = json.loads(line) + except json.JSONDecodeError as error: + raise ValueError(f"invalid journal JSON on line {number}") from error + if isinstance(row, dict) and row.get("kind") == "motion_branch_initialization": + reports.append(diagnose_image_solve_record(row)) + return reports + + +def main(argv=None): + parser = argparse.ArgumentParser(description="只读查看零位图像双候选的历史求解结果") + parser.add_argument("journal", type=Path, help="采集会话的 raw_samples.jsonl") + selected = parser.parse_args(argv) + print(json.dumps(analyze_journal(selected.journal), ensure_ascii=False, indent=2, allow_nan=False)) + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/trajectory.py b/src/linkerhand_calibration/linkerhand_calibration/trajectory.py new file mode 100644 index 0000000..9581daf --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/trajectory.py @@ -0,0 +1,4 @@ +"""Compatibility import for G20 trajectory.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.trajectory") diff --git a/src/linkerhand_calibration/linkerhand_calibration/urdf_comparison.py b/src/linkerhand_calibration/linkerhand_calibration/urdf_comparison.py new file mode 100644 index 0000000..dc3786a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/urdf_comparison.py @@ -0,0 +1,175 @@ +"""Read-only, model-independent URDF pose comparison; never a release gate. + +Coordinates are URDF joint radians, NOT SDK feedback. Link origins are not +fingertip contact points. A matching model is not a physical accuracy proof. +""" + +import argparse +import hashlib +import json +import math +from pathlib import Path +import xml.etree.ElementTree as ET + +import numpy as np +from scipy.spatial.transform import Rotation + +from .storage import atomic_write_json + + +def _vector(value): + a = np.asarray([float(x) for x in value.split()]) + if a.shape != (3,) or not np.isfinite(a).all(): + raise ValueError("invalid URDF vector") + return a + + +class _Model: + def __init__(self, path): + self.path = Path(path).resolve(strict=True) + root = ET.parse(self.path).getroot() + self.links = {x.get("name"): ET.tostring(x) for x in root.findall("link")} + self.joints = {x.get("name"): x for x in root.findall("joint")} + if len(self.links) != len(root.findall("link")) or len(self.joints) != len(root.findall("joint")): + raise ValueError("duplicate URDF names") + self.parents = {} + for name, j in self.joints.items(): + if j.get("type") not in {"fixed", "revolute", "continuous"}: + raise ValueError(f"unsupported joint type: {name}") + p, c = j.find("parent").get("link"), j.find("child").get("link") + if p not in self.links or c not in self.links or c in self.parents: + raise ValueError(f"invalid topology: {name}") + self.parents[c] = name + roots = set(self.links) - set(self.parents) + if len(roots) != 1: + raise ValueError("URDF must have one root") + self.root = roots.pop() + self.active = {n for n, j in self.joints.items() + if j.get("type") != "fixed" and j.find("mimic") is None} + + def bounds(self, name): + j = self.joints[name] + if j.get("type") == "continuous": + return -math.pi, math.pi + lim = j.find("limit") + values = float(lim.get("lower")), float(lim.get("upper")) + if not all(math.isfinite(v) for v in values) or values[0] > values[1]: + raise ValueError(f"invalid limits: {name}") + return values + + def fk(self, values): + angles, poses = {}, {self.root: np.eye(4)} + + def angle(name, stack=()): + if name in angles: + return angles[name] + if name in stack or name not in self.joints: + raise ValueError("invalid mimic dependency") + j = self.joints[name] + mimic = j.find("mimic") + if j.get("type") == "fixed": + v = 0. + elif mimic is None: + v = float(values.get(name, 0.)) + else: + v = (float(mimic.get("multiplier", "1")) * + angle(mimic.get("joint"), (*stack, name)) + float(mimic.get("offset", "0"))) + if not math.isfinite(v): + raise ValueError("non-finite joint coordinate") + angles[name] = v + return v + + def pose(link, stack=()): + if link in poses: + return poses[link] + if link in stack: + raise ValueError("cyclic URDF topology") + name = self.parents[link] + j = self.joints[name] + origin = j.find("origin") + t = np.eye(4) + if origin is not None: + t[:3, 3] = _vector(origin.get("xyz", "0 0 0")) + t[:3, :3] = Rotation.from_euler("xyz", _vector(origin.get("rpy", "0 0 0"))).as_matrix() + q = angle(name) + if j.get("type") != "fixed": + a = j.find("axis") + axis = _vector("1 0 0" if a is None else a.get("xyz", "1 0 0")) + if np.linalg.norm(axis) < 1.e-12: + raise ValueError("zero joint axis") + t[:3, :3] = t[:3, :3] @ Rotation.from_rotvec(axis / np.linalg.norm(axis) * q).as_matrix() + poses[link] = pose(j.find("parent").get("link"), (*stack, link)) @ t + return poses[link] + + for link in self.links: + pose(link) + return poses + + +def compare_urdfs(reference, candidate): + a, b = _Model(reference), _Model(candidate) + if set(a.links) != set(b.links) or set(a.joints) != set(b.joints) or a.active != b.active: + raise ValueError("models have different links/joints/actuators") + for name in a.joints: + x, y = a.joints[name], b.joints[name] + if x.get("type") != y.get("type") or any(x.find(k).attrib != y.find(k).attrib for k in ("parent", "child")): + raise ValueError("models have different topology") + bounds = {} + for name in sorted(a.active): + al, au = a.bounds(name) + bl, bu = b.bounds(name) + bounds[name] = max(al, bl), min(au, bu) + if bounds[name][0] > bounds[name][1]: + raise ValueError(f"no common joint interval: {name}") + neutral = {n: float(np.clip(0., lo, hi)) for n, (lo, hi) in bounds.items()} + samples = {"neutral": neutral} + if len(bounds) > 1: + samples["combined_middle"] = {n: (lo + hi) / 2 for n, (lo, hi) in bounds.items()} + samples["combined_upper"] = {n: hi for n, (lo, hi) in bounds.items()} + for name, (lo, hi) in bounds.items(): + for label, q in (("lower", lo), ("middle", (lo + hi) / 2), ("upper", hi)): + samples[f"{name}:{label}"] = {**neutral, name: q} + errors = {link: {"maximum_origin_distance_mm": 0., "maximum_orientation_difference_deg": 0.} + for link in sorted(a.links)} + for q in samples.values(): + left, right = a.fk(q), b.fk(q) + for link, item in errors.items(): + distance = float(np.linalg.norm(left[link][:3, 3] - right[link][:3, 3]) * 1000) + rotation = float(np.degrees(Rotation.from_matrix(left[link][:3, :3].T @ right[link][:3, :3]).magnitude())) + item["maximum_origin_distance_mm"] = max(item["maximum_origin_distance_mm"], distance) + item["maximum_orientation_difference_deg"] = max(item["maximum_orientation_difference_deg"], rotation) + return { + "comparison_schema": 1, + "scope": "same_urdf_joint_angles_not_sdk_feedback", + "is_accuracy_certificate": False, + "note": "Link origins are not fingertip contact points; never send these offline probe poses to hardware.", + "reference": str(a.path), "candidate": str(b.path), + "reference_sha256": hashlib.sha256(a.path.read_bytes()).hexdigest(), + "candidate_sha256": hashlib.sha256(b.path.read_bytes()).hexdigest(), + "link_elements_identical": a.links == b.links, + "active_joint_ranges_rad": {n: {"reference": a.bounds(n), "candidate": b.bounds(n), + "comparison_interval": bounds[n]} for n in bounds}, + "pose_count": len(samples), "probe_joint_positions_rad": samples, + "link_frame_differences": errors, + "maximum_origin_distance_mm": max(x["maximum_origin_distance_mm"] for x in errors.values()), + "maximum_orientation_difference_deg": max(x["maximum_orientation_difference_deg"] for x in errors.values()), + } + + +def main(args=None): + parser = argparse.ArgumentParser(description="离线 URDF 姿态对比,不驱动硬件、不改变标定结果") + parser.add_argument("--reference", required=True) + parser.add_argument("--candidate", required=True) + parser.add_argument("--output", required=True) + selected = parser.parse_args(args) + target = Path(selected.output).resolve() + if target.exists(): + parser.error("output must be a new file") + result = compare_urdfs(selected.reference, selected.candidate) + atomic_write_json(target, result) + print(f"模型对比完成(非精度PASS):最大连杆原点差 {result['maximum_origin_distance_mm']:.6f} mm;" + f"最大方向差 {result['maximum_orientation_difference_deg']:.6f}°;报告 {target}") + + +if __name__ == "__main__": + main() diff --git a/src/linkerhand_calibration/linkerhand_calibration/urdf_zero.py b/src/linkerhand_calibration/linkerhand_calibration/urdf_zero.py new file mode 100644 index 0000000..d475e4e --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/urdf_zero.py @@ -0,0 +1,7 @@ +"""One-release module alias for the relocated model zero solver.""" + +import sys + +from linkerhand_calibration.models.g20 import zero_solver as _implementation + +sys.modules[__name__] = _implementation diff --git a/src/linkerhand_calibration/linkerhand_calibration/zero_calibration.py b/src/linkerhand_calibration/linkerhand_calibration/zero_calibration.py new file mode 100644 index 0000000..8b85e9a --- /dev/null +++ b/src/linkerhand_calibration/linkerhand_calibration/zero_calibration.py @@ -0,0 +1,4 @@ +"""Compatibility import for G20 zero_calibration.""" +from importlib import import_module +import sys +sys.modules[__name__] = import_module("linkerhand_calibration.models.g20.zero_calibration")