"""Per-swing 2D face-on hitting metrics from OBP landmarks (run with python -I). usage: python -I compute_hitting_metrics.py LANDMARKS_CSV METADATA_CSV POI_CSV OUT_DIR Writes OUT_DIR/swing_metrics_hitting.csv (long: one row per swing x camera config) and OUT_DIR/swing_validation_hitting.csv (3D reference values per swing). Lab frame (OBP README): +x home->pitcher, +y toward RH batter's box, +z up. Camera facing the hitter's chest looks along the lateral (y) axis: image u = x (toward pitcher), image v = z (up). (Task text said image x = lateral axis; physically a chest-facing camera sees the pitcher-catcher axis horizontally, so the stride is horizontal. See report.) Left-handed swings are mirrored (y -> -y) so every hitter is a RH-equivalent and yaw sign is body-relative. Yaw +theta: camera rotated about vertical so u = x cos(t) + y sin(t) (positive = camera swung toward the catcher/pitcher axis in the RH-equivalent frame); tilt phi: v' = z cos(p) + depth sin(p). """ import sys, math import numpy as np import pandas as pd lm_path, meta_path, poi_path, out_dir = sys.argv[1:5] IN = 0.0254 QUIET_THR = 0.15 # m/s, whole-body speed below this = "still" QUIET_S = 0.10 # must be still this long SMOOTH = 5 # frames (360 Hz) moving-average for positions CONFIGS = {"base": (0, 0), "yaw+10": (10, 0), "yaw-10": (-10, 0), "yaw+20": (20, 0), "yaw-20": (-20, 0), "tilt3": (0, 3), "yaw+10_tilt3": (10, 3), "yaw-10_tilt3": (-10, 3)} def sm(a): return pd.DataFrame(a).rolling(SMOOTH, center=True, min_periods=1).mean().values def ang3(a, b, c): v1, v2 = a - b, c - b cs = np.sum(v1 * v2, -1) / (np.linalg.norm(v1, axis=-1) * np.linalg.norm(v2, axis=-1)) return np.degrees(np.arccos(np.clip(cs, -1, 1))) def tilt_lead_high(lead, back): # lead/back: (...,2) image (u,v); positive = lead higher; uses |du| d = lead - back return np.degrees(np.arctan2(d[..., 1], np.abs(d[..., 0]))) def project(P, yaw, tilt): """P: (n,3) lab (mirrored to RH-equivalent) -> (n,2) image (u, v) in metres.""" t, p = math.radians(yaw), math.radians(tilt) u = P[:, 0] * math.cos(t) + P[:, 1] * math.sin(t) d = -P[:, 0] * math.sin(t) + P[:, 1] * math.cos(t) # depth along optical axis v = P[:, 2] * math.cos(p) + d * math.sin(p) return np.stack([u, v], 1) def idx_at(time, t): return int(np.argmin(np.abs(time - t))) def _smooth_v(x, dt, n): v = np.gradient(x, dt, axis=0) return pd.DataFrame(v).rolling(n, center=True, min_periods=1).mean().values def app_like_events(time, I, Jall, i_fp, i_ct, H): """Re-implementation (on lab data, base camera, units of body height H) of the app's rules in baseball-engine/baseball_mvp/events.py: swing_start, stride, load_start, stance_set. fp/contact come from OBP. I: dict of base-projection (n,2) metres; Jall: list of (n,2) metre arrays for body-speed. Returns dict(load_start, stance_set, flags).""" dt = float(np.median(np.diff(time))) fps = 1 / dt ns = max(1, int(round(0.067 * fps))) n = i_ct + int(0.1 * fps) + 1 # rep ends shortly after contact n = min(n, len(time)) t = time[:n] def spd(x): return np.linalg.norm(_smooth_v(x[:n] / H, dt, ns), axis=1) wsp = (spd(I["lwrist"]) + spd(I["rwrist"])) / 2 peak = int(np.argmax(wsp[: i_ct + int(0.1 * fps) + 1])) thr = max(0.6, 0.25 * wsp[peak]) k = peak while k > 0 and not wsp[k] < thr: k -= 1 swing_start = k + 1 if (k > 0 or wsp[0] < thr) else None ref = swing_start if swing_start is not None else peak flags = {"swing_start_found": swing_start is not None} # stride (lead foot move): baseline = median ankle over [0, stance_hi) hi = min(ref + int(0.1 * fps), i_ct) stance_hi = max(2, ref - int(0.5 * fps)) p = I["lead_ankle"][:n] / H bx, by = np.median(p[:stance_hi, 0]), np.median(p[:stance_hi, 1]) d = np.fmax(by - p[:, 1], p[:, 0] - bx) over = [i for i in range(stance_hi, max(stance_hi, hi)) if d[i] >= 0.03] stride = None first_moved = None if over: first_moved = over[0] kk = over[0] while kk > 0 and d[kk - 1] > 0.03 / 4: kk -= 1 stride = kk # load start: hands move backward (away from pitcher; image u decreasing) before swing hands = (I["lwrist"][:n] + I["rwrist"][:n]) / 2 / H hx = hands[:, 0] w0 = max(0, ref - int(round(1.0 * fps))) seg = hx[w0:ref + 1] load = None hs = pd.Series(hx).rolling(ns, center=True, min_periods=1).mean().values ml = w0 + int(np.flatnonzero(seg <= seg.min() + 0.01)[0]) step = 0.03 / fps kk = ml while kk > 0 and hs[kk - 1] - hs[kk] > step: kk -= 1 if (hs[kk] - hs[ml]) >= 0.03 and kk < ref: load = kk if stride is not None: load = min(load, stride) flags["load_from_hands"] = load is not None if load is None: # app would report load_start missing; we fall back so the swing is usable load = stride if stride is not None else ref flags["load_fallback"] = 1 # stance set: last still run before load allv = np.stack([np.linalg.norm(_smooth_v(a[:n] / H, dt, ns), axis=1) for a in Jall], 1) second = -np.sort(-allv, axis=1)[:, 1] fin = second thr_s = max(0.15, 2 * np.percentile(fin, 10)) ok = fin[: load + 1] < thr_s minlen = int(round(0.25 * fps)) runs, i = [], 0 while i < len(ok): if ok[i]: j = i while j + 1 < len(ok) and ok[j + 1]: j += 1 if j - i + 1 >= minlen: runs.append((i, j)) i = j + 1 else: i += 1 stance = runs[-1][1] if runs else None flags["stance_found"] = stance is not None if stance is None: stance = load fp_app = None if first_moved is not None: sp_a = np.linalg.norm(_smooth_v(I["lead_ankle"][:n] / H, dt, ns), axis=1) hold = max(1, int(round(0.067 * fps))) for i in range(first_moved + 1, min(i_ct, n - hold) + 1): if np.all(sp_a[i:i + hold] < 0.25): fp_app = i break return {"fp_app": fp_app, "load_start": load, "stance_set": stance, "swing_start": swing_start if swing_start is not None else peak, "stride": stride, **flags} 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, vrows = [], [] for sw, g in lm.groupby("session_swing", sort=False): if sw not in meta.index: continue m = meta.loc[sw] side = m.hitter_side H = m.session_height_in * IN g = g.sort_values("time") time = g.time.values fp10, fp100, ct = g.fp_10_time.iloc[0], g.fp_100_time.iloc[0], g.contact_time.iloc[0] # PRIMARY foot plant = OBP fp_100 (100% bodyweight on lead plate): the app's rule (lead ankle speed < 0.25 H/s # for 67 ms) lands a median +8 ms from fp_100 but +53 ms from fp_10 (see report). Fallback: fp_10 + 47 ms # (median fp_10->fp_100 gap in the data) when fp_100 is missing. fp_src = "fp100" fp = fp100 if not np.isfinite(fp): if np.isfinite(fp10): fp, fp_src = fp10 + 0.047, "fp10+47ms" else: continue L, R = ("l", "r") if side == "R" else ("r", "l") # lead = opposite of batting hand def pt(name): a = g[[name + "_x", name + "_y", name + "_z"]].values.astype(float) if side == "L": a = a * np.array([1, -1, 1]) return sm(a) nm = {"hip": lambda s: "left_hip" if s == "l" else "right_hip"} J = {"lead_hip": pt("left_hip" if L == "l" else "right_hip"), "back_hip": pt("left_hip" if L == "r" else "right_hip"), "lead_knee": pt(L + "kjc"), "lead_ankle": pt(L + "ajc"), "back_ankle": pt(R + "ajc"), "lead_sh": pt(L + "sjc"), "back_sh": pt(R + "sjc"), "head": pt("thorax_prox"), "lwrist": pt("lwjc"), "rwrist": pt("rwjc"), "lelbow": pt("lejc"), "relbow": pt("rejc"), "lknee": pt("lkjc"), "rknee": pt("rkjc")} J["hipmid"] = (J["lead_hip"] + J["back_hip"]) / 2 J["shmid"] = (J["lead_sh"] + J["back_sh"]) / 2 i_fp, i_ct = idx_at(time, fp), idx_at(time, ct) if i_ct <= i_fp: continue Ib = {k: project(v, 0, 0) for k, v in J.items()} Jall = [Ib[k] for k in ("lead_hip", "back_hip", "lead_knee", "lead_ankle", "back_ankle", "lead_sh", "back_sh", "head", "lwrist", "rwrist", "lelbow", "relbow", "lknee", "rknee")] ev = app_like_events(time, Ib, Jall, i_fp, i_ct, H) i_ls, i_st = ev["load_start"], ev["stance_set"] i_fpapp = ev["fp_app"] never_quiet = int(not ev["stance_found"]) if i_ls >= i_fp: # load start must precede foot plant continue # ---- 3D reference values kn3 = ang3(J["lead_hip"], J["lead_knee"], J["lead_ankle"]) v3 = {"swing": sw, "knee3d_fp": kn3[i_fp], "knee3d_ct": kn3[i_ct], "stride3d_x": J["lead_ankle"][i_fp, 0] - J["lead_ankle"][i_ls, 0], "stride3d_norm": np.linalg.norm((J["lead_ankle"][i_fp] - J["lead_ankle"][i_ls])[:2]), "sh_yaw_fp": math.degrees(math.atan2(*(J["lead_sh"][i_fp] - J["back_sh"][i_fp])[[0, 1]][::-1])), "hip_yaw_fp": math.degrees(math.atan2(*(J["lead_hip"][i_fp] - J["back_hip"][i_fp])[[0, 1]][::-1])), "obp_lead_knee_launchpos": poi.loc[sw, "lead_knee_launchpos_x"] if sw in poi.index else np.nan, "obp_xfactor_fp_z": poi.loc[sw, "x_factor_fp_z"] if sw in poi.index else np.nan, "sh_elev3d_ct": math.degrees(math.asin((J["lead_sh"][i_ct,2]-J["back_sh"][i_ct,2])/np.linalg.norm(J["lead_sh"][i_ct]-J["back_sh"][i_ct]))), "fp_app_t": time[i_fpapp] if i_fpapp is not None else np.nan, "fp10": fp10, "fp100": fp100, "contact": ct, "load_start_t": time[i_ls], "stance_t": time[i_st], "fp_t": time[i_fp]} vrows.append(v3) for cname, (yaw, tilt) in CONFIGS.items(): I = {k: project(v, yaw, tilt) for k, v in J.items()} r = {"session_swing": sw, "config": cname, "user": m.user, "level": m.highest_playing_level, "side": side, "height_m": H, "fp_src": fp_src, "never_quiet": never_quiet, "load_from_hands": int(ev["load_from_hands"]), "swing_start_found": int(ev["swing_start_found"])} r["stride_pct_height"] = abs(I["lead_ankle"][i_fp, 0] - I["lead_ankle"][i_ls, 0]) / H * 100 r["foot_plant_to_contact_ms"] = (ct - fp) * 1000 r["fp10_to_contact_ms"] = (ct - fp10) * 1000 if np.isfinite(fp10) else np.nan r["fpapp_to_contact_ms"] = (ct - time[i_fpapp]) * 1000 if i_fpapp is not None else np.nan r["load_tempo_fp10_s"] = (fp10 - time[i_ls]) if np.isfinite(fp10) else np.nan r["load_tempo_fpapp_s"] = (time[i_fpapp] - time[i_ls]) if i_fpapp is not None else np.nan lt = time[i_fp] - time[i_ls] r["load_tempo_s"] = lt r["load_launch_ratio"] = lt / (ct - fp) h = I["head"][i_st:i_ct + 1] r["head_movement_pct_height"] = np.max(np.linalg.norm(h - h[0], axis=1)) / H * 100 # app definition r["head_path_pct_height"] = np.sum(np.linalg.norm(np.diff(h, axis=0), axis=1)) / H * 100 a2 = lambda a, b, c: ang3(np.c_[a, [0]], np.c_[b, [0]], np.c_[c, [0]]) r["lead_knee_angle_contact_deg"] = float(a2(I["lead_hip"][i_ct:i_ct+1], I["lead_knee"][i_ct:i_ct+1], I["lead_ankle"][i_ct:i_ct+1])[0]) r["lead_knee_angle_fp_deg"] = float(a2(I["lead_hip"][i_fp:i_fp+1], I["lead_knee"][i_fp:i_fp+1], I["lead_ankle"][i_fp:i_fp+1])[0]) r["lateral_trunk_tilt_contact_deg"] = float(tilt_lead_high(I["lead_sh"][i_ct], I["back_sh"][i_ct])) sh = tilt_lead_high(I["lead_sh"][i_fp], I["back_sh"][i_fp]) hp = tilt_lead_high(I["lead_hip"][i_fp], I["back_hip"][i_fp]) r["hip_shoulder_separation_foot_plant_deg"] = float(sh - hp) dx = I["lead_ankle"][i_ct, 0] - I["back_ankle"][i_ct, 0] r["com_drift_pct_height"] = (I["hipmid"][i_ct, 0] - I["lead_ankle"][i_ct, 0]) * math.copysign(1, dx) / H * 100 r["stride_sep_fp_pct_height"] = abs(I["lead_ankle"][i_fp, 0] - I["back_ankle"][i_fp, 0]) / H * 100 r["stride_from_clipstart_pct_height"] = abs(I["lead_ankle"][i_fp, 0] - I["lead_ankle"][:max(3, int(0.3 * 360)), 0].mean()) / H * 100 r["shoulder_du_ct_cm"] = abs(I["lead_sh"][i_ct, 0] - I["back_sh"][i_ct, 0]) * 100 tl = I["hipmid"][i_ct] - I["shmid"][i_ct] sd = I["shmid"][i_ct] - I["hipmid"][i_ct] r["trunk_lean_toward_pitcher_ct_deg"] = float(np.degrees(np.arctan2(sd[0], sd[1]))) rows.append(r) pd.DataFrame(rows).to_csv(out_dir + "/swing_metrics_hitting.csv", index=False) pd.DataFrame(vrows).to_csv(out_dir + "/swing_validation_hitting.csv", index=False) print(len(vrows), "swings;", len(rows), "rows")