Download code/ti5_arm_scripts/analyze_settling.py from chenhuaDr/data_calibration_robot: direct link, hf CLI and curl.
- Browser
- Download file 4.38 kB
-
https://huggingface.co/datasets/chenhuaDr/data_calibration_robot/resolve/main/code/ti5_arm_scripts/analyze_settling.py
- Command line
-
hf download hf://datasets/chenhuaDr/data_calibration_robot/code/ti5_arm_scripts/analyze_settling.py
-
curl -L -o analyze_settling.py https://huggingface.co/datasets/chenhuaDr/data_calibration_robot/resolve/main/code/ti5_arm_scripts/analyze_settling.py
4.38 kB
| #!/usr/bin/env python3 | |
| """Measure motion after the actual PDO target stops; read original native CSV.""" | |
| import argparse | |
| import hashlib | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| def main(): | |
| parser = argparse.ArgumentParser(__doc__) | |
| parser.add_argument("csv", type=Path) | |
| parser.add_argument("--output", required=True, type=Path) | |
| args = parser.parse_args() | |
| cols = ["elapsed_s", "cycle", "axis", "position_rad", "target_position_rad", | |
| "enabled", "fault", "error_code", "active_mode", "operational"] | |
| df = pd.read_csv(args.csv, comment="#", usecols=cols) | |
| if df.duplicated(["cycle", "axis"]).any(): | |
| raise ValueError("duplicate cycle/axis") | |
| arrays = {c: df.pivot(index="cycle", columns="axis", values=c).to_numpy() | |
| for c in cols if c not in ("cycle", "axis")} | |
| if arrays["position_rad"].shape[1] != 6: | |
| raise ValueError("expected six axes") | |
| t = arrays["elapsed_s"][:, 0] | |
| q, u = arrays["position_rad"], arrays["target_position_rad"] | |
| valid = (np.isfinite(q).all(axis=1) & np.isfinite(u).all(axis=1) | |
| & (arrays["enabled"] == 1).all(axis=1) | |
| & (arrays["fault"] == 0).all(axis=1) | |
| & (arrays["error_code"] == 0).all(axis=1) | |
| & (arrays["active_mode"] == 8).all(axis=1) | |
| & (arrays["operational"] == 1).all(axis=1)) | |
| constant = np.r_[False, (np.abs(np.diff(u, axis=0)) < 1e-10).all(axis=1)] | |
| constant &= valid & np.r_[False, valid[:-1]] | |
| constant &= np.r_[False, (np.diff(t) > 0) & (np.diff(t) < .01)] | |
| edges = np.diff(np.r_[False, constant, False].astype(int)) | |
| records, segments = [], [] | |
| for start, end in zip(np.flatnonzero(edges == 1), np.flatnonzero(edges == -1)): | |
| if t[end-1] - t[start] < 3: | |
| continue | |
| local_t = t[start:end] - t[start] | |
| actual = np.degrees(q[start:end]) | |
| record = {"start_s": float(t[start]), "duration_s": float(local_t[-1])} | |
| for name, lo, hi in [("first_3s", 0, 3), ("after_0p5_to_3s", .5, 3), | |
| ("after_3s", 3, float("inf"))]: | |
| sample = actual[(local_t >= lo) & (local_t < hi)] | |
| record[name + "_ptp_deg"] = np.ptp(sample, axis=0).tolist() if len(sample) else None | |
| record["final_error_deg"] = np.degrees(u[end-1] - q[end-1]).tolist() | |
| # Retrospective settling: last departure from a ±0.02° final-position band. | |
| # It is a measurement, not a causal online completion rule. | |
| record["last_departure_0p02deg_s"] = [ | |
| float(local_t[np.flatnonzero(np.abs(actual[:, j]-actual[-1, j]) > .02)[-1]]) | |
| if np.any(np.abs(actual[:, j]-actual[-1, j]) > .02) else 0.0 | |
| for j in range(6)] | |
| records.append(record) | |
| segments.append((start, end)) | |
| if not records: | |
| raise ValueError("no healthy constant-target holds >=3 s") | |
| sha = hashlib.sha256() | |
| with args.csv.open("rb") as source: | |
| for block in iter(lambda: source.read(1024*1024), b""): | |
| sha.update(block) | |
| report = {"source": str(args.csv), "sha256": sha.hexdigest(), "hold_count": len(records), | |
| "max_after_0p5_to_3s_ptp_deg": np.max( | |
| [r["after_0p5_to_3s_ptp_deg"] for r in records], axis=0).tolist(), | |
| "holds": records} | |
| args.output.mkdir(parents=True, exist_ok=True) | |
| (args.output / "report.json").write_text(json.dumps(report, indent=2) + "\n") | |
| import matplotlib | |
| matplotlib.use("Agg") | |
| import matplotlib.pyplot as plt | |
| worst = int(np.argmax([max(r["after_0p5_to_3s_ptp_deg"]) for r in records])) | |
| start, end = segments[worst] | |
| fig, axes = plt.subplots(3, 2, figsize=(11, 8), sharex=True) | |
| for j, ax in enumerate(axes.flat): | |
| ax.plot(t[start:end]-t[start], np.degrees(q[start:end, j]-u[start, j]), label="actual - target") | |
| ax.axhline(0, color="black", lw=.7, label="constant PDO target") | |
| ax.set(title=f"J{j+1}", ylabel="error (deg)", xlabel="time after target stops (s)") | |
| ax.grid(alpha=.3) | |
| axes[0, 0].legend() | |
| fig.suptitle(f"Native PDO hold at {t[start]:.3f} s; target constant on all six axes") | |
| fig.tight_layout() | |
| fig.savefig(args.output / "worst_hold.png", dpi=150) | |
| print(json.dumps({k: v for k, v in report.items() if k != "holds"}, indent=2)) | |
| if __name__ == "__main__": | |
| main() | |