File size: 18,617 Bytes
0a35b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebede04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a35b6f
 
 
 
 
 
 
 
 
11fcb85
 
 
 
 
 
 
 
 
 
 
 
ebede04
 
 
 
 
 
 
 
0a35b6f
 
 
 
 
 
 
 
 
 
 
11fcb85
 
 
 
 
 
 
 
 
 
0a35b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11fcb85
 
 
 
 
 
 
 
ebede04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a35b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebede04
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a35b6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11fcb85
0a35b6f
 
 
 
 
 
 
 
11fcb85
 
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
"""Known articulated motion, rejection/rollback, clocks, projection and API agreement."""
import json
import numpy as np
import pytest
from baseball_batting.motion_contract import MotionInput,RefinementSettings,MotionTrackingSettings
from baseball_batting.motion_refinement import (fit_window,acceptance,continuous_windows,project_torch,
    NAMES,LOCAL,INDICES,refine_sequence)
from baseball_batting.geometry import project
from baseball_batting.motion_tracking import AthleteRecovery
from baseball_batting.sam_motion import correct_motion
from test_motion_player import raw_for,inputs
from baseball_batting.ingest import ingest


def articulated_fixture(n=25):
    torch=pytest.importorskip('torch')
    # A constrained articulated rig with one shared shape. Positions are derived
    # from its rotations, never independently optimized joint coordinates.
    rest=np.zeros((20,3))
    for side,sign in [('left',-1),('right',1)]:
        for part,y in [('ear',-.75),('shoulder',-.5),('hip',0),('knee',.4),('ankle',.8),('heel',.83),('big_toe',.83),('small_toe',.83)]:
            rest[LOCAL[side+'_'+part]]=[sign*(.12 if part=='ear' else .2),y,0]
        rest[LOCAL[side+'_heel'],2]=-.08
        rest[LOCAL[side+'_big_toe'],2]=.15;rest[LOCAL[side+'_small_toe'],2]=.12
    base=torch.tensor(rest,dtype=torch.float32)
    def forward(pose,camera):
        p=base[None].expand(len(pose),-1,-1).clone()
        for side,sign in [('left',-1),('right',1)]:
            shoulder=LOCAL[side+'_shoulder'];elbow=LOCAL[side+'_elbow'];wrist=LOCAL[side+'_wrist']
            a=pose[:,1]+sign*.1
            direction=torch.stack([sign*.30*torch.cos(a),.30*torch.sin(a),torch.zeros_like(a)],-1)
            p[:,elbow]=p[:,shoulder]+direction
            p[:,wrist]=p[:,elbow]+direction
        yaw=pose[:,0];co,si=torch.cos(yaw),torch.sin(yaw)
        x=co[:,None]*p[...,0]+si[:,None]*p[...,2]
        z=-si[:,None]*p[...,0]+co[:,None]*p[...,2]
        return torch.stack([x,p[...,1],z],-1)+camera[:,None]
    times=np.cumsum(np.linspace(.014,.020,n));times-=times[0]
    truth_pose=np.column_stack([.2+times*.3,.5+1.2/(1+np.exp(-25*(times-.2)))])
    camera=np.tile([0,0,4.],(n,1))
    rng=np.random.default_rng(83)
    initial=truth_pose+rng.normal(0,.035,truth_pose.shape)
    with torch.no_grad():
        truth=forward(torch.tensor(truth_pose,dtype=torch.float32),torch.tensor(camera,dtype=torch.float32)).numpy()
        raw=forward(torch.tensor(initial,dtype=torch.float32),torch.tensor(camera,dtype=torch.float32)).numpy()
    k=np.tile([[650,0,320],[0,650,240],[0,0,1.]],(n,1,1))
    pixels=np.stack([project(p,K) for p,K in zip(truth,k)])
    return forward,initial,camera,raw,truth,pixels,times,k


