File size: 12,085 Bytes
9ec8d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe40b87
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ec8d34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe40b87
 
 
9ec8d34
 
 
 
 
 
 
 
 
 
 
 
 
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
"""Known synthetic motion and pipeline regression, not real-video accuracy labels."""
import json

import av
import numpy as np
import pytest
from scipy.spatial.transform import Rotation
from test_sam_batting import pose, raw_pose

from baseball_batting.body_pitcher_direction import METHOD, estimate
from baseball_batting.ingest import ingest
from baseball_batting.motion_contract import MotionInput
from baseball_batting.motion_export import export_motion, reproduce_measurements


def swing(side=1, fps=30):
    """A stationary-foot swing with a known target along -side * X.

    Independently prescribed smooth hand travel and rotating torso. No production
    constants or event-window code defines the truth. Left/right are anatomical.
    """
    t = np.arange(0, 3, 1/fps)
    p = pose(len(t))
    q = (1+np.tanh((t-1.5)/.15))/2
    for joints, theta in (([9, 10], .7*q), ([5, 6], 1.4*q)):
        r = Rotation.from_rotvec(np.column_stack([q*0, -side*theta, q*0])).as_matrix()
        p[:, joints] = np.einsum('nij,nkj->nki', r, p[:, joints])
    hand = np.column_stack([side*(.35-.9*q), -.5+.1*q, .15+.4*np.sin(np.pi*q)])
    p[:, 41] = hand+[0, -.03, 0]
    p[:, 62] = hand+[0, .03, 0]
    p[:, 7] = (p[:, 5]+p[:, 62])/2
    p[:, 8] = (p[:, 6]+p[:, 41])/2
    return p, t, np.array([-float(side), 0, 0])


def run(p, t, up=(0, -1, 0), **kwargs):
    options = kwargs.pop('options', MotionInput(up_vector=up, up_source='Fixture vertical'))
    corrected = {'points_relative': p, 'boundary': np.zeros(p.shape[:2], bool),
                 'valid': np.isfinite(p).all(axis=-1)}
    corrected.update(kwargs.pop('masks', {}))
    return estimate(corrected, t, options, {}, **kwargs)


@pytest.mark.parametrize('side', [-1, 1])
@pytest.mark.parametrize('angles', [(0, 0, 0), (10, 60, -12), (-20, 150, 30), (80, -90, 25)])
@pytest.mark.parametrize('fps', [30, 60])
def test_no_plate_camera_calibration_or_handedness_needed(side, angles, fps):
    p, t, truth = swing(side, fps)
    r = Rotation.from_euler('xyz', angles, degrees=True).as_matrix()
    out = run(p @ r.T, t, up=r @ [0., -1., 0.])
    assert out['status'] == 'estimated', out
    assert np.degrees(np.arccos(np.clip(out['pitcher_vector'] @ (r @ truth), -1, 1))) < 2
    assert abs(np.dot(out['pitcher_vector'], r @ [0., -1., 0.])) < 1e-12
    assert out['reference_kind'] == 'estimated_batting_direction'
    assert out['accuracy_validated'] is False and out['confidence'] is None
    assert not out['target_alignment_verified']


def test_translation_scale_slow_motion_and_small_pose_noise():
    p, t, truth = swing()
    rng = np.random.default_rng(2026)
    p += rng.normal(0, .0015, p.shape)
    p = p*1.7+np.column_stack([t*.4, t*.1, -t*.2])[:, None, :]
    out = run(p, t*2)
    assert out['status'] == 'estimated', out
    assert np.degrees(np.arccos(np.clip(out['pitcher_vector'] @ truth, -1, 1))) < 3


@pytest.mark.parametrize('side', [-1, 1])
@pytest.mark.parametrize('fps', [30, 60])
def test_turning_during_preparation_does_not_invalidate_a_later_stable_setup(side, fps):
    p, t, truth = swing(side, fps)
    # A gradual walk-in/load changes body orientation, then settles before the
    # swing. V1 rejected the entire low-speed stretch (15.7 degrees at 30 fps).
    # This reconstructs the failure mechanism, not the server's unavailable 3D track.
    yaw = np.radians(28)*np.clip(1-t/1.1, 0, 1)
    rotation = Rotation.from_rotvec(np.column_stack([t*0, -yaw, t*0])).as_matrix()
    p = np.einsum('nij,nkj->nki', rotation, p)
    result = run(p, t)
    assert result['status'] == 'estimated', result
    assert np.degrees(np.arccos(np.clip(result['pitcher_vector'] @ truth, -1, 1))) < 3
    accepted = next(row for row in result['candidates'] if row['accepted'])
    assert accepted['setup_search_spread_deg'] > 12
    assert accepted['setup_spread_deg'] <= 12
    assert accepted['setup_start_frame'] > accepted['setup_search_start_frame']
    assert accepted['setup_end_frame'] < accepted['peak_frame'] < accepted['extension_start_frame']
    assert accepted['setup_end_frame']-accepted['setup_start_frame']+1 >= 5


