File size: 12,122 Bytes
b13d358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41b4a14
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b13d358
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Known-geometry/timing and failure cases. Synthetic fixtures are not accuracy evidence."""
from copy import deepcopy
import json
from pathlib import Path
import numpy as np
import pytest
from baseball_batting.sam_batting_contract import SamBattingInput,CorrectionSettings,SamBattingResult
from baseball_batting.sam_motion import correct_motion,derivative,unwrap_heading,BOUNDARY
from baseball_batting.sam_measurements import frame_curves,calculate_measurements,wrap180,peak
from baseball_batting.geometry import project


def pose(n=90):
    p=np.zeros((n,70,3))
    for j,v in {3:[-.08,-.8,0],4:[.08,-.8,0],5:[-.25,-.5,0],6:[.25,-.5,0],
                7:[-.4,-.25,0],8:[.4,-.25,0],9:[-.15,0,0],10:[.15,0,0],
                11:[-.2,.45,0],12:[.2,.45,0],13:[-.3,.9,0],14:[.3,.9,0],
                15:[-.3,.95,.15],16:[-.25,.95,.15],17:[-.3,.95,0],
                18:[.3,.95,.15],19:[.35,.95,.15],20:[.3,.95,0],
                62:[-.45,0,0],41:[.45,0,0]}.items():p[:,j]=v
    return p


def options(**kwargs):
    return SamBattingInput(camera_stability='fixed_verified',up_vector=[0,-1,0],
        up_source='Known synthetic vertical',handedness='right',
        timing={'kind':'unretimed','source':'Known fixture capture clock'},**kwargs)


def raw_pose(p,width=640,height=480):
    n=len(p);k=np.array([[600.,0,width/2],[0,600.,height/2],[0,0,1]])
    translation=np.tile([0,0,5.],(n,1))
    return {'points_body':p,'camera_translation':translation,
        'projection':project(p+translation[:,None,:],k),'projection_valid':np.ones(n,bool),
        'intrinsics':np.tile(k,(n,1,1)),'image_size':np.array([width,height])}


def corrected(p):
    return {'points_relative':p,'boundary':np.zeros(p.shape[:2],bool)}


@pytest.mark.parametrize('fps',[30,60,120])
def test_single_swing_declaration_does_not_count_preparation_or_recovery_as_reps(fps):
    from baseball_batting.sam_measurements import automatic_windows
    t=np.arange(0,5,1/fps);p=pose(len(t))
    # Three separated motion bursts, with the middle burst dominant. Their
    # locations and amplitudes are fixture parameters, not video-specific labels.
    displacement=sum(a*np.tanh((t-center)/.08) for a,center in [(.03,1),(.4,2.5),(.05,4)])
    p[:,[41,62],0]+=displacement[:,None]
    assert len(automatic_windows(p,t))==3
    groups,private=calculate_measurements(corrected(p),t,options(single_swing=True))
    assert all(len(swings)==1 for swings in groups.values())
    window=private[0]['window']
    assert window['start_frame']==0 and window['end_frame']==len(t)-1
    assert t[window['forward_start_frame']]<2.5<t[window['forward_end_frame']]
    row=next(m for m in groups['rotation'][0].measurements if m.key=='hip_rotation_from_start_deg')
    assert row.statistic=='window_end_minus_baseline'
    assert 'automatic_forward_window_not_reviewed' in row.quality_flags


def test_single_swing_cannot_be_declared_with_multiple_reviewed_reps():
    from pydantic import ValidationError
    with pytest.raises(ValidationError,match='single-swing'):
        options(single_swing=True,windows=[{'start_frame':0,'end_frame':20},{'start_frame':21,'end_frame':50}])


def test_nonuniform_derivative_and_wrapped_angles():
    t=np.array([0,.01,.03]);assert derivative(t*t,t)[1]==pytest.approx(.02)
    assert derivative(np.array([10,14,18.]),np.array([0,.01,.02]))[1]==pytest.approx(400)
    assert wrap180(-179-179)==2
    assert unwrap_heading([179,-179,-177],[0,.01,.02]).tolist()==pytest.approx([179,181,183])
    q=derivative([0,1,2,3,4],[0,.01,.02,.5,.51])
    assert np.isnan(q[2]) and np.isnan(q[3])


def test_known_hip_and_shoulder_headings_and_torso_lean():
    p=pose();a=np.radians(30);b=np.radians(60)
    p[:,9]=[-.15*np.cos(a),0,-.15*np.sin(a)];p[:,10]=-p[:,9]
    p[:,5]=[-.25*np.cos(b),-.5,-.25*np.sin(b)+.1]
    p[:,6]=[.25*np.cos(b),-.5,.25*np.sin(b)+.1]
    opts=options(pitcher_vector=[1,0,0],pitcher_source='Known fixture X')
    curves,ref,_=frame_curves(p,np.arange(len(p))/100,np.zeros((len(p),70),bool),opts,0)
    assert curves['hip_heading_deg'][10]==pytest.approx(30)
    assert curves['shoulder_heading_deg'][10]==pytest.approx(60)
    assert curves['hip_shoulder_separation_deg'][10]==pytest.approx(30)
    # Body-forward axis rotates with the pelvis, while analysis headings remain fixed.
    assert curves['forward_lean_deg'][10]==pytest.approx(np.degrees(np.arctan2(.1*np.cos(a),.5)))
    p=pose();p[:,5:7,2]=.1
    curves,_,_=frame_curves(p,np.arange(len(p))/100,np.zeros((len(p),70),bool),options(),0)
    assert curves['forward_lean_deg'][10]==pytest.approx(11.309932)


def test_translation_invariance_head_excursion_stance_and_wrist_speed():
    p=pose();t=np.arange(len(p))*.01
    p[:,[3,4],0]+=np.linspace(0,.02,len(p))[:,None]
    p[:,[3,4],2]-=np.linspace(0,.01,len(p))[:,None]
    p[:,[41,62],0]+=2*t[:,None]
    c,_,_=frame_curves(p,t,np.zeros((len(p),70),bool),options(),0)
    assert c['head_excursion_relative_cm'][-1]==pytest.approx(2.2360679)
    assert c['stance_span_cm'][10]==pytest.approx(60)
    assert c['hand_speed_relative_m_s'][10]==pytest.approx(2)
    moved=p+np.column_stack([3*t,t*t,-2*t])[:,None,:]
    d,_,_=frame_curves(moved,t,np.zeros((len(p),70),bool),options(),0)
    for key in c:np.testing.assert_allclose(c[key],d[key],atol=1e-9,equal_nan=True)


def test_missing_wrist_does_not_remove_stance_or_posture():
    p=pose();p[40,62]=np.nan;t=np.arange(len(p))*.01
    curves,_,_=frame_curves(p,t,np.zeros((len(p),70),bool),options(),0)
    assert np.isnan(curves['hand_speed_relative_m_s'][39:42]).all()
    assert curves['stance_span_cm'][40]==pytest.approx(60)
    assert curves['forward_lean_deg'][40]==pytest.approx(0)


def test_unknown_vertical_and_clock_never_invent_horizontal_or_speed_measurements():
    p=pose();t=np.arange(len(p))*.01
    opts=SamBattingInput(camera_stability='fixed_verified')
    groups,_=calculate_measurements(corrected(p),t,opts,clock_known=False)
    rows={m.key:m for g in groups.values() for s in g for m in s.measurements}
    assert rows['hip_shoulder_separation_deg'].value is None
    assert rows['hand_speed_relative_m_s'].value is None
    assert rows['hip_peak_time_ms'].reason_code=='capture_time_unknown'
    assert rows['head_excursion_relative_cm'].value==0
    assert rows['center_of_mass_displacement_cm'].reason_code=='missing_mass_model'
    assert rows['stride_ground_length_cm'].reason_code=='missing_ground_reference'


def test_relative_stride_requires_reviewed_events_and_field_direction_for_components():
    p=pose();p[70:,13,0]-=.2;p[70:,13,2]+=.1;t=np.arange(len(p))*.01
    window={'start_frame':0,'end_frame':89,'baseline_frame':0,'stride_start_frame':20,'landing_frame':70}
    opts=options(windows=[window])
    groups,_=calculate_measurements(corrected(p),t,opts)
    rows={m.key:m for g in groups.values() for s in g for m in s.measurements}
    assert rows['stride_relative_length_cm'].value==pytest.approx(22.361,abs=.001)
    assert rows['stride_duration_ms'].value==500
    assert rows['stride_relative_forward_cm'].reason_code=='missing_3d_pitcher_direction'
    assert rows['stride_ground_length_cm'].value is None


def test_peak_gaps_boundaries_competitors_and_negative_order():
    t=np.arange(101)/100
    assert peak(np.arange(101),t,0,100)[1]=='peak_at_window_boundary'
    q=np.exp(-((t-.3)/.05)**2)+np.exp(-((t-.7)/.05)**2)
    assert peak(q,t,0,100)[1]=='ambiguous_peak'
    q=np.exp(-((t-.5)/.05)**2);q[40]=np.nan
    assert peak(q,t,0,100)[1]=='incomplete_peak_window'
    assert peak(np.exp(-((t-.5)/.05)**2),t,0,100)==(50,None)


def test_measured_peak_order_is_not_forced_to_hips_first():
    from scipy.special import erf
    n=201;t=np.arange(n)/100;p=pose(n)
    hip=np.radians(80*(1+erf((t-1.2)/.08))/2)
    shoulder=np.radians(70*(1+erf((t-1.)/.08))/2)
    for a,b,angle,size,y in [(9,10,hip,.15,0),(5,6,shoulder,.25,-.5)]:
        p[:,a]=np.column_stack([-size*np.cos(angle),np.full(n,y),-size*np.sin(angle)])
        p[:,b]=np.column_stack([size*np.cos(angle),np.full(n,y),size*np.sin(angle)])
    displacement=.3*(1+erf((t-1.4)/.08))/2
    p[:,[41,62],0]+=displacement[:,None]
    groups,_=calculate_measurements(corrected(p),t,options(windows=[{
        'start_frame':0,'end_frame':200,'baseline_frame':0,
        'forward_start_frame':40,'forward_end_frame':180,'forward_rotation_sign':1}]))
    rows={m.key:m for g in groups.values() for s in g for m in s.measurements}
    assert rows['hip_to_shoulder_ms'].value==pytest.approx(-200,abs=10)
    assert rows['shoulder_to_hands_ms'].value==pytest.approx(400,abs=10)
    assert groups['timing'][0].movement_peak_order==['shoulder','hip','hands']


def test_correction_reduces_static_jitter_preserves_fast_motion_and_never_fills_gaps():
    rng=np.random.default_rng(123);n=240;t=np.arange(n)/120;p=pose(n)
    baseline=p.copy();noise=rng.normal(0,.003,p[:,62].shape);p[:,62]+=noise
    pulse=.25*np.exp(-((t-1)/.055)**2);p[:,41,2]+=pulse
    raw=raw_pose(p);original=p.copy()
    c=correct_motion(raw,t,CorrectionSettings())
    np.testing.assert_array_equal(raw['points_body'],original)
    assert np.std(c['points_relative'][10:-10,62,0])<np.std(noise[10:-10,0])*.85
    assert np.nanmax(c['points_relative'][:,41,2])>.95*pulse.max()
    assert abs(np.nanargmax(c['points_relative'][:,41,2])-np.argmax(pulse))<=1
    assert not c['interpolated'].any()
    p[120,62]=np.nan;c=correct_motion(raw_pose(p),t,CorrectionSettings())
    assert not c['valid'][120,62] and np.isnan(c['points_relative'][120,62]).all()
    assert c['boundary'][121:123,62].all()


def test_corroborated_isolated_spike_is_flagged_not_fabricated():
    p=pose();p[40,62,0]-=1
    c=correct_motion(raw_pose(p),np.arange(len(p))/60,CorrectionSettings())
    assert not c['valid'][40,62]
    assert c['metadata']['rejected_point_count']>0
    assert not c['interpolated'][40,62]


def test_corrected_projection_uses_same_3d_points():
    from baseball_batting.sam_pose_worker import native_prediction
    p=pose(1)[0];cam=np.array([0,0,5.]);k=np.array([[600,0,320],[0,600,240],[0,0,1.]])
    predicted={'pred_keypoints_3d':p,'pred_cam_t':cam,'focal_length':600,
               'pred_keypoints_2d':project(p+cam,k)}
    xyz,xy,translation,intrinsics,okay=native_prediction(predicted,(480,640,3))
    assert okay
    np.testing.assert_allclose(project(xyz+translation,intrinsics),xy)
    predicted['pred_keypoints_2d']+=3
    assert not native_prediction(predicted,(480,640,3))[-1]


def test_complete_pipeline_exports_four_timed_videos_and_no_public_pose_points(tmp_path,video):
    pytest.importorskip('ai_coach')
    from ai_coach.service import CoachService
    from ai_coach.config import Settings
    from baseball_batting.ingest import ingest,iter_frames
    from baseball_batting.sam_measurement_worker import process_predictions
    from fractions import Fraction
    opts=options(coaching=False)
    capture=ingest(video,opts.metadata());n=capture['frame_count'];first=capture['frames'][0]
    raw=raw_pose(pose(n),first['width'],first['height'])
    service=CoachService(Settings(_env_file=None,google_api_key=None,cache_path=tmp_path/'cache.sqlite',log_dir=tmp_path/'logs'))
    report=process_predictions(tmp_path,video,capture,raw,opts,{'name':'synthetic contract fixture; not SAM inference'},coach_service=service)
    SamBattingResult.model_validate(report)
    assert len(report['groups'])==4
    for group in report['groups']:
        clip=group['annotated_video'];assert clip['status']=='available' and clip['overlay'] is True
        frames=list(iter_frames(tmp_path/'group-videos'/(group['key']+'.mp4')))
        assert len(frames)==n
        actual=[float(pts*base) for _,pts,base,_ in frames]
        expected=[f['playback_s']-capture['frames'][0]['playback_s'] for f in capture['frames']]
        np.testing.assert_allclose(actual,expected,atol=2e-6)
        assert all(m['coaching'] for s in group['swings'] for m in s['measurements'])
    dumped=json.dumps(report)
    assert 'points_corrected_3d' not in dumped and 'timestamp_s' not in dumped and 'points_relative' not in dumped
    assert (tmp_path/'corrected-points-private.npz').exists()