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 3 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
8 changes: 7 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,12 @@ 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: per_video
Copy link
Collaborator

Choose a reason for hiding this comment

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

Perhaps we should give this a more accurate/descriptive name such as:

Suggested change
- name: per_video
- name: threshold

label: Threshold
type: int
default: 10

- name: target
label: Target
Expand Down
82 changes: 82 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,86 @@ 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
):
# ONCE labels.numpy works: delete lfs ~322 - 328
lfs = labels.find(video)
frames = len(lfs)

if frames < 2:
return []


video_instances = labels.numpy(video=video, all_frames=True, untracked=False)
frames = len(video_instances)

if frames < 2:
return []

# ONCE labels.numpy works: delete print statements ~336 - 340
print('type of video_instances: ', type(video_instances))
print(video_instances[0])
print('type of video_instances[0]: ', type(video_instances[0]))
print(f"Number of elements returned by labels.numpy(): {video_instances.shape}")
print(f"Number of elements returned by labels.numpy(): {len(video_instances)}")


print('type of video_instances: ', type(video_instances))
print('type of video_instances[0]: ', type(video_instances[0]))


displacements = []
for idx in range(1, frames):
prev_points = video_instances[idx-1]
curr_points = video_instances[idx]


if prev_points.shape != curr_points.shape:
continue

# Mask to identify non-nan values
valid_mask = ~np.isnan(prev_points) & ~np.isnan(curr_points)
# Filter out nan values
valid_prev_points = prev_points[valid_mask].reshape(-1, 2)
valid_curr_points = curr_points[valid_mask].reshape(-1, 2)

if valid_prev_points.size == 0 or valid_curr_points.size == 0:
continue

displacement = np.linalg.norm(valid_curr_points - valid_prev_points, axis=1).sum()
displacements.append((displacement, idx))

frame_idxs = [
frame_idx for displacement, frame_idx in displacements if displacement > displacement_threshold
]
Copy link
Collaborator

Choose a reason for hiding this comment

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

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
Suggested change
# ONCE labels.numpy works: delete lfs ~322 - 328
lfs = labels.find(video)
frames = len(lfs)
if frames < 2:
return []
video_instances = labels.numpy(video=video, all_frames=True, untracked=False)
frames = len(video_instances)
if frames < 2:
return []
# ONCE labels.numpy works: delete print statements ~336 - 340
print('type of video_instances: ', type(video_instances))
print(video_instances[0])
print('type of video_instances[0]: ', type(video_instances[0]))
print(f"Number of elements returned by labels.numpy(): {video_instances.shape}")
print(f"Number of elements returned by labels.numpy(): {len(video_instances)}")
print('type of video_instances: ', type(video_instances))
print('type of video_instances[0]: ', type(video_instances[0]))
displacements = []
for idx in range(1, frames):
prev_points = video_instances[idx-1]
curr_points = video_instances[idx]
if prev_points.shape != curr_points.shape:
continue
# Mask to identify non-nan values
valid_mask = ~np.isnan(prev_points) & ~np.isnan(curr_points)
# Filter out nan values
valid_prev_points = prev_points[valid_mask].reshape(-1, 2)
valid_curr_points = curr_points[valid_mask].reshape(-1, 2)
if valid_prev_points.size == 0 or valid_curr_points.size == 0:
continue
displacement = np.linalg.norm(valid_curr_points - valid_prev_points, axis=1).sum()
displacements.append((displacement, idx))
frame_idxs = [
frame_idx for displacement, frame_idx in displacements if displacement > displacement_threshold
]
# 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()) # [0, len(frames - 1)]


return cls.idx_list_to_frame_list(frame_idxs, video)


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

# something like this?
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 = 300
),
)
assert len(suggestions) == 6
assert suggestions[0].frame_idx == 2117
assert suggestions[1].frame_idx == 4937

def test_frame_increment(centered_pair_predictions: Labels):
# Testing videos that have less frames than desired Samples per Video (stride)
Expand Down