"""Bat geometry and movement (standard section 7.4: handle, tip, blade orientation). Two sources, in order of preference: 1. DETECTED: a bat keypoint model (handle top, toe) trained with train_bat.py from reviewer clicks in the Bat labels tab (models.bat_weights in config.yaml). 2. ESTIMATED: from the batter's hand and forearm keypoints plus standard bat dimensions (registry/equipment.yaml). The bat is assumed to continue the line of the forearms from the hands, with a length scaled from the batter's torso. This ignores wrist cock and foreshortening, so treat it as a rough, low-confidence proxy that is useful for timing (backlift, downswing) more than for exact angles. All values are 2D image-plane estimates.""" import numpy as np from events import KCONF, _speed, torso_length def load_equipment(): from common import CODE, load_yaml p = CODE / "registry" / "equipment.yaml" return load_yaml(p) if p.exists() else {} def bat_length_torso(eq, player_id=None): """Visible bat length (hands to toe) in torso lengths for this player.""" est = (eq or {}).get("estimation", {}) pl = ((eq or {}).get("players") or {}).get(player_id or "", {}) size = pl.get("bat_size", est.get("bat_size", "short_handle_SH")) length = ((eq or {}).get("typical_sizes", {}).get(size) or {}).get("length_cm", 85.0) torso = pl.get("torso_length_cm", est.get("torso_length_cm", 50.0)) return length * est.get("grip_to_toe_fraction", 0.80) / torso, size, length def estimate_from_hands(kpts, scale_torso): """Per frame: handle (hands centre) and toe, from both forearms. NaN where unknown.""" n = len(kpts) tl = torso_length(kpts) out = np.full((n, 2, 2), np.nan) conf = np.zeros(n) if not np.isfinite(tl): return out, conf for i, k in enumerate(kpts): ok = [s for s in ((7, 9), (8, 10)) if k[s[0], 2] > KCONF and k[s[1], 2] > KCONF] if not ok: continue hands = np.mean([k[w, :2] for _, w in ok], axis=0) d = np.mean([k[w, :2] - k[e, :2] for e, w in ok], axis=0) nrm = np.linalg.norm(d) if nrm < 1e-3: continue out[i, 0] = hands out[i, 1] = hands + d / nrm * scale_torso * tl conf[i] = 0.3 * np.mean([min(k[e, 2], k[w, 2]) for e, w in ok]) return out, conf def bat_motion(t, kpts, time_scale, t0_video, events, eq, player_id=None, detected=None): """Bat series and summary measures for one delivery's batter track.""" t = np.asarray(t, float) if len(t) < 5: return None scale, size, length_cm = bat_length_torso(eq, player_id) if detected is not None and np.isfinite(detected).any(): pts, conf, source = detected["pts"], detected["conf"], "model" else: pts, conf = estimate_from_hands(kpts, scale) source = "estimated_from_hands" ok = np.isfinite(pts).all(axis=(1, 2)) if ok.sum() < 5: return None tl = torso_length(kpts) v = pts[:, 1] - pts[:, 0] # angle in the image: 0 = bat pointing straight down, 180 = straight up (toe above hands) ang = np.degrees(np.arctan2(np.abs(v[:, 0]), v[:, 1])) lift = (pts[:, 0, 1] - pts[:, 1, 1]) / tl # toe height above hands, torso units tr = t / time_scale tip_speed = _speed(tr, pts[:, 1], ok, tl) ang_u = np.unwrap(np.radians(np.where(ok, np.degrees(np.arctan2(v[:, 0], v[:, 1])), np.nan))) dang = np.full(len(t), np.nan) for a, b in zip(np.flatnonzero(ok)[:-1], np.flatnonzero(ok)[1:]): if tr[b] > tr[a]: dang[b] = abs(np.degrees(ang_u[b] - ang_u[a])) / (tr[b] - tr[a]) contact = (events.get("bat_ball_contact") or {}).get("t_video") bounce = (events.get("ball_bounce") or {}).get("t_video") t_end = contact or (bounce + 0.3 * time_scale if bounce else t[ok][-1]) pre = ok & (t <= t_end) out = {"source": source, "bat_size": size, "bat_length_cm": length_cm, "confidence": round(float(np.mean(conf[ok])), 3), "space": "image_2d"} if pre.any(): i = int(np.argmax(np.where(pre & np.isfinite(lift), lift, -np.inf))) out["backlift_top"] = {"t_clip": round(float(t[i] - t0_video), 3), "height_torso": round(float(lift[i]), 2), "angle_deg": round(float(ang[i]), 1)} after = ok & (t > t[i]) & np.isfinite(dang) if after.any(): j = int(np.argmax(np.where(after, dang, -np.inf))) out["peak_swing"] = {"t_clip": round(float(t[j] - t0_video), 3), "angular_speed_deg_s": round(float(dang[j]), 0), "toe_speed_torso_s": None if not np.isfinite(tip_speed[j]) else round(float(tip_speed[j]), 1)} if contact: k = int(np.argmin(np.where(ok, np.abs(t - contact), np.inf))) out["at_contact"] = {"angle_deg": round(float(ang[k]), 1), "t_clip": round(float(t[k] - t0_video), 3)} step = max(1, len(t) // 200) idx = np.flatnonzero(ok)[::step] out["series"] = {"t_clip": [round(float(t[i] - t0_video), 3) for i in idx], "handle": [[round(float(x), 1) for x in pts[i, 0]] for i in idx], "toe": [[round(float(x), 1) for x in pts[i, 1]] for i in idx], "angle_deg": [round(float(ang[i]), 1) for i in idx]} return out def ground_measures(bowler, batter, events, homography_fn, w, side): """Feet on the pitch in metres (calibrated views only): bowler's front foot vs the popping crease at front-foot contact, and the batter's forward/back movement.""" from events import OPP, SIDES from pitch import POPPING_GAP_M out = {} ffc = events.get("front_foot_contact") if bowler is not None and ffc: k = int(np.argmin(np.abs(bowler["frames"] - ffc["frame"]))) an = SIDES[OPP[side]]["an"] if side in SIDES else 15 if bowler["kpts"][k, an, 2] > KCONF: x, y = homography_fn(bowler["kpts"][k, an, :2]) back_an = SIDES[side]["an"] if side in SIDES else 16 out["bowler_front_foot"] = {"y_from_bowler_popping_m": round(y, 2), "x_m": round(x, 2), "behind_popping_crease_cm": round(-y * 100, 0), "note": "ankle keypoint, not the heel: expect +/- 15 cm"} if bowler["kpts"][k, back_an, 2] > KCONF: bx, by = homography_fn(bowler["kpts"][k, back_an, :2]) out["bowler_stride_m"] = round(float(np.hypot(x - bx, y - by)), 2) trg, contact = events.get("batter_trigger_start"), events.get("bat_ball_contact") bounce = events.get("ball_bounce") if batter is not None and (trg or bounce): f0 = (trg or bounce)["frame"] - int(0.3 * w["fps"] * w["time_scale"]) if not trg else trg["frame"] f1 = (contact or bounce or {}).get("frame") if f1 and f1 > f0: def feet_y(f): k = int(np.argmin(np.abs(batter["frames"] - f))) ys = [homography_fn(batter["kpts"][k, a, :2])[1] for a in (15, 16) if batter["kpts"][k, a, 2] > KCONF] return float(np.mean(ys)) if ys else None ya, yb = feet_y(f0), feet_y(f1) if ya is not None and yb is not None: fwd = ya - yb # towards the bowler = smaller y out["batter_feet_move_m"] = round(fwd, 2) out["batter_movement"] = "front_foot" if fwd > 0.2 else ("back_foot" if fwd < -0.1 else "stayed") out["batter_feet_from_own_popping_m"] = round(POPPING_GAP_M - yb, 2) return out