#!/usr/bin/env python3 """Generate deterministic native/WASM evidence for pentapod kinematics.""" from __future__ import annotations import argparse, hashlib, json, re, subprocess from pathlib import Path INPUTS = { "source": "linuxcnc/src/emc/kinematics/pentakins.c", "header": "linuxcnc/src/emc/kinematics/pentakins.h", "config": "linuxcnc/configs/sim/axis/pentapod/pentapod.ini", "hal": "linuxcnc/configs/sim/axis/pentapod/kinematics.hal", "implementation": "wasm-core/src/sim_kinematics.c", "kinematics_header": "wasm-core/include/sim_kinematics.h", "test": "wasm-core/tests/sim_kinematics_test.c", } def sha256(path: Path) -> str: return hashlib.sha256(path.read_bytes()).hexdigest() def run_json(command: list[str], root: Path) -> dict[str, object]: result = subprocess.run(command, cwd=root, check=False, text=True, capture_output=True) if result.returncode: raise RuntimeError(f"{command[0]} exited {result.returncode}: {result.stderr.strip()}") for line in reversed(result.stdout.splitlines()): if line.lstrip().startswith("{"): return json.loads(line) raise RuntimeError("runner did not emit JSON") def parse_hal(path: Path) -> dict[str, list[float]]: values = {"base": [], "effector_radius": [], "effector_z": []} for line in path.read_text(encoding="utf-8").splitlines(): match = re.match(r"setp\s+pentakins\.(base|effector)\.(\d+)\.(x|y|z|r)\s+([-+0-9.eE]+)", line) if not match: continue group, _, axis, raw = match.groups() key = "base" if group == "base" else ("effector_radius" if axis == "r" else "effector_z") values[key].append(float(raw)) return values def generate(root: Path, output: Path) -> dict[str, object]: root = root.resolve() native_all = run_json([str(root / "build-native/sim_kinematics_test")], root) wasm_all = run_json(["node", str(root / "build-wasm/sim_kinematics_wasm_test.js")], root) native = {"pentapod": native_all["pentapod"], "boundaries": native_all["delta_edges"]["pentapod"]} wasm = {"pentapod": wasm_all["pentapod"], "boundaries": wasm_all["delta_edges"]["pentapod"]} config_text = (root / INPUTS["config"]).read_text(encoding="utf-8") report = { "schema": "pentapod-kinematics-report.v1", "status": "partial", "implementation_status": "verified", "source_records": {name: {"path": path, "sha256": sha256(root / path)} for name, path in INPUTS.items()}, "configuration_candidate": {"path": INPUTS["config"], "kinematics": "pentakins", "joints": 5, "coordinates": "XYZAB", "scan": "KINEMATICS = pentakins" in config_text and "JOINTS = 5" in config_text, "provenance": "shipped LinuxCNC simulation", "hal_geometry": parse_hal(root / INPUTS["hal"]), "hal_pins": ["last-iterations", "max-iterations", "limit-iterations", "max-error", "convergence-criterion", "tool-offset"]}, "configuration_candidates": [ {"id": "shipped-pentapod", "path": INPUTS["config"], "kind": "real", "coordinates": "XYZAB", "joints": 5}, {"id": "offset-seed-regression", "path": "wasm-core/tests/sim_kinematics_test.c", "kind": "derived", "coordinates": "XYZAB", "joints": 5, "initial_pose": [0.0, 500.0, 300.0, 0.0, 0.0], "target_pose": [0.0, 500.0, 300.0, 0.01, -0.01], "purpose": "non-zero roll/pitch Newton convergence and native/WASM comparison"}, ], "geometry": {"struts": 5, "orientation": "roll/pitch only; yaw is constrained to zero in the forward result", "units": "configuration units; XYZ linear and AB degrees", "tool_offset": "applied to both base and effector HAL z coordinates"}, "mapping": {"coordinates": "XYZAB", "kinematics_joint_count": 5, "joint_semantics": ["strut-0", "strut-1", "strut-2", "strut-3", "strut-4"], "extra_joint_policy": "rejected"}, "solver": {"inverse": "closed-form radial/z strut lengths", "forward": "Newton-Raphson 5x5 numerical Jacobian", "seed": [0.0, 500.0, 300.0, 0.0, 0.0], "seed_units": "XYZ in configuration units; A/B in radians internally", "default_iteration_limit": 120, "default_convergence_tolerance": 1e-9, "default_max_error": 1000.0, "alternate_seed_flag": "SIM_KIN_GENHEX_ALTERNATE_SEED bit 1; negative-z seed is explicitly bounded"}, "workspace_and_boundaries": {"nominal": native["pentapod"], "alternate_seed": native["boundaries"]["alternate_pose"], "alternate_seed_error": native["boundaries"]["alternate_status"], "alternate_seed_iterations": native["boundaries"].get("alternate_iterations", 0), "nonpositive_joint_error": native["boundaries"]["nonpositive"], "nonpositive_joint_iterations": native["boundaries"].get("nonpositive_iterations", 0), "iteration_limit_error": native["boundaries"]["iteration_limit"], "iteration_limit_iterations": native["boundaries"].get("iteration_limit_iterations", 0), "max_error_boundary": native["boundaries"]["max_error"], "max_error_iterations": native["boundaries"].get("max_error_iterations", 0), "singular_jacobian_error": native["boundaries"]["singular"], "singular_jacobian_iterations": native["boundaries"].get("singular_iterations", 0), "joint_limit_error": native["boundaries"]["limit_error"], "posture_constraint": "C/yaw is not a configured joint and forward output is exactly zero", "iterations": native["pentapod"]["iterations"], "residual": native["pentapod"]["residual"]}, "samples": {"native": native, "wasm": wasm, "byte_identical_json": json.dumps(native, sort_keys=True, separators=(",", ":")) == json.dumps(wasm, sort_keys=True, separators=(",", ":")), "state_hash_identical": native["pentapod"]["state_hash"] == wasm["pentapod"]["state_hash"]}, "native_wasm": {"status": "passed", "native_command": "build-native/sim_kinematics_test", "wasm_command": "node build-wasm/sim_kinematics_wasm_test.js"}, "oracle": {"status": "blocked", "reason": "linuxcnc/unit_tests/kinematics is absent from the locked source", "blocked_samples": ["nominal five-strut pose", "negative-z seed", "nonpositive strut", "iteration limit", "maximum error", "singular Jacobian", "joint limit"]}, } report["report_sha256"] = hashlib.sha256(json.dumps(report, sort_keys=True, separators=(",", ":")).encode()).hexdigest() output.parent.mkdir(parents=True, exist_ok=True) output.write_text(json.dumps(report, ensure_ascii=False, sort_keys=True, indent=2) + "\n", encoding="utf-8") return report def main() -> int: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo-root", type=Path, default=Path(__file__).resolve().parents[1]) parser.add_argument("--output", type=Path, default=Path("coverage/pentapod-kinematics.report.json")) args = parser.parse_args() report = generate(args.repo_root, args.repo_root / args.output) print(f"pentapod_kinematics={report['status']} native_wasm={report['native_wasm']['status']} oracle={report['oracle']['status']}") return 0 if __name__ == "__main__": raise SystemExit(main())