baseball-engine / data_ref /scripts /analyze_hitting_ranges.py
github-actions[bot]
Automated Deploy: f4f01388c7b26e818cffbd64414eac11381a7891
35e80ff
Raw History Blame
11.3 kB
"""Aggregate per-swing hitting metrics into per-level reference ranges (run with python -I).
usage: python -I analyze_hitting_ranges.py WORK_DIR METADATA_CSV CURRENT_RANGES_YAML OUT_DIR
"""
import sys, json
import numpy as np, pandas as pd, yaml
work, meta_path, cur_path, out = sys.argv[1:5]
d = pd.read_csv(work + "/swing_metrics_hitting.csv")
cur = yaml.safe_load(open(cur_path))["hitting"]
LEVEL_MAP = {"high_school": "hs_varsity", "college": "college", "independent": "pro_ref", "milb": "pro_ref"}
d["app_level"] = d.level.map(LEVEL_MAP)
METRICS = ["stride_pct_height", "stride_sep_fp_pct_height", "foot_plant_to_contact_ms", "load_tempo_s", "load_launch_ratio",
"head_movement_pct_height", "head_path_pct_height", "lead_knee_angle_contact_deg",
"lateral_trunk_tilt_contact_deg", "hip_shoulder_separation_foot_plant_deg", "com_drift_pct_height",
"trunk_lean_toward_pitcher_ct_deg"]
PCTS = [5, 10, 25, 50, 75, 90, 95]
def athlete_medians(df, m):
return df.groupby("user")[m].median()
def stats(df, m):
a = athlete_medians(df, m).dropna()
if len(a) == 0:
return None
s = {"n_athletes": int(len(a)), "n_swings": int(df[m].notna().sum())}
for p in PCTS:
s[f"p{p}"] = float(np.percentile(a, p))
s["mean"] = float(a.mean()); s["sd"] = float(a.std(ddof=1)) if len(a) > 1 else float("nan")
return s
def groups(base):
g = {"hs_varsity": base[base.app_level == "hs_varsity"], "college": base[base.app_level == "college"],
"pro_ref": base[base.app_level == "pro_ref"], "pooled": base}
return g
base = d[d.config == "base"]
res = {}
for m in METRICS:
res[m] = {lv: stats(g, m) for lv, g in groups(base).items()}
# handedness (college only and pooled)
hand = {}
for m in METRICS:
hand[m] = {}
for side in ("R", "L"):
hand[m][side] = stats(base[base.side == side], m)
c = base[base.app_level == "college"]
hand[m]["college_R"] = stats(c[c.side == "R"], m); hand[m]["college_L"] = stats(c[c.side == "L"], m)
# sensitivity: shift of median and p10/p90 (of per-athlete medians) vs base, pooled + per level
sens = {}
for cfg in d.config.unique():
if cfg == "base":
continue
dc = d[d.config == cfg]
sens[cfg] = {}
for m in METRICS:
sens[cfg][m] = {}
for lv in ("hs_varsity", "college", "pooled"):
gb = groups(base)[lv]; gc = groups(dc)[lv]
sb, sc = stats(gb, m), stats(gc, m)
sens[cfg][m][lv] = {"d_p50": sc["p50"] - sb["p50"], "d_p10": sc["p10"] - sb["p10"], "d_p90": sc["p90"] - sb["p90"],
"base_band_width": sb["p90"] - sb["p10"]}
# swing-level paired shift (median abs change per swing) for yaw+-10
paired = {}
for cfg in ("yaw+10", "yaw-10", "yaw+20", "yaw-20", "tilt3"):
dc = d[d.config == cfg].set_index("session_swing"); b = base.set_index("session_swing")
paired[cfg] = {m: float((dc[m] - b[m]).abs().median()) for m in METRICS}
# current bands
def cur_band(m, lv):
c = cur.get(m, {})
L = c.get("levels") if isinstance(c, dict) else None
if not L:
return None
lv2 = {"hs_varsity": "hs_varsity", "college": "college"}.get(lv)
return L.get(lv2) if lv2 else None
curmap = {"stride_pct_height": "stride_pct_height", "stride_sep_fp_pct_height": "stride_pct_height"} # PRD 43-51 compared to both
def current_for(m, lv):
return cur_band(curmap.get(m, m), lv)
CONF = { # (confidence cap, reason)
"foot_plant_to_contact_ms": ("medium", "event definitions differ: OBP contact is marker-derived, app contact is a wrist-speed estimate; OBP fp_100 = full weight on lead plate (first touch fp_10 is ~50 ms earlier and gives 175 ms median)"),
"load_tempo_s": ("low", "depends entirely on load_start definition (app uses backward hand movement; OBP provides no first-move time, reconstructed here)"),
"load_launch_ratio": ("low", "inherits load_tempo uncertainty; ratio of two event-definition-dependent durations"),
"stride_pct_height": ("medium", "ankle travel from reconstructed load start; robust to start definition (clip-start alt. within ~0.3 pp) but 2D lab hitters differ from phone hitters"),
"stride_sep_fp_pct_height": ("medium", "foot-to-foot separation at foot plant; matches the PRD 43-51 number, NOT the app's travel definition"),
"head_movement_pct_height": ("low", "OBP has no head landmark; neck-base (thorax_prox) proxy moves with trunk lean/rotation, so this is an upper bound"),
"head_path_pct_height": ("low", "same proxy problem; path length also noise sensitive"),
"lead_knee_angle_contact_deg": ("low", "chest-facing view sees knee flexion mostly out-of-plane: 2D angle ~30 deg straighter than 3D; strongly yaw dependent"),
"lateral_trunk_tilt_contact_deg": ("low", "at contact the shoulder line is nearly edge-on to a chest-facing camera (median horizontal extent ~4 cm): value is ~90 minus noise and tells nothing about trunk tilt"),
"hip_shoulder_separation_foot_plant_deg": ("low", "2D proxy only; correlation with OBP 3D x-factor at foot plant r~0.33 and opposite sign of covariance"),
"com_drift_pct_height": ("medium", "robust geometry, but hip-joint-centre vs app's hip keypoint offset"),
"trunk_lean_toward_pitcher_ct_deg": ("low", "suggested replacement for lateral tilt; not an app metric yet"),
}
rows = {}
for m in METRICS:
rows[m] = {}
sy = {}
for sgn in ("yaw+10", "yaw-10"):
sy[sgn] = sens[sgn][m]["pooled"]
shift10 = max(abs(sy[s][k]) for s in sy for k in ("d_p50",))
edge10 = {"lo": max(abs(sy[s]["d_p10"]) for s in sy), "hi": max(abs(sy[s]["d_p90"]) for s in sy)}
sy20 = {s: sens[s][m]["pooled"] for s in ("yaw+20", "yaw-20")}
for lv, s in res[m].items():
if s is None:
continue
widen = lv != "pooled" and m not in ("foot_plant_to_contact_ms", "load_tempo_s", "load_launch_ratio")
lo, hi = s["p10"], s["p90"]
material = False
bw = s["p90"] - s["p10"]
if widen:
material = max(edge10["lo"], edge10["hi"], shift10) > 0.1 * bw
if material:
lo -= edge10["lo"]; hi += edge10["hi"]
cb = current_for(m, lv)
a = athlete_medians(groups(base)[lv], m).dropna()
verdict = None; inside = None
if cb is not None:
inside = float(((a >= cb[0]) & (a <= cb[1])).mean())
ratio = (cb[1] - cb[0]) / bw if bw > 0 else float("nan")
if inside < 0.3:
verdict = "shifted/disagrees (only %.0f%% of athlete medians inside)" % (100 * inside)
elif ratio < 0.6:
verdict = "too narrow (current width %.2fx data p10-p90)" % ratio
elif ratio > 1.8:
verdict = "too wide (current width %.2fx data p10-p90)" % ratio
else:
verdict = "roughly agrees (%.0f%% inside, width %.2fx)" % (100 * inside, ratio)
conf, why = CONF[m]
n = s["n_athletes"]
if n < 10:
conf, why = "low", f"only {n} athletes; " + why
elif n < 20 and conf == "medium":
conf = "low" if lv != "pooled" and n < 15 else conf
why = f"small sample ({n} athletes); " + why
entry = {"n_athletes": n, "n_swings": s["n_swings"], **{f"p{p}": round(s[f"p{p}"], 3) for p in PCTS},
"mean": round(s["mean"], 3), "sd": round(s["sd"], 3),
"current_band": None if cb is None else [float(x) for x in cb], "current_band_pct_athletes_inside": None if inside is None else round(inside, 2),
"current_vs_data": verdict,
"proposed_band": [round(lo, 2), round(hi, 2)],
"proposed_band_widened_for_yaw": bool(widen and material),
"confidence_of_proposal": conf, "confidence_reason": why,
"sensitivity_yaw10_shift": {"d_median_plus10": round(sy["yaw+10"]["d_p50"], 3), "d_median_minus10": round(sy["yaw-10"]["d_p50"], 3),
"d_p10_plus10": round(sy["yaw+10"]["d_p10"], 3), "d_p90_plus10": round(sy["yaw+10"]["d_p90"], 3),
"d_p10_minus10": round(sy["yaw-10"]["d_p10"], 3), "d_p90_minus10": round(sy["yaw-10"]["d_p90"], 3),
"scope": "pooled athletes"},
"sensitivity_yaw20_shift": {"d_median_plus20": round(sy20["yaw+20"]["d_p50"], 3), "d_median_minus20": round(sy20["yaw-20"]["d_p50"], 3)},
"yaw_material": bool(material) if widen else None}
if m in ("lateral_trunk_tilt_contact_deg", "hip_shoulder_separation_foot_plant_deg"):
entry["recommend_enable"] = False
rows[m][lv] = entry
json.dump({"res": res, "hand": hand, "sens": sens, "paired": paired, "rows": rows}, open(out + "/analysis_hitting.json", "w"), indent=1, default=float)
# ---- level sample sizes
meta = pd.read_csv(meta_path)
ls = meta.groupby("highest_playing_level").agg(n_athletes=("user", "nunique"), n_swings=("session_swing", "size"))
# ---- yaml
doc = {"meta": {
"source": "OpenBiomechanics Project hitting landmarks (360 Hz joint centres), dataset-v1, CC BY-NC-SA",
"camera_model": "ideal face-on (chest-facing) camera; image u = pitcher-catcher axis, v = vertical; 2D projection",
"statistics": "per-athlete median first, then percentiles across athletes (p5..p95 of athlete medians, mean, SD across athletes)",
"levels": {"hs_varsity": "OBP highest_playing_level == high_school (12 athletes; proxy, mixed ages)",
"hs_jv": "NO DATA - no JV group exists; use hs_varsity numbers with extra caution",
"college": "OBP college", "pro_ref": "OBP independent + milb (reference only)", "pooled": "all athletes"},
"swings_used": int(base.shape[0]), "swings_total_in_obp": int(len(meta)),
"athletes_by_obp_level": {k: int(v) for k, v in ls.n_athletes.items()},
"events": {"foot_plant": "OBP fp_100_time (100% BW on lead plate; matches the app's ankle-settle rule within ~8 ms median); fallback fp_10_time+47 ms when missing",
"contact": "OBP contact_time", "load_start": "reconstructed with the app's own rule (backward hand run), see report",
"stance_set": "reconstructed (last still run); falls back to load_start when none"},
"disclaimer": "typical != ideal; lab marker data, mostly college/pro; not validated on phone pose estimation"},
"metrics": {}}
for m in METRICS:
doc["metrics"][m] = {}
for lv, e in rows[m].items():
doc["metrics"][m][lv] = e
doc["metrics"][m]["hs_jv"] = {"note": "no OBP JV data; mirror hs_varsity proposal with confidence one notch lower",
"proposed_band": list(rows[m]["hs_varsity"]["proposed_band"]), "confidence_of_proposal": "low"}
yaml.safe_dump(doc, open(out + "/hitting_ranges.yaml", "w"), sort_keys=False, default_flow_style=None, width=140)
print(ls)
for m in METRICS:
for lv in ("hs_varsity", "college", "pro_ref", "pooled"):
e = rows[m][lv]
print(f"{m:42s}{lv:11s} n={e['n_athletes']:3d}/{e['n_swings']:3d} p10={e['p10']:8.2f} p50={e['p50']:8.2f} p90={e['p90']:8.2f} cur={e['current_band']} prop={e['proposed_band']} {e['confidence_of_proposal']} | {e['current_vs_data']}")
print(json.dumps(paired, indent=0))