File size: 4,376 Bytes
4bcbe8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#!/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()