import numpy as np import pytest from baseball_batting.api_contract import StereoTrackingInput, AnalysisInput from baseball_batting.tracking_geometry import reconstruct_rep, _sample from baseball_batting.load_timing import build_load_timing_report from baseball_batting.timing_evidence import build_timing_evidence, TimingEvidencePayload from test_load_timing import timing_result, metrics def two_view_fixture(fps=120): n=150; t=np.arange(n)/fps result=timing_result(fps); track=result['pose_track']; rep=track['reps'][0] rep['events']['swing_start']['frame']=45 rep['events']['load_start']['frame']=15 rep['events']['foot_contact']['frame']=30 rep['events']['finish']={'frame':125,'method':'test'} k=np.array([[1000.,0,640],[0,1000.,480],[0,0,1]]) r=np.eye(3) translations=[np.array([0.,0,0]),np.array([-1.,.3,0])] config=StereoTrackingInput.model_validate(dict( cameras=[{'intrinsics':k.tolist(),'rotation':r.tolist(),'translation_m':v.tolist()} for v in translations], source='Synthetic calibration fixture',synchronization_source='Same fixture clock', secondary_offset_s=0.,synchronization_bound_ms=0.,position_bound_m=.001, position_bound_source='Exact linear fixture paths; includes interpolation',bat_length_m=1., barrel_radius_m=.03,secondary_timing={'kind':'unretimed','source':'Fixture clock'})) # A miss: bat crosses x=0 at .65s, ball crosses z=5 at .75s. bat=np.zeros((n,2,3)); bat[:,:,0]=4*(t[:,None]-.65); bat[:,1,1]=1.; bat[:,:,2]=5. ball=np.column_stack([np.zeros(n),np.full(n,.7),5+4*(t-.75)]) def project(p,v): h=(p+v)@k.T return (h[...,:2]/h[...,2:3]).tolist() observations=[] for v in translations: frames=[] for i in range(n): bp=project(bat[i],v); pp=project(ball[i],v) frames.append({'capture_time_s':float(t[i]),'bat':[{'points':bp}], 'ball':[{'point':pp, 'radius_px':3.}]}) if len(observations)==0: track['frames']['kp'][i][9]=bp[0]; track['frames']['kp'][i][10]=bp[0] observations.append({'frames':frames}) return result,observations,config def test_two_views_supply_physical_miss_and_nonempty_shift(): result,(a,b),config=two_view_fixture() rep=result['pose_track']['reps'][0] out=reconstruct_rep(a,b,result['pose_track'],rep,config) assert out['outcome']=='miss',out assert out['end_event']=='closest_approach' assert out['shift']['value'] is not None and out['shift']['value'] > 0 assert out['spatial']['max_reprojection_px'] < 1e-6 report=build_load_timing_report(result,ball_evidence={1:out}) assert all(v['value'] is not None for v in metrics(report).values()) options=AnalysisInput(timing={'kind':'unretimed','source':'Fixture'},stereo_tracking=config,practice_type='live',camera_stability='fixed_verified') rich=TimingEvidencePayload.model_validate(build_timing_evidence(report,result,options)) assert rich.legacy()==report['payload'] assert rich.reps[0].metrics[3].uncertainty.kind=='supplied_geometry_bound' @pytest.mark.parametrize('failure,reason',[('ball_gap','spatial_track_incomplete'), ('bat_gap','spatial_track_incomplete'),('multiple','ball_identity_ambiguous'), ('hands','barrel_identity_unresolved'),('clock','synchronization_unresolved'), ('length','bat_geometry_ambiguous')]) def test_missing_or_ambiguous_two_view_evidence_withholds(failure,reason): result,(a,b),config=two_view_fixture() if failure=='ball_gap': b['frames'][60]['ball']=[] if failure=='bat_gap': b['frames'][60]['bat'][0]['points']=None if failure=='multiple': b['frames'][60]['ball'] *= 2 if failure=='hands': for row in result['pose_track']['frames']['kp']: row[9:11]=[None,None] if failure=='clock': b['frames'][60]['capture_time_s']=b['frames'][59]['capture_time_s'] if failure=='length': config.bat_length_m=.4 out=reconstruct_rep(a,b,result['pose_track'],result['pose_track']['reps'][0],config) assert out['outcome']=='unknown' and out['reason_code']==reason def test_interpolation_state_and_no_gap_fill(): rows=[{'ball':[{'point':[0.,0]}]}, {'ball':[{'point':[2.,2]}]}] got=_sample(rows,np.array([0.,1/60]),1/120,'ball') assert got[0]['point']==[1.,1.] and got[0]['state']=='interpolated_between_observed_frames' rows[1]['ball']=[] assert _sample(rows,np.array([0.,1/60]),1/120,'ball')==[] assert _sample(rows,np.array([0.,1/60]),-1/120,'ball')==[] def test_return_from_net_does_not_supply_an_early_late_correction(): result,(a,b),config=two_view_fixture() # Reverse the observed flight after the approach window, preserving valid # camera projections/scale. This is another interaction, not this pitch. for frames in (a['frames'],b['frames']): for i in range(100,126): frames[i]['ball']=frames[200-i]['ball'] out=reconstruct_rep(a,b,result['pose_track'],result['pose_track']['reps'][0],config) assert out['outcome']=='unknown' and out['reason_code']=='incoming_ball_motion_unresolved'