File size: 6,057 Bytes
6963661
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""Derive pitch-1.1 references with the producer geometry, per-athlete medians.

Reference data: OpenBiomechanics dataset-v1, CC BY-NC-SA 4.0. These are
population descriptions, not technique targets or phone-video validation.
"""

import argparse
import hashlib
from pathlib import Path

import numpy as np
import pandas as pd
import yaml

from ai_coach.pitch_report.v1_1.contract import METRICS
from baseball_batting.coach_geometry import follow_through_frame
from baseball_batting.pitching_geometry import curves, evaluate
from baseball_batting.sam_motion import MHR


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("landmarks")
    parser.add_argument("metadata")
    parser.add_argument("poi")
    parser.add_argument("output")
    args = parser.parse_args()
    lm = pd.read_csv(args.landmarks)
    meta = pd.read_csv(args.metadata).set_index("session_pitch")
    poi = pd.read_csv(args.poi).set_index("session_pitch")
    rows = []
    skipped = 0
    for trial, g in lm.groupby("session_pitch", sort=False):
        if (
            trial not in meta.index
            or trial not in poi.index
            or poi.loc[trial, "pitch_type"] != "FF"
        ):
            continue
        side = poi.loc[trial, "p_throws"]
        if side not in ("R", "L"):
            continue
        hand = "right" if side == "R" else "left"
        lead = "left" if hand == "right" else "right"
        g = g.sort_values("time")
        times = g.time.to_numpy()
        pk, foot, release = [
            float(g[key].iloc[0]) for key in ("pkh_time", "fp_10_time", "BR_time")
        ]
        if (
            not np.isfinite([pk, foot, release]).all()
            or not (0 <= pk < foot < release <= times[-1])
            or not 0.03 <= release - foot <= 0.4
        ):
            skipped += 1
            continue
        indices = {
            key: int(np.argmin(abs(times - t)))
            for key, t in zip(
                ("leg_lift", "foot_strike", "release"), (pk, foot, release)
            )
        }
        indices["early_follow_through"] = follow_through_frame(
            times, indices["release"], len(g) - 1
        )
        points = np.full((len(g), 70, 3), np.nan)
        mapping = {
            lead + "_hip": "lead_hip",
            hand + "_hip": "rear_hip",
            lead + "_knee": "lead_knee_jc",
            hand + "_knee": "rear_knee_jc",
            lead + "_ankle": "lead_ankle_jc",
            hand + "_ankle": "rear_ankle_jc",
            hand + "_shoulder": "shoulder_jc",
            lead + "_shoulder": "glove_shoulder_jc",
            hand + "_elbow": "elbow_jc",
            hand + "_wrist": "wrist_jc",
        }
        for target, source in mapping.items():
            points[:, MHR[target]] = (
                g[[source + "_" + axis for axis in "xyz"]]
                .rolling(5, center=True, min_periods=1)
                .mean()
                .to_numpy()
            )
        values = curves(points, hand, [0, 0, 1])
        for key, spec in METRICS.items():
            if key == "ankle_span_at_foot_strike_cm":
                continue  # Absolute ankle spacing is not a stature-matched technique benchmark.
            frames = [indices[event] for event in spec[3]]
            value = (
                evaluate(key, frames, values, times)
                if all(i is not None for i in frames)
                else np.nan
            )
            if np.isfinite(value):
                rows.append(
                    {
                        "trial": trial,
                        "athlete": meta.loc[trial, "user"],
                        "level": meta.loc[trial, "playing_level"],
                        "hand": hand,
                        "metric": key,
                        "value": value,
                    }
                )
    df = pd.DataFrame(rows)
    result = {
        "version": "2026-11-02.1",
        "definition_version": "pitch-1.1",
        "source_reference": "OpenBiomechanics dataset-v1 pitching landmarks, per-athlete medians; https://github.com/drivelineresearch/openbiomechanics/releases/tag/dataset-v1",
        "license": "CC BY-NC-SA 4.0; derived data retains source attribution and terms",
        "source_sha256": {
            key: hashlib.sha256(Path(getattr(args, key)).read_bytes()).hexdigest()
            for key in ("landmarks", "metadata", "poi")
        },
        "n_pitches": int(df.trial.nunique()),
        "n_athletes": int(df.athlete.nunique()),
        "excluded_event_trials": skipped,
        "events": "pkh_time, fp_10_time, BR_time, BR+100ms; 5-sample centred landmark mean",
        "limitations": "Fastball reference distributions, not ideal technique. Visible foot strike approximates a force threshold; model/lab joint definitions and physical video accuracy remain unvalidated.",
        "metrics": {key: {"cells": {}} for key in METRICS},
    }
    for (key, hand, level), group in df.groupby(["metric", "hand", "level"]):
        if level not in ("high_school", "college"):
            continue
        medians = group.groupby("athlete").value.median()
        if len(medians) < 10:
            continue
        low, q1, q3, high = np.percentile(medians, [10, 25, 75, 90])
        result["metrics"][key]["cells"][f"{hand}/{level}"] = {
            "population": f"{level.replace('_', ' ').title()} {hand}-handed pitchers ({len(medians)} athletes)",
            "n_athletes": len(medians),
            "n_pitches": int(group.trial.nunique()),
            "on_target": {"lower": round(float(q1), 3), "upper": round(float(q3), 3)},
            "satisfactory": {
                "lower": round(float(low), 3),
                "upper": round(float(high), 3),
            },
        }
    Path(args.output).write_text(
        yaml.safe_dump(result, sort_keys=False, allow_unicode=True)
    )
    print({k: result[k] for k in ("n_pitches", "n_athletes", "excluded_event_trials")})
    print({key: list(value["cells"]) for key, value in result["metrics"].items()})


if __name__ == "__main__":
    main()