"""Independent geometry, uncertainty, provider failure and notebook checks. Constructed cases verify definitions and stability, never real-world accuracy. """ import ast from copy import deepcopy import json from pathlib import Path import numpy as np import nbformat import pytest from baseball_batting.api_contract import AnalysisInput from baseball_batting.batting_measurements import analyze_batting, coach_payload from baseball_batting.event_body3d import backproject, camera_geometry, reconstruct_events, selected_event_frames from baseball_batting.measurement_quality import angle_value, apply_measurement_quality from baseball_batting.sam_event_worker import sam_to_coco from test_batting_measurements import swing_track, options, metric_map ROOT = Path(__file__).resolve().parents[1] def measurement_result(track=None, opt=None): track = track or swing_track() opt = opt or options(single_swing=True, measurement_backend="sam3d") pose, reps, capture, warnings, method = analyze_batting(track, opt) track = deepcopy(track); track["reps"] = pose result = {"pose_track": track, "measurements": {"schema_version": "2.0", "discipline": "hitting", "view": "face_on", "fps": track["video"]["capture_fps"], "capture": capture, "reps": reps}, "measurement_method": method, "capabilities": {"body_3d": False}, "warnings": warnings} result["coach_payload"] = coach_payload(result["measurements"]) ids, omitted = selected_event_frames(result) rows = [] for i in ids: px = np.asarray(track["frames"]["kp"][i]) xyz = np.column_stack(((px[:, 0]-330)*.003, (px[:, 1]-350)*.003, np.full(17, 5.))) rows.append({"frame": i, "points": xyz.tolist(), "projection": px.tolist(), "scores": [None]*17}) report = {"backend": opt.measurement_backend, "status": "ready", "reason": "constructed geometry", "frames": rows, "geometry": {"assumed": False}, "requested_frames": ids, "omitted_windows": omitted} return result, opt, report def test_known_three_dimensional_angles_and_handedness(): p = np.zeros((17, 3)); p[:, 2] = 5 p[11], p[12] = [.15, 0, 5], [-.15, 0, 5] centre = np.array([.5*np.tan(np.radians(20)), -.5, 5]) axis = np.array([np.cos(np.radians(30)), 0, np.sin(np.radians(30))])*.2 p[5], p[6] = centre+axis, centre-axis p[13] = p[11]+[0, .4, 0] p[15] = p[13]+[.2, .4*np.sqrt(3)/2, 0] opt = options() assert angle_value("lead_knee_angle_contact_deg", p, opt) == pytest.approx(150) assert angle_value("lateral_trunk_tilt_contact_deg", p, opt) == pytest.approx(20) assert angle_value("hip_shoulder_separation_foot_plant_deg", p, opt) == pytest.approx(30) opt.handedness = "left" assert angle_value("lateral_trunk_tilt_contact_deg", p, opt) == pytest.approx(-20) # A rigid camera rotation must not change the angles when up is transformed. r = np.array([[1, 0, 0], [0, 0, -1], [0, 1, 0]]) opt.handedness = "right"; opt.camera_up = tuple(r @ [0, -1, 0]) assert angle_value("lateral_trunk_tilt_contact_deg", p @ r.T, opt) == pytest.approx(20) assert angle_value("hip_shoulder_separation_foot_plant_deg", p @ r.T, opt) == pytest.approx(30) def test_all_nine_have_values_when_constructed_evidence_supports_them(): result, opt, report = measurement_result() raw = deepcopy(result["pose_track"]) result = apply_measurement_quality(result, opt, report) metrics = metric_map(result["measurements"]["reps"][0]) assert len(metrics) == 9 and all(m["value"] is not None for m in metrics.values()) assert all(m["confidence"] == "est" for m in metrics.values()) assert metrics["lateral_trunk_tilt_contact_deg"]["value"] == 0 assert metrics["hip_shoulder_separation_foot_plant_deg"]["value"] == 0 assert result["pose_track"] == raw assert result["coach_payload"] == coach_payload(result["measurements"]) assert result["capabilities"]["body_3d"] is True assert len(result["measurement_diagnostics"][0]["metrics"]) == 9 import jsonschema jsonschema.validate(result["coach_payload"], json.loads((ROOT/"docs/coach-payload.schema.json").read_text())) def test_sam_mapping_units_and_translation_are_not_applied_twice(): points = np.arange(70*3).reshape(70, 3)/100 pixels = np.arange(70*2).reshape(70, 2) row = sam_to_coco({"pred_keypoints_3d": points, "pred_keypoints_2d": pixels, "pred_cam_t": [1, 2, 3]}) np.testing.assert_allclose(row["points"][9], points[62]+[1, 2, 3]) np.testing.assert_allclose(row["points"][10], points[41]+[1, 2, 3]) np.testing.assert_allclose(row["points"][11], points[9]+[1, 2, 3]) assert row["scores"] == [None]*17 # no invented 3D confidence # Native SAM MHR70 names: wrists are 62/41, hips 9/10, knees 11/12, # ankles 13/14. Check every mapped landmark, not just the first hip. from baseball_batting.event_body3d import SAM_COCO np.testing.assert_allclose(row['points'], points[SAM_COCO]+[1, 2, 3]) np.testing.assert_allclose(row['projection'], pixels[SAM_COCO]) def test_lightweight_backprojection_uses_same_units_on_all_axes(): k = np.array([[1000, 0, 500], [0, 1000, 400], [0, 0, 1.]]) points = backproject([[600, 500], [400, 300]], [.5, -.5], k, 5) np.testing.assert_allclose(points, [[.55, .55, 5.5], [-.45, -.45, 4.5]]) assert np.isnan(backproject([[600, 500]], [-6], k, 5)).all() def test_lightweight_decoder_does_not_treat_depth_response_as_2d_confidence(monkeypatch): pytest.importorskip("rtmlib") from types import SimpleNamespace from baseball_batting.event_body3d import RTMW3DPose outputs = [] for bins, index, peak in ((576, 200, .9), (768, 300, .95), (576, 200, .08)): axis = np.zeros((1, 133, bins), np.float32); axis[:, :, index] = peak; outputs.append(axis) class Session: def get_inputs(self): return [SimpleNamespace(name="input", shape=[1, 3, 384, 288])] def run(self, names, values): return outputs monkeypatch.setattr("baseball_batting.detection.ort_session", lambda *a: Session()) adapter = RTMW3DPose("fixture.onnx", "cpu") row = adapter(np.zeros((384, 288, 3), np.uint8), [0, 0, 288, 384], np.array([[1000, 0, 144], [0, 1000, 192], [0, 0, 1.]]), 5) assert row["scores"] == pytest.approx([.9]*17) assert row["depth_peak_response"] == pytest.approx([.08]*17) assert np.asarray(row["points"]).shape == (17, 3) def test_geometry_prior_is_invariant_to_image_resizing(): track = swing_track(); doubled = deepcopy(track) doubled["video"]["width"] *= 2; doubled["video"]["height"] *= 2 opt = options() k, depth, _ = camera_geometry(track, opt, 400) k2, depth2, _ = camera_geometry(doubled, opt, 800) px = np.array([[400, 450], [300, 250]]) np.testing.assert_allclose(backproject(px, [.1, -.2], k, depth), backproject(px*2, [.1, -.2], k2, depth2)) def test_camera_declarations_and_priors_are_distinguished(): track = swing_track() k, depth, geometry = camera_geometry(track, options(), 400) assert geometry["assumed"] is True and depth == pytest.approx(k[1, 1]*1.75/400) assert "assumed 1.75" in geometry["depth_source"] opt = options(camera={"fx": 1000, "fy": 1200, "cx": 640, "cy": 360, "source": "calibration"}, root_depth_m=6, root_depth_source="measured distance") k, depth, geometry = camera_geometry(track, opt, 400) assert geometry["assumed"] is False and depth == 6 and k[1, 1] == 1200 opt.root_depth_m = None; opt.height_m = 1.8 assert camera_geometry(track, opt, 400)[1] == pytest.approx(5.4) for kwargs in ({"measurement_backend": "magic"}, {"root_depth_m": 4}, {"camera_up": [0, 0, 0]}, {"camera_up": [float("nan"), 0, 0]}): with pytest.raises(ValueError): AnalysisInput(**kwargs) @pytest.mark.parametrize("failure", ["missing", "disagreement", "scores", "depth_flip", "length_jump"]) def test_bad_3d_never_falls_back_to_a_projected_anatomical_angle(failure): result, opt, report = measurement_result() contact = result["pose_track"]["reps"][0]["events"]["contact"]["frame"] for row in report["frames"]: if abs(row["frame"]-contact) > 1: continue if failure == "missing": row["points"][13] = [None]*3 elif failure == "disagreement": row["projection"][13][0] += 100 elif failure == "scores": row["scores"][13] = .1 elif failure == "depth_flip": row["points"][13][2] = -1 elif row["frame"] == contact: row["points"][13][2] += 1 apply_measurement_quality(result, opt, report) metrics = metric_map(result["coach_payload"]["reps"][0]) assert metrics["lead_knee_angle_contact_deg"]["value"] is None assert metrics["stride_pct_height"]["value"] is not None def test_rejected_opposite_hip_does_not_poison_supported_knee_geometry(): result, opt, report = measurement_result() contact = result['pose_track']['reps'][0]['events']['contact']['frame'] for row in report['frames']: if abs(row['frame']-contact) <= 2: row['projection'][12][0] += 100 apply_measurement_quality(result, opt, report) metrics = metric_map(result['coach_payload']['reps'][0]) assert metrics['lead_knee_angle_contact_deg']['value'] is not None assert metrics['lateral_trunk_tilt_contact_deg']['value'] is None assert 'right_hip' in metrics['lateral_trunk_tilt_contact_deg']['note'] def test_projection_disagreement_is_explained_per_joint_without_changing_points(): result, opt, report = measurement_result() contact = result['pose_track']['reps'][0]['events']['contact']['frame'] for row in report['frames']: if row['frame'] == contact: row['projection'][11][0] += 24 # 6% of known 400 px stature original = deepcopy(report) apply_measurement_quality(result, opt, report) metric = metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg'] assert metric['value'] is None and 'left_hip differs by 6.00%' in metric['note'] diagnostic = next(m for m in result['measurement_diagnostics'][0]['metrics'] if m['key']==metric['key']) assert diagnostic['required_joints'] == ['left_hip', 'left_knee', 'left_ankle'] assert next(r for r in diagnostic['pose_agreement'] if r['frame']==contact)['rejected_joints'][0]['reasons'] == ['model_projection_disagreement'] assert report == original def test_projection_convention_is_checked_again_before_measurement(): result, opt, report = measurement_result() for row in report['frames']: row['camera_intrinsics'] = [[1000, 0, 330], [0, 1000, 350], [0, 0, 1]] row['points'] = np.column_stack(((np.asarray(row['projection'])-[330,350])*.005, np.full(17, 5.))).tolist() apply_measurement_quality(result, opt, deepcopy(report)) assert metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg']['value'] is not None for row in report['frames']: row['points'][13][0] += .02 apply_measurement_quality(result, opt, report) metric = metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg'] assert metric['value'] is None and 'camera_projection_inconsistent' in metric['note'] @pytest.mark.parametrize('failure', ['bad_dimensions', 'duplicate', 'bad_scores']) def test_invalid_optional_3d_rows_withhold_angles_without_losing_2d_results(failure): result, opt, report = measurement_result() contact = result['pose_track']['reps'][0]['events']['contact']['frame'] row = next(r for r in report['frames'] if r['frame']==contact) if failure == 'bad_dimensions': row['points'] = [[0,0,5]] elif failure == 'duplicate': report['frames'].append(deepcopy(row)) else: row['scores'] = [.9] apply_measurement_quality(result, opt, report) metrics = metric_map(result['coach_payload']['reps'][0]) assert metrics['lead_knee_angle_contact_deg']['value'] is None assert metrics['stride_pct_height']['value'] is not None def test_possible_left_right_swap_is_reported_without_remapping(): result, opt, report = measurement_result() for row in report['frames']: for a,b in ((5,6),(7,8),(9,10),(11,12),(13,14),(15,16)): row['projection'][a],row['projection'][b] = row['projection'][b],row['projection'][a] original = deepcopy(report) apply_measurement_quality(result,opt,report) metric = next(m for m in result['measurement_diagnostics'][0]['metrics'] if m['key']=='lead_knee_angle_contact_deg') assert any(r['side_swap_check']['possible_side_swap'] for r in metric['pose_agreement']) assert metric_map(result['coach_payload']['reps'][0])['lead_knee_angle_contact_deg']['value'] is None assert report == original def test_unknown_timing_and_moving_camera_remain_withheld_with_3d(): track = swing_track(); track["frames"]["t_s"] = [None]*180; track["video"]["capture_fps"] = None opt = options(single_swing=True, measurement_backend="sam3d"); opt.camera_stability = "moving" result, opt, report = measurement_result(track, opt) apply_measurement_quality(result, opt, report) metrics = metric_map(result["coach_payload"]["reps"][0]) for key in ("stride_pct_height", "head_movement_pct_height", "foot_plant_to_contact_ms", "load_tempo_s", "load_launch_ratio", "hip_shoulder_separation_foot_plant_deg"): assert metrics[key]["value"] is None assert metrics["lead_knee_angle_contact_deg"]["value"] is not None @pytest.mark.parametrize("cadence,key,event_names,scale", [ ((100, 120), "foot_plant_to_contact_ms", ("foot_plant", "contact"), 1000), ((30, 40), "load_tempo_s", ("load_start", "swing_start"), 1), ]) def test_known_variable_capture_clock_uses_original_timestamps(cadence, key, event_names, scale): track = swing_track(); track["video"]["capture_fps"] = None intervals = np.resize([1/cadence[0], 1/cadence[1]], 179) track["frames"]["t_s"] = np.r_[0, np.cumsum(intervals)].tolist() pose, reps, _, _, _ = analyze_batting(track, options(single_swing=True)) a, b = (pose[0]["events"][name]["frame"] for name in event_names) expected = (track["frames"]["t_s"][b]-track["frames"]["t_s"][a])*scale assert metric_map(reps[0])[key]["value"] == pytest.approx(expected, abs=.001) track["frames"]["t_s"][90:] = [t+.1 for t in track["frames"]["t_s"][90:]] metrics = metric_map(analyze_batting(track, options(single_swing=True))[1][0]) assert metrics[key]["value"] is None def test_30fps_frame_sensitivity_keeps_long_load_and_withholds_short_timings(): result, opt, _ = measurement_result(swing_track(fps=30), options(single_swing=True, measurement_backend="2d")) # Independently supplied event frames: a 16-frame load and a 5-frame launch. result["pose_track"]["reps"][0]["events"] = { name: {"frame": frame, "t_s": frame/30} for name, frame in (("stance_set", 5), ("load_start", 54), ("foot_plant", 70), ("swing_start", 70), ("contact", 75))} metrics = metric_map(result["measurements"]["reps"][0]) for key, value in (("load_tempo_s", .533), ("foot_plant_to_contact_ms", 166.667), ("load_launch_ratio", 3.2)): metrics[key]["value"] = value report = reconstruct_events(Path("unused.mp4"), result, opt, Path("."), Path(".")) full = apply_measurement_quality(result, opt, report) metrics = metric_map(full["coach_payload"]["reps"][0]) assert metrics["load_tempo_s"]["value"] == .533 for key in ("foot_plant_to_contact_ms", "load_launch_ratio"): assert metrics[key]["value"] is None and "±1-frame" in metrics[key]["note"] diagnostic = {m["key"]: m for m in full["measurement_diagnostics"][0]["metrics"]} assert diagnostic["load_tempo_s"]["capture_interval_ms"] == [33.333, 33.333] assert diagnostic["load_tempo_s"]["event_frame_sensitivity_range"] == pytest.approx([14/30, 18/30]) assert diagnostic["load_tempo_s"]["event_frame_sensitivity_unit"] == "s" assert diagnostic['load_tempo_s']['resolution_status'] == 'resolved_under_frame_shift_check' assert diagnostic['load_launch_ratio']['duration_frame_intervals']['swing_start_to_contact'] == 5 assert diagnostic['load_launch_ratio']['resolution_status'] == 'insufficient_event_resolution' assert diagnostic['load_launch_ratio']['event_frame_sensitivity_range'] == pytest.approx([2,6]) def test_more_real_samples_resolve_ratio_and_changing_fps_alone_does_not(): from baseball_batting.timing_quality import check_timing from test_batting_measurements import swing_track for frames, fps, supported in [((20,36,41),30,False), ((20,36,41),120,False), ((20,84,104),120,True)]: rep = {'start_frame':0, 'end_frame':179, 'events':{ name:{'frame':i} for name,i in zip(('load_start','swing_start','contact'),frames)}} metric = {'key':'load_launch_ratio', 'value':3.2, 'note':'constructed evidence'} diagnostic = {} check_timing(metric,rep,swing_track(fps=fps),diagnostic) assert (metric['value'] is not None) == supported assert diagnostic['duration_frame_intervals']['swing_start_to_contact'] == frames[2]-frames[1] def test_timing_quality_cannot_fill_clock_or_missing_event(): from baseball_batting.timing_quality import check_timing track = swing_track(fps=30) rep = {'start_frame':0, 'end_frame':179, 'events':{'load_start':{'frame':20},'swing_start':{'frame':50}}} metric = {'key':'load_tempo_s','value':1.,'note':'constructed evidence'} track['frames']['t_s'][25] = None diagnostic = {}; check_timing(metric,rep,track,diagnostic) assert metric['value'] is None and diagnostic['resolution_status']=='capture_clock_unknown_or_invalid' metric = {'key':'load_launch_ratio','value':None,'note':'missing contact'} diagnostic = {}; check_timing(metric,rep,track,diagnostic) assert metric['value'] is None and diagnostic['missing_events']==['contact'] def test_ratio_sensitivity_matches_exhaustive_shared_onset_shifts(): from itertools import product from baseball_batting.timing_quality import check_timing track = swing_track(fps=60) times = np.r_[0,np.cumsum(np.resize([1/60,1/80],179))] track['frames']['t_s'] = times.tolist() load,onset,contact = 20,80,105 rep = {'start_frame':0,'end_frame':179,'events':{name:{'frame':i} for name,i in (('load_start',load),('swing_start',onset),('contact',contact))}} metric={'key':'load_launch_ratio','value':float((times[onset]-times[load])/(times[contact]-times[onset])),'note':'constructed'} diagnostic={};check_timing(metric,rep,track,diagnostic) ratios=[(times[onset+b]-times[load+a])/(times[contact+c]-times[onset+b]) for a,b,c in product((-1,0,1),repeat=3)] assert diagnostic['event_frame_sensitivity_range']==pytest.approx([min(ratios),max(ratios)]) def test_frame_budget_keeps_complete_event_windows(): result, _, _ = measurement_result() frames, omitted = selected_event_frames(result, limit=5) assert len(frames) == 5 and len(omitted) == 1 contact = result["pose_track"]["reps"][0]["events"]["contact"]["frame"] assert frames == list(range(contact-2, contact+3)) def test_missing_models_sam_access_and_2d_selection_do_not_download(tmp_path, monkeypatch): result, opt, _ = measurement_result() monkeypatch.delenv("BASEBALL_SAM_WORKER_RECORD", raising=False) for backend in ("sam3d", "rtmw3d", "2d"): opt.measurement_backend = backend report = reconstruct_events(tmp_path/"missing.mp4", result, opt, tmp_path, tmp_path) assert report["status"] == ("disabled" if backend == "2d" else "unavailable") if backend != "2d": apply_measurement_quality(result, opt, report) metrics = metric_map(result["coach_payload"]["reps"][0]) assert metrics["lead_knee_angle_contact_deg"]["value"] is None assert metrics["foot_plant_to_contact_ms"]["value"] is not None def test_cuda_failure_in_optional_model_returns_partial_data_without_cpu_fallback(tmp_path, monkeypatch): from baseball_batting import event_body3d result, opt, _ = measurement_result(); opt.measurement_backend = "rtmw3d" result["pose_track"]["video"]["rotation_degrees_applied"] = 0 model = tmp_path/"body_pose_3d/model.onnx"; model.parent.mkdir(); model.write_bytes(b"fixture") import yaml expected = yaml.safe_load((ROOT/"configs/resources.yaml").read_text())["resources"]["body_pose_3d"]["sha256"] monkeypatch.setattr(event_body3d, "sha256_file", lambda _: expected) monkeypatch.setattr(event_body3d, "selected_event_frames", lambda *args: ([0, 1, 2], [])) monkeypatch.setattr(event_body3d, "iter_frames", lambda *args: iter([(0, None, None, np.zeros((8, 8, 3), np.uint8))])) devices = [] class Model: def __init__(self, path, device): devices.append(device) def __call__(self, *args): raise RuntimeError("CUDA operator verification failed") monkeypatch.setattr(event_body3d, "RTMW3DPose", Model) report = reconstruct_events(tmp_path/"video.mp4", result, opt, tmp_path, tmp_path) assert devices == ["cuda"] and report["status"] == "unavailable" assert "CUDA" in report["reason"] result = apply_measurement_quality(result, opt, report) assert metric_map(result["coach_payload"]["reps"][0])["stride_pct_height"]["value"] == 42.5 def test_new_notebook_and_legacy_notebook_are_valid_and_separate(): from tools.build_measurement_notebook import build notebook = nbformat.read(ROOT/"notebooks/batting_measurements_test.ipynb", as_version=4) nbformat.validate(notebook) assert json.loads(nbformat.writes(notebook)) == build() source = [] for cell in notebook.cells: if cell.cell_type == "code": ast.parse(cell.source); source.append(cell.source) assert cell.outputs == [] source = "\n".join(source) assert 'MEASUREMENT_BACKEND = "rtmw3d"' in source assert '"measurement_backend": MEASUREMENT_BACKEND' in source assert "tools.setup_sam_api_worker" in source assert "setup_full_worker" not in source and "opensim" not in source.lower() def test_full_result_with_quality_and_sparse_3d_matches_both_schemas(): from baseball_batting.api_output import build_api_result import jsonschema result, opt, report = measurement_result() track = result["pose_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": [{"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} for i in range(180)]} full = build_api_result(capture, observations, opt, {"body_pose": "fixture", "person_detector": "fixture"}) report.update(validation="reference_validation_pending", unit="m", frame_of_reference="camera", axes="x right, y down, z away", elapsed_s=0.) full = apply_measurement_quality(full, opt, report) jsonschema.validate(full, json.loads((ROOT/"docs/api-result.schema.json").read_text())) jsonschema.validate(full["coach_payload"], json.loads((ROOT/"docs/coach-payload.schema.json").read_text())) assert "experimental_body3d" not in full["coach_payload"] and "kp3d" not in full["pose_track"] assert all(m["value"] is not None for m in full["coach_payload"]["reps"][0]["metrics"]) def test_docker_build_context_includes_every_local_copy_source(): import fnmatch, shlex patterns = (ROOT/".dockerignore").read_text().splitlines() for dockerfile in ("Dockerfile", "Dockerfile.sam"): stages={line.split()[-1] for line in (ROOT/dockerfile).read_text().splitlines() if line.startswith('FROM ') and ' AS ' in line} for line in (ROOT/dockerfile).read_text().splitlines(): if not line.startswith("COPY "): continue arguments=shlex.split(line)[1:] origin=next((a.split('=',1)[1] for a in arguments if a.startswith('--from=')),None) files=[a for a in arguments if not a.startswith('--')] if origin: assert origin in stages assert all(source.startswith('/') for source in files[:-1]) continue for source in files[:-1]: assert (ROOT/source).exists(), source allowed = True for pattern in patterns: if not pattern or pattern.startswith("#"): continue negated = pattern.startswith("!") name = pattern[1:] if negated else pattern if fnmatch.fnmatch(source, name.rstrip("/")): allowed = negated assert allowed, f"{source} excluded from {dockerfile} build context"