"""Reference intervals for the AI-coach swing payload contract v1.0 metrics, from OBP 3D hitting landmarks (run with python -I). usage: python -I compute_contract_v1_benchmarks.py LANDMARKS_CSV METADATA_CSV POI_CSV OUT_DIR Writes OUT_DIR/contract_v1_swings.csv (one row per swing) and OUT_DIR/contract_v1_benchmarks.json (aggregates). The formulas follow the contract's section 5 exactly, so a benchmark and a measurement share one definition: hip_shoulder_separation_at_{foot_down,contact} = wrap180(shoulder_heading - hip_heading), degrees, [-180, 180). Lines run anatomical left -> right (left joint centre to right joint centre), projected on the horizontal plane (lab x-y; +z is up). Heading = atan2(dy, dx) in fixed lab axes, so positive = shoulder line counter-clockwise from the hip line seen from above. NOT mirrored for left-handed hitters (the contract keeps one convention for both sides), so intervals are reported per batting side. stride_relative_length = 100 * |horizontal(r(front_foot_down) - r(stride_start))| cm, r = lead ankle - rear ankle. Lab frame (OBP README): +x home -> pitcher, +y toward the RH batter's box, +z up. Joint centres are model-derived. Events: contact = OBP contact_time. front_foot_down = OBP fp_10_time (first touch, 10% bodyweight) as the primary "landing" event; fp_100_time (full plant) is reported as a sensitivity variant because the contract allows "landing or plant" and the two differ. OBP has no stride-start time, so stride_start is detected here (see stride_start()); two speed thresholds are reported as a sensitivity check. """ import sys, json import numpy as np import pandas as pd lm_path, meta_path, poi_path, out_dir = sys.argv[1:5] SMOOTH = 5 # frames (360 Hz) centred moving average on positions STILL_S = 0.10 # the lead ankle must be still this long before the stride begins STILL_THRESHOLDS = (0.15, 0.25) # m/s horizontal lead-ankle speed; first one is primary LEVEL_MAP = {"high_school": "high_school", "college": "college", "independent": "pro", "milb": "pro"} PCTS = [5, 10, 25, 50, 75, 90, 95] def sm(a): return pd.DataFrame(a).rolling(SMOOTH, center=True, min_periods=1).mean().values def wrap180(a): return (np.asarray(a) + 180.0) % 360.0 - 180.0 def heading(left, right): d = right - left return np.degrees(np.arctan2(d[..., 1], d[..., 0])) def separation(P, i): return float(wrap180(heading(P["lsjc"][i], P["rsjc"][i]) - heading(P["left_hip"][i], P["right_hip"][i]))) def stride_start(lead, dt, i_fd, thr): """Last frame of the final still period (horizontal lead-ankle speed < thr for >= STILL_S) before front_foot_down. Returns None when the ankle never rests long enough before landing.""" v = np.linalg.norm(np.gradient(lead[:, :2], dt, axis=0), axis=1) need = max(1, int(round(STILL_S / dt))) run = 0 for i in range(i_fd, -1, -1): if v[i] < thr: run += 1 if run >= need: return i + need - 1 # the still run spans i .. i+need-1; stride starts at its end else: run = 0 return None def stride_cm(lead, rear, i0, i1): r = lead[:, :2] - rear[:, :2] return float(100.0 * np.linalg.norm(r[i1] - r[i0])) lm = pd.read_csv(lm_path) meta = pd.read_csv(meta_path).set_index("session_swing") poi = pd.read_csv(poi_path).set_index("session_swing") rows = [] for sw, g in lm.groupby("session_swing", sort=False): if sw not in meta.index: continue m = meta.loc[sw] t = g.time.values dt = float(np.median(np.diff(t))) P = {k: sm(g[[f"{k}_x", f"{k}_y", f"{k}_z"]].values) for k in ("left_hip", "right_hip", "lsjc", "rsjc", "lajc", "rajc")} lead, rear = (P["lajc"], P["rajc"]) if m.hitter_side == "R" else (P["rajc"], P["lajc"]) ev = {k: g[k].iloc[0] for k in ("fp_10_time", "fp_100_time", "contact_time")} idx = {k: (int(np.argmin(np.abs(t - v))) if pd.notna(v) else None) for k, v in ev.items()} row = {"session_swing": sw, "user": m.user, "level": LEVEL_MAP.get(m.highest_playing_level), "batting_hand": "right" if m.hitter_side == "R" else "left", "height_cm": m.session_height_in * 2.54, "x_factor_fp_z_obp": poi.loc[sw, "x_factor_fp_z"] if sw in poi.index else np.nan} i_fd, i_fp, i_ct = idx["fp_10_time"], idx["fp_100_time"], idx["contact_time"] ordered = i_fd is not None and i_ct is not None and i_fd < i_ct row["events_ok"] = ordered row["sep_fd_deg"] = separation(P, i_fd) if ordered else np.nan row["sep_fp100_deg"] = separation(P, i_fp) if (i_fp is not None and i_ct is not None and i_fp < i_ct) else np.nan row["sep_contact_deg"] = separation(P, i_ct) if ordered else np.nan for j, thr in enumerate(STILL_THRESHOLDS): s = stride_start(lead, dt, i_fd, thr) if ordered else None key = "stride_cm" if j == 0 else f"stride_cm_thr{thr}" row[key] = stride_cm(lead, rear, s, i_fd) if s is not None else np.nan if j == 0: row["stride_start_found"] = s is not None row["stride_dur_ms"] = (t[i_fd] - t[s]) * 1000 if s is not None else np.nan row["stride_cm_fp100"] = stride_cm(lead, rear, s, i_fp) if (s is not None and i_fp is not None and i_fp > s) else np.nan row["stride_pct_height"] = row["stride_cm"] / row["height_cm"] * 100 rows.append(row) d = pd.DataFrame(rows) d.to_csv(f"{out_dir}/contract_v1_swings.csv", index=False) def stats(df, col): a = df.groupby("user")[col].median().dropna() # athlete medians first, so prolific athletes don't dominate if len(a) < 3: return {"n_athletes": int(len(a))} s = {"n_athletes": int(len(a)), "n_swings": int(df[col].notna().sum())} s.update({f"p{p}": round(float(np.percentile(a, p)), 1) for p in PCTS}) return s METRICS = {"hip_shoulder_separation_at_foot_down": "sep_fd_deg", "hip_shoulder_separation_at_contact": "sep_contact_deg", "stride_relative_length": "stride_cm"} SENSITIVITY = {"separation_at_fp100_instead_of_fp10": "sep_fp100_deg", "stride_to_fp100": "stride_cm_fp100", f"stride_still_threshold_{STILL_THRESHOLDS[1]}": f"stride_cm_thr{STILL_THRESHOLDS[1]}", "stride_pct_height": "stride_pct_height", "stride_duration_ms": "stride_dur_ms"} out = {"n_swings": int(len(d)), "n_athletes": int(d.user.nunique()), "events_ok": int(d.events_ok.sum()), "stride_start_found": int(d.stride_start_found.sum()), "metrics": {}, "sensitivity": {}, "validation": {}} levels = ["all", "high_school", "college", "pro"] for name, col in {**METRICS, **SENSITIVITY}.items(): target = out["metrics"] if name in METRICS else out["sensitivity"] target[name] = {} for hand in ("right", "left"): for lv in levels: sub = d[(d.batting_hand == hand) & ((d.level == lv) | (lv == "all"))] target[name][f"{hand}/{lv}"] = stats(sub, col) v = d[["sep_fd_deg", "x_factor_fp_z_obp", "sep_fp100_deg", "batting_hand"]].dropna() for hand in ("right", "left"): vv = v[v.batting_hand == hand] if len(vv) > 5: out["validation"][f"corr_sep_fp100_vs_obp_x_factor_fp_z/{hand}"] = round(float(np.corrcoef(vv.sep_fp100_deg, vv.x_factor_fp_z_obp)[0, 1]), 3) json.dump(out, open(f"{out_dir}/contract_v1_benchmarks.json", "w"), indent=1) print(json.dumps(out, indent=1))