Files
linuxcncWebWASM/scripts/generate_genhex_kinematics_report.py

100 lines
5.9 KiB
Python

#!/usr/bin/env python3
"""Generate deterministic native/WASM evidence for the generalized hexapod."""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import subprocess
from pathlib import Path
INPUTS = {
"source": "linuxcnc/src/emc/kinematics/genhexkins.c",
"header": "linuxcnc/src/emc/kinematics/genhexkins.h",
"config": "linuxcnc/configs/sim/axis/vismach/hexapod-sim/hexapod.ini",
"hal": "linuxcnc/configs/sim/axis/vismach/hexapod-sim/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(f"{command[0]} did not emit JSON")
def parse_hal(path: Path) -> dict[str, object]:
values: dict[str, list[float]] = {"base": [], "platform": []}
for line in path.read_text(encoding="utf-8").splitlines():
match = re.match(r"setp\s+genhexkins\.(base|platform)\.(\d+)\.(x|y|z)\s+([-+0-9.eE]+)", line)
if match:
values.setdefault(match.group(1), []).append(float(match.group(4)))
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 = {"genhex": native_all["genhex"], "boundaries": native_all["delta_edges"]["genhex"]}
wasm = {"genhex": wasm_all["genhex"], "boundaries": wasm_all["delta_edges"]["genhex"]}
source_records = {name: {"path": path, "sha256": sha256(root / path)} for name, path in INPUTS.items()}
config_text = (root / INPUTS["config"]).read_text(encoding="utf-8")
report = {
"schema": "genhex-kinematics-report.v1",
"status": "partial",
"implementation_status": "verified",
"source_records": source_records,
"configuration_candidate": {
"path": INPUTS["config"],
"kinematics": "genhexkins",
"joints": 6,
"coordinates": "XYZABC",
"scan": "KINEMATICS = genhexkins" in config_text and "JOINTS = 6" in config_text,
"hal_geometry": parse_hal(root / INPUTS["hal"]),
"hal_pins": ["last-iterations", "max-iterations", "limit-iterations", "max-error", "convergence-criterion", "fwd-kins-fail", "x", "y", "z", "a", "b", "c"],
},
"geometry": {
"struts": 6,
"base_points": [[-22.950, 13.250, 0.0], [22.950, 13.250, 0.0], [22.950, 13.250, 0.0], [0.0, -26.500, 0.0], [0.0, -26.500, 0.0], [-22.950, 13.250, 0.0]],
"platform_points": [[-1.0, 11.5, 0.0], [1.0, 11.5, 0.0], [10.459, -4.884, 0.0], [9.459, -6.616, 0.0], [-9.459, -6.616, 0.0], [-10.459, -4.884, 0.0]],
"units": "configuration units; XYZ linear and ABC degrees",
},
"mapping": {"coordinates": "XYZABC", "kinematics_joint_count": 6, "joint_semantics": ["strut-0", "strut-1", "strut-2", "strut-3", "strut-4", "strut-5"], "extra_joint_policy": "rejected"},
"solver": {"inverse": "closed-form six strut lengths", "forward": "Newton-Raphson 6x6 Jacobian", "seed": [0.0, 0.0, 50.0, 0.0, 0.0, 0.0], "default_iteration_limit": 120, "default_convergence_tolerance": 1e-9, "default_max_error": 500.0, "alternate_seed_flag": "SIM_KIN_GENHEX_ALTERNATE_SEED bit 1"},
"workspace_and_boundaries": {"nominal": native["genhex"], "alternate_seed": native["boundaries"]["alternate_pose"], "nonpositive_joint_error": native["boundaries"]["nonpositive"], "iteration_limit_error": native["boundaries"]["iteration_limit"], "max_error_boundary": native["boundaries"]["max_error"], "singular_jacobian_error": native["boundaries"]["singular"], "joint_limit_error": native["boundaries"]["limit_error"], "iterations": native["genhex"]["iterations"], "residual": native["genhex"]["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["genhex"]["state_hash"] == wasm["genhex"]["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 six-leg pose", "alternate initial 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/genhex-kinematics.report.json"))
args = parser.parse_args()
report = generate(args.repo_root, args.repo_root / args.output)
print(f"genhex_kinematics={report['status']} native_wasm={report['native_wasm']['status']} oracle={report['oracle']['status']}")
return 0
if __name__ == "__main__":
raise SystemExit(main())