Download code/ti5_arm_scripts/analyze_csp_smoothness.py from chenhuaDr/data_calibration_robot: direct link, hf CLI and curl.
- Browser
- Download file 7.87 kB
-
https://huggingface.co/datasets/chenhuaDr/data_calibration_robot/resolve/main/code/ti5_arm_scripts/analyze_csp_smoothness.py
- Command line
-
hf download hf://datasets/chenhuaDr/data_calibration_robot/code/ti5_arm_scripts/analyze_csp_smoothness.py
-
curl -L -o analyze_csp_smoothness.py https://huggingface.co/datasets/chenhuaDr/data_calibration_robot/resolve/main/code/ti5_arm_scripts/analyze_csp_smoothness.py
7.87 kB
| #!/usr/bin/env python3 | |
| """Summarize the direct CSP diagnostic CSV using only the Python stdlib.""" | |
| import argparse | |
| import csv | |
| import json | |
| import math | |
| from pathlib import Path | |
| from statistics import median | |
| def sine_fit(times, values, period, origin): | |
| """Least squares fit of offset + b*sin(w*t) + c*cos(w*t).""" | |
| basis = [(1.0, math.sin(2 * math.pi * (t - origin) / period), | |
| math.cos(2 * math.pi * (t - origin) / period)) for t in times] | |
| matrix = [[sum(x[i] * x[j] for x in basis) for j in range(3)] | |
| + [sum(x[i] * y for x, y in zip(basis, values))] for i in range(3)] | |
| for i in range(3): | |
| pivot = max(range(i, 3), key=lambda row: abs(matrix[row][i])) | |
| matrix[i], matrix[pivot] = matrix[pivot], matrix[i] | |
| scale = matrix[i][i] | |
| if abs(scale) < 1e-12: | |
| raise ValueError("singular sine fit") | |
| matrix[i] = [v / scale for v in matrix[i]] | |
| for j in range(3): | |
| if j != i: | |
| factor = matrix[j][i] | |
| matrix[j] = [a - factor * b for a, b in zip(matrix[j], matrix[i])] | |
| center, b, c = [matrix[i][3] for i in range(3)] | |
| residual = [y - (center + b * x[1] + c * x[2]) for x, y in zip(basis, values)] | |
| return {"center_deg": center, "amplitude_deg": math.hypot(b, c), | |
| "phase_rad": math.atan2(c, b), | |
| "residual_rms_deg": math.sqrt(sum(x * x for x in residual) / len(residual))} | |
| def tracking_metrics(rows): | |
| errors = [float(r["pdo_target_deg"]) - float(r["actual_deg"]) for r in rows] | |
| return {"samples": len(rows), "max_error_deg": max(map(abs, errors)), | |
| "rms_error_deg": math.sqrt(sum(e * e for e in errors) / len(errors)), | |
| "p99_error_deg": percentile(list(map(abs, errors)), 0.99), | |
| "peak_reported_speed_deg_s": max(abs(float(r["velocity_deg_s"])) for r in rows), | |
| "peak_torque_nm": max(abs(float(r["torque_nm"])) for r in rows)} | |
| def percentile(values, fraction): | |
| ordered = sorted(values) | |
| return ordered[int((len(ordered) - 1) * fraction)] if ordered else None | |
| def analyze(path, joint, phase="all"): | |
| metadata = {} | |
| with path.open() as source: | |
| def data_lines(): | |
| for line in source: | |
| if line.startswith("#"): | |
| for item in line[1:].strip().split(","): | |
| if "=" in item: | |
| key, value = item.split("=", 1) | |
| metadata[key.strip()] = value.strip() | |
| else: | |
| yield line | |
| rows = [r for r in csv.DictReader(data_lines()) | |
| if int(r["joint"]) == joint and (phase == "all" or r.get("phase", "oscillate") == phase)] | |
| if len(rows) < 2: | |
| raise ValueError("need at least two samples for the selected joint") | |
| times = [float(r["t_s"]) for r in rows] | |
| actual = [float(r["actual_deg"]) for r in rows] | |
| targets = [float(r["pdo_target_deg"]) for r in rows] | |
| gaps = [float(r["command_dt_ms"]) for r in rows[1:]] | |
| nominal_ms = 1000.0 / float(metadata.get("rate_hz", 1000.0)) | |
| cycles = [int(r["cycle"]) for r in rows] | |
| # Detect long identical raw-encoder plateaus while the PDO target moves. | |
| # A flag is evidence to inspect, not a diagnosis of the motor or bus. | |
| plateaus = [] | |
| start = 0 | |
| for end in range(1, len(rows) + 1): | |
| if end < len(rows) and rows[end]["position_counts"] == rows[start]["position_counts"]: | |
| continue | |
| last = end - 1 | |
| seconds = times[last] - times[start] | |
| target_span = max(targets[start:end]) - min(targets[start:end]) | |
| if seconds >= 0.05 and target_span >= 0.03: | |
| plateaus.append({"start_s": times[start], "duration_ms": seconds * 1000, | |
| "pdo_target_span_deg": target_span, | |
| "cycle_advanced": cycles[last] > cycles[start]}) | |
| start = end | |
| # Long stretches of the same cycle suggest stale feedback or a stalled | |
| # backend; the API does not provide a hardware timestamp for each PDO. | |
| stale_max = 0.0 | |
| start = 0 | |
| for end in range(1, len(rows) + 1): | |
| if end < len(rows) and cycles[end] == cycles[start]: | |
| continue | |
| stale_max = max(stale_max, times[end - 1] - times[start]) | |
| start = end | |
| errors = [abs(t - a) for t, a in zip(targets, actual)] | |
| middle_metrics = None | |
| period = float(metadata.get("period_s", 0)) | |
| cycles_count = int(metadata.get("cycles", 0)) | |
| if period > 0 and cycles_count >= 3: | |
| origin = float(metadata.get("prepare_s", 0)) + period | |
| end = origin + period * (cycles_count - 2) | |
| middle = [r for r in rows if origin <= float(r["t_s"]) <= end] | |
| if len(middle) >= 10: | |
| middle_metrics = tracking_metrics(middle) | |
| ts = [float(r["t_s"]) for r in middle] | |
| for name, column in [("target_fit", "pdo_target_deg"), ("actual_fit", "actual_deg")]: | |
| middle_metrics[name] = sine_fit(ts, [float(r[column]) for r in middle], period, origin) | |
| phase_difference = (middle_metrics["target_fit"]["phase_rad"] | |
| - middle_metrics["actual_fit"]["phase_rad"]) | |
| phase_difference = (phase_difference + math.pi) % (2 * math.pi) - math.pi | |
| middle_metrics["equivalent_phase_lag_s"] = phase_difference * period / (2 * math.pi) | |
| middle_metrics["interval_s"] = [origin, end] | |
| return { | |
| "file": str(path), "joint": joint, "phase": phase, "samples": len(rows), | |
| "metadata": metadata, | |
| "duration_s": times[-1] - times[0], | |
| "observed_command_rate_hz": (len(rows) - 1) / (times[-1] - times[0]), | |
| "command_gap_ms": {"median": median(gaps), "p99": percentile(gaps, 0.99), | |
| "max": max(gaps), "over_5ms": sum(g > 5 for g in gaps), | |
| "nominal": nominal_ms, | |
| "over_twice_nominal": sum(g > 2 * nominal_ms for g in gaps)}, | |
| "observed_control_cycles_per_s": (cycles[-1] - cycles[0]) / (times[-1] - times[0]), | |
| "max_same_cycle_span_ms": stale_max * 1000, | |
| "actual_span_deg": max(actual) - min(actual), | |
| "pdo_target_span_deg": max(targets) - min(targets), | |
| "pdo_following_error_deg": {"p99": percentile(errors, 0.99), "max": max(errors)}, | |
| "tracking": tracking_metrics(rows), | |
| "full_amplitude_middle": middle_metrics, | |
| "last_sample_target_minus_actual_deg": targets[-1] - actual[-1], | |
| "final_offset_from_first_sample_deg": actual[-1] - actual[0], | |
| "working_counters_seen": sorted({int(r["working_counter"]) for r in rows}), | |
| "error_codes_seen": sorted({int(r["error_code"]) for r in rows}), | |
| "modes_seen": sorted({int(r["mode"]) for r in rows}), | |
| "encoder_plateaus_while_target_moves": plateaus, | |
| "note": "Feedback is sampled by the application, not a lossless per-PDO trace. " | |
| "PDO target is a software write echo; it does not confirm drive receipt. " | |
| "Inspect plateaus with command gaps, cycle progress and onsite observations. " | |
| "Phase lag is a sinusoidal frequency-response estimate, not measured network delay. " | |
| "Simulation cannot establish real motor smoothness.", | |
| } | |
| def main(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("csv", type=Path) | |
| parser.add_argument("--joint", type=int, default=6) | |
| parser.add_argument("--phase", choices=["all", "prepare", "oscillate", "hold"], default="all") | |
| args = parser.parse_args() | |
| result = analyze(args.csv, args.joint, args.phase) | |
| if not math.isfinite(result["actual_span_deg"]): | |
| raise ValueError("non-finite position in capture") | |
| print(json.dumps(result, indent=2, ensure_ascii=False)) | |
| if __name__ == "__main__": | |
| main() | |