def test_constrained_fit_improves_known_motion_without_stretching_limbs():
    forward,pose,camera,raw,truth,pixels,times,k=articulated_fixture()
    settings=RefinementSettings(iterations=45,learning_rate=.01).model_dump()
    result=fit_window(forward,pose,camera,raw,pixels,np.ones(pixels.shape[:2]),times,k,np.full(len(times),300),settings,device='cpu')
    before=np.mean(np.linalg.norm(raw-truth,axis=-1));after=np.mean(np.linalg.norm(result['points_camera']-truth,axis=-1))
    assert after<before*.6
    original_xy=np.stack([project(p,K) for p,K in zip(raw,k)])
    ok,checks=acceptance(raw,result['points_camera'],original_xy,result['projection'],pixels,
        np.ones(pixels.shape[:2]),times,np.full(len(times),300),settings)
    assert ok,checks
    for side in ('left','right'):
        a,b=[LOCAL[side+'_'+p] for p in ('shoulder','elbow')]
        np.testing.assert_allclose(np.linalg.norm(result['points_camera'][:,a]-result['points_camera'][:,b],axis=-1),.3,atol=2e-6)


def test_batched_native_gradients_match_whole_trajectory_gradients_across_batch_joins():
    torch=pytest.importorskip('torch')
    from baseball_batting.motion_refinement import accumulate_body_gradients
    forward,pose,camera,*_=articulated_fixture(12)
    def loss(points):
        return points.square().mean()+3*(points[2:]-2*points[1:-1]+points[:-2]).square().mean()
    p=torch.tensor(pose,dtype=torch.float32,requires_grad=True);c=torch.tensor(camera,dtype=torch.float32,requires_grad=True)
    loss(forward(p,c)).backward();expected_p=p.grad.clone();expected_c=c.grad.clone()
    p=torch.tensor(pose,dtype=torch.float32,requires_grad=True);c=torch.tensor(camera,dtype=torch.float32,requires_grad=True)
    with torch.no_grad():values=forward(p,c)
    points=values.detach().requires_grad_(True);loss(points).backward()
    accumulate_body_gradients(forward,p,c,points.grad,3)
    torch.testing.assert_close(p.grad,expected_p,atol=1e-6,rtol=1e-5)
    torch.testing.assert_close(c.grad,expected_c,atol=1e-6,rtol=1e-5)


def test_acceptance_rejects_worse_image_alignment_and_deformation():
    _,_,_,_,truth,pixels,times,k=articulated_fixture(12)
    candidate=truth.copy();candidate[:,LOCAL['left_wrist'],0]+=.4
    candidate_xy=np.stack([project(p,K) for p,K in zip(candidate,k)])
    ok,checks=acceptance(truth,candidate,pixels,candidate_xy,pixels,np.ones(pixels.shape[:2]),times,np.full(len(times),300),RefinementSettings().model_dump())
    assert not ok and 'body_proportions_changed' in checks['reasons']
    assert 'image_alignment_worsened' in checks['reasons']


def test_ambiguous_image_fit_cannot_select_a_pose_outside_its_trust_region():
    forward,pose,camera,raw,truth,pixels,times,k=articulated_fixture(16)
    pixels[:,LOCAL['left_wrist'],0]+=80
    settings=RefinementSettings(iterations=30,learning_rate=.03,maximum_body_change_fraction=.025).model_dump()
    fit=fit_window(forward,pose,camera,raw,pixels,np.ones(pixels.shape[:2]),times,k,np.full(len(times),300),settings,device='cpu')
    from baseball_batting.motion_refinement import body_size
    hip=[LOCAL['left_hip'],LOCAL['right_hip']]
    a=fit['points_camera']-fit['points_camera'][:,hip].mean(1)[:,None]
    b=fit['normalized_initializer']-fit['normalized_initializer'][:,hip].mean(1)[:,None]
    assert np.max(np.linalg.norm(a-b,axis=-1))/body_size(raw)<=.025001


def test_large_pts_origin_does_not_change_temporal_fit():
    f,p,c,raw,_,xy,t,k=articulated_fixture(12)
    s=RefinementSettings(iterations=8).model_dump();w=np.ones(xy.shape[:2]);heights=np.full(len(t),300)
    a=fit_window(f,p,c,raw,xy,w,t,k,heights,s,device='cpu')
    b=fit_window(f,p,c,raw,xy,w,t+1e7,k,heights,s,device='cpu')
    np.testing.assert_allclose(a['points_camera'],b['points_camera'],atol=1e-5)


def test_windows_preserve_every_owner_and_never_cross_identity_clock_or_missing_frames():
    t=np.arange(100)/60;t[60:]+=.3;valid=np.ones(100,bool);valid[30:33]=False
    sequence=np.zeros(100,int);sequence[80:]=1
    windows=list(continuous_windows(valid,t,sequence,24,5,.1));owners=np.zeros(100,int)
    for context,core in windows:
        owners[core]+=1
        assert np.diff(context).max()==1 and np.diff(t[context]).max()<.1
        assert len(np.unique(sequence[context]))==1
    assert (owners[valid]==1).all() and (owners[~valid]==0).all()