def test_setup_without_five_consistent_frames_is_still_rejected():
    p, t, _ = swing()
    # Sustained alternating bad torso observations have no locally stable setup.
    yaw = np.radians(np.where(np.arange(40) % 2, -20, 20))
    rotation = Rotation.from_rotvec(np.column_stack([yaw*0, yaw, yaw*0])).as_matrix()
    for joints in ([9, 10], [5, 6]):
        p[:40, joints] = np.einsum('nij,nkj->nki', rotation, p[:40, joints])
    result = run(p, t)
    assert result['status'] == 'unknown', result
    assert result['reason_code'] == 'setup_axis_unstable'


def test_stride_and_foot_angle_do_not_define_direction():
    p, t, _ = swing()
    expected = run(p, t)['pitcher_vector']
    p[:, 13:21] = np.nan  # Upper-body evidence works even if feet are cropped.
    assert run(p, t)['pitcher_vector'] == expected
    p[:, 13] = np.column_stack([t*0, t*0+.9, t])  # Deliberately sideways stride.
    assert run(p, t)['pitcher_vector'] == expected


@pytest.mark.parametrize('damage', ['no_setup', 'no_extension', 'gap', 'boundary', 'mask',
                                  'sequence_break', 'clock_gap', 'separate_hands', 'no_hip_turn'])
def test_incomplete_or_conflicting_body_evidence_stays_unknown(damage):
    p, t, _ = swing()
    kwargs = {}
    if damage == 'no_setup':
        p, t = p[46:], t[46:]
    elif damage == 'no_extension':
        p, t = p[:44], t[:44]
    elif damage == 'gap':
        p[44:47, 41] = np.nan
    elif damage in ('boundary', 'mask'):
        mask = np.zeros(p.shape[:2], bool)
        mask[44:47, 41] = True
        kwargs['masks'] = {('boundary' if damage == 'boundary' else 'valid'): mask if damage == 'boundary' else ~mask}
    elif damage == 'sequence_break':
        kwargs['sequence_ids'] = np.arange(len(t)) >= 45
    elif damage == 'clock_gap':
        t[45:] += 1
    elif damage == 'separate_hands':
        p[:, 41, 2] += 1
    elif damage == 'no_hip_turn':
        p[:, [9, 10]] = p[0, [9, 10]]
    result = run(p, t, **kwargs)
    assert result['status'] == 'unknown', result
    assert result['pitcher_vector'] is None and not result['applied']


@pytest.mark.parametrize('kind', ['still', 'noise', 'hand_wave'])
def test_non_swing_motion_does_not_produce_a_direction(kind):
    p, t, _ = swing()
    if kind != 'hand_wave':
        p[:] = p[0]
    if kind == 'noise':
        p += np.random.default_rng(6).normal(0, .001, p.shape)
    if kind == 'hand_wave':
        p[:, [5, 6, 9, 10]] = p[0, [5, 6, 9, 10]]
    assert run(p, t)['status'] == 'unknown'


@pytest.mark.parametrize('other_side', [1, -1])
def test_repeated_swings_require_direction_agreement(other_side):
    p, t, _ = swing()
    other, _, _ = swing(other_side)
    sequence = np.r_[np.zeros(len(t)), np.ones(len(t))]
    result = run(np.concatenate([p, other]), np.r_[t, t+3], sequence_ids=sequence)
    assert result['accepted_candidate_count'] == 2, result
    assert result['status'] == ('estimated' if other_side == 1 else 'unknown')
    if other_side == -1:
        assert result['reason_code'] == 'inconsistent_body_swing_directions'


def test_returning_to_setup_is_not_counted_as_another_forward_swing():
    p, _t, _ = swing()
    repeated = np.concatenate([p, p[::-1], p])
    result = run(repeated, np.arange(len(repeated))/30)
    assert result['status'] == 'estimated', result
    accepted = [row for row in result['candidates'] if row['accepted']]
    assert len(accepted) == 2
    assert all(not len(p) <= row['peak_frame'] < 2*len(p) for row in accepted)


