File size: 6,476 Bytes
e302b11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/usr/bin/env python3
"""Export a receive-only Piper capture and compare fresh target/feedback samples."""

from __future__ import annotations

import argparse
import csv
import json
from pathlib import Path

import numpy as np


def save_csv(path: Path, columns: list[str], rows) -> None:
    with path.open("x", newline="", encoding="utf-8") as stream:
        writer = csv.writer(stream)
        writer.writerow(columns)
        writer.writerows(rows)


def interval_stats(t: np.ndarray) -> dict:
    if len(t) < 2:
        return {"samples": len(t)}
    gaps = np.diff(t)
    return {
        "samples": len(t), "median_gap_ms": float(np.median(gaps) * 1000),
        "p95_gap_ms": float(np.percentile(gaps, 95) * 1000),
        "max_gap_ms": float(gaps.max() * 1000),
        "gaps_over_100ms": [{"from_sec": float(t[i]), "to_sec": float(t[i+1]),
                              "gap_sec": float(gaps[i])} for i in np.where(gaps > 0.1)[0]],
    }


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("capture", type=Path)
    args = parser.parse_args()
    capture = args.capture.resolve()
    output = capture / "analysis"
    output.mkdir(exist_ok=False)
    summary = json.loads((capture / "summary.json").read_text())
    before = json.loads((capture / "link_before.json").read_text())
    after = json.loads((capture / "link_after.json").read_text())
    samples = [json.loads(line) for line in (capture / "joint_samples.jsonl").read_text().splitlines()]
    groups = sorted({(row["kind"], row["offset"]) for row in samples})
    data = {}
    exported = []
    for kind, offset in groups:
        selected = [row for row in samples if (row["kind"], row["offset"]) == (kind, offset)]
        times = np.array([row["time_sec"] for row in selected])
        angles = np.array([row["joint_deg"] for row in selected])
        if not np.all(np.isfinite(angles)) or not np.all(np.diff(times) > 0):
            raise ValueError(f"nonfinite angles or nonmonotonic complete samples: {kind}/{offset}")
        data[kind, offset] = (times, angles)
        name = f"{kind}_joints_offset_0x{offset:02X}.csv"
        save_csv(output / name, ["host_relative_time_sec"] + [f"joint_{j}_deg" for j in range(1, 7)],
                 ([t, *q] for t, q in zip(times, angles, strict=True)))
        exported.append(name)

    grippers = {}
    raw_count = 0
    with (capture / "frames.jsonl").open() as stream:
        for line in stream:
            frame = json.loads(line)
            raw_count += 1
            decoded = frame.get("decoded")
            if decoded and decoded["kind"] in ("target_gripper", "feedback_gripper"):
                key = (decoded["kind"], decoded["offset"])
                grippers.setdefault(key, []).append([frame["time_sec"], frame["host_monotonic_ns"],
                    frame["kernel_timestamp_sec"], decoded["opening_mm"], decoded["status_or_command_byte"]])
    if raw_count != summary["received_frames"]:
        raise ValueError("raw frame count does not match capture summary")
    gripper_stats = {}
    for (kind, offset), rows in grippers.items():
        name = f"{kind}_offset_0x{offset:02X}.csv"
        save_csv(output / name, ["host_relative_time_sec", "host_monotonic_ns", "kernel_timestamp_sec",
                                "opening_mm", "status_or_command_byte"], rows)
        exported.append(name)
        openings = [row[3] for row in rows]
        gripper_stats[f"{kind}_0x{offset:02X}"] = {"samples": len(rows),
            "min_opening_mm": min(openings), "max_opening_mm": max(openings)}

    # Only compare the default pair here. Other offsets remain separately exported;
    # a shared numerical offset by itself does not establish physical arm pairing.
    comparison = None
    if ("target", 0) in data and ("feedback", 0) in data:
        tt, qt = data["target", 0]
        tf, qf = data["feedback", 0]
        target_index = np.searchsorted(tt, tf, side="right") - 1
        mask = target_index >= 0
        mask &= tf - tt[np.maximum(target_index, 0)] <= 0.05
        if mask.any():
            err = qf[mask] - qt[target_index[mask]]
            correlations = []
            for joint in range(6):
                target_values, feedback_values = qt[target_index[mask], joint], qf[mask, joint]
                correlations.append(float(np.corrcoef(target_values, feedback_values)[0, 1])
                                    if target_values.std() > 1e-9 and feedback_values.std() > 1e-9 else None)
            comparison = {
                "method": "each feedback sample versus most recent target; target age <=50ms; no delay compensation",
                "matched_feedback_samples": int(mask.sum()), "unmatched_feedback_samples": int((~mask).sum()),
                "mae_deg_by_joint": np.mean(np.abs(err), axis=0).tolist(),
                "p95_absolute_error_deg_by_joint": np.percentile(np.abs(err), 95, axis=0).tolist(),
                "max_absolute_error_deg_by_joint": np.max(np.abs(err), axis=0).tolist(),
                "correlation_by_joint": correlations,
            }

    metrics = {
        "capture": str(capture), "received_frames": raw_count, "duration_sec": summary["duration_sec"],
        "streams": {f"{kind}_0x{offset:02X}": interval_stats(times)
                    for (kind, offset), (times, angles) in data.items()},
        "default_pair_comparison": comparison, "grippers": gripper_stats,
        "rx_errors_delta": after["stats64"]["rx"]["errors"] - before["stats64"]["rx"]["errors"],
        "rx_dropped_delta": after["stats64"]["rx"]["dropped"] - before["stats64"]["rx"]["dropped"],
        "tx_packets_delta": after["stats64"]["tx"]["packets"] - before["stats64"]["tx"]["packets"],
        "csv_files": exported,
        "limits": ["Message roles are inferred from SDK CAN IDs, not physical serial identification.",
                   "Host reception time includes bus, USB and process scheduling delays.",
                   "No source sequence counter is available; zero interface drops is not proof of zero upstream loss.",
                   "Command gaps remain gaps; held targets older than 50ms are excluded from the comparison.",
                   "This observation does not calibrate physical pose accuracy or camera synchronization."],
    }
    (output / "tracking_analysis.json").write_text(json.dumps(metrics, indent=2) + "\n")
    print(json.dumps(metrics, indent=2))


if __name__ == "__main__":
    main()