Spaces:
Running on T4
Running on T4
Download tests/test_pitcher_direction.py from modventures/baseball-engine: direct link, hf CLI and curl.
- Browser
- Download file 12.7 kB
-
https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_pitcher_direction.py
- Command line
-
hf download hf://spaces/modventures/baseball-engine/tests/test_pitcher_direction.py
-
curl -L -o test_pitcher_direction.py https://huggingface.co/spaces/modventures/baseball-engine/resolve/main/tests/test_pitcher_direction.py
12.7 kB
| """Independent projected floor truth, abstention, and shared adapter integration.""" | |
| import copy | |
| import json | |
| import numpy as np | |
| import pytest | |
| from scipy.spatial.transform import Rotation | |
| from baseball_batting.motion_contract import MotionInput | |
| from baseball_batting.camera_up import reference | |
| from baseball_batting.pitcher_direction import resolve | |
| from baseball_batting.geometry import project | |
| from baseball_batting.ingest import ingest | |
| from baseball_batting.motion_export import export_motion,reproduce_measurements | |
| from test_motion_player import raw_for | |
| def capture(w=1920,h=1080): | |
| return {'frames':[{'width':w,'height':h,'pts':i*11,'time_base':'1/1000','playback_s':3+i*.011} for i in range(8)]} | |
| def scene(angles=(0,0,0),height=1.5,distortion=None): | |
| rotation=Rotation.from_euler('xyz',angles,degrees=True).as_matrix() | |
| truth=np.array([[-1.,height,4.],[2.,height,6.]])@rotation.T | |
| up=rotation@np.array([0.,-1.,0.]);direction=truth[1]-truth[0];direction/=np.linalg.norm(direction) | |
| k=np.array([[900,0,925],[0,900,500],[0,0,1.]]) | |
| pixels=project(truth,k,distortion) | |
| opts=MotionInput(camera_stability='fixed_verified',up_vector=up,up_source='Known synthetic gravity', | |
| camera={'fx':900,'fy':900,'cx':925,'cy':500,'source':'Known synthetic camera', | |
| 'distortion':distortion,'calibration_status':'calibrated'}, | |
| pitcher_floor_points={'source_frame_index':3,'near_batter':pixels[0],'toward_pitcher':pixels[1]}) | |
| return opts,direction | |
| def test_projected_floor_points_recover_camera_direction_with_camera_tilt_and_distortion(angles,distortion): | |
| opts,truth=scene(angles,distortion=distortion);out=resolve(opts,capture(),reference(opts)) | |
| assert out['status']=='estimated' and out['reliable'] is True,out | |
| np.testing.assert_allclose(out['pitcher_vector'],truth,atol=1e-9) | |
| assert np.linalg.norm(out['pitcher_vector'])==pytest.approx(1) | |
| assert np.dot(out['pitcher_vector'],opts.up_vector)==pytest.approx(0,abs=1e-10) | |
| assert out['source_frame']['source_frame_index']==3 and out['source_frame']['source_pts']==33 | |
| assert out['source_frame']['video_time_s']==pytest.approx(.033) | |
| assert out['evaluated_scenarios']==289 and out['confidence'] is None and not out['accuracy_validated'] | |
| assert opts.pitcher_vector is None | |
| def test_point_order_sets_direction_and_camera_height_is_not_required(): | |
| opts,truth=scene();first=resolve(opts,capture(),reference(opts)) | |
| data=opts.model_dump(mode='json');p=data['pitcher_floor_points'];p['near_batter'],p['toward_pitcher']=p['toward_pitcher'],p['near_batter'] | |
| reverse=resolve(MotionInput(**data),capture(),reference(opts)) | |
| np.testing.assert_allclose(reverse['pitcher_vector'],-truth,atol=1e-10) | |
| # Scaling all physical camera-relative points preserves the source pixels. | |
| xyz=np.array([[-1.,1.5,4.],[2.,1.5,6.]]) | |
| k=np.array([[1100,0,925],[0,1050,500],[0,0,1.]]) | |
| np.testing.assert_allclose(project(xyz,k),project(xyz*4.3,k)) | |
| assert first['assumptions'][1]=='camera_above_floor' | |
| def test_unreliable_inputs_are_unknown_with_actionable_reasons(patch,reason): | |
| opts,_=scene();data=opts.model_dump(mode='json') | |
| for key,value in patch.items():data[key]={**data[key],**value} if isinstance(value,dict) else value | |
| opts=MotionInput(**data);out=resolve(opts,capture(),reference(opts)) | |
| assert out['status']=='unknown' and out['reason_code']==reason,out | |
| assert out['pitcher_vector'] is None and out['pitcher_source'] is None | |
| assert not out['applied'] and not out['reliable'] | |
| def test_accepted_estimated_up_is_used_with_its_uncertainty_and_unreliable_up_is_rejected(): | |
| opts,_=scene();auto={**reference(opts),'status':'estimated','reliable':True, | |
| 'maximum_model_uncertainty_deg':2.,'maximum_deviation_deg':.5} | |
| out=resolve(opts,capture(),auto) | |
| assert out['status']=='estimated' and out['up_sensitivity_deg_used']==2.5,out | |
| assert resolve(opts,capture(),{**auto,'reliable':False})['reason_code']=='pitcher_up_reference_unreliable' | |
| assert resolve(opts,capture(),{**auto,'maximum_model_uncertainty_deg':None})['reason_code']=='pitcher_up_uncertainty_unknown' | |
| out=resolve(opts,capture(),{**auto,'maximum_model_uncertainty_deg':8.}) | |
| assert out['status']=='unknown' and out['reason_code'].startswith('floor_direction_uncertainty'),out | |
| def test_changed_frame_dimensions_do_not_silently_reuse_calibration(): | |
| opts,_=scene();c=capture();c['frames'][6]['width']=1280 | |
| assert resolve(opts,c,reference(opts))['reason_code']=='source_image_dimensions_changed' | |
| def test_explicit_manual_vector_and_source_take_priority_without_normalization(): | |
| opts=MotionInput(pitcher_vector=[-2.,.1,3.],pitcher_source='Surveyed camera-space vector', | |
| pitcher_floor_points={'source_frame_index':500,'near_batter':[1,1],'toward_pitcher':[1,1]}) | |
| out=resolve(opts,None,None) | |
| assert out['status']=='provided' and out['method']=='caller_supplied' and out['reliable'] is None | |
| assert out['pitcher_vector']==[-2.,.1,3.] and out['pitcher_source']==opts.pitcher_source | |
| assert resolve(MotionInput(),None,None)['reason_code']=='floor_points_not_supplied' | |
| def test_shared_export_applies_floor_reference_preserves_inputs_and_reproduces_all_measurements(tmp_path,video,model,automatic_up): | |
| from baseball_batting.motion_contract import MotionFrame,ProjectionFrame | |
| opts=MotionInput(model=model,annotated_videos=False,single_swing=True,handedness='right', | |
| camera_stability='fixed_verified',timing={'kind':'unretimed','source':'Known synthetic clock'}, | |
| up_vector=None if automatic_up else [0,-1,0],up_source=None if automatic_up else 'Known synthetic gravity', | |
| camera={'fx':100,'fy':110,'cx':80,'cy':40,'source':'Known synthetic calibration','calibration_status':'calibrated'}, | |
| pitcher_floor_points={'source_frame_index':2,'near_batter':[63.333333333333,95],'toward_pitcher':[110,73], | |
| 'selection_uncertainty_px':.5}, | |
| windows=[{'start_frame':0,'end_frame':7,'baseline_frame':1,'stride_start_frame':2,'landing_frame':5}]) | |
| c=ingest(video,opts.metadata());raw=raw_for(c);original=copy.deepcopy(opts.model_dump(mode='json')) | |
| k=np.array([[100,0,80],[0,110,40],[0,0,1.]]) | |
| raw['intrinsics'][:]=k | |
| raw['projection']=np.stack([project(p+t,k) for p,t in zip(raw['points_body'],raw['camera_translation'])]) | |
| auto=None if not automatic_up else {**reference(opts),'status':'estimated','reliable':True, | |
| 'up_vector':[0,-1,0],'up_source':'Test image estimator','maximum_model_uncertainty_deg':1.,'maximum_deviation_deg':.2} | |
| manifest=export_motion(tmp_path,video,c,raw,opts,{'name':'fixture'}, | |
| {'analysis_id':'floor-fixture','analysis_revision':1},up_reference=auto) | |
| assert opts.model_dump(mode='json')==original==manifest.pipeline['inputs'] | |
| estimated=manifest.coordinates['pitcher_estimation'];assert estimated['status']=='estimated',estimated | |
| np.testing.assert_allclose(manifest.coordinates['pitcher_vector'],[2**-.5,0,2**-.5],atol=1e-10) | |
| assert manifest.coordinates['frame']=='declared_field_axes' | |
| assert manifest.pipeline['calculation_inputs']['pitcher_vector']==estimated['pitcher_vector'] | |
| report=json.loads((tmp_path/'measurements.json').read_text()) | |
| assert report['pitcher_reference']==estimated | |
| assert json.loads((tmp_path/'quality.json').read_text())['pitcher_reference']==estimated | |
| stride=next(m for m in report['summaries'] if m['metric_id']=='stride_relative_forward_cm') | |
| assert stride['value'] is not None and 'pitcher_reference_estimated_from_floor_points' in stride['quality_flags'] | |
| reproduced=reproduce_measurements(manifest,tmp_path/'motion.jsonl') | |
| values={(s.rep,m.key):m.value for swings in reproduced.values() for s in swings for m in s.measurements} | |
| for row in report['summaries']: | |
| expected=values[row['rep'],row['metric_id']] | |
| assert row['value']==pytest.approx(expected) if expected is not None else row['value'] is None | |
| rotation=np.array(manifest.coordinates['camera_to_export_rotation']) | |
| for a,b in zip((tmp_path/'motion.jsonl').read_text().splitlines(),(tmp_path/'projections.jsonl').read_text().splitlines()): | |
| frame=MotionFrame.model_validate_json(a);projection=ProjectionFrame.model_validate_json(b) | |
| for name,joint in frame.joints.items(): | |
| if joint.position is not None and projection.joints[name]['valid']: | |
| camera=(np.array(joint.position)+frame.root_translation)@rotation | |
| np.testing.assert_allclose(project(camera,projection.camera_intrinsics),projection.joints[name]['pixel'],atol=1e-9) | |
| def test_observed_camera_motion_blocks_floor_estimation_but_keeps_manual_inputs(tmp_path,video): | |
| opts=MotionInput(camera_stability='fixed_verified',annotated_videos=False, | |
| up_vector=[0,-1,0],up_source='test',pitcher_floor_points={'source_frame_index':0,'near_batter':[40,100],'toward_pitcher':[120,100]}) | |
| c=ingest(video,opts.metadata()) | |
| manifest=export_motion(tmp_path,video,c,raw_for(c),opts,{'name':'fixture'}, | |
| {'analysis_id':'test','analysis_revision':1},refinement={'image_evidence':{'declared_static_camera_conflict':True}}) | |
| assert manifest.pipeline['inputs']['camera_stability']=='fixed_verified' | |
| assert manifest.coordinates['pitcher_estimation']['reason_code']=='camera_not_fixed_for_pitcher_reference' | |
| assert manifest.pipeline['calculation_inputs']['pitcher_vector'] is None | |
| def test_floor_selection_uses_upright_image_after_source_rotation(tmp_path,video): | |
| opts=MotionInput(rotation_degrees=90,annotated_videos=False,single_swing=True,camera_stability='fixed_verified', | |
| up_vector=[0,-1,0],up_source='Upright source gravity', | |
| camera={'fx':100,'fy':100,'cx':60,'cy':60,'source':'Upright test calibration','calibration_status':'calibrated'}, | |
| pitcher_floor_points={'source_frame_index':1,'near_batter':[30,130],'toward_pitcher':[95,100]}) | |
| c=ingest(video,opts.metadata());out=resolve(opts,c,reference(opts)) | |
| assert out['status']=='estimated',out | |
| assert (out['source_frame']['image_width'],out['source_frame']['image_height'])==(120,160) | |
| bad=opts.model_copy(update={'pitcher_floor_points':opts.pitcher_floor_points.model_copy(update={'toward_pitcher':(140,100)})}) | |
| assert resolve(bad,c,reference(opts))['reason_code']=='floor_points_outside_source_image' | |
| def test_malformed_floor_options_rejected_at_request_validation(value): | |
| with pytest.raises(ValueError):MotionInput(pitcher_floor_points=value) | |