Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generate suggestions using max point displacement threshold #1862

Merged
merged 14 commits into from
Jul 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion sleap/config/suggestions.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ main:
label: Method
type: stacked
default: " "
options: " ,image features,sample,prediction score,velocity,frame chunk"
options: " ,image features,sample,prediction score,velocity,frame chunk,max point displacement"
" ":

sample:
Expand Down Expand Up @@ -175,6 +175,13 @@ main:
type: double
default: 0.1
range: 0.1,1.0

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove trailing spaces.

Trailing spaces are unnecessary and should be removed for clean code.

-    
+
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
Tools
yamllint

[error] 178-178: trailing spaces

(trailing-spaces)

"max point displacement":
- name: displacement_threshold
label: Maximum Displacement Threshold
type: int
default: 10
range: 0,999
Comment on lines +178 to +184
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove trailing spaces.

Trailing spaces are unnecessary and should be removed for clean code.

-    
+
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
"max point displacement":
- name: displacement_threshold
label: Maximum Displacement Threshold
type: int
default: 10
range: 0,999
"max point displacement":
- name: displacement_threshold
label: Maximum Displacement Threshold
type: int
default: 10
range: 0,999
Tools
yamllint

[error] 178-178: trailing spaces

(trailing-spaces)


- name: target
label: Target
Expand Down
52 changes: 52 additions & 0 deletions sleap/gui/suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def suggest(cls, params: dict, labels: "Labels" = None) -> List[SuggestionFrame]
prediction_score=cls.prediction_score,
velocity=cls.velocity,
frame_chunk=cls.frame_chunk,
max_point_displacement=cls.max_point_displacement,
)

method = str.replace(params["method"], " ", "_")
Expand Down Expand Up @@ -213,6 +214,7 @@ def _prediction_score_video(
):
lfs = labels.find(video)
frames = len(lfs)

# initiate an array filled with -1 to store frame index (starting from 0).
idxs = np.full((frames), -1, dtype="int")

Expand Down Expand Up @@ -291,6 +293,56 @@ def _velocity_video(

return cls.idx_list_to_frame_list(frame_idxs, video)

@classmethod
def max_point_displacement(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In order to access this as a classmethod as you do here:

max_point_displacement = cls.max_point_displacement,

, make sure to wrap it with:

Suggested change
def max_point_displacement(
@classmethod
def max_point_displacement(

cls,
labels: "Labels",
videos: List[Video],
displacement_threshold: float,
**kwargs,
):
"""Finds frames with maximum point displacement above a threshold."""

proposed_suggestions = []
for video in videos:
proposed_suggestions.extend(
cls._max_point_displacement_video(video, labels, displacement_threshold)
)

suggestions = VideoFrameSuggestions.filter_unique_suggestions(
labels, videos, proposed_suggestions
)

return suggestions

@classmethod
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix undefined name Labels.

The Labels class should be imported or properly referenced.

-        cls, video: Video, labels: "Labels", displacement_threshold: float
+        cls, video: Video, labels: "Labels", displacement_threshold: float
+    ):
+        from sleap.io.dataset import Labels
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
@classmethod
@classmethod
def _max_point_displacement_video(
cls, video: Video, labels: "Labels", displacement_threshold: float
):
from sleap.io.dataset import Labels

def _max_point_displacement_video(
cls, video: Video, labels: "Labels", displacement_threshold: float
):
# Get numpy of shape (frames, tracks, nodes, x, y)
labels_numpy = labels.numpy(video=video, all_frames=True, untracked=False)

# Return empty list if not enough frames
n_frames, n_tracks, n_nodes, _ = labels_numpy.shape

if n_frames < 2:
return []

# Calculate displacements
diff = labels_numpy[1:] - labels_numpy[:-1] # (frames - 1, tracks, nodes, x, y)
euc_norm = np.linalg.norm(diff, axis=-1) # (frames - 1, tracks, nodes)
mean_euc_norm = np.nanmean(euc_norm, axis=-1) # (frames - 1, tracks)

# Find frames where mean displacement is above threshold
threshold_mask = np.any(
mean_euc_norm > displacement_threshold, axis=-1
) # (frames - 1,)
frame_idxs = list(
np.argwhere(threshold_mask).flatten() + 1
) # [0, len(frames - 1)]

return cls.idx_list_to_frame_list(frame_idxs, video)

Comment on lines +318 to +345
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handle nan values in displacement calculation.

The suggested approach handles nan values as we want by:

  1. Resulting in nan in the Euclidean norm.
  2. Being excluded in the mean calculation for all points in an Instance.
        # Get numpy of shape (frames, tracks, nodes, x, y)
        labels_numpy = labels.numpy(video=video, all_frames=True, untracked=False)

        # Return empty list if not enough frames
        n_frames, n_tracks, n_nodes, _ = labels_numpy.shape

        if n_frames < 2:
            return []

        # Calculate displacements
        diff = labels_numpy[1:] - labels_numpy[:-1]  # (frames - 1, tracks, nodes, x, y)
        euc_norm = np.linalg.norm(diff, axis=-1)  # (frames - 1, tracks, nodes)
        mean_euc_norm = np.nanmean(euc_norm, axis=-1)  # (frames - 1, tracks)

        # Find frames where mean displacement is above threshold
        threshold_mask = np.any(
            mean_euc_norm > displacement_threshold, axis=-1
        )  # (frames - 1,)
        frame_idxs = list(
            np.argwhere(threshold_mask).flatten() + 1
        )  # [0, len(frames - 1)]

        return cls.idx_list_to_frame_list(frame_idxs, video)

Committable suggestion was skipped due to low confidence.

Tools
Ruff

320-320: Undefined name Labels

(F821)

@classmethod
def frame_chunk(
cls,
Expand Down
14 changes: 14 additions & 0 deletions tests/gui/test_suggestions.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,20 @@ def test_velocity_suggestions(centered_pair_predictions):
assert suggestions[1].frame_idx == 45


def test_max_point_displacement_suggestions(centered_pair_predictions):
suggestions = VideoFrameSuggestions.suggest(
labels=centered_pair_predictions,
params=dict(
videos=centered_pair_predictions.videos,
method="max_point_displacement",
displacement_threshold=6,
),
)
assert len(suggestions) == 19
assert suggestions[0].frame_idx == 28
assert suggestions[1].frame_idx == 82


def test_frame_increment(centered_pair_predictions: Labels):
# Testing videos that have less frames than desired Samples per Video (stride)
# Expected result is there should be n suggestions where n is equal to the frames
Expand Down