"""Analytic geometry, missing evidence, old-contract compatibility and live QA regressions.""" import json from pathlib import Path import numpy as np import pytest from ai_coach.config import Settings from ai_coach.swing_report import AthleteContext, build_report, validate_payload from baseball_batting.coach_geometry import inclination, knee_angle, rotation_amount from baseball_batting.motion_coach import build_coach_payload from baseball_batting.motion_contract import MotionInput from baseball_batting.motion_refine import static_camera_conflict from baseball_batting.sam_motion import MHR from test_sam_batting import pose def fixture_payload(*, hand='right', clock=True, camera='fixed_verified', transform=None, vertical_known=True): n = 31; p = pose(n); times = np.arange(n) / 30 for i in range(n): a = np.radians(3 * i) matrix = np.array([[np.cos(a), 0, -np.sin(a)], [0, 1, 0], [np.sin(a), 0, np.cos(a)]]) p[i] = p[i] @ matrix.T up = np.array([0., -1., 0.]) if transform is not None: p = p @ transform.T; up = transform @ up corrected = {'points_relative': p, 'valid': np.isfinite(p).all(-1), 'boundary': np.zeros((n, 70), bool), 'interpolated': np.zeros((n, 70), bool)} opts = MotionInput(single_swing=True, camera_stability=camera, up_vector=up.tolist() if vertical_known else None, up_source='Synthetic known vertical' if vertical_known else None, handedness=hand, athlete={'athlete_id': 'fixture', 'batting_hand': hand}, context={'practice_type': 'tee'}, contact_frame=20, windows=[{'start_frame': 0, 'end_frame': 30, 'stride_start_frame': 3, 'landing_frame': 10}]) return build_coach_payload(opts, {'analysis_id': 'fixture', 'analysis_revision': 1}, corrected, times, times if clock else np.full(n, np.nan), []).model_dump(mode='json') def test_extended_measurements_have_analytic_values_and_all_groups_score(): p = fixture_payload(); parsed, problems = validate_payload(p) assert parsed is not None and not problems rows = {m['metric_id']: m for m in p['measurements']} assert len(rows) == 9 and p['schema_version'] == '1.1' assert rows['pelvis_rotation_to_contact']['value'] == pytest.approx(30) assert rows['shoulder_rotation_after_contact']['value'] == pytest.approx(9) assert rows['torso_inclination_at_stride_start']['value'] == pytest.approx(0) assert rows['lead_knee_extension_to_contact']['value'] == pytest.approx(0) assert p['events']['follow_through']['source_frame_index'] == 23 assert p['events']['follow_through']['source'] == 'derived_from_contact' report = build_report(p, AthleteContext(level='college'), settings=Settings(_env_file=None, google_api_key=None)) assert len(report['groups']) == 4 assert all(g['metric_ids'] and g['score'] is not None for g in report['groups']) assert all(m['rating_is_tentative'] for m in report['measurements']) for row in rows.values(): assert row['value_interval']['lower'] <= row['value'] <= row['value_interval']['upper'] def test_geometry_does_not_depend_on_camera_axes_or_batting_hand_sign_for_rotation_amount(): a = .7; r = np.array([[1, 0, 0], [0, np.cos(a), -np.sin(a)], [0, np.sin(a), np.cos(a)]]) base = fixture_payload(); rotated = fixture_payload(transform=r); left = fixture_payload(hand='left') for x, y in zip(base['measurements'], rotated['measurements']): assert y['value'] == pytest.approx(x['value'], abs=.001) assert next(m for m in left['measurements'] if m['metric_id'] == 'pelvis_rotation_to_contact')['value'] == 30 assert knee_angle(np.array([0, 1, 0]), np.array([0, 0, 0]), np.array([1, 0, 0])) == pytest.approx(90) assert inclination([0, 0, 0], [1, 0, 1], [0, 0, 1]) == pytest.approx(45) assert rotation_amount([170, 179, -175, -160], 0, 3) == pytest.approx(30) def test_unknown_clock_blocks_only_timed_follow_through_and_moving_camera_blocks_pose_comparisons(): p = fixture_payload(clock=False) assert not validate_payload(p)[1] unavailable = [m for m in p['measurements'] if m['value'] is None] assert len(unavailable) == 1 and unavailable[0]['metric_id'] == 'shoulder_rotation_after_contact' assert 'capture_time_unknown' in unavailable[0]['reasons'] moving = fixture_payload(camera='moving') assert all(m['value'] is None for m in moving['measurements'] if m['metric_id'] != 'lead_knee_extension_to_contact') assert next(m for m in moving['measurements'] if m['metric_id'] == 'lead_knee_extension_to_contact')['value'] == 0 def test_intrinsic_knee_angle_survives_unknown_vertical_and_camera_rotation(): rotation = np.array([[0., 0., 1.], [1., 0., 0.], [0., 1., 0.]]) p = fixture_payload(vertical_known=False, camera='moving', transform=rotation) assert not validate_payload(p)[1] usable = [m for m in p['measurements'] if m['value'] is not None] assert len(usable) == 1 and usable[0]['metric_id'] == 'lead_knee_extension_to_contact' assert usable[0]['value'] == 0 and usable[0]['status'] == 'limited' report = build_report(p, AthleteContext(level='college'), settings=Settings(_env_file=None, google_api_key=None)) assert [g['group'] for g in report['groups'] if g['score'] is not None] == ['power_move'] groups = {g['group']: g for g in report['groups']} assert 'upright' in groups['balance_load']['summary'] assert 'only part of this phase' in groups['power_move']['summary'] assert 'partial_measurement_coverage' in {n['code'] for n in report['data_quality']} @pytest.mark.parametrize('missing_joint', [None, 'left_hip', 'left_knee', 'left_ankle']) def test_intrinsic_knee_change_under_time_varying_camera_requires_all_three_landmarks(missing_joint): n = 31; times = np.arange(n) / 30; p = pose(n) # A known 60-to-90 degree knee change between landing (10) and contact (20). angles = np.radians(30 + 3 * np.arange(n)) p[:, MHR['left_knee']] = 0 p[:, MHR['left_hip']] = [0, 1, 0] p[:, MHR['left_ankle']] = np.column_stack((np.sin(angles), np.cos(angles), np.zeros(n))) for i in range(n): a = .1 * i rotation = np.array([[np.cos(a), 0, np.sin(a)], [0, 1, 0], [-np.sin(a), 0, np.cos(a)]]) p[i] = (1 + i / 100) * (p[i] @ rotation.T) + [i / 10, -i / 20, i / 30] if missing_joint is not None: p[15, MHR[missing_joint]] = np.nan corrected = {'points_relative': p, 'valid': np.isfinite(p).all(-1), 'boundary': np.zeros((n, 70), bool), 'interpolated': np.zeros((n, 70), bool)} options = MotionInput(single_swing=True, camera_stability='moving', handedness='right', athlete={'athlete_id': 'fixture', 'batting_hand': 'right'}, contact_frame=20, windows=[{'start_frame': 0, 'end_frame': 30, 'stride_start_frame': 3, 'landing_frame': 10}]) payload = build_coach_payload(options, {'analysis_id': 'fixture', 'analysis_revision': 1}, corrected, times, times, []).model_dump(mode='json') assert not validate_payload(payload)[1] knee = next(m for m in payload['measurements'] if m['metric_id'] == 'lead_knee_extension_to_contact') if missing_joint is None: assert knee['value'] == pytest.approx(30) assert knee['value_interval']['lower'] == pytest.approx(24) assert knee['value_interval']['upper'] == pytest.approx(36) else: assert knee['value'] is None and knee['reasons'] == ['required_landmarks_unusable'] def test_old_three_metric_payload_still_builds_without_inventing_new_values(): p = json.loads((Path(__file__).parents[1] / 'docs/motion-coach-payload.example.json').read_text()) assert p['schema_version'] == '1.0' and not validate_payload(p)[1] report = build_report(p, settings=Settings(_env_file=None, google_api_key=None)) assert len(report['measurements']) == 3 assert {g['group'] for g in report['groups'] if not g['metric_ids']} == {'balance_load', 'power_move'} assert report['meta']['input_schema_version'] == '1.0' def test_slow_camera_drift_is_not_lost_and_unsigned_jitter_is_not_accumulated(): assert static_camera_conflict({'background_displacement_image_fraction': [.001] * 100, 'background_anchor_displacement_image_fraction': [.002, .008, .015, .025, .04]}, .003) assert not static_camera_conflict({'background_displacement_image_fraction': [.001] * 1000, 'background_anchor_displacement_image_fraction': [.001] * 125}, .003) assert not static_camera_conflict({'background_displacement_image_fraction': [np.nan] * 4}, .003) def test_unknown_drill_does_not_prescribe_a_shorter_stride_and_frame_sensitivity_is_visible(): p = fixture_payload(); p['context']['practice_type'] = 'unknown' row = next(m for m in p['measurements'] if m['metric_id'] == 'stride_relative_length') row['value'] = 97.597; row['value_interval'] = {'lower': 89.3, 'upper': 102.7, 'source': 'adjacent_event_frames'} contact = next(m for m in p['measurements'] if m['metric_id'] == 'hip_shoulder_separation_at_contact') contact['value'] = -7.575 contact['value_interval'] = {'lower': -16.126, 'upper': -2.142, 'source': 'adjacent_event_frames'} p['athlete']['batting_hand'] = 'left'; p['athlete']['lead_foot'] = 'right' report = build_report(p, AthleteContext(level='college'), settings=Settings(_env_file=None, google_api_key=None)) contact = next(m for m in report['measurements'] if m['metric_id'] == 'hip_shoulder_separation_at_contact') assert contact['score'] == 79 and contact['score_interval'] == {'lower': 0, 'upper': 100} # A frame-sensitive result is shown but never coached or chosen as the focus. assert contact['coach_tip'] is None and report['focus_area']['metric_id'] != contact['metric_id'] # An unknown drill still gets coaching, but never stride advice: this walk-through stride is far beyond any # reference swing, so it is a measurement problem and is not rated at all. stride = next(m for m in report['measurements'] if m['metric_id'] == 'stride_relative_length') assert stride['not_rated_reason'] == 'implausible_value' and stride['coach_tip'] is None assert report['focus_area']['metric_id'] != 'stride_relative_length' assert 'shorten' not in report['focus_area']['coach_message'].lower() assert {'implausible_value', 'event_sensitive_scores'} <= {x['code'] for x in report['data_quality']} def test_contract_does_not_accept_an_interval_that_excludes_its_value(): p = fixture_payload(); p['measurements'][0]['value_interval']['lower'] = 100 assert validate_payload(p)[0] is None def test_contradictory_source_frames_and_missing_follow_through_clock_are_rejected(): p = fixture_payload() p['events']['contact']['source_frame_index'] = 9 assert 'events.front_foot_down.source_frame_index' in validate_payload(p)[1] p = fixture_payload() p['events']['follow_through']['capture_time_s'] = None assert 'events.follow_through.capture_time_s' in validate_payload(p)[1]