def test_window_seams_prefer_quiet_motion_without_losing_or_duplicating_frames():
    n=70;t=np.arange(n)/60;score=np.ones(n);score[24:43]=100
    windows=list(continuous_windows(np.ones(n,bool),t,np.zeros(n,int),48,8,.1,score))
    owners=np.zeros(n,int)
    for context,core in windows:
        assert len(context)<=48;owners[core]+=1
        if core[-1]!=n-1:assert not 26<=core[-1]<=40
    assert (owners==1).all()


def test_torch_and_public_distortion_projection_agree_and_have_gradients():
    torch=pytest.importorskip('torch')
    points=torch.tensor([[[.4,.3,2.],[-.3,.2,3.]]],requires_grad=True)
    k=torch.tensor([[[700.,0,320],[0,690,240],[0,0,1]]]);d=[-.2,.03,.001,-.002,.01]
    actual=project_torch(points,k,torch.tensor(d));expected=project(points.detach().numpy()[0],k.numpy()[0],d)
    np.testing.assert_allclose(actual.detach().numpy()[0],expected,atol=5e-5)
    actual.sum().backward();assert torch.isfinite(points.grad).all()


def test_accepted_rig_points_are_not_independently_smoothed(video):
    opts=inputs();capture=ingest(video,opts.metadata());raw=raw_for(capture)
    raw['refinement_accepted']=np.ones(capture['frame_count'],bool)
    t=np.array([f['playback_s'] for f in capture['frames']])
    corrected=correct_motion(raw,t,opts.correction)
    expected=raw['points_body']-(raw['points_body'][:,9]+raw['points_body'][:,10])[:,None]/2
    valid=corrected['valid']
    np.testing.assert_allclose(corrected['points_relative'][valid],expected[valid],atol=1e-12)


def test_short_loss_recovery_needs_spatial_and_appearance_agreement():
    tracker=AthleteRecovery(MotionTrackingSettings());image=np.zeros((200,300,3),np.uint8)
    image[20:180,30:120]=[0,0,255]
    def box(x=30):return {'class_id':0,'score':.9,'box':[x,20,x+90,180]}
    assert tracker.update(image,[box()],0)[0] is not None
    assert tracker.update(image,[],.05)[0] is None
    assert tracker.update(image,[box()],.1)[0] is not None
    tracker.update(image,[],.15)
    assert tracker.update(image,[box(190)],.2)[0] is None
    assert tracker.update(image,[box()],.5)[0] is None


def test_ambiguous_crossing_does_not_reidentify_by_clothing_alone():
    tracker=AthleteRecovery(MotionTrackingSettings());image=np.full((200,300,3),100,np.uint8)
    box=lambda x:{'class_id':0,'score':.9,'box':[x,20,x+90,180]}
    tracker.update(image,[box(30)],0)
    assert tracker.update(image,[box(30),box(40)],.02)[1]=='identity_ambiguous_multiple_overlapping_athletes'
    assert tracker.update(image,[box(30)],.04)[0] is None


def test_spatial_overlap_cannot_override_an_appearance_conflict():
    tracker=AthleteRecovery(MotionTrackingSettings());red=np.full((200,300,3),[0,0,255],np.uint8)
    blue=np.full((200,300,3),[255,0,0],np.uint8)
    person={'class_id':0,'score':.9,'box':[30,20,120,180]}
    tracker.update(red,[person],0)
    assert tracker.update(blue,[person],.02)[1]=='athlete_appearance_conflict'


