File size: 12,663 Bytes
220c87b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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


@pytest.mark.parametrize('angles',[(0,0,0),(12,-10,15),(-8,7,-22),(3,25,-10),(-12,-15,28)])
@pytest.mark.parametrize('distortion',[None,[-.12,.03,.001,-.002,.005]])
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'


@pytest.mark.parametrize('patch,reason',[
    ({'pitcher_floor_points':{'source_frame_index':8}},'floor_source_frame_out_of_range'),
    ({'pitcher_floor_points':{'near_batter':[-1,900]}},'floor_points_outside_source_image'),
    ({'pitcher_floor_points':{'near_batter':[0,900]}},'floor_point_uncertainty_outside_source_image'),
    ({'pitcher_floor_points':{'near_batter':[700,800],'toward_pitcher':[700,800]}},'floor_points_too_close'),
    ({'pitcher_floor_points':{'near_batter':[700,800],'toward_pitcher':[704,801]}},'floor_points_too_close'),
    ({'pitcher_floor_points':{'near_batter':[700,500],'toward_pitcher':[1300,850]}},'floor_points_not_below_horizon'),
    ({'pitcher_floor_points':{'near_batter':[700,510],'toward_pitcher':[1300,850]}},'floor_points_too_near_horizon'),
    ({'pitcher_floor_points':{'near_batter':[700,560],'toward_pitcher':[1300,850]}},'floor_direction_uncertainty_unreliable'),
    ({'camera':None},'pitcher_camera_calibration_missing'),
    ({'camera':{'calibration_status':'unknown'}},'pitcher_camera_calibration_unverified'),
    ({'camera':{'calibration_status':'estimated'}},'pitcher_camera_calibration_unverified'),
    ({'camera':{'cx':3000}},'pitcher_camera_calibration_implausible'),
    ({'camera':{'fx':1e7}},'pitcher_camera_calibration_implausible'),
    ({'camera':{'distortion':[-5,0,0,0,0]}},'camera_undistortion_unreliable'),
    ({'up_vector':None,'up_source':None},'pitcher_up_reference_unknown'),
    ({'camera_stability':'moving'},'camera_not_fixed_for_pitcher_reference'),
    ({'camera_stability':'unknown'},'camera_not_fixed_for_pitcher_reference'),
])
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'


@pytest.mark.parametrize('model',['sam3d','gvhmr'])
@pytest.mark.parametrize('automatic_up',[False,True])
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'


@pytest.mark.parametrize('value',[{'source_frame_index':True,'near_batter':[1,2],'toward_pitcher':[3,4]},
    {'source_frame_index':0,'near_batter':[float('nan'),2],'toward_pitcher':[3,4]},
    {'source_frame_index':0,'near_batter':[1,2,3],'toward_pitcher':[3,4]}])
def test_malformed_floor_options_rejected_at_request_validation(value):
    with pytest.raises(ValueError):MotionInput(pitcher_floor_points=value)