diff --git a/docs/rally-training.md b/docs/rally-training.md index b73697c..b85fd50 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -191,3 +191,31 @@ training recipe fixed. Report interval F1 and signed start/end errors by camera. The motion views change both pose normalization and velocity channels, so comparisons against the original views measure their combined effect. The filter windows span less time at higher FPS. + +## Singles service-box ablation + +The `serve_boxes` view adds four scores to the canonical motion-and-audio +features. The order is near-left, near-right, far-left, far-right, using the +same court x-axis for both players. On each frame, project both visible +ankles to the court floor and average their positions. Measure Euclidean +distance `d` in metres from that midpoint to each singles service rectangle. +Each rectangle runs from its short service line to its baseline. The score +is `exp(-0.5 * (d / 0.75)^2)`, with a score of 1 anywhere inside or on the +rectangle. These are independent scores in [0, 1]. + +The `serve_boxes_diagonal` view also adds +`max(near_right * far_left, near_left * far_right)`. A player's scores are +masked if either ankle is unavailable. The diagonal score needs both players. + +```bash +for view in full_audio_zscore_motion serve_boxes serve_boxes_diagonal; do + python -m src.temporal_selector.rally_experiment \ + --config config/rally-experiment.local.json --clean-only --preset rtmpose-audio \ + --feature-view "$view" --output-dir "outputs/serve-box-ablation/$view" +done +python -m experiments.temporal_selector.serve_box_ablation outputs/serve-box-ablation +``` + +The comparison verifies the source artifacts, training recipe, and camera +splits. It reports matched rally-start error in frames alongside interval F1, +recall, and the number of matched starts for each held-out camera. diff --git a/experiments/temporal_selector/serve_box_ablation.py b/experiments/temporal_selector/serve_box_ablation.py new file mode 100644 index 0000000..d9322bc --- /dev/null +++ b/experiments/temporal_selector/serve_box_ablation.py @@ -0,0 +1,73 @@ +"""Compare the three matched InPlay serve-box feature runs.""" + +import argparse +import json +from pathlib import Path +from statistics import fmean + +from src.temporal_selector.rally_features import CANONICAL_RALLY_FEATURE_VIEW + +VIEWS = (CANONICAL_RALLY_FEATURE_VIEW, "serve_boxes", "serve_boxes_diagonal") + + +def summarize(run_root: Path) -> dict: + reference = None + arms = {} + for view in VIEWS: + metrics = json.loads((run_root / view / "metrics.json").read_text()) + dataset = metrics["dataset_manifest"] + if dataset["feature_view"] != view: + raise ValueError(f"expected {view}, got {dataset['feature_view']}") + identity = { + "dataset": {key: dataset[key] for key in ( + "sources", "annotation_fingerprint", "context_seconds", "ownership_seconds", + "pose_visibility_threshold", "pose_representation_version", "audio_coverage", + )}, + "recipe": metrics["training_recipe"], + "folds": [], + } + by_camera = {} + for fold in metrics["folds"]: + split = fold["split_manifest"] + identity["folds"].append({ + "camera": split["held_out_camera"], + "ranges": split["train_validation"]["cameras"], + **{f"{part}_window_ids": split[f"{part}_window_ids"] + for part in ("train", "validation", "test")}, + }) + test = fold["test"] + starts = [ + match["start_error"] for match in test["interval_matches"] + if match["match_status"] == "matched" + ] + by_camera[split["held_out_camera"]] = { + "interval_f1": test["intervals"]["f1"], + "interval_recall": test["intervals"]["recall"], + "matched_starts": len(starts), + "start_mae_frames": fmean(map(abs, starts)) if starts else None, + "signed_start_error_frames": fmean(starts) if starts else None, + } + if reference is None: + reference = identity + elif reference != identity: + raise ValueError(f"{view} differs from baseline in data, recipe, or split") + start_maes = [row["start_mae_frames"] for row in by_camera.values() + if row["start_mae_frames"] is not None] + arms[view] = { + **metrics["macro"], + "macro_start_mae_frames": fmean(start_maes) if start_maes else None, + "by_camera": by_camera, + } + return {"training_recipe": reference["recipe"], "arms": arms} + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("run_root", type=Path) + args = parser.parse_args() + report = summarize(args.run_root) + (args.run_root / "comparison.json").write_text(json.dumps(report, indent=2) + "\n") + + +if __name__ == "__main__": + main() diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index fefca4c..da8b05d 100644 --- a/src/temporal_selector/rally_dataset.py +++ b/src/temporal_selector/rally_dataset.py @@ -39,6 +39,7 @@ normalize_rally_motion_pose, rally_feature_view, rally_motion_features, + rally_serve_box_features, smooth_rally_court_positions, ) from .rally_intervals import read_rally_intervals @@ -462,6 +463,11 @@ def _compile_source( reliable_feet.append(frame_reliability) value_tensor = torch.tensor(source_values, dtype=torch.float32) validity_tensor = torch.tensor(source_validity, dtype=torch.bool) + serve_box_count = self.feature_view.serve_box_count + if serve_box_count: + box_scores, box_valid = rally_serve_box_features( + value_tensor, validity_tensor, homography, image_size + ) if self.feature_view.uses_motion: track_tensor = torch.tensor(track_ids) normalize_rally_motion_pose(value_tensor, validity_tensor, track_tensor, image_size) @@ -473,6 +479,9 @@ def _compile_source( ) value_tensor = torch.cat((value_tensor, velocity), dim=-1) validity_tensor = torch.cat((validity_tensor, velocity_valid), dim=-1) + if serve_box_count: + value_tensor = torch.cat((value_tensor, box_scores[:, :serve_box_count]), dim=-1) + validity_tensor = torch.cat((validity_tensor, box_valid[:, :serve_box_count]), dim=-1) if audio is not None: value_tensor = torch.cat((value_tensor, torch.as_tensor(audio_values)), dim=-1) validity_tensor = torch.cat((validity_tensor, torch.as_tensor(audio.validity)), dim=-1) diff --git a/src/temporal_selector/rally_experiment.py b/src/temporal_selector/rally_experiment.py index 6645646..7757f13 100644 --- a/src/temporal_selector/rally_experiment.py +++ b/src/temporal_selector/rally_experiment.py @@ -1494,7 +1494,7 @@ def main(argv: Sequence[str] | None = None) -> int: if rtmpose_preset: if not args.clean_only: raise ValueError("the RTMPose audio preset requires --clean-only") - if args.feature_view not in (None, "full_audio_zscore", CANONICAL_RALLY_FEATURE_VIEW): + if args.feature_view is not None and not rally_feature_view(args.feature_view).audio_zscore: raise ValueError("the RTMPose audio preset requires a normalized-audio feature view") overrides.setdefault("temporal_smoothing_weight", 0.1) recipe = RallyTrainingRecipe.from_preset( diff --git a/src/temporal_selector/rally_features.py b/src/temporal_selector/rally_features.py index b418c5b..08fb387 100644 --- a/src/temporal_selector/rally_features.py +++ b/src/temporal_selector/rally_features.py @@ -6,9 +6,12 @@ from dataclasses import dataclass from typing import Final +import numpy as np import torch from torch import Tensor +from src.court_projection import HALF_LENGTH, HALF_SINGLES_WIDTH, SHORT_SERVICE_DISTANCE, CourtHomography + from .rally_audio import RALLY_AUDIO_FEATURE_NAMES RALLY_FEATURE_SCHEMA: Final = "baddievision.rally.feature_views" @@ -45,6 +48,47 @@ for name in FULL_RALLY_FEATURE_NAMES ) _POSE_START: Final = len(PLAYER_CONTEXT_FIELDS) * 2 +SERVE_BOX_NAMES: Final = ( + "near_left_service_box", "near_right_service_box", + "far_left_service_box", "far_right_service_box", "diagonal_service_boxes", +) +_SERVICE_BOX_MIN: Final = ( + ((-HALF_SINGLES_WIDTH, -HALF_LENGTH), (0, -HALF_LENGTH)), + ((-HALF_SINGLES_WIDTH, SHORT_SERVICE_DISTANCE), (0, SHORT_SERVICE_DISTANCE)), +) +_SERVICE_BOX_MAX: Final = ( + ((0, -SHORT_SERVICE_DISTANCE), (HALF_SINGLES_WIDTH, -SHORT_SERVICE_DISTANCE)), + ((0, HALF_LENGTH), (HALF_SINGLES_WIDTH, HALF_LENGTH)), +) +_SERVE_DISTANCE_SCALE_METRES: Final = 0.75 + + +def rally_serve_box_features( + values: Tensor, validity: Tensor, homography: CourtHomography, image_size: tuple[int, int], +) -> tuple[Tensor, Tensor]: + """Score singles boxes from both visible ankles of each assigned player.""" + ankles = values[:, _POSE_START:].reshape(-1, 2, 33, 2)[:, :, 27:29].numpy() + visible = ( + validity[:, _POSE_START:].reshape(-1, 2, 33, 2)[:, :, 27:29] + .all(dim=-1).all(dim=-1).numpy() + ) + frame, player = np.nonzero(visible) + points = homography.project_normalized_to_court( + ankles[frame, player].reshape(-1, 2), image_size, + ) + midpoint = points.reshape(-1, 2, 2).mean(axis=1)[:, None, :] + lower = np.asarray(_SERVICE_BOX_MIN)[player] + upper = np.asarray(_SERVICE_BOX_MAX)[player] + outside = np.maximum(np.maximum(lower - midpoint, midpoint - upper), 0.0) + distance_squared = np.square(outside).sum(axis=-1) + scores = np.zeros((len(values), 2, 2), dtype=np.float32) + scores[frame, player] = np.exp(-0.5 * distance_squared / _SERVE_DISTANCE_SCALE_METRES**2) + near_left, near_right, far_left, far_right = scores.reshape(-1, 4).T + diagonal = np.maximum(near_right * far_left, near_left * far_right) + return ( + torch.from_numpy(np.column_stack((near_left, near_right, far_left, far_right, diagonal))), + torch.from_numpy(np.column_stack((np.repeat(visible, 2, axis=1), visible.all(axis=1)))), + ) _COURT_POSITION_INDICES: Final = tuple( index for index, name in enumerate(FULL_RALLY_FEATURE_NAMES) @@ -146,6 +190,7 @@ class RallyFeatureView: uses_audio: bool = False audio_zscore: bool = False uses_motion: bool = False + serve_box_count: int = 0 @property def dimension(self) -> int: @@ -154,7 +199,7 @@ def dimension(self) -> int: def select(self, values: Tensor, validity: Tensor) -> tuple[Tensor, Tensor]: if values.shape != validity.shape: raise ValueError("rally values and validity must have identical shapes") - input_dimension = len(FULL_RALLY_FEATURE_NAMES) + input_dimension = len(FULL_RALLY_FEATURE_NAMES) + self.serve_box_count if self.uses_motion: input_dimension += len(MOTION_FEATURE_NAMES) if self.uses_audio: @@ -178,13 +223,14 @@ def _names_for_fields(fields: Sequence[str], *, include_pose: bool = True) -> tu def _view( name: str, names: Sequence[str], *, uses_audio: bool = False, audio_zscore: bool = False, - uses_motion: bool = False, + uses_motion: bool = False, serve_box_count: int = 0, ) -> RallyFeatureView: requested = tuple(names) if len(requested) != len(set(requested)): raise AssertionError(f"duplicate feature in rally view {name}") input_names = ( (MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES if uses_motion else FULL_RALLY_FEATURE_NAMES) + + SERVE_BOX_NAMES[:serve_box_count] + (RALLY_AUDIO_FEATURE_NAMES if uses_audio else ()) ) positions = {feature: index for index, feature in enumerate(input_names)} @@ -192,7 +238,8 @@ def _view( if missing: raise AssertionError(f"unknown feature in rally view {name}: {missing}") return RallyFeatureView( - name, requested, tuple(positions[item] for item in requested), uses_audio, audio_zscore, uses_motion + name, requested, tuple(positions[item] for item in requested), + uses_audio, audio_zscore, uses_motion, serve_box_count, ) @@ -206,6 +253,14 @@ def _view( MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, uses_audio=True, audio_zscore=True, uses_motion=True, ), + **{ + name: _view( + name, MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES + SERVE_BOX_NAMES[:count] + + RALLY_AUDIO_FEATURE_NAMES, + uses_audio=True, audio_zscore=True, uses_motion=True, serve_box_count=count, + ) + for name, count in (("serve_boxes", 4), ("serve_boxes_diagonal", 5)) + }, "full_audio": _view( "full_audio", FULL_RALLY_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, uses_audio=True ), @@ -288,6 +343,8 @@ def rally_feature_indices(names: Sequence[str]) -> tuple[int, ...]: "full": 154, "full_motion": 290, "full_audio_zscore_motion": 297, + "serve_boxes": 301, + "serve_boxes_diagonal": 302, "full_audio": 161, "full_audio_zscore": 161, "calibrated_canonical": 142, diff --git a/tests/test_rally_serve_boxes.py b/tests/test_rally_serve_boxes.py new file mode 100644 index 0000000..e4904cd --- /dev/null +++ b/tests/test_rally_serve_boxes.py @@ -0,0 +1,53 @@ +import numpy as np +import pytest +import torch + +from src.court_projection import CourtHomography +from src.temporal_selector.rally_features import ( + CANONICAL_RALLY_FEATURE_VIEW, + FULL_RALLY_FEATURE_NAMES, + SERVE_BOX_NAMES, + rally_feature_view, + rally_serve_box_features, +) + + +def test_service_box_scores_use_both_ankles_and_mask_missing_players(): + # Pixel court origin (10, 10), one metre per pixel. + court = CourtHomography(np.array([[1, 0, -10], [0, 1, -10], [0, 0, 1]])) + values = torch.zeros((4, len(FULL_RALLY_FEATURE_NAMES))) + validity = torch.zeros_like(values, dtype=torch.bool) + poses = values[:, 22:].reshape(-1, 2, 33, 2) + visible = validity[:, 22:].reshape_as(poses) + poses[:3, :, 27:29] = torch.tensor([ + [[[-1.4, -4], [-0.6, -4]], [[0.6, 4], [1.4, 4]]], + [[[0.6, -4], [1.4, -4]], [[0.6, 4], [1.4, 4]]], + [[[0.6, -4], [1.4, -4]], [[-1.4, 4], [-0.6, 4]]], + ]).add(10).div(20) + visible[:3, :, 27:29] = True + visible[2, 1, 28] = False + + scores, valid = rally_serve_box_features(values, validity, court, (20, 20)) + + decay = np.exp(-0.5 * (1 / 0.75) ** 2) + assert scores[0].tolist() == pytest.approx([1, decay, decay, 1, 1], abs=2e-6) + assert scores[1].tolist() == pytest.approx([decay, 1, decay, 1, decay], abs=2e-6) + assert scores[2].tolist() == pytest.approx([decay, 1, 0, 0, 0], abs=2e-6) + assert valid.tolist() == [[True] * 5, [True] * 5, + [True, True, False, False, False], [False] * 5] + assert not scores[3].any() + + +def test_serve_views_keep_baseline_order_and_audio_tail(): + baseline = rally_feature_view(CANONICAL_RALLY_FEATURE_VIEW) + four = rally_feature_view("serve_boxes") + five = rally_feature_view("serve_boxes_diagonal") + for view, count in ((four, 4), (five, 5)): + assert view.dimension == baseline.dimension + count + assert view.names[-7 - count:-7] == SERVE_BOX_NAMES[:count] + assert view.names[:-7 - count] + view.names[-7:] == baseline.names + values = torch.arange(view.dimension, dtype=torch.float32)[None, :] + valid = torch.ones_like(values, dtype=torch.bool) + selected, selected_valid = view.select(values, valid) + assert torch.equal(selected, values) + assert torch.equal(selected_valid, valid) diff --git a/tests/test_shortcut_diagnostic.py b/tests/test_shortcut_diagnostic.py index caca755..6fb0ba5 100644 --- a/tests/test_shortcut_diagnostic.py +++ b/tests/test_shortcut_diagnostic.py @@ -49,6 +49,8 @@ def test_registered_feature_views_have_exact_names_dimensions_and_masks() -> Non "full": 154, "full_motion": 290, "full_audio_zscore_motion": 297, + "serve_boxes": 301, + "serve_boxes_diagonal": 302, "full_audio": 161, "full_audio_zscore": 161, "calibrated_canonical": 142,