def test_neighboring_images_reject_an_isolated_2d_detector_error_without_inventing_points():
    import cv2
    from baseball_batting.motion_evidence import flow_support,observation_weights
    rng=np.random.default_rng(6);source=cv2.GaussianBlur(rng.integers(0,255,(512,512),dtype=np.uint8),(5,5),0)
    middle=cv2.warpAffine(source,np.float32([[1,0,4],[0,1,0]]),(512,512),borderMode=cv2.BORDER_REFLECT)
    future=cv2.warpAffine(source,np.float32([[1,0,8],[0,1,0]]),(512,512),borderMode=cv2.BORDER_REFLECT)
    score=np.ones(1);wrong=np.array([[288.,256.]])
    f,ft=flow_support(source,middle,np.array([[256.,256.]]),wrong,score,score,.45)
    b,bt=flow_support(future,middle,np.array([[264.,256.]]),wrong,score,score,.45)
    assert ft[0] and bt[0] and not f[0] and not b[0]
    assert observation_weights(score,f,ft,b,bt)[0]==.25
    correct=np.array([[260.,256.]])
    f,ft=flow_support(source,middle,np.array([[256.,256.]]),correct,score,score,.45)
    b,bt=flow_support(future,middle,np.array([[264.,256.]]),correct,score,score,.45)
    assert observation_weights(score,f,ft,b,bt)[0]==1.
    # One corroborating neighbor wins over the other pair's failed observation.
    assert observation_weights(score,np.array([False]),np.array([True]),np.array([True]),np.array([True]))[0]==1.


def test_camera_input_preserves_legacy_sam_contract_and_rejects_bad_distortion():
    camera={'fx':700,'fy':690,'cx':320,'cy':240,'source':'calibration fixture','distortion':[-.2,.03,.001,-.002,.01]}
    options=MotionInput(camera=camera)
    assert options.sam_options().camera.fx==700
    assert options.camera.distortion[0]==-.2
    with pytest.raises(ValueError):MotionInput(camera={**camera,'distortion':[1,2]})


def test_export_uses_distortion_for_same_motion_video_and_reports_refinement(tmp_path,video):
    from baseball_batting.motion_export import export_motion,reproduce_measurements
    opts=inputs(annotated_videos=False,camera={'fx':60,'fy':60,'cx':160,'cy':120,'source':'fixture',
        'distortion':[-.05,.01,0,0,0]},timing={'kind':'unretimed','source':'fixture'})
    capture=ingest(video,opts.metadata());raw=raw_for(capture)
    raw['refinement_accepted']=np.ones(len(capture['frames']),bool)
    manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'fixture'},
        {'analysis_id':'fixture','analysis_revision':1},refinement={'enabled':True,'accepted_frame_count':len(capture['frames'])})
    motion=[json.loads(q) for q in (tmp_path/'motion.jsonl').read_text().splitlines()]
    projections=[json.loads(q) for q in (tmp_path/'projections.jsonl').read_text().splitlines()]
    r=np.asarray(manifest.coordinates['camera_to_export_rotation'])
    for frame,p in zip(motion,projections):
        for name,joint in frame['joints'].items():
            if joint['position'] is not None:
                xyz=(np.array(joint['position'])+frame['root_translation'])@r
                np.testing.assert_allclose(project(xyz,p['camera_intrinsics'],p['camera_distortion']),p['joints'][name]['pixel'],atol=1e-9)
    assert manifest.pipeline['refinement']['accepted_frame_count']==len(motion)
    groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
    values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
    for summary in json.loads((tmp_path/'measurements.json').read_text())['summaries']:
        assert summary['value']==values[summary['rep'],summary['metric_id']]
        assert summary['stability']['status']=='not_evaluated'


def test_numerically_bad_fit_rolls_back_without_filling_gap(monkeypatch):
    import baseball_batting.motion_refinement as module
    _,pose,camera,points,truth,pixels,times,k=articulated_fixture(12)
    n=len(times);body=np.full((n,70,3),np.nan);body[:,list(INDICES)]=points-camera[:,None]
    raw={'points_body':body,'camera_translation':camera,'intrinsics':k,'projection_valid':np.ones(n,bool),
         'projection':np.full((n,70,2),np.nan),'image_size':np.array([640,480])}
    evidence={'pixels':pixels,'weights':np.ones((n,20)),'box_heights':np.full(n,300),'frame_usable':np.ones(n,bool)}
    evidence['frame_usable'][6]=False
    def bad(*args,**kwargs):raise FloatingPointError('controlled optimizer failure')
    monkeypatch.setattr(module,'fit_window',bad)
    result,metadata=refine_sequence(lambda ids:None,{'pose':pose,'camera':camera},raw,evidence,times,
                                    RefinementSettings().model_dump(),.1,device='cpu')
    np.testing.assert_equal(result['points_body'],raw['points_body'])
    assert not result['refinement_accepted'].any() and metadata['accepted_frame_count']==0
    assert len(metadata['windows'])==2


