"""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()