baseball-engine / tests /test_motion_refinement.py
github-actions[bot]
Automated Deploy: bfc2534d4ddb0a114466a5bed5d28d2e173f8a17
ebede04
Raw History Blame Contribute Delete
18.6 kB
"""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