@pytest.mark.parametrize('sensitivity_failure',[False,True])
def test_continuous_fit_has_no_artificial_derivative_seams_between_quality_windows(monkeypatch,sensitivity_failure):
    import baseball_batting.motion_refinement as module
    _,pose,camera,_,points,pixels,times,k=articulated_fixture(70);n=len(times)
    body=np.full((n,70,3),np.nan);body[:,list(INDICES)]=points-camera[:,None]
    raw={'points_body':body,'camera_translation':camera,'intrinsics':k,'projection_valid':np.ones(n,bool),
         'projection':np.full((n,70,2),np.nan),'image_size':np.array([640,480])}
    evidence={'pixels':pixels,'weights':np.ones((n,20)),'box_heights':np.full(n,300),'frame_usable':np.ones(n,bool)}
    calls=[]
    def known_fit(forward,p,c,target,*args,**kwargs):
        calls.append(len(p))
        if sensitivity_failure and len(calls)==2:raise FloatingPointError('Injected sensitivity failure')
        return {'points_camera':target.copy(),'projection':pixels.copy(),'pose':p.copy(),'camera':c.copy(),
                'normalized_initializer':target.copy()}
    monkeypatch.setattr(module,'fit_window',known_fit)
    result,metadata=refine_sequence(lambda ids:None,{'pose':pose,'camera':camera},raw,evidence,times,
                                    RefinementSettings().model_dump(),.1,device='cpu')
    assert calls==[n,n,n]  # One complete trajectory, plus its two sensitivity fits.
    assert len(metadata['windows'])>1 and result['refinement_accepted'].all()
    assert not result['refinement_boundary'].any()
    assert len(np.unique(result['sequence_ids']))==1
    if sensitivity_failure:
        assert not result['refinement_scenario_valid'][0].any()
        assert all(not w['sensitivity_complete'] for w in metadata['windows'])


def test_supported_fast_peak_cannot_be_delayed_by_fitting():
    _,_,_,_,truth,pixels,times,k=articulated_fixture(25)
    candidate=np.concatenate([truth[:1].repeat(3,axis=0),truth[:-3]])
    candidate_xy=np.stack([project(p,K) for p,K in zip(candidate,k)])
    ok,checks=acceptance(truth,candidate,pixels,candidate_xy,pixels,np.ones(pixels.shape[:2]),times,
                         np.full(len(times),300),RefinementSettings().model_dump())
    assert not ok
    assert 'fast_hand_peak_shifted' in checks['reasons']


def test_stability_reports_measurement_units_and_camera_conflict_is_reproducible(tmp_path,video):
    from baseball_batting.motion_export import export_motion,reproduce_measurements
    opts=inputs(annotated_videos=False,timing={'kind':'unretimed','source':'fixture'})
    capture=ingest(video,opts.metadata());raw=raw_for(capture);n=capture['frame_count']
    raw['refinement_accepted']=np.ones(n,bool)
    raw['refinement_scenario_points_body']=np.repeat(raw['points_body'][None],2,axis=0)
    raw['refinement_scenario_valid']=np.ones((2,n),bool)
    metadata={'enabled':True,'accepted_frame_count':n,'image_evidence':{'declared_static_camera_conflict':True}}
    manifest=export_motion(tmp_path,video,capture,raw,opts,{'name':'fixture'},
        {'analysis_id':'fixture','analysis_revision':1},refinement=metadata)
    assert manifest.pipeline['inputs']['camera_stability']=='fixed_verified'
    assert manifest.pipeline['calculation_inputs']['camera_stability']=='moving'
    assert manifest.coordinates['frame']=='camera_oriented_hip_relative'
    report=json.loads((tmp_path/'measurements.json').read_text())['summaries']
    groups=reproduce_measurements(manifest,tmp_path/'motion.jsonl')
    values={(s.rep,m.key):m.value for swings in groups.values() for s in swings for m in s.measurements}
    for summary in report:
        assert summary['value']==values[summary['rep'],summary['metric_id']]
        if summary['value'] is not None:
            assert summary['stability']['status']=='evaluated'
            assert summary['stability']['minimum']==summary['stability']['maximum']==summary['value']
    for key in ('head_excursion_relative_cm','hand_speed_relative_m_s'):
        assert next(m for m in report if m['metric_id']==key)['value'] is None