#!/usr/bin/env python3 """Offline scale audit of historical HORUS captures; never connects to hardware. Replays the causal position regression on capture timestamps. Historical captures are only ~100 Hz, so this is not a validation of the 1 kHz PDO implementation. Both the replay and the reference use position, not an independent tachometer. """ import argparse from collections import deque import hashlib import json from pathlib import Path import numpy as np def audit(path): columns = ("elapsed_s", "axis", "position_rad", "velocity_rad_s", "enabled", "fault") # Recorder format: first line is a comment, second line is the CSV header. data = np.genfromtxt(path, delimiter=",", names=True, skip_header=1, usecols=columns, dtype=float) report = { "source": str(path), "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), "method": "Historical capture causal 20 ms position-regression replay; " "reference is central 200 ms position difference. " "Not 1 kHz hardware validation or independent velocity calibration.", "axes": [], } for axis in sorted(np.unique(data["axis"]).astype(int)): rows = data[data["axis"] == axis] t, q = rows["elapsed_s"], rows["position_rad"] reported = rows["velocity_rad_s"] enabled = (rows["enabled"] > 0) & (rows["fault"] == 0) estimate = np.full(len(t), np.nan) history = deque() for i in range(len(t)): if i and (t[i] - t[i-1] > 0.05 or t[i] <= t[i-1]): history.clear() history.append(i) while len(history) > 2 and t[i] - t[history[1]] >= 0.02: history.popleft() if len(history) >= 3 and t[i] - t[history[0]] >= 0.002: indices = np.array(history) times = t[indices] - t[i] positions = q[indices] - q[i] times -= times.mean() positions -= positions.mean() estimate[i] = np.dot(times, positions) / np.dot(times, times) reference = (np.interp(t + 0.1, t, q) - np.interp(t - 0.1, t, q)) / 0.2 selected = (enabled & np.isfinite(estimate) & (abs(reference) > 0.03) & (t > t[0] + 0.2) & (t < t[-1] - 0.2)) # Reference windows must not cross telemetry gaps or state transitions. cuts = np.flatnonzero((np.diff(t) > 0.05) | (np.diff(t) <= 0) | (enabled[1:] != enabled[:-1])) for cut in cuts: selected[(t >= t[cut] - 0.11) & (t <= t[cut+1] + 0.11)] = False def metrics(values): if not selected.any(): return None ref = reference[selected] return { "gain_vs_position_reference": float(np.dot(ref, values[selected]) / np.dot(ref, ref)), "rmse_rad_s": float(np.sqrt(np.mean((ref - values[selected]) ** 2))), } report["axes"].append({ "axis": int(axis), "moving_samples": int(selected.sum()), "recorded_velocity": metrics(reported), "position_velocity_replay": metrics(estimate), }) return report def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--csv", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) args = parser.parse_args() report = audit(args.csv) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json.dumps(report, indent=2) + "\n") for row in report["axes"]: before, after = row["recorded_velocity"], row["position_velocity_replay"] if before is not None: print(f"J{row['axis']}: recorded gain={before['gain_vs_position_reference']:.4f}, " f"position gain={after['gain_vs_position_reference']:.4f}, " f"RMSE={before['rmse_rad_s']:.5f} -> {after['rmse_rad_s']:.5f} rad/s") if __name__ == "__main__": main()