From 7728c4e62214d76465d712f8746d47c1d533ae47 Mon Sep 17 00:00:00 2001 From: Max Lin Date: Sun, 22 Nov 2026 12:29:56 -0600 Subject: [PATCH 1/5] Add optional motion features for InPlay rally segmentation --- docs/rally-training.md | 21 ++++ .../temporal_selector/shortcut_diagnostic.py | 6 +- src/temporal_selector/rally_dataset.py | 111 ++++++++++-------- src/temporal_selector/rally_experiment.py | 8 +- src/temporal_selector/rally_features.py | 58 ++++++++- tests/test_independent_rally_segmenter.py | 38 ++++++ tests/test_rally_pipeline.py | 2 +- tests/test_shortcut_diagnostic.py | 4 +- 8 files changed, 187 insertions(+), 61 deletions(-) diff --git a/docs/rally-training.md b/docs/rally-training.md index fde6ccc..85dc1e4 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -152,3 +152,24 @@ Each fold tunes a higher rally entry threshold and a lower continuation threshold on its validation frames. The production checkpoint freezes both thresholds using out-of-fold predictions, along with the gap and minimum-duration settings. + +## Joint and court velocity experiment + +Use `--clean-only --feature-view full_motion` to add signed x/y velocity for +each pose landmark and each player's court position. Use +`full_audio_zscore_motion` for the corresponding normalized-audio recipe. +Both views retain the original normalized court x/y positions. + +The features fit a trailing four-frame linear slope to the player-relative +pose coordinates and the normalized coordinates of the projected court foot +position. Slopes are expressed per second, in pose-scale units for joints +and court half-width or half-length units for court position. A velocity +requires four valid consecutive samples of the same track. The first three +frames, missing observations, and track changes invalidate the affected +velocity channels. The computation runs once per source or split clip before +creating overlapping model windows. + +Compare each motion view with its corresponding position-only view on the +same camera folds and source artifacts. Hold the training recipe fixed and +compare interval F1 and signed start/end errors by camera. The four-frame +window is an experimental default and has a shorter time span at higher FPS. diff --git a/experiments/temporal_selector/shortcut_diagnostic.py b/experiments/temporal_selector/shortcut_diagnostic.py index 495427b..ec6f833 100644 --- a/experiments/temporal_selector/shortcut_diagnostic.py +++ b/experiments/temporal_selector/shortcut_diagnostic.py @@ -369,8 +369,8 @@ def project_rally_windows( view = RALLY_FEATURE_VIEWS.get(feature_view) if view is None: raise ValueError(f"unknown rally feature view: {feature_view}") - if view.uses_audio: - raise ValueError("audio features must be compiled from the source recording") + if view.uses_audio or view.uses_motion: + raise ValueError("audio and motion features must be compiled from the source recording") output: list[RallyWindow] = [] for window in windows: if window.frame_values.shape[-1] != len(FULL_RALLY_FEATURE_NAMES): @@ -659,7 +659,7 @@ def run_rally_feature_ablations( view_results: dict[str, Any] = {} predictions: dict[str, list[dict[str, Any]]] = {} for view_name, view in RALLY_FEATURE_VIEWS.items(): - if view.uses_audio: + if view.uses_audio or view.uses_motion: continue view_dir = output_dir / view_name view_dir.mkdir() diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index b42c308..e44ea3c 100644 --- a/src/temporal_selector/rally_dataset.py +++ b/src/temporal_selector/rally_dataset.py @@ -36,6 +36,7 @@ from .rally_audio import read_rally_audio from .rally_features import ( FULL_RALLY_FEATURE_NAMES, + rally_motion_features, rally_feature_view, ) from .rally_intervals import read_rally_intervals @@ -383,6 +384,57 @@ def _compile_source( radius = max(1, round(fps * self.config.context_seconds)) if radius < ownership // 2: raise ValueError("rally context radius must cover the entire ownership window") + source_values: list[list[float]] = [] + source_validity: list[list[bool]] = [] + track_ids: list[list[int]] = [] + for frame in range(frame_count): + frame_values, frame_validity = frame_context( + assignments[frame], + poses, + frame, + image_size, + "full_context", + self.config.pose_visibility_threshold, + self.config.pose_coordinate_mode, + ) + for player_index, role in enumerate(("P1", "P2")): + item = assignments[frame].get("slots", {}).get(role, {}).get("assignment") + if not isinstance(item, Mapping): + continue + projected = homography.project_to_court([item["foot"]])[0] + cached = np.asarray([item.get("court_x"), item.get("court_y")], dtype=float) + if not np.isfinite(cached).all() or not np.allclose( + cached, + projected, + rtol=0.0, + atol=self.config.cached_court_tolerance, + ): + raise ValueError( + f"cached assignment court coordinates disagree with canonical calibration at frame {frame} {role}" + ) + offset = player_index * 11 + frame_values[offset + 6] = float(projected[0]) / HALF_WIDTH + frame_values[offset + 7] = float(projected[1]) / HALF_LENGTH + source_values.append(frame_values) + source_validity.append(frame_validity) + if self.feature_view.uses_motion: + slots = assignments[frame]["slots"] + track_ids.append([ + int(item["track_id"]) if isinstance(item, Mapping) else -1 + for item in (slots.get(role, {}).get("assignment") for role in ("P1", "P2")) + ]) + value_tensor = torch.tensor(source_values, dtype=torch.float32) + validity_tensor = torch.tensor(source_validity, dtype=torch.bool) + if self.feature_view.uses_motion: + velocity, velocity_valid = rally_motion_features( + value_tensor, validity_tensor, torch.tensor(track_ids), fps + ) + value_tensor = torch.cat((value_tensor, velocity), dim=-1) + validity_tensor = torch.cat((validity_tensor, velocity_valid), 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) + value_tensor, validity_tensor = self.feature_view.select(value_tensor, validity_tensor) windows: list[RallyWindow] = [] for owned_start in range(0, frame_count, ownership): owned = frozenset( @@ -392,51 +444,12 @@ def _compile_source( start = max(0, anchor - radius) end = min(frame_count - 1, anchor + radius) frames = tuple(range(start, end + 1)) - values: list[list[float]] = [] - validity: list[list[bool]] = [] - targets: list[int] = [] - for frame in frames: - frame_values, frame_validity = frame_context( - assignments[frame], - poses, - frame, - image_size, - "full_context", - self.config.pose_visibility_threshold, - self.config.pose_coordinate_mode, - ) - for player_index, role in enumerate(("P1", "P2")): - item = assignments[frame].get("slots", {}).get(role, {}).get("assignment") - if not isinstance(item, Mapping): - continue - projected = homography.project_to_court([item["foot"]])[0] - cached = np.asarray([item.get("court_x"), item.get("court_y")], dtype=float) - if not np.isfinite(cached).all() or not np.allclose( - cached, - projected, - rtol=0.0, - atol=self.config.cached_court_tolerance, - ): - raise ValueError( - f"cached assignment court coordinates disagree with canonical calibration at frame {frame} {role}" - ) - offset = player_index * 11 - frame_values[offset + 6] = float(projected[0]) / HALF_WIDTH - frame_values[offset + 7] = float(projected[1]) / HALF_LENGTH - if audio is not None: - frame_values.extend(audio_values[frame].tolist()) - frame_validity.extend(audio.validity[frame].tolist()) - selected_values, selected_validity = self.feature_view.select( - torch.tensor(frame_values, dtype=torch.float32), - torch.tensor(frame_validity, dtype=torch.bool), - ) - values.append(selected_values.tolist()) - validity.append(selected_validity.tolist()) - targets.append( - self.rally_index.target(source.source_id, frame) - if self.rally_index is not None and frame in owned - else MASKED_TARGET - ) + targets = [ + self.rally_index.target(source.source_id, frame) + if self.rally_index is not None and frame in owned + else MASKED_TARGET + for frame in frames + ] if self.rally_index is not None: start_targets, end_targets = rally_boundary_targets( self.rally_index.for_source(source.source_id), @@ -460,12 +473,8 @@ def _compile_source( [(frame - anchor) / fps for frame in frames], dtype=torch.float32, ), - frame_values=torch.tensor( - values, dtype=torch.float32 - ).reshape(len(frames), self.feature_view.dimension), - frame_validity=torch.tensor( - validity, dtype=torch.bool - ).reshape(len(frames), self.feature_view.dimension), + frame_values=value_tensor[start : end + 1].clone(), + frame_validity=validity_tensor[start : end + 1].clone(), inplay_targets=torch.tensor(targets, dtype=torch.long), rally_start_targets=start_targets, rally_end_targets=end_targets, diff --git a/src/temporal_selector/rally_experiment.py b/src/temporal_selector/rally_experiment.py index 345fdbf..2446e03 100644 --- a/src/temporal_selector/rally_experiment.py +++ b/src/temporal_selector/rally_experiment.py @@ -1490,8 +1490,8 @@ 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"): - raise ValueError("the RTMPose audio preset requires the full_audio_zscore feature view") + if args.feature_view not in (None, "full_audio_zscore", "full_audio_zscore_motion"): + raise ValueError("the RTMPose audio preset requires a normalized-audio feature view") overrides.setdefault("temporal_smoothing_weight", 0.1) recipe = RallyTrainingRecipe.from_preset( "default" if rtmpose_preset else args.preset, **overrides @@ -1517,7 +1517,9 @@ def main(argv: Sequence[str] | None = None) -> int: RALLY_TRANSFORMER_CONTEXT_RADIUS_SECONDS if rtmpose_preset else RallyDataConfig.context_seconds ), ) - feature_view = "full_audio_zscore" if rtmpose_preset else args.feature_view + feature_view = args.feature_view + if rtmpose_preset and feature_view is None: + feature_view = "full_audio_zscore" if feature_view is not None: data_config = replace(data_config, feature_view=feature_view) camera_sources = _load_camera_sources(raw.get("camera_sources")) diff --git a/src/temporal_selector/rally_features.py b/src/temporal_selector/rally_features.py index d1067d1..daaff6d 100644 --- a/src/temporal_selector/rally_features.py +++ b/src/temporal_selector/rally_features.py @@ -39,6 +39,42 @@ ) +MOTION_POSITION_INDICES: Final = tuple( + index for index, name in enumerate(FULL_RALLY_FEATURE_NAMES) + if "_pose_" in name or name.endswith(("_court_x", "_court_y")) +) +MOTION_FEATURE_NAMES: Final = tuple( + FULL_RALLY_FEATURE_NAMES[index].rsplit("_", 1)[0] + "_velocity_" + + FULL_RALLY_FEATURE_NAMES[index][-1] + for index in MOTION_POSITION_INDICES +) + + +# Two court coordinates per player, followed by 66 pose coordinates per player. +_MOTION_PLAYER_INDICES: Final = (0, 0, 1, 1) + (0,) * 66 + (1,) * 66 + + +def rally_motion_features( + values: Tensor, validity: Tensor, track_ids: Tensor, fps: float, +) -> tuple[Tensor, Tensor]: + """Fit a trailing four-frame slope over each continuously observed coordinate.""" + positions = values[:, MOTION_POSITION_INDICES] + observed = validity[:, MOTION_POSITION_INDICES] + velocity = torch.zeros_like(positions) + valid = torch.zeros_like(observed) + if len(positions) < 4: + return velocity, valid + + # Least-squares slope for four uniformly spaced samples, per second. + track_history = track_ids.unfold(0, 4, 1) + same_track = (track_history == track_history[..., :1]).all(dim=-1) + same_track &= track_history[..., 0] >= 0 + valid[3:] = observed.unfold(0, 4, 1).all(dim=-1) & same_track[:, _MOTION_PLAYER_INDICES] + slope = (3 * (positions[3:] - positions[:-3]) + positions[2:-1] - positions[1:-2]) + velocity[3:] = torch.where(valid[3:], slope * (fps / 10), 0.0) + return velocity, valid + + @dataclass(frozen=True) class RallyFeatureView: """A stable ordered projection of visual features and optional audio features.""" @@ -48,6 +84,7 @@ class RallyFeatureView: full_indices: tuple[int, ...] uses_audio: bool = False audio_zscore: bool = False + uses_motion: bool = False @property def dimension(self) -> int: @@ -57,6 +94,8 @@ 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) + if self.uses_motion: + input_dimension += len(MOTION_FEATURE_NAMES) if self.uses_audio: input_dimension += len(RALLY_AUDIO_FEATURE_NAMES) if values.shape[-1] != input_dimension: @@ -78,22 +117,35 @@ 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, ) -> RallyFeatureView: requested = tuple(names) if len(requested) != len(set(requested)): raise AssertionError(f"duplicate feature in rally view {name}") - input_names = FULL_RALLY_FEATURE_NAMES + (RALLY_AUDIO_FEATURE_NAMES if uses_audio else ()) + input_names = ( + FULL_RALLY_FEATURE_NAMES + + (MOTION_FEATURE_NAMES if uses_motion else ()) + + (RALLY_AUDIO_FEATURE_NAMES if uses_audio else ()) + ) positions = {feature: index for index, feature in enumerate(input_names)} missing = [feature for feature in requested if feature not in positions] 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 + name, requested, tuple(positions[item] for item in requested), uses_audio, audio_zscore, uses_motion ) RALLY_FEATURE_VIEWS: Final[Mapping[str, RallyFeatureView]] = { "full": _view("full", FULL_RALLY_FEATURE_NAMES), + "full_motion": _view( + "full_motion", FULL_RALLY_FEATURE_NAMES + MOTION_FEATURE_NAMES, uses_motion=True + ), + "full_audio_zscore_motion": _view( + "full_audio_zscore_motion", + FULL_RALLY_FEATURE_NAMES + MOTION_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, + uses_audio=True, audio_zscore=True, uses_motion=True, + ), "full_audio": _view( "full_audio", FULL_RALLY_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, uses_audio=True ), @@ -173,6 +225,8 @@ def rally_feature_indices(names: Sequence[str]) -> tuple[int, ...]: assert len(FULL_RALLY_FEATURE_NAMES) == 154 assert {name: view.dimension for name, view in RALLY_FEATURE_VIEWS.items()} == { "full": 154, + "full_motion": 290, + "full_audio_zscore_motion": 297, "full_audio": 161, "full_audio_zscore": 161, "calibrated_canonical": 142, diff --git a/tests/test_independent_rally_segmenter.py b/tests/test_independent_rally_segmenter.py index 680f54b..89d5f68 100644 --- a/tests/test_independent_rally_segmenter.py +++ b/tests/test_independent_rally_segmenter.py @@ -367,3 +367,41 @@ def test_mixed_fps_camera_split_includes_exact_fractional_boundary() -> None: assert [window.window_id for window in validation] == [ f"late-{frame}" for frame in range(140, 175) ] + + +@pytest.mark.parametrize("fps", [25.0, 30.0, 60.0]) +def test_rally_motion_uses_elapsed_time_and_masks_gaps_and_track_changes(fps) -> None: + from src.temporal_selector.rally_features import ( + FULL_RALLY_FEATURE_NAMES, + MOTION_FEATURE_NAMES, + rally_feature_view, + rally_motion_features, + ) + + positions = torch.zeros(9, len(FULL_RALLY_FEATURE_NAMES)) + observed = torch.ones_like(positions, dtype=torch.bool) + tracks = torch.ones(9, 2, dtype=torch.long) + tracks[4:, 0] = 2 + time = torch.arange(9) / fps + positions[:, FULL_RALLY_FEATURE_NAMES.index("p1_court_x")] = -2 * time + joint = FULL_RALLY_FEATURE_NAMES.index("p2_pose_0_y") + positions[:, joint] = 3 * time + observed[4, joint] = False + + velocity, valid = rally_motion_features(positions, observed, tracks, fps) + court_x = MOTION_FEATURE_NAMES.index("p1_court_velocity_x") + joint_y = MOTION_FEATURE_NAMES.index("p2_pose_0_velocity_y") + expected_valid = [False, False, False, True, False, False, False, True, True] + assert valid[:, court_x].tolist() == expected_valid + assert valid[:, joint_y].tolist() == [*expected_valid[:7], False, True] + assert torch.allclose(velocity[valid[:, court_x], court_x], torch.full((3,), -2.0)) + assert torch.allclose(velocity[valid[:, joint_y], joint_y], torch.full((2,), 3.0)) + assert torch.count_nonzero(velocity[~valid]) == 0 + + view = rally_feature_view("full_motion") + values, mask = view.select( + torch.cat((positions, velocity), dim=-1), + torch.cat((observed, valid), dim=-1), + ) + assert values.shape == mask.shape == (9, 290) + assert torch.equal(values[:, :positions.shape[1]], positions) diff --git a/tests/test_rally_pipeline.py b/tests/test_rally_pipeline.py index 73968d1..6dc0f64 100644 --- a/tests/test_rally_pipeline.py +++ b/tests/test_rally_pipeline.py @@ -435,7 +435,7 @@ def test_explicit_device_failure_and_auto_fallback(pipeline, monkeypatch): assert calls == {"person": 0, "players": 0} -@pytest.mark.parametrize("view", ["no_position", "full_audio"]) +@pytest.mark.parametrize("view", ["no_position", "full_audio", "full_motion", "full_audio_zscore_motion"]) def test_pipeline_uses_manifest_feature_view(pipeline, view): kwargs, _ = pipeline config = RallySegmenterConfig( diff --git a/tests/test_shortcut_diagnostic.py b/tests/test_shortcut_diagnostic.py index f2e3f52..caca755 100644 --- a/tests/test_shortcut_diagnostic.py +++ b/tests/test_shortcut_diagnostic.py @@ -47,6 +47,8 @@ def test_registered_feature_views_have_exact_names_dimensions_and_masks() -> Non assert len(FULL_RALLY_FEATURE_NAMES) == 154 assert {name: view.dimension for name, view in RALLY_FEATURE_VIEWS.items()} == { "full": 154, + "full_motion": 290, + "full_audio_zscore_motion": 297, "full_audio": 161, "full_audio_zscore": 161, "calibrated_canonical": 142, @@ -55,7 +57,7 @@ def test_registered_feature_views_have_exact_names_dimensions_and_masks() -> Non } full = _window() for name, view in RALLY_FEATURE_VIEWS.items(): - if view.uses_audio: + if view.uses_audio or view.uses_motion: with pytest.raises(ValueError, match="compiled from the source recording"): project_rally_windows([full], name) continue From 42cdb164ef77ac14f7801ad123898935a0d95980 Mon Sep 17 00:00:00 2001 From: Max Lin Date: Sun, 22 Nov 2026 12:48:07 -0600 Subject: [PATCH 2/5] Stabilize torso scale and shorten InPlay joint velocity window --- docs/rally-training.md | 30 ++++++----- src/temporal_selector/rally_dataset.py | 16 +++--- src/temporal_selector/rally_features.py | 65 +++++++++++++++++------ tests/test_independent_rally_segmenter.py | 42 ++++++++++++++- 4 files changed, 117 insertions(+), 36 deletions(-) diff --git a/docs/rally-training.md b/docs/rally-training.md index 85dc1e4..73e0a8c 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -160,16 +160,20 @@ each pose landmark and each player's court position. Use `full_audio_zscore_motion` for the corresponding normalized-audio recipe. Both views retain the original normalized court x/y positions. -The features fit a trailing four-frame linear slope to the player-relative -pose coordinates and the normalized coordinates of the projected court foot -position. Slopes are expressed per second, in pose-scale units for joints -and court half-width or half-length units for court position. A velocity -requires four valid consecutive samples of the same track. The first three -frames, missing observations, and track changes invalidate the affected -velocity channels. The computation runs once per source or split clip before -creating overlapping model windows. - -Compare each motion view with its corresponding position-only view on the -same camera folds and source artifacts. Hold the training recipe fixed and -compare interval F1 and signed start/end errors by camera. The four-frame -window is an experimental default and has a shorter time span at higher FPS. +The motion views map crop landmarks back to image pixels using the exact +stored crop box. They center pose on the midpoint of the hips and normalize +by the median visible shoulder-midpoint to hip-midpoint distance for that +player track within the source or split clip. Frames with either hip missing +or no usable track torso scale have masked pose features. + +Joint velocity uses a trailing three-frame slope and court velocity uses +four frames. Slopes are per second, in torso-length units for joints and +court half-width or half-length units for court position. A velocity requires +all samples in its window to be valid and on the same track. Motion is computed +before slicing overlapping model windows. + +Compare motion views on the same camera folds and source artifacts, with the +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. diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index e44ea3c..90d0154 100644 --- a/src/temporal_selector/rally_dataset.py +++ b/src/temporal_selector/rally_dataset.py @@ -36,8 +36,9 @@ from .rally_audio import read_rally_audio from .rally_features import ( FULL_RALLY_FEATURE_NAMES, - rally_motion_features, + normalize_rally_motion_pose, rally_feature_view, + rally_motion_features, ) from .rally_intervals import read_rally_intervals @@ -164,9 +165,10 @@ def __init__(self, config: RallyDataConfig): "feature_view": self.feature_view.name, "feature_names": self.feature_view.names, "pose_coordinate_mode": config.pose_coordinate_mode, - "pose_representation_version": POSE_REPRESENTATION_VERSION[ - config.pose_coordinate_mode - ], + "pose_representation_version": ( + "pelvis-root-track-median-torso-v1" if self.feature_view.uses_motion + else POSE_REPRESENTATION_VERSION[config.pose_coordinate_mode] + ), "pose_visibility_threshold": config.pose_visibility_threshold, "context_seconds": config.context_seconds, "ownership_seconds": config.ownership_seconds, @@ -395,7 +397,7 @@ def _compile_source( image_size, "full_context", self.config.pose_visibility_threshold, - self.config.pose_coordinate_mode, + "image" if self.feature_view.uses_motion else self.config.pose_coordinate_mode, ) for player_index, role in enumerate(("P1", "P2")): item = assignments[frame].get("slots", {}).get(role, {}).get("assignment") @@ -426,8 +428,10 @@ def _compile_source( value_tensor = torch.tensor(source_values, dtype=torch.float32) validity_tensor = torch.tensor(source_validity, dtype=torch.bool) if self.feature_view.uses_motion: + track_tensor = torch.tensor(track_ids) + normalize_rally_motion_pose(value_tensor, validity_tensor, track_tensor, image_size) velocity, velocity_valid = rally_motion_features( - value_tensor, validity_tensor, torch.tensor(track_ids), fps + value_tensor, validity_tensor, track_tensor, fps ) value_tensor = torch.cat((value_tensor, velocity), dim=-1) validity_tensor = torch.cat((validity_tensor, velocity_valid), dim=-1) diff --git a/src/temporal_selector/rally_features.py b/src/temporal_selector/rally_features.py index daaff6d..3e8e451 100644 --- a/src/temporal_selector/rally_features.py +++ b/src/temporal_selector/rally_features.py @@ -39,6 +39,11 @@ ) +MEDIAN_TORSO_FEATURE_NAMES: Final = tuple( + name.replace("_pose_", "_median_torso_pose_") for name in FULL_RALLY_FEATURE_NAMES +) +_POSE_START: Final = len(PLAYER_CONTEXT_FIELDS) * 2 + MOTION_POSITION_INDICES: Final = tuple( index for index, name in enumerate(FULL_RALLY_FEATURE_NAMES) if "_pose_" in name or name.endswith(("_court_x", "_court_y")) @@ -54,24 +59,55 @@ _MOTION_PLAYER_INDICES: Final = (0, 0, 1, 1) + (0,) * 66 + (1,) * 66 +def normalize_rally_motion_pose( + values: Tensor, validity: Tensor, track_ids: Tensor, image_size: tuple[int, int], +) -> None: + """Normalize image pose in place using one median torso length per player track.""" + poses = values[:, _POSE_START:].reshape(-1, 2, 33, 2) + valid = validity[:, _POSE_START:].reshape_as(poses) + poses.mul_(poses.new_tensor(image_size)) + visible = valid.all(dim=-1) + hips = poses[:, :, [23, 24]].mean(dim=-2, keepdim=True) + shoulders = poses[:, :, [11, 12]].mean(dim=-2, keepdim=True) + torso = (shoulders - hips).norm(dim=-1).squeeze(-1) + has_hips = visible[:, :, 23] & visible[:, :, 24] + has_torso = has_hips & visible[:, :, 11] & visible[:, :, 12] & (torso > 1.0) + for player in range(2): + scale = torch.zeros_like(torso[:, player]) + player_tracks = track_ids[:, player] + for track in player_tracks[has_torso[:, player] & (player_tracks >= 0)].unique(): + frames = player_tracks == track + scale[frames] = torso[:, player][frames & has_torso[:, player]].quantile(0.5) + usable = has_hips[:, player] & (scale > 0) + valid[:, player] &= usable[:, None, None] + relative = (poses[:, player] - hips[:, player]) / scale.clamp_min(1)[:, None, None] + poses[:, player] = torch.where(valid[:, player], relative, 0.0) + + def rally_motion_features( values: Tensor, validity: Tensor, track_ids: Tensor, fps: float, ) -> tuple[Tensor, Tensor]: - """Fit a trailing four-frame slope over each continuously observed coordinate.""" + """Fit trailing slopes over continuously observed coordinates on the same track.""" positions = values[:, MOTION_POSITION_INDICES] observed = validity[:, MOTION_POSITION_INDICES] velocity = torch.zeros_like(positions) valid = torch.zeros_like(observed) - if len(positions) < 4: - return velocity, valid - - # Least-squares slope for four uniformly spaced samples, per second. - track_history = track_ids.unfold(0, 4, 1) - same_track = (track_history == track_history[..., :1]).all(dim=-1) - same_track &= track_history[..., 0] >= 0 - valid[3:] = observed.unfold(0, 4, 1).all(dim=-1) & same_track[:, _MOTION_PLAYER_INDICES] - slope = (3 * (positions[3:] - positions[:-3]) + positions[2:-1] - positions[1:-2]) - velocity[3:] = torch.where(valid[3:], slope * (fps / 10), 0.0) + + # Court motion uses four samples. Joints use three to retain faster motion. + for columns, count in ((slice(0, 4), 4), (slice(4, None), 3)): + if len(positions) < count: + continue + tracks = track_ids.unfold(0, count, 1) + same_track = (tracks == tracks[..., :1]).all(dim=-1) & (tracks[..., 0] >= 0) + valid[count - 1:, columns] = ( + observed[:, columns].unfold(0, count, 1).all(dim=-1) + & same_track[:, _MOTION_PLAYER_INDICES[columns]] + ) + samples = positions[:, columns].unfold(0, count, 1) + slope = (samples[..., -1] - samples[..., 0]) / 2 + if count == 4: + slope = (3 * (samples[..., -1] - samples[..., 0]) + samples[..., 2] - samples[..., 1]) / 10 + velocity[count - 1:, columns] = torch.where(valid[count - 1:, columns], slope * fps, 0.0) return velocity, valid @@ -123,8 +159,7 @@ def _view( if len(requested) != len(set(requested)): raise AssertionError(f"duplicate feature in rally view {name}") input_names = ( - FULL_RALLY_FEATURE_NAMES - + (MOTION_FEATURE_NAMES if uses_motion else ()) + (MEDIAN_TORSO_FEATURE_NAMES + MOTION_FEATURE_NAMES if uses_motion else FULL_RALLY_FEATURE_NAMES) + (RALLY_AUDIO_FEATURE_NAMES if uses_audio else ()) ) positions = {feature: index for index, feature in enumerate(input_names)} @@ -139,11 +174,11 @@ def _view( RALLY_FEATURE_VIEWS: Final[Mapping[str, RallyFeatureView]] = { "full": _view("full", FULL_RALLY_FEATURE_NAMES), "full_motion": _view( - "full_motion", FULL_RALLY_FEATURE_NAMES + MOTION_FEATURE_NAMES, uses_motion=True + "full_motion", MEDIAN_TORSO_FEATURE_NAMES + MOTION_FEATURE_NAMES, uses_motion=True ), "full_audio_zscore_motion": _view( "full_audio_zscore_motion", - FULL_RALLY_FEATURE_NAMES + MOTION_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, + MEDIAN_TORSO_FEATURE_NAMES + MOTION_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, uses_audio=True, audio_zscore=True, uses_motion=True, ), "full_audio": _view( diff --git a/tests/test_independent_rally_segmenter.py b/tests/test_independent_rally_segmenter.py index 89d5f68..f8348c3 100644 --- a/tests/test_independent_rally_segmenter.py +++ b/tests/test_independent_rally_segmenter.py @@ -393,9 +393,9 @@ def test_rally_motion_uses_elapsed_time_and_masks_gaps_and_track_changes(fps) -> joint_y = MOTION_FEATURE_NAMES.index("p2_pose_0_velocity_y") expected_valid = [False, False, False, True, False, False, False, True, True] assert valid[:, court_x].tolist() == expected_valid - assert valid[:, joint_y].tolist() == [*expected_valid[:7], False, True] + assert valid[:, joint_y].tolist() == [False, False, True, True, False, False, False, True, True] assert torch.allclose(velocity[valid[:, court_x], court_x], torch.full((3,), -2.0)) - assert torch.allclose(velocity[valid[:, joint_y], joint_y], torch.full((2,), 3.0)) + assert torch.allclose(velocity[valid[:, joint_y], joint_y], torch.full((4,), 3.0)) assert torch.count_nonzero(velocity[~valid]) == 0 view = rally_feature_view("full_motion") @@ -405,3 +405,41 @@ def test_rally_motion_uses_elapsed_time_and_masks_gaps_and_track_changes(fps) -> ) assert values.shape == mask.shape == (9, 290) assert torch.equal(values[:, :positions.shape[1]], positions) + + +def test_rally_motion_pose_uses_crop_geometry_and_track_median_torso() -> None: + from src.temporal_selector.observations import frame_context + from src.temporal_selector.rally_features import ( + FULL_RALLY_FEATURE_NAMES, + normalize_rally_motion_pose, + ) + + image_size = (640, 480) + crop = [85, 70, 215, 330] + assignment = {"slots": {"P1": {"confidence": 1, "assignment": { + "track_id": 1, "bbox": [100, 100, 200, 300], "foot": [150, 300], + "court_x": 0, "court_y": 0, "detection_confidence": 1, "activity": 0, + }}}} + observations = [] + for frame, torso in enumerate((20, 20, 100, 40, 40)): + pixels = [(160, 200)] * 33 + for left, right, y in ((11, 12, 200 - torso), (23, 24, 200)): + pixels[left], pixels[right] = (140, y), (160, y) + landmarks = [ + {"x": (x - crop[0]) / (crop[2] - crop[0]), + "y": (y - crop[1]) / (crop[3] - crop[1]), + "visibility": 0 if (frame, index) == (4, 24) else 1} + for index, (x, y) in enumerate(pixels) + ] + track = 1 if frame < 3 else 2 + assignment["slots"]["P1"]["assignment"]["track_id"] = track + poses = {(frame, track): { + "status": "detected", "pose_bbox": crop, "pose_landmarks": landmarks, + }} + observations.append(frame_context(assignment, poses, frame, image_size, "full_context", 0.5, "image")) + values, valid = map(torch.tensor, zip(*observations)) + track_ids = torch.tensor([[1, -1], [1, -1], [1, -1], [2, -1], [2, -1]]) + normalize_rally_motion_pose(values, valid, track_ids, image_size) + wrist_x = FULL_RALLY_FEATURE_NAMES.index("p1_pose_15_x") + assert values[:, wrist_x].tolist() == pytest.approx([0.5, 0.5, 0.5, 0.25, 0.0]) + assert valid[:, wrist_x].tolist() == [True, True, True, True, False] From 395b0eb7b4295f6dc4a1caa91c7fdf2340d91ffa Mon Sep 17 00:00:00 2001 From: Max Lin Date: Sun, 22 Nov 2026 12:53:53 -0600 Subject: [PATCH 3/5] Median-filter calibrated InPlay court positions --- docs/rally-training.md | 8 +++++- src/temporal_selector/rally_dataset.py | 2 ++ src/temporal_selector/rally_features.py | 35 ++++++++++++++++++----- tests/test_independent_rally_segmenter.py | 31 ++++++++++++++++++++ 4 files changed, 68 insertions(+), 8 deletions(-) diff --git a/docs/rally-training.md b/docs/rally-training.md index 73e0a8c..f52d151 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -158,7 +158,13 @@ predictions, along with the gap and minimum-duration settings. Use `--clean-only --feature-view full_motion` to add signed x/y velocity for each pose landmark and each player's court position. Use `full_audio_zscore_motion` for the corresponding normalized-audio recipe. -Both views retain the original normalized court x/y positions. +Both views use the existing court-centered coordinate convention, with the +court center at zero and the outer lines at ±1 along each axis. Coordinates +can extend beyond the lines. A centered three-frame median on each court +axis suppresses isolated foot-position spikes before the position and +velocity features are emitted. The median uses one frame of lookahead +within the offline source or split clip. At source edges, missing +observations, and track changes, it keeps the current sample and its mask. The motion views map crop landmarks back to image pixels using the exact stored crop box. They center pose on the midpoint of the hips and normalize diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index 90d0154..c6bacdb 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, + smooth_rally_court_positions, ) from .rally_intervals import read_rally_intervals @@ -430,6 +431,7 @@ def _compile_source( if self.feature_view.uses_motion: track_tensor = torch.tensor(track_ids) normalize_rally_motion_pose(value_tensor, validity_tensor, track_tensor, image_size) + smooth_rally_court_positions(value_tensor, validity_tensor, track_tensor) velocity, velocity_valid = rally_motion_features( value_tensor, validity_tensor, track_tensor, fps ) diff --git a/src/temporal_selector/rally_features.py b/src/temporal_selector/rally_features.py index 3e8e451..c9941e6 100644 --- a/src/temporal_selector/rally_features.py +++ b/src/temporal_selector/rally_features.py @@ -39,14 +39,19 @@ ) -MEDIAN_TORSO_FEATURE_NAMES: Final = tuple( - name.replace("_pose_", "_median_torso_pose_") for name in FULL_RALLY_FEATURE_NAMES +MOTION_BASE_FEATURE_NAMES: Final = tuple( + name.replace("_pose_", "_median_torso_pose_").replace("_court_", "_smoothed_court_") + for name in FULL_RALLY_FEATURE_NAMES ) _POSE_START: Final = len(PLAYER_CONTEXT_FIELDS) * 2 -MOTION_POSITION_INDICES: Final = tuple( +_COURT_POSITION_INDICES: Final = tuple( index for index, name in enumerate(FULL_RALLY_FEATURE_NAMES) - if "_pose_" in name or name.endswith(("_court_x", "_court_y")) + if name.endswith(("_court_x", "_court_y")) +) +MOTION_POSITION_INDICES: Final = _COURT_POSITION_INDICES + tuple( + index for index, name in enumerate(FULL_RALLY_FEATURE_NAMES) + if "_pose_" in name ) MOTION_FEATURE_NAMES: Final = tuple( FULL_RALLY_FEATURE_NAMES[index].rsplit("_", 1)[0] + "_velocity_" + @@ -84,6 +89,22 @@ def normalize_rally_motion_pose( poses[:, player] = torch.where(valid[:, player], relative, 0.0) +def smooth_rally_court_positions(values: Tensor, validity: Tensor, track_ids: Tensor) -> None: + """Apply a centered three-sample median within a continuously observed track.""" + if len(values) < 3: + return + + court = values[:, _COURT_POSITION_INDICES] + samples = court.unfold(0, 3, 1) + observed = validity[:, _COURT_POSITION_INDICES].unfold(0, 3, 1).all(dim=-1) + tracks = track_ids.unfold(0, 3, 1) + same_track = (tracks == tracks[..., :1]).all(dim=-1) & (tracks[..., 0] >= 0) + usable = observed & same_track.repeat_interleave(2, dim=-1) + values[1:-1, _COURT_POSITION_INDICES] = torch.where( + usable, samples.median(dim=-1).values, court[1:-1] + ) + + def rally_motion_features( values: Tensor, validity: Tensor, track_ids: Tensor, fps: float, ) -> tuple[Tensor, Tensor]: @@ -159,7 +180,7 @@ def _view( if len(requested) != len(set(requested)): raise AssertionError(f"duplicate feature in rally view {name}") input_names = ( - (MEDIAN_TORSO_FEATURE_NAMES + MOTION_FEATURE_NAMES if uses_motion else FULL_RALLY_FEATURE_NAMES) + (MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES if uses_motion else FULL_RALLY_FEATURE_NAMES) + (RALLY_AUDIO_FEATURE_NAMES if uses_audio else ()) ) positions = {feature: index for index, feature in enumerate(input_names)} @@ -174,11 +195,11 @@ def _view( RALLY_FEATURE_VIEWS: Final[Mapping[str, RallyFeatureView]] = { "full": _view("full", FULL_RALLY_FEATURE_NAMES), "full_motion": _view( - "full_motion", MEDIAN_TORSO_FEATURE_NAMES + MOTION_FEATURE_NAMES, uses_motion=True + "full_motion", MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES, uses_motion=True ), "full_audio_zscore_motion": _view( "full_audio_zscore_motion", - MEDIAN_TORSO_FEATURE_NAMES + MOTION_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, + MOTION_BASE_FEATURE_NAMES + MOTION_FEATURE_NAMES + RALLY_AUDIO_FEATURE_NAMES, uses_audio=True, audio_zscore=True, uses_motion=True, ), "full_audio": _view( diff --git a/tests/test_independent_rally_segmenter.py b/tests/test_independent_rally_segmenter.py index f8348c3..54d1362 100644 --- a/tests/test_independent_rally_segmenter.py +++ b/tests/test_independent_rally_segmenter.py @@ -443,3 +443,34 @@ def test_rally_motion_pose_uses_crop_geometry_and_track_median_torso() -> None: wrist_x = FULL_RALLY_FEATURE_NAMES.index("p1_pose_15_x") assert values[:, wrist_x].tolist() == pytest.approx([0.5, 0.5, 0.5, 0.25, 0.0]) assert valid[:, wrist_x].tolist() == [True, True, True, True, False] + + +def test_court_median_suppresses_spikes_before_velocity_and_preserves_track_edges() -> None: + from src.temporal_selector.rally_features import ( + FULL_RALLY_FEATURE_NAMES, + MOTION_FEATURE_NAMES, + rally_motion_features, + smooth_rally_court_positions, + ) + + values = torch.zeros(9, len(FULL_RALLY_FEATURE_NAMES)) + valid = torch.ones_like(values, dtype=torch.bool) + tracks = torch.ones(9, 2, dtype=torch.long) + tracks[7:, 0] = 2 + court_x = FULL_RALLY_FEATURE_NAMES.index("p1_court_x") + other_x = FULL_RALLY_FEATURE_NAMES.index("p2_court_x") + values[:, court_x] = torch.tensor([0., 0., 10., 0., 0., 8., 0., 7., 0.]) + valid[6, court_x] = False + values[:, other_x] = torch.arange(len(values)) + original_mask = valid.clone() + + smooth_rally_court_positions(values, valid, tracks) + assert values[:, court_x].tolist() == [0., 0., 0., 0., 0., 8., 0., 7., 0.] + assert torch.equal(values[:, other_x], torch.arange(len(values))) + assert torch.equal(valid, original_mask) + + velocity, mask = rally_motion_features(values, valid, tracks, fps=30) + court_vx = MOTION_FEATURE_NAMES.index("p1_court_velocity_x") + assert mask[3, court_vx] + assert velocity[3, court_vx] == 0 + assert not mask[6:, court_vx].any() From 896f56893841c349b3e0aaaeddea55b4b963bf9a Mon Sep 17 00:00:00 2001 From: Max Lin Date: Sun, 22 Nov 2026 12:57:26 -0600 Subject: [PATCH 4/5] Fit raw court velocity and gate position smoothing --- docs/rally-training.md | 12 +++--- src/temporal_selector/rally_dataset.py | 48 ++++++++++++++++++++--- src/temporal_selector/rally_features.py | 9 +++-- tests/test_independent_rally_segmenter.py | 30 ++++++++++++-- 4 files changed, 81 insertions(+), 18 deletions(-) diff --git a/docs/rally-training.md b/docs/rally-training.md index f52d151..c7ac390 100644 --- a/docs/rally-training.md +++ b/docs/rally-training.md @@ -161,10 +161,12 @@ each pose landmark and each player's court position. Use Both views use the existing court-centered coordinate convention, with the court center at zero and the outer lines at ±1 along each axis. Coordinates can extend beyond the lines. A centered three-frame median on each court -axis suppresses isolated foot-position spikes before the position and -velocity features are emitted. The median uses one frame of lookahead -within the offline source or split clip. At source edges, missing -observations, and track changes, it keeps the current sample and its mask. +axis suppresses isolated spikes in the position channels. It uses one frame +of lookahead within the offline source or split clip. All three samples must +be valid, belong to the same track, and have an accepted, unrepaired pose with +visible landmarks on both feet. An available foot diagnostic must not +disagree with the assigned side and court bounds. Other positions retain +their original values and masks. The motion views map crop landmarks back to image pixels using the exact stored crop box. They center pose on the midpoint of the hips and normalize @@ -173,7 +175,7 @@ player track within the source or split clip. Frames with either hip missing or no usable track torso scale have masked pose features. Joint velocity uses a trailing three-frame slope and court velocity uses -four frames. Slopes are per second, in torso-length units for joints and +four raw projected positions before the median. Slopes are per second, in torso-length units for joints and court half-width or half-length units for court position. A velocity requires all samples in its window to be valid and on the same track. Motion is computed before slicing overlapping model windows. diff --git a/src/temporal_selector/rally_dataset.py b/src/temporal_selector/rally_dataset.py index c6bacdb..fefca4c 100644 --- a/src/temporal_selector/rally_dataset.py +++ b/src/temporal_selector/rally_dataset.py @@ -130,6 +130,32 @@ class RallyWindow: metadata: Mapping[str, Any] = field(default_factory=dict) +def _reliable_court_foot( + slot: Mapping, pose: Mapping, visibility_threshold: float, +) -> bool: + """Require an accepted, unrepaired pose with visible evidence from both feet.""" + if ( + pose.get("status") != "detected" + or pose.get("temporal_status") not in (None, "original", "validated") + ): + return False + if slot.get("foot_diagnostic", {}).get("status") == "disagrees": + return False + landmarks = pose.get("pose_landmarks") or [] + if len(landmarks) != 33: + return False + threshold = max(0.5, visibility_threshold) + return all( + any( + float(landmarks[index].get("visibility", 0)) >= threshold + and math.isfinite(float(landmarks[index]["x"])) + and math.isfinite(float(landmarks[index]["y"])) + for index in foot + ) + for foot in ((29, 31), (30, 32)) + ) + + class RallyWindowDataset(Dataset[RallyWindow]): """Compile dense source-local windows without loading shuttle artifacts.""" @@ -390,6 +416,7 @@ def _compile_source( source_values: list[list[float]] = [] source_validity: list[list[bool]] = [] track_ids: list[list[int]] = [] + reliable_feet: list[list[bool]] = [] for frame in range(frame_count): frame_values, frame_validity = frame_context( assignments[frame], @@ -421,20 +448,29 @@ def _compile_source( source_values.append(frame_values) source_validity.append(frame_validity) if self.feature_view.uses_motion: - slots = assignments[frame]["slots"] - track_ids.append([ - int(item["track_id"]) if isinstance(item, Mapping) else -1 - for item in (slots.get(role, {}).get("assignment") for role in ("P1", "P2")) - ]) + frame_tracks = [] + frame_reliability = [] + for role in ("P1", "P2"): + slot = assignments[frame]["slots"].get(role, {}) + item = slot.get("assignment") + track = int(item["track_id"]) if isinstance(item, Mapping) else -1 + frame_tracks.append(track) + frame_reliability.append(_reliable_court_foot( + slot, poses.get((frame, track), {}), self.config.pose_visibility_threshold, + )) + track_ids.append(frame_tracks) + reliable_feet.append(frame_reliability) value_tensor = torch.tensor(source_values, dtype=torch.float32) validity_tensor = torch.tensor(source_validity, dtype=torch.bool) if self.feature_view.uses_motion: track_tensor = torch.tensor(track_ids) normalize_rally_motion_pose(value_tensor, validity_tensor, track_tensor, image_size) - smooth_rally_court_positions(value_tensor, validity_tensor, track_tensor) velocity, velocity_valid = rally_motion_features( value_tensor, validity_tensor, track_tensor, fps ) + smooth_rally_court_positions( + value_tensor, validity_tensor, track_tensor, torch.tensor(reliable_feet) + ) value_tensor = torch.cat((value_tensor, velocity), dim=-1) validity_tensor = torch.cat((validity_tensor, velocity_valid), dim=-1) if audio is not None: diff --git a/src/temporal_selector/rally_features.py b/src/temporal_selector/rally_features.py index c9941e6..cc5c9f5 100644 --- a/src/temporal_selector/rally_features.py +++ b/src/temporal_selector/rally_features.py @@ -40,7 +40,7 @@ MOTION_BASE_FEATURE_NAMES: Final = tuple( - name.replace("_pose_", "_median_torso_pose_").replace("_court_", "_smoothed_court_") + name.replace("_pose_", "_median_torso_pose_").replace("_court_", "_reliable_median_court_") for name in FULL_RALLY_FEATURE_NAMES ) _POSE_START: Final = len(PLAYER_CONTEXT_FIELDS) * 2 @@ -89,7 +89,9 @@ def normalize_rally_motion_pose( poses[:, player] = torch.where(valid[:, player], relative, 0.0) -def smooth_rally_court_positions(values: Tensor, validity: Tensor, track_ids: Tensor) -> None: +def smooth_rally_court_positions( + values: Tensor, validity: Tensor, track_ids: Tensor, reliable_feet: Tensor, +) -> None: """Apply a centered three-sample median within a continuously observed track.""" if len(values) < 3: return @@ -99,7 +101,8 @@ def smooth_rally_court_positions(values: Tensor, validity: Tensor, track_ids: Te observed = validity[:, _COURT_POSITION_INDICES].unfold(0, 3, 1).all(dim=-1) tracks = track_ids.unfold(0, 3, 1) same_track = (tracks == tracks[..., :1]).all(dim=-1) & (tracks[..., 0] >= 0) - usable = observed & same_track.repeat_interleave(2, dim=-1) + reliable_window = reliable_feet.unfold(0, 3, 1).all(dim=-1) + usable = observed & (same_track & reliable_window).repeat_interleave(2, dim=-1) values[1:-1, _COURT_POSITION_INDICES] = torch.where( usable, samples.median(dim=-1).values, court[1:-1] ) diff --git a/tests/test_independent_rally_segmenter.py b/tests/test_independent_rally_segmenter.py index 54d1362..c685923 100644 --- a/tests/test_independent_rally_segmenter.py +++ b/tests/test_independent_rally_segmenter.py @@ -445,7 +445,7 @@ def test_rally_motion_pose_uses_crop_geometry_and_track_median_torso() -> None: assert valid[:, wrist_x].tolist() == [True, True, True, True, False] -def test_court_median_suppresses_spikes_before_velocity_and_preserves_track_edges() -> None: +def test_court_median_gates_low_quality_frames_without_filtering_velocity() -> None: from src.temporal_selector.rally_features import ( FULL_RALLY_FEATURE_NAMES, MOTION_FEATURE_NAMES, @@ -464,13 +464,35 @@ def test_court_median_suppresses_spikes_before_velocity_and_preserves_track_edge values[:, other_x] = torch.arange(len(values)) original_mask = valid.clone() - smooth_rally_court_positions(values, valid, tracks) + reliable = torch.ones_like(tracks, dtype=torch.bool) + reliable[2, 0] = False + velocity, mask = rally_motion_features(values, valid, tracks, fps=30) + smooth_rally_court_positions(values, valid, tracks, reliable) + assert values[2, court_x] == 10 + + reliable[2, 0] = True + smooth_rally_court_positions(values, valid, tracks, reliable) assert values[:, court_x].tolist() == [0., 0., 0., 0., 0., 8., 0., 7., 0.] assert torch.equal(values[:, other_x], torch.arange(len(values))) assert torch.equal(valid, original_mask) - velocity, mask = rally_motion_features(values, valid, tracks, fps=30) court_vx = MOTION_FEATURE_NAMES.index("p1_court_velocity_x") assert mask[3, court_vx] - assert velocity[3, court_vx] == 0 + assert velocity[3, court_vx] == 30 assert not mask[6:, court_vx].any() + + + +def test_court_foot_reliability_requires_two_visible_feet_and_accepted_pose() -> None: + from src.temporal_selector.rally_dataset import _reliable_court_foot + + landmarks = [{"visibility": 0.0, "x": 0.4, "y": 0.8} for _ in range(33)] + pose = {"status": "detected", "pose_landmarks": landmarks} + landmarks[31]["visibility"] = 0.8 + assert not _reliable_court_foot({}, pose, 0.5) + landmarks[32]["visibility"] = 0.8 + assert _reliable_court_foot({}, pose, 0.5) + assert not _reliable_court_foot({}, pose, 0.9) + assert not _reliable_court_foot({"foot_diagnostic": {"status": "disagrees"}}, pose, 0.5) + assert _reliable_court_foot({}, dict(pose, temporal_status="validated"), 0.5) + assert not _reliable_court_foot({}, dict(pose, temporal_status="interpolated_single_gap"), 0.5) From e3a459a82cfbaea584baf0fa9b569f4c4aab4e56 Mon Sep 17 00:00:00 2001 From: Max Lin Date: Sun, 22 Nov 2026 14:21:41 -0600 Subject: [PATCH 5/5] Allow motion features in InPlay audio attention --- src/temporal_selector/rally.py | 4 +++- tests/test_rally_pipeline.py | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/temporal_selector/rally.py b/src/temporal_selector/rally.py index 5db7239..b858c73 100644 --- a/src/temporal_selector/rally.py +++ b/src/temporal_selector/rally.py @@ -195,7 +195,9 @@ def __post_init__(self) -> None: raise ValueError("dropout must be in [0, 1)") if self.layer_norm_eps <= 0: raise ValueError("layer_norm_eps must be positive") - if self.audio_attention and self.frame_feature_dim != RALLY_FEATURE_VIEWS["full_audio"].dimension: + if self.audio_attention and self.frame_feature_dim not in { + view.dimension for view in RALLY_FEATURE_VIEWS.values() if view.uses_audio + }: raise ValueError("audio attention requires the full visual and audio features") diff --git a/tests/test_rally_pipeline.py b/tests/test_rally_pipeline.py index 6dc0f64..312e2bd 100644 --- a/tests/test_rally_pipeline.py +++ b/tests/test_rally_pipeline.py @@ -440,6 +440,7 @@ def test_pipeline_uses_manifest_feature_view(pipeline, view): kwargs, _ = pipeline config = RallySegmenterConfig( frame_feature_dim=RALLY_FEATURE_VIEWS[view].dimension, + audio_attention=RALLY_FEATURE_VIEWS[view].uses_audio, token_size=8, num_layers=1, num_attention_heads=2,