def test_instant_pose_jump_is_not_a_swing():
    p, t, _ = swing()
    p[:45] = p[0]
    p[45:] = p[-1]
    assert run(p, t)['status'] == 'unknown'


def test_missing_vertical_and_camera_movement_are_explicit():
    p, t, _ = swing()
    assert run(p, t, options=MotionInput())['reason_code'] == 'automatic_up_unavailable'
    opts = MotionInput(up_vector=[0, -1, 0], up_source='Test', camera_stability='moving')
    assert run(p, t, options=opts)['reason_code'] == 'camera_moving'


@pytest.fixture
def swing_video(tmp_path):
    p, _, _ = swing()
    path = tmp_path/'swing.mp4'
    # Blank scene: a visible plate cannot be contributing any evidence.
    with av.open(str(path), 'w') as output:
        stream = output.add_stream('libx264', rate=30)
        stream.width, stream.height, stream.pix_fmt = 640, 480, 'yuv420p'
        for _ in p:
            for packet in stream.encode(av.VideoFrame.from_ndarray(np.zeros((480, 640, 3), np.uint8), format='bgr24')):
                output.mux(packet)
        for packet in stream.encode():
            output.mux(packet)
    return path, p


@pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
def test_both_exports_apply_body_direction_and_reproduce_measurements(tmp_path, swing_video, model, capsys):
    video, p = swing_video
    options = MotionInput(model=model, annotated_videos=False, camera_stability='fixed_verified',
                          single_swing=True, timing={'kind':'unretimed', 'source':'Fixture clock'})
    capture = ingest(video, options.metadata())
    automatic_up = {'status': 'estimated', 'reliable': True, 'up_vector': [0, -1, 0], 'up_source': 'Fixture provider',
                        'coordinate_frame': 'upright_camera_x_right_y_down_z_away'}
    manifest = export_motion(tmp_path, video, capture, raw_pose(p), options, {'name':'synthetic'},
                             {'analysis_id':'body-direction', 'analysis_revision':1}, up_reference=automatic_up)
    ref = manifest.coordinates['pitcher_estimation']
    assert ref['status'] == 'estimated' and ref['method'] == METHOD, ref
    assert manifest.coordinates['frame'] == 'estimated_batting_axes'
    assert manifest.coordinates['axes']['x'] == 'estimated_hitting_direction'
    assert manifest.pipeline['inputs']['pitcher_vector'] is None
    assert manifest.pipeline['inputs']['handedness'] is None
    assert manifest.pipeline['calculation_inputs']['pitcher_vector'] == ref['pitcher_vector']
    report = json.loads((tmp_path/'measurements.json').read_text())
    assert report['pitcher_reference'] == ref
    flags = [flag for metric in report['summaries'] for flag in metric['quality_flags']]
    assert 'pitcher_reference_estimated_from_body_motion' in flags
    assert 'target_alignment_unverified' in flags
    assert 'pitcher_reference_estimated_from_home_plate' not in flags
    reproduced = reproduce_measurements(manifest, tmp_path/'motion.jsonl')
    expected = {(s.rep, m.key): m.value for group in reproduced.values() for s in group for m in s.measurements}
    for row in report['summaries']:
        value = expected[row['rep'], row['metric_id']]
        assert row['value'] == pytest.approx(value) if value is not None else row['value'] is None
    from baseball_batting.job_terminal import JobTerminal
    JobTerminal('body-direction', tmp_path).finish('completed')
    output = capsys.readouterr().out
    assert 'pitcher=estimated vector=' in output
    assert f'method={METHOD}' in output
    evidence = next(row for row in ref['candidates'] if row['accepted'])
    assert f"pitcher_evidence frame={evidence['peak_frame']} setup={evidence['setup_start_frame']}-{evidence['setup_end_frame']}" in output


def test_explicit_direction_still_wins(tmp_path, swing_video, monkeypatch):
    video, p = swing_video
    def unexpected(*args, **kwargs):
        raise AssertionError('Automatic estimator called despite explicit direction')
    monkeypatch.setattr('baseball_batting.body_pitcher_direction.estimate', unexpected)
    opts = MotionInput(annotated_videos=False, up_vector=[0, -1, 0], up_source='Test',
                       pitcher_vector=[0, 0, 1], pitcher_source='Reviewed direction')
    manifest = export_motion(tmp_path, video, ingest(video, opts.metadata()), raw_pose(p), opts,
                             {'name':'fixture'}, {'analysis_id':'manual', 'analysis_revision':1})
    assert manifest.coordinates['pitcher_vector'] == [0, 0, 1]
    assert manifest.coordinates['pitcher_estimation']['status'] == 'provided'