"""Estimate a batting-direction proxy from a setup followed by a swing. Both adapters supply camera-oriented MHR landmarks. The setup hip line gives an approximate axis; loaded hands and subsequent hand/torso motion resolve its sign. Neither stride nor ball flight defines the axis. This is a deterministic pose heuristic, not a trained target detector or a measured field direction. """ from pathlib import Path import numpy as np from scipy.signal import find_peaks from .camera_up_provider import CAMERA_FRAME from .sam_motion import derivative, segments from .storage import sha256_file METHOD = 'automatic_body_swing_direction_v2' SOURCE = 'Automatic body swing estimate; setup hip axis signed by loaded hands and forward hand/torso motion; target alignment unverified' LIMITS = { 'minimum_run_frames': 16, 'minimum_setup_frames': 5, 'minimum_extension_frames': 3, 'maximum_candidates': 40, 'maximum_setup_spread_deg': 12., 'maximum_setup_hip_shoulder_deg': 35., 'maximum_between_swing_spread_deg': 20., 'minimum_shoulder_rotation_deg': 25., 'minimum_hip_rotation_deg': 10., 'minimum_loaded_offset_hip_widths': .35, 'minimum_extension_offset_hip_widths': .2, 'minimum_hand_progress_hip_widths': 1., 'maximum_wrist_separation_shoulder_widths': .75, 'minimum_forward_velocity_fraction': .25, 'maximum_axis_step_deg': 60., 'maximum_hand_step_shoulder_widths': 1., } JOINTS = [5, 6, 9, 10, 41, 62] def reference(reason='no_clear_setup_and_swing'): return {'status': 'unknown', 'pitcher_vector': None, 'pitcher_source': None, 'coordinate_frame': CAMERA_FRAME, 'method': METHOD, 'automatic': True, 'applied': False, 'reliable': False, 'confidence': None, 'accuracy_validated': False, 'reason_code': reason, 'limits': dict(LIMITS), 'implementation_sha256': sha256_file(Path(__file__)), 'reference_kind': 'estimated_batting_direction', 'target_alignment_verified': False, 'assumptions': ['setup_hip_line_approximately_aligned_with_hitting_direction', 'hands_load_on_rear_side_before_forward_swing', 'camera_orientation_constant_during_evidence_window'], 'reliability_kind': 'pose_and_temporal_consistency_checks; not validated accuracy', 'candidates': [], 'accepted_candidate_count': 0} def _unit(q): length = np.linalg.norm(q, axis=-1, keepdims=True) return np.divide(q, length, out=np.full_like(q, np.nan), where=length > 1e-8) def _angle(a, b): return np.degrees(np.arccos(np.clip(np.sum(a*b, axis=-1), -1., 1.))) def _turn(a, b, up): return np.degrees(np.arctan2(np.cross(a, b) @ up, np.sum(a*b, axis=-1))) def _setup_axes(ids, hip_axis, shoulder_axis): axis = _unit(np.median(hip_axis[ids], axis=0)) shoulder = _unit(np.median(shoulder_axis[ids], axis=0)) if not np.isfinite([axis, shoulder]).all(): return None spread = float(max(np.max(_angle(hip_axis[ids], axis)), np.max(_angle(shoulder_axis[ids], shoulder)))) return axis, shoulder, spread def _stable_setup(chunks, hip_axis, shoulder_axis): """Find the latest locally stable setup, without including the whole load. A walk-in or a gradual load can change orientation over a long, low hand-speed stretch. It need not be one fixed pose. Use the required consecutive samples nearest the movement, all passing the same spread check. Extending back into preparation would bias the reference toward an earlier body orientation. """ minimum = LIMITS['minimum_setup_frames'] maximum_spread = LIMITS['maximum_setup_spread_deg'] for chunk in reversed(chunks): for stop in range(len(chunk), minimum-1, -1): ids = chunk[stop-minimum:stop] axes = _setup_axes(ids, hip_axis, shoulder_axis) if axes is None or axes[2] > maximum_spread: continue return ids, axes, chunk return None def _candidate(p, t, run, peak, next_peak, velocity, speed, up, hip_axis, shoulder_axis, width, hip_width): """Require a continuous setup → forward motion → extension, with no gaps.""" row = {'peak_frame': int(peak), 'accepted': False, 'reason_code': 'no_stable_loaded_setup'} hip = (p[:, 9]+p[:, 10])/2 hands = (p[:, 41]+p[:, 62])/2-hip shoulders = (p[:, 5]+p[:, 6])/2-hip height = shoulders @ up # A setup is near the rear shoulder, with hands together and relatively # still. Arms extended in follow-through must not become a new setup. side = np.sign(np.sum(hands*hip_axis, axis=1)) rear_shoulder = shoulders + side[:, None]*(p[:, 6]-p[:, 5])/2 setup_ok = ((speed <= .3*speed[peak]) & (height > .5*width) & (hands @ up > .35*height) & (hands @ up < 1.65*height) & (np.linalg.norm(hands-rear_shoulder, axis=1) < 1.2*width) & (_angle(hip_axis, shoulder_axis) < LIMITS['maximum_setup_hip_shoulder_deg'])) setup_ok &= np.abs(np.sum(hands*hip_axis, axis=1)) > LIMITS['minimum_loaded_offset_hip_widths']*hip_width setup_mask = np.zeros(len(p), bool) setup_mask[run[run < peak]] = setup_ok[run[run < peak]] # The run already encodes valid timestamps and model sequence boundaries. chunks = segments(setup_mask, t, np.inf) chunks = [ids for ids in chunks if len(ids) >= LIMITS['minimum_setup_frames']] if not chunks: return row selected = _stable_setup(chunks, hip_axis, shoulder_axis) if selected is None: row['reason_code'] = 'setup_axis_unstable' axes = _setup_axes(chunks[-1], hip_axis, shoulder_axis) if axes is not None: row['setup_spread_deg'] = axes[2] return row setup, (axis, shoulder, spread), search = selected search_axes = _setup_axes(search, hip_axis, shoulder_axis) row.update(setup_start_frame=int(setup[0]), setup_end_frame=int(setup[-1]), setup_spread_deg=spread, setup_selection='latest_stable_loaded_interval', setup_search_start_frame=int(search[0]), setup_search_end_frame=int(search[-1]), setup_search_spread_deg=search_axes[2] if search_axes is not None else None) start_hands = np.median(hands[setup], axis=0) hip_span = float(np.median(hip_width[setup])) loaded = float(start_hands @ axis) if abs(loaded) < LIMITS['minimum_loaded_offset_hip_widths']*hip_span: row['reason_code'] = 'loaded_hand_side_ambiguous' return row loaded_sign = np.sign(loaded) direction = -loaded_sign*axis if np.any((hands[setup] @ direction) > -LIMITS['minimum_loaded_offset_hip_widths']*hip_span): row['reason_code'] = 'loaded_hand_side_inconsistent' return row alignment = float(velocity[peak] @ direction / speed[peak]) row['forward_velocity_fraction'] = alignment if alignment < LIMITS['minimum_forward_velocity_fraction']: row['reason_code'] = 'hand_motion_opposes_loaded_side' return row # Avoid reaching into a later repetition to validate a failed motion peak. # The window scales with this movement's timing, including slow-motion video. deadline = t[peak]+max(2*(t[peak]-t[setup[-1]]), 3*np.median(np.diff(t[run]))) after = run[(run > peak) & (run < next_peak) & (t[run] <= deadline)] extended = np.zeros(len(p), bool) extended[after] = (hands[after] @ direction) > LIMITS['minimum_extension_offset_hip_widths']*hip_span extensions = [ids for ids in segments(extended, t, np.inf) if len(ids) >= LIMITS['minimum_extension_frames']] if not extensions: row['reason_code'] = 'forward_hand_extension_unavailable' return row end = extensions[0][:LIMITS['minimum_extension_frames']] evidence = np.arange(setup[-1], end[-1]+1) step = max(float(np.max(_angle(hip_axis[evidence[:-1]], hip_axis[evidence[1:]]))), float(np.max(_angle(shoulder_axis[evidence[:-1]], shoulder_axis[evidence[1:]])))) hand_step = float(np.max(np.linalg.norm(np.diff(hands[evidence], axis=0), axis=1) / width[evidence[:-1]])) row.update(maximum_axis_step_deg=step, maximum_hand_step_shoulder_widths=hand_step) if step > LIMITS['maximum_axis_step_deg'] or hand_step > LIMITS['maximum_hand_step_shoulder_widths']: row['reason_code'] = 'body_track_discontinuous' return row shoulder_turn = float(np.median(_turn(shoulder, shoulder_axis[end], up))*loaded_sign) hip_turn = float(np.median(_turn(axis, hip_axis[end], up))*loaded_sign) wrist_progress = [(np.median(p[end, j]-hip[end], axis=0) -np.median(p[setup, j]-hip[setup], axis=0)) @ direction / hip_span for j in (41, 62)] row.update(extension_start_frame=int(end[0]), extension_end_frame=int(end[-1]), shoulder_forward_turn_deg=shoulder_turn, hip_forward_turn_deg=hip_turn, wrist_progress_hip_widths=[float(v) for v in wrist_progress]) if min(wrist_progress) < LIMITS['minimum_hand_progress_hip_widths']: row['reason_code'] = 'insufficient_forward_hand_progress' elif not LIMITS['minimum_shoulder_rotation_deg'] <= shoulder_turn < 150: row['reason_code'] = 'shoulder_turn_does_not_support_swing' elif not LIMITS['minimum_hip_rotation_deg'] <= hip_turn < 130: row['reason_code'] = 'hip_turn_does_not_support_swing' else: row.update(accepted=True, reason_code=None, pitcher_vector=direction.tolist()) return row def estimate(corrected, times, options, up_reference, *, sequence_ids=None, progress=lambda *a: None): """Shared SAM/GVHMR path. No image detector, handedness or camera intrinsics.""" out = reference() if options.camera_stability == 'moving': out['reason_code'] = 'camera_moving' return out if options.up_vector is None: out['reason_code'] = 'automatic_up_unavailable' return out if up_reference.get('status') == 'estimated' and not up_reference.get('reliable'): out['reason_code'] = 'automatic_up_unreliable' return out p = np.asarray(corrected['points_relative'], float) t = np.asarray(times, float) if p.ndim != 3 or p.shape[1:] != (70, 3) or t.shape != (len(p),): raise ValueError('Body direction requires N x 70 x 3 points and matching timestamps') if not np.isfinite(t).all() or np.any(np.diff(t) <= 0): raise ValueError('Body direction timestamps must increase strictly') up = _unit(np.asarray(options.up_vector, float)) if not np.isfinite(up).all(): out['reason_code'] = 'vertical_reference_invalid' return out mask = np.isfinite(p[:, JOINTS]).all(axis=(1, 2)) for key, exclude in (('valid', False), ('boundary', True), ('interpolated', True)): if key in corrected: values = np.asarray(corrected[key], bool) if values.shape != p.shape[:2]: raise ValueError('Body direction masks differ from motion shape') mask &= ~values[:, JOINTS].any(axis=1) if exclude else values[:, JOINTS].all(axis=1) sequence = np.asarray(sequence_ids if sequence_ids is not None else np.zeros(len(p), int)) if sequence.shape != t.shape: raise ValueError('Body direction sequence IDs differ from timestamps') h, s = p[:, 10]-p[:, 9], p[:, 6]-p[:, 5] width = np.linalg.norm(s, axis=1) h = h-(h @ up)[:, None]*up s = s-(s @ up)[:, None]*up hip_width = np.linalg.norm(h, axis=1) hip_axis, shoulder_axis = _unit(h), _unit(s) mask &= ((width > 1e-6) & (hip_width > .3*width) & (np.linalg.norm(s, axis=1) > .6*width) & (np.linalg.norm(p[:, 41]-p[:, 62], axis=1) < LIMITS['maximum_wrist_separation_shoulder_widths']*width)) runs = [] for ids in segments(mask, t, options.correction.max_gap_s): runs.extend(part for part in np.split(ids, np.flatnonzero(np.diff(sequence[ids]) != 0)+1) if len(part) >= LIMITS['minimum_run_frames']) out['usable_run_count'] = len(runs) out['camera_stability'] = options.camera_stability if not runs: out['reason_code'] = 'insufficient_continuous_body_frames' return out hands = (p[:, 41]+p[:, 62]-p[:, 9]-p[:, 10])/2 accepted = [] progress('pitcher_direction_estimation', 0, len(runs)) for index, run in enumerate(runs): speed = np.full(len(p), np.nan) velocity = np.full_like(hands, np.nan) velocity[run] = derivative(hands[run], t[run], max_gap=options.correction.max_gap_s) speed[run] = np.linalg.norm(velocity[run], axis=1) finite = speed[run][np.isfinite(speed[run])] # Relative prominence is invariant to native body scale and uniform # playback-speed changes. Displacement/rotation checks reject tiny noise. prominence = max(float(np.percentile(finite, 90))*.3, float(np.percentile(finite, 20))*3, 1e-8) peaks, _ = find_peaks(np.nan_to_num(speed[run]), prominence=prominence) for peak, next_peak in zip(run[peaks], [*run[peaks[1:]], run[-1]+1]): if len(out['candidates']) >= LIMITS['maximum_candidates']: out['reason_code'] = 'too_many_motion_candidates' return out row = _candidate(p, t, run, peak, next_peak, velocity, speed, up, hip_axis, shoulder_axis, width, hip_width) out['candidates'].append(row) # Multiple speed peaks during one swing are one piece of evidence. if row['accepted'] and not any(a['setup_start_frame'] <= row['setup_end_frame'] <= a['extension_end_frame'] for a in accepted): accepted.append(row) progress('pitcher_direction_estimation', index+1, len(runs)) out['accepted_candidate_count'] = len(accepted) if not accepted: if not out['candidates']: out['reason_code'] = 'no_swing_motion' else: reasons = {row['reason_code'] for row in out['candidates']} if len(reasons) == 1: out['reason_code'] = reasons.pop() return out vectors = np.array([row['pitcher_vector'] for row in accepted]) spread = float(np.max(_angle(vectors[:, None], vectors[None, :]))) out['between_swing_spread_deg'] = spread if spread > LIMITS['maximum_between_swing_spread_deg']: out['reason_code'] = 'inconsistent_body_swing_directions' return out out.update(status='estimated', pitcher_vector=_unit(np.median(vectors, axis=0)).tolist(), pitcher_source=SOURCE, applied=True, reliable=True, reason_code=None) return out