Spaces:
Running on T4
Running on T4
File size: 6,241 Bytes
e21e264 | 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 | from copy import deepcopy
import numpy as np
import pytest
from baseball_batting.bat_ball_timing import visual_contact, physical_shift
from baseball_batting.api_contract import AnalysisInput
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 contact_sequence(*, tee=False, fps=120):
result = timing_result(fps)
track = result['pose_track']; rep = track['reps'][0]
rep['events']['finish'] = {'frame': 125, 'method': 'test'}
rows = []
# A directly observed ball changes direction at frame 100; bat crosses
# that location. This is a geometry fixture, not an accuracy benchmark.
for i, t in enumerate(track['frames']['t_s']):
phase = t-100/fps
xy = [100 + (0 if tee else 300*phase), 80] if phase <= 0 else [100-400*phase, 80-300*phase]
rows.append({'frame': i, 'capture_time_s': t,
'bat': [{'points': [[100-800*phase, 20], [100-800*phase, 130]]}],
'ball': [{'point': xy, 'radius_px': 2.}]})
return result, {'frames': rows}
@pytest.mark.parametrize('tee', [False, True])
def test_actual_visual_endpoint_supplies_duration_and_rich_event(tee):
result, observed = contact_sequence(tee=tee)
track = result['pose_track']; rep = track['reps'][0]
hit = visual_contact(observed, track, rep, practice_type='tee' if tee else 'live')
assert hit['outcome'] == 'hit'
assert hit['time_interval_s'][0] <= 100/120 <= hit['time_interval_s'][1]
report = build_load_timing_report(result, ball_evidence={1: hit})
values = metrics(report)
assert values['swing_duration_ms']['value'] == pytest.approx(333.333)
assert values['swing_duration_ms']['end_event'] == 'contact'
assert values['early_late_shift_ms']['status'] == 'not_applicable'
rich = TimingEvidencePayload.model_validate(build_timing_evidence(report, result, AnalysisInput(practice_type='tee' if tee else 'live')))
assert rich.legacy() == report['payload']
assert all(e.event != 'body_extension_proxy' for e in rich.reps[0].events)
endpoint = next(e for e in rich.reps[0].events if e.event == 'contact')
assert endpoint.accuracy_validated is False
assert ('tee_ball_departure' in endpoint.method) is tee
@pytest.mark.parametrize('failure', ['no_bat', 'gap', 'no_deflection', 'two_balls', 'tee_without_context', 'clock', 'low_fps'])
def test_projection_overlap_or_missing_objects_never_proves_a_hit_or_miss(failure):
result, observed = contact_sequence(tee=failure == 'tee_without_context', fps=25 if failure == 'low_fps' else 120)
if failure == 'no_bat':
for r in observed['frames']: r['bat'] = []
if failure == 'gap':
for i in range(97, 105): observed['frames'][i]['ball'] = []
if failure == 'no_deflection':
for i, r in enumerate(observed['frames']): r['ball'][0]['point'] = [100+(i-100)*3, 80]
if failure == 'two_balls':
for r in observed['frames']: r['ball'].append({'point': [p+.7 for p in r['ball'][0]['point']], 'radius_px': 2.})
if failure == 'clock': result['pose_track']['frames']['t_s'] = [None]*150
hit = visual_contact(observed, result['pose_track'], result['pose_track']['reps'][0])
assert hit['outcome'] == 'unknown' and hit['reason_code']
report = build_load_timing_report(result, ball_evidence={1: hit})
assert metrics(report)['swing_duration_ms']['value'] is None
def paths(crossing=.45, fps=60, speed=4.):
times = np.arange(fps+1)/fps
bat = np.zeros((len(times),2,3)); bat[:,:,0] = speed*(times[:,None]-crossing)
bat[:,1,1] = 1.; bat[:,:,2] = 5.
ball = np.column_stack([np.zeros(len(times)), np.full(len(times),.7), 5+speed*(times-.55)])
return times, bat, ball
def shift(t,b,p,**overrides):
kw = dict(bat_radius_m=.03, ball_radius_m=.0366, position_bound_m=.001)
return physical_shift(t,b,p,**(kw|overrides))
@pytest.mark.parametrize('crossing,sign', [(.45,1), (.65,-1)])
def test_timing_shift_sign_and_certified_feasible_value(crossing,sign):
t,b,p=paths(crossing)
out=shift(t,b,p)
assert out['reason_code'] is None
assert sign*out['value'] > 0
assert abs(out['value']-(.55-crossing)*1000) < 35
assert len(out['feasible_shift_intervals_ms']) == 1
a,z=out['feasible_shift_intervals_ms'][0]
assert a <= out['value'] <= z
assert out['selection_policy'] == 'closest_to_zero_certified_feasible_shift'
def test_realistic_pitch_and_bat_speed_fit_search_budget():
t,b,p=paths(speed=40.)
out=shift(t,b,p)
assert out['value'] is not None and out['value'] > 0
def test_unreachable_is_limited_to_observed_window_not_a_global_claim():
t,b,p=paths(); p[:,1]=2
out=shift(t,b,p)
assert out['value'] is None
assert out['reason_code'] == 'no_feasible_shift_in_observed_window'
@pytest.mark.parametrize('failure,reason', [('gap','spatial_track_incomplete'),('nan','spatial_track_incomplete'),
('budget','search_resolution_insufficient'),('bound','shift_unresolved_under_position_error'),
('edge','shift_search_boundary'),('zero','ambiguous_time_shift')])
def test_unresolved_search_never_invents_shift(failure,reason):
t,b,p=paths(crossing=.55 if failure=='zero' else .31 if failure=='edge' else .45)
kw={}
if failure=='gap': t=t[::3]; b=b[::3]; p=p[::3]
if failure=='nan': b[20,0,0]=np.nan
if failure=='budget': kw['max_cells']=10
if failure=='bound': kw['position_bound_m']=.03
out=shift(t,b,p,**kw)
assert out['value'] is None and out['reason_code']==reason
def test_disconnected_shift_bands_are_retained_without_average():
t,b,p=paths(); b[:,:,0] = (20*(t-.3)*(t-.8))[:,None]
out=shift(t,b,p,max_shift_s=.4)
assert out['value'] is None and out['reason_code']=='ambiguous_time_shift'
assert len(out['feasible_shift_intervals_ms'])==2
def test_background_ball_bounce_near_stationary_bat_is_not_swing_contact():
result,observed=contact_sequence()
for row in observed['frames']:
row['bat']=[{'points':[[100,20],[100,130]]}]
out=visual_contact(observed,result['pose_track'],result['pose_track']['reps'][0])
assert out['outcome']=='unknown'
|