"""Export versioned coach measurements from the same corrected motion as replay. The selected source frames are manual review, not automatic event detections. They identify sampled video moments, not measured ground force or subframe contact. """ import numpy as np from .motion_coach_contract import (CoachEvents, CoachEvent, MotionCoachPayload, SeparationAtFootDown, RelativeStride, SeparationAtContact, ExtendedMeasurement, ValueInterval) from .coach_geometry import follow_through_frame, inclination, knee_angle, rotation_amount from .sam_measurements import frame_curves, wrap180 from .sam_motion import MHR def swing_identity(options, analysis_id): return options.swing_id or analysis_id + ':swing_1' def build_coach_payload(options, lineage, corrected, video_times, capture_times, contexts): if options.athlete is None: return None if not options.single_swing or len(contexts) > 1: raise ValueError('The coach contract requires one swing per video') n = len(video_times) options.validate_frame_count(n) window = options.windows[0] if options.windows else None stride_start = window.stride_start_frame if window else None landing = window.landing_frame if window else None contact = options.contact_frame lead = options.lead_foot or {'right': 'left', 'left': 'right'}.get(options.handedness) athlete = options.athlete.model_copy(update={'batting_hand': options.handedness, 'lead_foot': lead}) def event(index, missing_reason, source='manual_review'): if index is None: return CoachEvent(status='unavailable', video_time_s=None, capture_time_s=None, source=None, reasons=[missing_reason]) return CoachEvent(status='limited', video_time_s=float(video_times[index]), capture_time_s=float(capture_times[index]) if np.isfinite(capture_times[index]) else None, source=source, source_frame_index=index, reasons=['event_timing_uncertain']) finish = follow_through_frame(capture_times, contact, window.end_frame if window else n - 1) finish_reason = 'capture_time_unknown' if not np.isfinite(capture_times).all() else 'follow_through_not_recorded' events = CoachEvents(stride_start=event(stride_start, 'event_not_detected'), front_foot_down=event(landing, 'event_not_detected'), contact=event(contact, 'contact_not_applicable' if options.context.practice_type == 'dry_swing' else 'contact_not_verified'), follow_through=event(finish, finish_reason, 'derived_from_contact')) if contexts: context = contexts[0] curves = context['curves'] # Reuse exactly the fixed orientation/baseline of the existing calculator. _, reference, oriented = frame_curves(corrected['points_relative'], video_times, corrected['boundary'], options.sam_options(), context['baseline']) else: hips = corrected['valid'][:, [MHR['left_hip'], MHR['right_hip']]].all(axis=1) baseline = int(np.flatnonzero(hips)[0]) if hips.any() else 0 curves, reference, oriented = frame_curves(corrected['points_relative'], video_times, corrected['boundary'], options.sam_options(), baseline) def quality(indices, names, requires_orientation=True): ids = [i for i in indices if i is not None] joints = [MHR[name] for name in names] selected = np.ix_(ids, joints) interpolated = bool(ids and corrected['interpolated'][selected].any()) reasons = [] if ids and not corrected['valid'][selected].all(): reasons.append('required_landmarks_unusable') if requires_orientation and options.up_vector is None: reasons.append('ground_plane_unknown') if requires_orientation and options.camera_stability != 'fixed_verified': reasons.append('temporal_inconsistency') if requires_orientation and reference == 'degenerate_analysis_axis': reasons.append('required_landmarks_unusable') warnings = [] if ids and (corrected['boundary'][selected].any() or interpolated): warnings.append('temporal_inconsistency') return interpolated, list(dict.fromkeys(reasons)), warnings def result(model, value, missing, timing, interpolated, warnings): missing = list(dict.fromkeys(missing)) if missing: return model(value=None, status='unavailable', confidence=None, uses_interpolated_input=interpolated, reasons=missing) reasons = list(dict.fromkeys([*timing, *warnings, 'model_accuracy_unvalidated'])) return model(value=value, status='limited' if reasons else 'available', confidence=None, uses_interpolated_input=interpolated, reasons=reasons) def separation(model, index, selected_event): interpolated, missing, warnings = quality([index], ['left_hip', 'right_hip', 'left_shoulder', 'right_shoulder']) if selected_event.status == 'unavailable': missing = ['required_event_unavailable', *selected_event.reasons, *missing] value = None if not missing: q = curves['hip_shoulder_separation_deg'][index] if np.isfinite(q): # Round before wrapping so 179.9998 cannot serialize as +180. value = float(wrap180(round(float(q), 3))) else: missing.append('required_landmarks_unusable') return result(model, value, missing, selected_event.reasons, interpolated, warnings) def add_interval(metric, evaluate, indices, names, requires_orientation=True): if metric.value is None or any(i is None for i in indices): return metric from itertools import product lo, hi = (window.start_frame, window.end_frame) if window else (0, n - 1) values = [metric.value] for ids in product(*(range(max(lo, i - 1), min(hi, i + 1) + 1) for i in indices)): if len(ids) > 1 and ids[0] >= ids[-1]: continue checked = list(range(ids[0], ids[-1] + 1)) if len(ids) > 1 else ids if quality(checked, names, requires_orientation)[1]: return metric # A partial neighborhood cannot bound event sensitivity. value = evaluate(*ids) if not np.isfinite(value): return metric values.append(float(value)) # A wrapped angle can straddle -180/+180; a linear interval would be misleading. if metric.reference == 'signed_horizontal_shoulder_minus_hip_heading' and max(values) - min(values) > 180: return metric metric.value_interval = ValueInterval(lower=min(values), upper=max(values)) return metric sep = lambda i: curves['hip_shoulder_separation_deg'][i] torso_names = ['left_hip', 'right_hip', 'left_shoulder', 'right_shoulder'] foot_angle = add_interval(separation(SeparationAtFootDown, landing, events.front_foot_down), sep, [landing], torso_names) contact_angle = add_interval(separation(SeparationAtContact, contact, events.contact), sep, [contact], torso_names) interpolated, missing, warnings = quality([stride_start, landing], ['left_hip', 'right_hip', 'left_ankle', 'right_ankle']) timing = [] for selected_event in (events.stride_start, events.front_foot_down): if selected_event.status == 'unavailable': missing += ['required_event_unavailable', *selected_event.reasons] else: timing += selected_event.reasons if lead is None: missing.append('lead_foot_unknown') if options.scale_status == 'unknown': missing.append('scale_unknown') elif options.scale_status == 'model_estimated': warnings.append('scale_is_model_estimated') stride = None if not missing: if oriented is None: missing.append('required_landmarks_unusable') else: li, ri = (MHR['left_ankle'], MHR['right_ankle']) if lead == 'left' else ( MHR['right_ankle'], MHR['left_ankle']) start = oriented[stride_start, li] - oriented[stride_start, ri] end = oriented[landing, li] - oriented[landing, ri] q = 100 * np.linalg.norm((end - start)[:2]) if np.isfinite(q): stride = round(float(q), 3) else: missing.append('required_landmarks_unusable') stride_metric = result(RelativeStride, stride, missing, timing, interpolated, warnings) if oriented is not None and lead is not None: li, ri = (MHR['left_ankle'], MHR['right_ankle']) if lead == 'left' else (MHR['right_ankle'], MHR['left_ankle']) def stride_value(a, b): return 100 * np.linalg.norm(((oriented[b, li] - oriented[b, ri]) - (oriented[a, li] - oriented[a, ri]))[:2]) add_interval(stride_metric, stride_value, [stride_start, landing], ['left_hip', 'right_hip', 'left_ankle', 'right_ankle']) hip_names = ['left_hip', 'right_hip'] torso_names = [*hip_names, 'left_shoulder', 'right_shoulder'] lean = np.full(n, np.nan) knee = np.full(n, np.nan) if oriented is not None: lean = inclination((oriented[:, 9] + oriented[:, 10]) / 2, (oriented[:, 5] + oriented[:, 6]) / 2, [0, 0, 1]) if lead is not None: # An intrinsic joint angle is unchanged by camera rotation, translation or uniform scale. # Unlike horizontal headings, it does not require an estimated vertical reference. native = corrected['points_relative'] knee = knee_angle(native[:, MHR[lead + '_hip']], native[:, MHR[lead + '_knee']], native[:, MHR[lead + '_ankle']]) event_map = {'stride_start': events.stride_start, 'front_foot_down': events.front_foot_down, 'contact': events.contact, 'follow_through': events.follow_through} def extra(metric_id, group, reference_name, names, ids, event_ids, evaluate, *, lead_required=False, requires_orientation=True): checked = list(range(ids[0], ids[-1] + 1)) if len(ids) == 2 and all(i is not None for i in ids) else ids interp, absent, warns = quality(checked, names, requires_orientation) event_reasons = [] for key in event_ids: ev = event_map[key] if ev.status == 'unavailable': absent += ['required_event_unavailable', *ev.reasons] else: event_reasons += ev.reasons if lead_required and lead is None: absent.append('lead_foot_unknown') value = evaluate(*ids) if not absent else np.nan if not absent and not np.isfinite(value): absent.append('required_landmarks_unusable') common = dict(metric_id=metric_id, group=group, reference=reference_name) common.update({'event_id': event_ids[0]} if len(event_ids) == 1 else {'start_event_id': event_ids[0], 'end_event_id': event_ids[-1]}) rounded = round(float(value), 3) if np.isfinite(value) else None if rounded is not None and reference_name == 'signed_horizontal_shoulder_minus_hip_heading': rounded = float(wrap180(rounded)) row = result(lambda **fields: ExtendedMeasurement(**common, **fields), rounded, absent, event_reasons, interp, warns) return add_interval(row, evaluate, ids, names, requires_orientation) extended = [ extra('torso_inclination_at_stride_start', 'balance_load', 'torso_angle_from_vertical', torso_names, [stride_start], ['stride_start'], lambda i: lean[i]), extra('hip_shoulder_separation_at_stride_start', 'balance_load', 'signed_horizontal_shoulder_minus_hip_heading', torso_names, [stride_start], ['stride_start'], sep), extra('pelvis_rotation_to_contact', 'power_move', 'absolute_net_horizontal_rotation', hip_names, [landing, contact], ['front_foot_down', 'contact'], lambda a, b: rotation_amount(curves['hip_heading_deg'], a, b)), extra('lead_knee_extension_to_contact', 'power_move', 'change_in_3d_lead_knee_angle', [lead + '_' + part for part in ('hip', 'knee', 'ankle')] if lead else hip_names, [landing, contact], ['front_foot_down', 'contact'], lambda a, b: knee[b] - knee[a], lead_required=True, requires_orientation=False), extra('torso_inclination_at_contact', 'contact_follow_through', 'torso_angle_from_vertical', torso_names, [contact], ['contact'], lambda i: lean[i]), extra('shoulder_rotation_after_contact', 'contact_follow_through', 'absolute_net_horizontal_rotation', ['left_shoulder', 'right_shoulder'], [contact, finish], ['contact', 'follow_through'], lambda a, b: rotation_amount(curves['shoulder_heading_deg'], a, b)), ] return MotionCoachPayload(analysis_id=lineage['analysis_id'], analysis_revision=lineage['analysis_revision'], swing_id=swing_identity(options, lineage['analysis_id']), athlete=athlete, context=options.context, events=events, measurements=[foot_angle, stride_metric, contact_angle, *extended])