File size: 5,879 Bytes
6c0b843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Compare delivered 3D joint centres with a paired Theia C3D, without fitting to predictions.

This is an inter-method comparison, not marker-based ground truth. Requires ezc3d.
Run: python tools/validate_pitching_reference.py --reference-dir PATH --alignment PATH
"""

import argparse
import hashlib
import json
from pathlib import Path

import numpy as np

from baseball_batting.pitching_geometry import curves
from baseball_batting.sam_motion import MHR

SEGMENTS = {f"{side}_{joint}": f"{short}_{segment}_4X4"
            for side, short in [("left", "l"), ("right", "r")]
            for joint, segment in [("hip", "thigh"), ("knee", "shank"), ("ankle", "foot"),
                                   ("shoulder", "uarm"), ("elbow", "larm"), ("wrist", "hand")]}


def comparison(predicted, reference):
    valid = np.isfinite(predicted) & np.isfinite(reference)
    delta = predicted[valid] - reference[valid]
    if not len(delta):
        return {"n": 0}
    return {"n": int(len(delta)), "bias": float(np.mean(delta)),
            "mae": float(np.mean(abs(delta))), "median_absolute_difference": float(np.median(abs(delta))),
            "p95_absolute_difference": float(np.percentile(abs(delta), 95)),
            "rmse": float(np.sqrt(np.mean(delta ** 2)))}


def compare(directory, alignment_path):
    import ezc3d
    manifest = json.loads((directory / "manifest.json").read_text())
    provenance = json.loads((directory / "provenance.json").read_text())
    frames = np.asarray(provenance["original_frame_indices"], int)
    records = [json.loads(line) for line in (directory / "motion.jsonl").read_text().splitlines()]
    assert len(records) == len(frames), "Reference mapping must cover every delivered frame"
    predicted = np.full((len(frames), 70, 3), np.nan)
    export_rotation = np.asarray(manifest["coordinates"]["camera_to_export_rotation"])
    for i, row in enumerate(records):
        assert row["source_frame_index"] == i
        for name in SEGMENTS:
            j = row["joints"][name]
            if j["position"] is not None and j["status"] == "estimated":
                predicted[i, MHR[name]] = np.asarray(j["position"]) @ export_rotation
    alignment = json.loads(alignment_path.read_text())
    rotation = np.asarray(alignment["rotation"])
    c = ezc3d.c3d(str(directory / "theia.c3d"))
    labels = c["parameters"]["ROTATION"]["LABELS"]["value"]
    raw = c["data"]["rotations"]
    opts = manifest["pipeline"].get("calculation_inputs", manifest["pipeline"]["inputs"])
    hand = opts["handedness"]
    estimate = curves(predicted, hand, opts.get("up_vector"))
    output = {"scope": "Single trial, single camera; SAM3D vs paired Theia markerless reference; not absolute accuracy",
              "source_provenance": provenance, "alignment_sha256": hashlib.sha256(alignment_path.read_bytes()).hexdigest(),
              "analysis_id": manifest["analysis_id"], "model": manifest.get("model"),
              "alignment_fitted_to_model_predictions": False, "offset_sensitivity": {},
              "limitations": ["Theia is another pose estimator, not marker-based ground truth.",
                              "Published camera alignment is provisional and was fitted using all eight cameras.",
                              "Body centre definitions can differ between models.",
                              "No independent physical synchronization validation; offsets zero and one are compared.",
                              "One athlete, camera and delivery cannot validate general pitching accuracy."]}
    for offset in (0, 1):
        ref = np.full_like(predicted, np.nan)
        for name, label in SEGMENTS.items():
            ref[:, MHR[name]] = raw[:3, 3, labels.index(label), frames + offset].T * .001
        values = curves(ref, hand, [0, 0, 1])
        metrics = {}
        for key in ("knee", "elbow", "torso", "separation", "span"):
            a, b = estimate[key], values[key]
            if key == "separation":
                delta = (a - b + 180) % 360 - 180
                metrics[key] = comparison(delta, np.zeros_like(delta))
            else:
                metrics[key] = comparison(a, b)
        ref_camera = ref @ rotation.T
        joint_indices = [MHR[name] for name in SEGMENTS]
        pred_root = (predicted[:, MHR["left_hip"]] + predicted[:, MHR["right_hip"]]) / 2
        ref_root = (ref_camera[:, MHR["left_hip"]] + ref_camera[:, MHR["right_hip"]]) / 2
        errors = np.linalg.norm((predicted - pred_root[:, None])[:, joint_indices] -
                                (ref_camera - ref_root[:, None])[:, joint_indices], axis=-1) * 100
        per_joint = {name: comparison(errors[:, i], np.zeros(len(frames))) for i, name in enumerate(SEGMENTS)}
        output["offset_sensitivity"][str(offset)] = {"angle_differences_deg_distance_cm": metrics,
            "root_relative_joint_difference_cm": per_joint,
            "events": {event: {key: {"model": float(estimate[key][index]), "reference": float(values[key][index])}
                               for key in ("knee", "elbow", "torso", "separation")
                               if np.isfinite(estimate[key][index]) and np.isfinite(values[key][index])}
                       for event, index in {"foot_strike": opts["windows"][0]["foot_strike_frame"],
                                            "release": opts["release_frame"]}.items()}}
    (directory / "reference-comparison.json").write_text(json.dumps(output, indent=2, allow_nan=False) + "\n")
    return output


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--reference-dir", type=Path, required=True)
    parser.add_argument("--alignment", type=Path, required=True)
    args = parser.parse_args()
    result = compare(args.reference_dir, args.alignment)
    print(json.dumps(result["offset_sensitivity"], indent=2))