baseball-engine / tests /test_batting_measurements.py
github-actions[bot]
Automated Deploy: 0c9644d4b82d28d1b44a78e1b678fc6b46953d96
999db75
Raw History Blame Contribute Delete
13.8 kB
"""Numerical contract checks against constructed trajectories, not accuracy tests."""
from copy import deepcopy
import json
from pathlib import Path
import numpy as np
import pytest
from baseball_batting.api_contract import AnalysisInput
from baseball_batting.batting_measurements import (
analyze_batting, analysis_points, coach_payload, CAPTURE_REASONS)
def swing_track(fps=120, repeats=1, mirror=False):
n = 180
kp, feet = [], []
for i in range(n):
body = np.array([[330,150], [325,145], [335,145], [315,155], [345,155],
[300,250], [360,250], [320,290], [360,290], [330,260], [335,260],
[310,350], [350,350], [350,480], [260,480], [370,620], [260,620]], float)
hx = np.interp(i, [0,20,40,60,95,110,130,179], [330,330,280,280,500,510,430,430])
body[9] = [hx,260]; body[10] = [hx+5,260]
bend = min(40, abs(i-95)*4)
body[7] = (body[5]+body[9])/2 + [0,bend]
progress = np.clip((i-25)/20, 0, 1)
body[15] += [60*progress, -40*np.sin(np.pi*progress)]
body[0,0] += np.clip((i-20)/75, 0, 1)*2
extra = np.array([body[15]+[12,20], body[15]+[8,18], body[15]+[-8,15],
body[16]+[12,20], body[16]+[8,18], body[16]+[-8,15]])
if mirror:
body[:,0] = 1280-body[:,0]; extra[:,0] = 1280-extra[:,0]
kp.append(body.tolist()); feet.append(extra.tolist())
count = n*repeats
return {"video": {"width":1280, "height":720, "frame_count":count, "capture_fps":fps},
"frames": {"kp":kp*repeats, "kp_extra":feet*repeats,
"conf":[[.9]*17 for _ in range(count)],
"box":[[200,130,580,660] for _ in range(count)],
"people_count":[1]*count, "blur":[.1]*count, "brightness":[128]*count,
"t_s":[i/fps for i in range(count)],
"playback_t_s":[i/30 for i in range(count)]}}
def options(**overrides):
return AnalysisInput(view="face_on", handedness="right", camera_stability="fixed_verified",
body_height_px=400, body_height_source="constructed 400-pixel standing stature", **overrides)
def metric_map(rep):
return {m["key"]:m for m in rep["metrics"]}
def test_constructed_swing_produces_events_and_independent_measurement_arithmetic():
track = swing_track()
original = deepcopy(track)
pose, measurements, capture, warnings, method = analyze_batting(track, options(single_swing=True))
assert track == original # raw points are never modified by analytical smoothing
assert capture == {"ok":True, "reasons":[]}
events = pose[0]["events"]
assert {"stance_set","load_start","stride","foot_contact","foot_plant","swing_start","contact","finish"} <= events.keys()
assert events["foot_contact"]["frame"] <= events["foot_plant"]["frame"]
assert 90 <= events["contact"]["frame"] <= 97
assert events["finish"]["frame"] < 179
metrics = metric_map(measurements[0])
assert metrics["stride_pct_height"]["value"] == pytest.approx(42.5)
assert metrics["com_drift_pct_height"]["value"] == pytest.approx(-25)
timing = (events["contact"]["frame"]-events["foot_plant"]["frame"])/120*1000
assert metrics["foot_plant_to_contact_ms"]["value"] == pytest.approx(timing, abs=.001)
assert metrics["load_tempo_s"]["value"] is not None
assert metrics["load_launch_ratio"]["value"] is not None
assert all(m["confidence"] == "est" for m in metrics.values())
assert all(m["note"] for m in metrics.values())
assert metrics["hip_shoulder_separation_foot_plant_deg"]["value"] is None
assert metrics["lateral_trunk_tilt_contact_deg"]["value"] is None
assert all(e["estimated"] for e in events.values())
def test_automatic_two_swings_and_rep_relative_times():
pose, reps, capture, _, _ = analyze_batting(swing_track(repeats=2), options())
assert len(pose) == len(reps) == 2
assert pose[0]["end_frame"] < pose[1]["start_frame"]
assert all(p["boundary_method"] == "automatic_2d_hand_motion_candidate" for p in pose)
for p, r in zip(pose, reps):
for key, value in r["events_ms"].items():
assert value == pytest.approx((p["events"][key]["frame"]-p["start_frame"])/120*1000, abs=.001)
assert metric_map(r)["stride_pct_height"]["value"] == pytest.approx(42.5)
def test_unknown_or_low_capture_clock_never_uses_playback_time():
for fps in (None, 25):
track = swing_track()
track["video"]["capture_fps"] = fps
if fps is None: track["frames"]["t_s"] = [None]*180
else: track["frames"]["t_s"] = [i/fps for i in range(180)]
pose, reps, capture, _, _ = analyze_batting(track, options(single_swing=True))
for key in ("foot_plant_to_contact_ms", "load_tempo_s", "load_launch_ratio"):
assert metric_map(reps[0])[key]["value"] is None
if fps is None:
assert reps[0]["events_ms"] == {}
assert all("t_s" not in e for e in pose[0]["events"].values())
@pytest.mark.parametrize("fps", [30, 29.97])
def test_nominal_30fps_known_clock_allows_resolved_load_duration(fps):
track = swing_track(fps=fps)
pose, reps, capture, _, _ = analyze_batting(track, options(single_swing=True))
assert capture["ok"] is True and "low_fps" in capture["reasons"]
events = pose[0]["events"]
expected = (events["swing_start"]["frame"]-events["load_start"]["frame"])/fps
assert metric_map(reps[0])["load_tempo_s"]["value"] == pytest.approx(expected, abs=.001)
def test_mirrored_image_keeps_stride_and_signed_body_position():
original = analyze_batting(swing_track(), options(single_swing=True))[1][0]
mirrored = analyze_batting(swing_track(mirror=True), options(single_swing=True))[1][0]
for key in ("stride_pct_height", "com_drift_pct_height", "foot_plant_to_contact_ms"):
assert metric_map(mirrored)[key]["value"] == metric_map(original)[key]["value"]
def test_static_pose_and_ambiguous_declared_rep_never_force_a_contact():
track = swing_track()
track["frames"]["kp"] = [track["frames"]["kp"][0]]*180
track["frames"]["kp_extra"] = [track["frames"]["kp_extra"][0]]*180
assert analyze_batting(track, options())[0] == []
pose, reps, _, _, _ = analyze_batting(swing_track(repeats=2), options(single_swing=True))
assert pose[0]["events"] == {}
assert all(m["value"] is None for m in reps[0]["metrics"])
def test_short_gaps_are_filled_only_in_analysis_long_gaps_stay_missing():
points = np.tile(np.arange(12)[:,None,None], (1,1,2)).astype(float)
points[2:5] = np.nan; points[7:11] = np.nan
filled = analysis_points(points)
assert np.isfinite(filled[2:5]).all()
assert np.isnan(filled[7:11]).all()
assert np.isnan(points[2:5]).all()
track = swing_track()
for i in range(55,110):
track["frames"]["kp"][i][9] = None
track["frames"]["conf"][i][9] = 0
pose, reps, _, _, _ = analyze_batting(track, options(single_swing=True))
assert "contact" not in pose[0]["events"]
assert metric_map(reps[0])["com_drift_pct_height"]["value"] is None
@pytest.mark.parametrize("change,reason", [("people","multiple_people"), ("dark","too_dark"),
("blur","too_blurry"), ("crop","partly_out_of_frame"), ("empty","no_person")])
def test_failed_capture_uses_only_coach_reason_keys_and_withholds_numbers(change,reason):
track = swing_track()
if change == "people": track["frames"]["people_count"] = [2]*180
if change == "dark": track["frames"]["brightness"] = [10]*180
if change == "blur": track["frames"]["blur"] = [.99]*180
if change == "crop":
track["frames"]["box"] = [[0,0,580,720]]*180
for frame, scores in zip(track["frames"]["kp"], track["frames"]["conf"]):
frame[15] = frame[16] = None
scores[15] = scores[16] = 0
if change == "empty":
track["frames"]["box"] = [None]*180
track["frames"]["kp"] = [[None]*17 for _ in range(180)]
track["frames"]["conf"] = [[0]*17 for _ in range(180)]
_, reps, capture, _, _ = analyze_batting(track, options(single_swing=True))
assert capture["ok"] is False and reason in capture["reasons"]
assert set(capture["reasons"]) <= CAPTURE_REASONS
assert all(m["value"] is None and m["note"] for m in reps[0]["metrics"])
def test_absent_handedness_or_moving_camera_withholds_dependent_measurements():
opt = options(single_swing=True)
opt.handedness = None
pose, reps, _, _, _ = analyze_batting(swing_track(), opt)
assert "contact" not in pose[0]["events"]
assert metric_map(reps[0])["stride_pct_height"]["value"] is None
opt = options(single_swing=True)
opt.camera_stability = "moving"
pose, reps, _, _, _ = analyze_batting(swing_track(), opt)
assert "contact" in pose[0]["events"]
assert "foot_plant" not in pose[0]["events"]
metrics = metric_map(reps[0])
assert metrics["stride_pct_height"]["value"] is None
assert metrics["head_movement_pct_height"]["value"] is None
assert metrics["lead_knee_angle_contact_deg"]["value"] is not None
assert metrics["com_drift_pct_height"]["value"] == pytest.approx(-25)
def test_payload_is_measurements_only_and_preserves_level():
_, reps, capture, _, _ = analyze_batting(swing_track(), options(single_swing=True))
payload = coach_payload({"reps":reps, "capture":capture, "fps":120,
"view":"face_on", "level":"college"})
assert set(payload) == {"schema_version","discipline","level","view","fps","capture","reps"}
assert payload["level"] == "college"
assert len(json.dumps(payload).encode()) < 2*1024*1024
unknown = coach_payload({"reps":reps,"capture":capture,"fps":None,"view":"unknown"})
assert "fps" not in unknown and "view" not in unknown
import jsonschema
schema = json.loads((Path(__file__).resolve().parents[1] / "docs/coach-payload.schema.json").read_text())
jsonschema.Draft202012Validator.check_schema(schema)
jsonschema.validate(payload, schema)
jsonschema.validate(unknown, schema)
wrong = deepcopy(payload)
wrong["reps"][0]["metrics"][0]["unit"] = "cm"
with pytest.raises(jsonschema.ValidationError): jsonschema.validate(wrong, schema)
def test_automatic_ranges_trim_setup_and_trailing_footage():
pose, _, _, _, _ = analyze_batting(swing_track(), options())
assert len(pose) == 1
assert pose[0]["start_frame"] < pose[0]["events"]["load_start"]["frame"]
assert pose[0]["end_frame"] < 179
for event in pose[0]["events"].values():
assert pose[0]["start_frame"] <= event["frame"] <= pose[0]["end_frame"]
def test_separate_rep_ranges_do_not_create_a_false_adjacent_frame_identity_jump():
from baseball_batting.batting_measurements import capture_checks
track = swing_track(repeats=2)
# A transition outside the submitted ranges is not an adjacent-frame jump.
track["frames"]["box"][180:] = [[500,130,880,660] for _ in range(180)]
capture, _ = capture_checks(track, options(), 400, list(range(30,100))+list(range(210,280)))
assert capture["ok"] is True and "player_switched" not in capture["reasons"]
capture, _ = capture_checks(track, options(), 400, range(360))
assert capture["ok"] is False and "player_switched" in capture["reasons"]
def test_left_handed_lead_side_and_automatic_scale():
track = swing_track()
for points in track["frames"]["kp"]:
for left,right in ((5,6),(7,8),(9,10),(11,12),(13,14),(15,16)):
points[left],points[right] = points[right],points[left]
for points in track["frames"]["kp_extra"]:
points[:3],points[3:] = points[3:],points[:3]
opt = options(single_swing=True)
opt.handedness = "left"
_, reps, _, _, _ = analyze_batting(track, opt)
assert metric_map(reps[0])["stride_pct_height"]["value"] == pytest.approx(42.5)
opt.body_height_px = opt.body_height_source = None
_, reps, _, _, method = analyze_batting(track, opt)
assert method["body_height_px"] > 120
assert "unmeasured" in method["body_height_method"]
assert all(m["confidence"] == "est" for m in reps[0]["metrics"])
def test_native_pose_to_full_result_and_exported_coach_schema():
from baseball_batting.api_output import build_api_result
import jsonschema
track = swing_track()
capture = {"frame_count":180, "rotation_degrees":0,
"frames":[{"width":1280,"height":720,"physical_s":i/120,"playback_s":i/30} for i in range(180)],
"quality":[{"blur_laplacian_variance":900,"mean_luminance":128} for _ in range(180)]}
observations = {"frames":[]}
for i in range(180):
observations["frames"].append({"frame_id":i,
"body_points":track["frames"]["kp"][i]+track["frames"]["kp_extra"][i]+[None]*110,
"body_scores":[.9]*23+[0]*110,"body_states":["model_inferred"]*23+["unknown"]*110,
"person":{"box":track["frames"]["box"][i]},"people_count":1})
opt = options(single_swing=True, level="hs_varsity", timing={"kind":"explicit",
"source":"constructed frame timestamps", "physical_times_s":[i/120 for i in range(180)]})
result = build_api_result(capture, observations, opt, {"body_pose":"fixture","person_detector":"fixture"})
root = Path(__file__).resolve().parents[1]
jsonschema.validate(result, json.loads((root/"docs/api-result.schema.json").read_text()))
jsonschema.validate(result["coach_payload"], json.loads((root/"docs/coach-payload.schema.json").read_text()))
assert result["coach_payload"] == result["measurements"]
assert result["coach_payload"]["fps"] == 120
assert metric_map(result["coach_payload"]["reps"][0])["stride_pct_height"]["value"] == 42.5
assert "kp3d" not in result["pose_track"]