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

(3f -> 3e) Add FrameGroup class #1665

Merged
merged 19 commits into from
Apr 12, 2024

Conversation

roomrys
Copy link
Collaborator

@roomrys roomrys commented Jan 18, 2024

Description

This PR adds the FrameGroup class which is akin to a LabeledFrame but across all views in a RecordingSession. The tasks to do here are:

  • Add FrameGroup class
  • Integrate with RecordingSession
  • Serialize/Deserialize FrameGroup
  • Add a hypotheses generation method to FrameGroup
  • Use FrameGroup hypotheses generation method

Add FrameGroup class

  • Link the FrameGroup to the RecordingSession through a FrameGroup.session instance attribute
  • Keep tabs on the which frame index is being used through FrameGroup.frame_idx instance attribute
  • Add _frame_idx_registry class attribute to ensure the FrameGroup is unique per RecordingSession and frame_idx
  • Enforce that frame_idx and session are unique to this FrameGroup upon initialization
  • Keep a list of InstanceGroups in the current FrameGroup via FrameGroup.instance_groups
  • Keep a dictionary mapping _labeled_frames_by_cam: Dict[Camcorder, LabeledFrame]
  • Maintain _labeled_frames_by_cam each time a LabeledFrame is added/removed from the FrameGroup.session.labels: Labels object
  • Maintain _labeled_frames_by_cam each time a Video is added/removed from the FrameGroup.session: RecordingSession object
  • Use _labeled_frames_by_cam to return a list of LabeledFrames in the labeled_frames property
  • Use _labeled_frames_by_cam to return a list of Camcorders in the cameras property
  • Add a class method to create a FrameGroup from a List[InstanceGroup] (and RecordingSession and frame_idx)
  • Add a class method to create a FrameGroup from a Dict[Camcorder, List[Instance]] (and RecordingSession and frame_idx)

Integrate with RecordingSession

  • Add a RecordingSession._frame_group_by_frame_idx: Dict[int, FrameGroup] attribute to store all known FrameGroups by their frame_idx (also used to ensure uniqueness of FrameGroups)
  • Use RecordingSesssion._frame_group_by_frame_idx in a RecordingSession.frame_group -> Dict[int, FrameGroup] property
  • Use RecordingSesssion._frame_group_by_frame_idx in a RecordingSession.frame_inds -> List[int] property
  • Add to the from_session_dict method to reconstruct FrameGroups
  • Add to the to_session_dict method to write a FrameGroup to an slp

Serialize/Deserialize FrameGroup

  • Add FrameGroup.make_cattr method
Attribute Name Type Description
frame_idx int Instance attribute
instance_groups List[InstanceGroup] Instance attribute, akin to LabeledFrame.instances
session RecordingSession Instance attribute
_frame_idx_registry Dict[RecordingSession, Set[int]] Class attribute to keep track of frame indices across all RecordingSessions
_cams_to_include Optional[List[Camcorder]] "Hidden" class attribute
_excluded_views Optional[Tuple[str]] "Hidden" class attribute
_labeled_frames_by_cam Dict[Camcorder, "LabeledFrame"] "Hidden" instance attribute, should be updated each time a LabeledFrame is added/removed from the Labels object or if a video is added/removed from the RecordingSession
_instances_by_cam Dict[Camcorder, Set["Instance"]] "Hidden" instance attribute
_locked_instance_groups List[InstanceGroup] "Hidden" instance attribute, should be updated each time an InstanceGroup is added/removed/locked/unlocked
_locked_instances_by_cam Dict[Camcorder, Set["Instance"]] "Hidden" instance attribute, internally updated in update_locked_instances_by_cam

Add a hypothesis generation with FrameGroup.generate_hypotheses

  • Keep track of which InstanceGroups are locked (or set by the user) in FrameGroup._locked_instance_groups: List[InstanceGroup]
  • Maintain FrameGroup._locked_instance_groups whenever an InstanceGroup is added/removed/locked/unlocked
  • Keep track of which Camcorders to include in the FrameGroup as a class attribute FrameGroup._cams_to_include: Optional[List[Camcorder]]
  • Use _cams_to_include in the cams_to_include property to return either the list of Camcorders in _cams_to_include or the list of Camcorders in FrameGroup.session.camera_cluster.cameras
  • Keep track of the _instances_by_cam: Dict[Camcorder, Set[Instance]] as an instance attribute
  • Maintain _instances_by_cam similarly to _labeled_frames_by_cam
  • Use _instances_by_cam in the instances_by_cams_to_include property to only return Dict[Camcorder, Set[Instance]] from the cams_to_include
  • Add a generate_hypotheses method which uses instances_by_cams_to_include to gather all unlocked instances across views, fill in the "missing" instances in each view, permute all unlocked instances, take products of unlocked instances, and reorganize products into grouping_hypotheses: Dict[frame_id: int, List[InstanceGroup]] OR grouping_hypotheses: Dict[frame_id: int, Dict[Camcorder, List[Instance]]]

Use FrameGroup hypotheses generation method

  • Swap out the hypotheses generation in TriangulateSession with the session.frame_group[frame_idx].generate_hypotheses()
  • Currently TriangulateSession uses the "cached" reprojections from all hypotheses to just update the Instances in TriangulateSession.do_action(), but we also need a way to trangulate, reproject, and update Instances without doing hypothesis testing

Others (not needed for this PR, but got distracted and added anyway)

  • Sort the RecordingSession.linked_cameras s.t. the ordering follows RecordingSession.cameras
  • Sort the RecordingSession.unlinked_cameras s.t. the ordering follows RecordingSession.cameras
  • Sort the RecordingSession.camera_cluster._videos_by_session[RecordingSession] s.t. the ordering follows RecordingSession.cameras (this is useful when navigating through views in the GUI)

image
Fig 1: Three different flavors of the flow chart plan with the middle plan being the most complete, but the top being the easiest (the bottom is just unneeded work).

Types of changes

  • Bugfix
  • New feature
  • Refactor / Code style update (no logical changes)
  • Build / CI changes
  • Documentation Update
  • Other (explain)

Does this address any currently open issues?

[list open issues here]

Outside contributors checklist

  • Review the guidelines for contributing to this repository
  • Read and sign the CLA and add yourself to the authors list
  • Make sure you are making a pull request against the develop branch (not main). Also you should start your branch off develop
  • Add tests that prove your fix is effective or that your feature works
  • Add necessary documentation (if appropriate)

Thank you for contributing to SLEAP!

❤️

Summary by CodeRabbit

  • New Features
    • Enhanced management of instance groups and labeled frames in the application.
  • Bug Fixes
    • Updated handling of instance groups to ensure accurate generation and management of hypotheses.
  • Tests
    • Adjusted and removed specific tests to align with the updated functionalities and data structures.

Copy link

coderabbitai bot commented Jan 18, 2024

Walkthrough

The recent updates introduce significant enhancements to the handling and management of FrameGroup objects in both the GUI and I/O components of the software. Key modifications include the transition from FrameGroup to InstanceGroup in the GUI, along with expanded functionalities in the cameras.py module to better manage instances and labeled frames across different views.

Changes

Files Change Summary
sleap/gui/commands.py
sleap/io/cameras.py
Updated FrameGroup to InstanceGroup in GUI commands and added new functionalities for managing FrameGroup objects in I/O cameras.
tests/gui/test_commands.py
tests/io/test_cameras.py
Removed outdated tests in GUI related to triangulation and updated tests in I/O to cover new FrameGroup functionalities.

Poem

🐇🌟
In the land of code where the data hops,
A change was made at the treetops.
FrameGroup dances, now InstanceGroup sings,
Across the wires, data flutters its wings.
Cheers to the bytes, in harmony they mesh,
For in this update, our systems refresh.
🌼🐇


Recent Review Details

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between 95071c1 and ff0924e.
Files selected for processing (4)
  • sleap/gui/commands.py (2 hunks)
  • sleap/io/cameras.py (10 hunks)
  • tests/gui/test_commands.py (1 hunks)
  • tests/io/test_cameras.py (4 hunks)
Additional comments not posted (5)
tests/io/test_cameras.py (1)

418-447: The tests for FrameGroup correctly verify the creation from instance groups and the management of frame indices. Ensure that the shared registry of frame indices behaves as expected in concurrent scenarios.

Verification successful

The search results from the script provide insights into the usage of _frame_idx_registry within the codebase. The references found in tests/io/test_cameras.py and sleap/io/cameras.py indicate that _frame_idx_registry is used to track frame indices across different instances of FrameGroup and within the RecordingSession context.

From the output:

  1. In test_cameras.py, the tests verify the behavior of _frame_idx_registry by asserting its contents after creating FrameGroup instances. This confirms that the test checks the shared registry behavior as intended.
  2. In cameras.py, _frame_idx_registry is initialized as an empty dictionary and is used to add frame indices as they are processed. This suggests that the class handles the addition of new frame indices and ensures that they are tracked correctly across sessions.

Given this information, the implementation and testing of _frame_idx_registry appear to be consistent with the expectations set in the review comment. The tests in test_cameras.py are aligned with the implementation in cameras.py, verifying the correct behavior of the frame index registry.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Search for any concurrent modifications to `_frame_idx_registry` across the codebase.
rg --type python '_frame_idx_registry' --context 5

Length of output: 81



Script:

#!/bin/bash
# Corrected search for any concurrent modifications to `_frame_idx_registry` across the codebase.
rg '_frame_idx_registry' --type py --context 5

Length of output: 3968

tests/gui/test_commands.py (1)

Line range hint 227-299: The tests for ExportAnalysisFile cover various scenarios effectively, including different file formats and conditions with no labeled frames. Ensure that the export functionality handles edge cases as expected.

Verification successful

It appears that the previous script failed due to an unrecognized file type specification for rg. The correct usage should not specify the file type as python since rg does not recognize it by default. Instead, we should use a more general approach or specify the file extensions directly.

Let's correct this and rerun the script to ensure we can verify the usage of ExportAnalysisFile across the codebase effectively.


The search results confirm the usage of ExportAnalysisFile within the tests/gui/test_commands.py and sleap/gui/commands.py files. The test cases in test_commands.py extensively use the ExportAnalysisFile class to test various scenarios, including exporting with different parameters and handling different file formats. The class is also referenced in sleap/gui/commands.py where it is used to execute export operations with specific parameters.

From the output, it is evident that the ExportAnalysisFile class is integral to the functionality of exporting analysis files in different formats and is well-integrated into the GUI command structure. The tests cover a wide range of scenarios ensuring that the functionality behaves as expected under various conditions.

Given this comprehensive integration and testing, the changes in the test_ExportAnalysisFile function and the usage of ExportAnalysisFile across the codebase are verified to be consistent and correctly implemented.

Scripts Executed

The following scripts were executed for the analysis:


Script:

#!/bin/bash
# Search for any additional usage of `ExportAnalysisFile` that might affect its behavior in edge cases.
rg --type python 'ExportAnalysisFile' --context 5

Length of output: 80



Script:

#!/bin/bash
# Search for any additional usage of `ExportAnalysisFile` that might affect its behavior in edge cases.
rg 'ExportAnalysisFile' --context 5 --type py

Length of output: 12138

sleap/gui/commands.py (3)

Line range hint 1712-1712: Avoid using bare except statements. Specify the exception types to handle specific errors appropriately.


Line range hint 1733-1733: Avoid using bare except statements. It's a good practice to specify the exceptions you are catching.


Line range hint 3145-3145: Avoid using bare except statements. It's a good practice to specify the exceptions you are catching.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@roomrys roomrys self-assigned this Jan 19, 2024
@roomrys roomrys added the MultiView Stack This PR is part of the MultView stacked PRs. label Jan 19, 2024
Copy link

codecov bot commented Jan 23, 2024

Codecov Report

Attention: Patch coverage is 46.15385% with 133 lines in your changes are missing coverage. Please review.

Project coverage is 73.60%. Comparing base (95071c1) to head (a99cef5).

❗ Current head a99cef5 differs from pull request most recent head ff0924e. Consider uploading reports for the commit ff0924e to get more accurate results

Files Patch % Lines
sleap/io/cameras.py 46.15% 133 Missing ⚠️
Additional details and impacted files
@@                        Coverage Diff                         @@
##           liezl/add-instance-group-class    #1665      +/-   ##
==================================================================
- Coverage                           73.85%   73.60%   -0.26%     
==================================================================
  Files                                 135      135              
  Lines                               24807    25037     +230     
==================================================================
+ Hits                                18322    18428     +106     
- Misses                               6485     6609     +124     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@roomrys roomrys marked this pull request as ready for review April 12, 2024 15:29
@roomrys roomrys merged commit 0c057c1 into liezl/add-instance-group-class Apr 12, 2024
5 checks passed
@roomrys roomrys deleted the liezl/add-frame-group branch April 12, 2024 15:30
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Actionable comments outside the diff hunks (8)
sleap/io/cameras.py (3)

Line range hint 80-82: Remove unnecessary f-strings as they do not contain any placeholders.

- f"No camera has been specified. "
+ "No camera has been specified. "
- f"This is likely because the `Camcorder.from_dict` method was not used to initialize this object. "
+ "This is likely because the `Camcorder.from_dict` method was not used to initialize this object. "
- f"Please use `Camcorder.from_dict` to recreate the object."
+ "Please use `Camcorder.from_dict` to recreate the object."

Line range hint 412-414: Add missing imports for Instance, Skeleton, and LabeledFrame to resolve undefined names.

+ from sleap.instance import Instance, PredictedInstance
+ from sleap.skeleton import Skeleton
+ from sleap.labels import LabeledFrame

Also applies to: 427-427, 448-448, 477-477, 504-504, 516-516, 532-532, 561-561, 586-586, 630-630, 650-650, 657-657, 708-708, 721-721, 722-722


Line range hint 743-743: Replace the bare except with a more specific exception handling to avoid catching unexpected exceptions.

- except:
+ except SomeSpecificException:
sleap/gui/commands.py (5)

Line range hint 38-40: Remove unused imports to clean up the code.

- from itertools import permutations, product
- from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
+ from typing import Callable, Dict, Iterator, List, Optional, Tuple, Type, Union

Line range hint 196-196: Undefined name MainWindow used. Ensure that MainWindow is defined or imported correctly in this context.


Line range hint 838-838: The local variable file_dir is assigned but never used. Consider removing it if it's unnecessary.

- file_dir = os.path.dirname(filename)

Line range hint 2470-2470: The f-string does not contain any placeholders. Use a regular string instead.

- f"Please select the area from which to remove instances. This will be applied to all frames."
+ "Please select the area from which to remove instances. This will be applied to all frames."

Line range hint 2802-2802: The f-string does not contain any placeholders. Use a regular string instead.

- f"An error occurred while generating suggestions. "
+ "An error occurred while generating suggestions. "

@@ -819,8 +821,13 @@ class RecordingSession:
metadata: dict = field(factory=dict)
_video_by_camcorder: Dict[Camcorder, Video] = field(factory=dict)
labels: Optional["Labels"] = None
Copy link

Choose a reason for hiding this comment

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

Add missing import for Labels to resolve the undefined name.

+ from sleap.labels 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.

Suggested change
labels: Optional["Labels"] = None
from sleap.labels import Labels
labels: Optional["Labels"] = None

# "Hidden" class attribute
_cams_to_include: Optional[List[Camcorder]] = None
_excluded_views: Optional[Tuple[str]] = ()
_dummy_labeled_frame: Optional["LabeledFrame"] = None
Copy link

Choose a reason for hiding this comment

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

Add missing imports for Instance, Skeleton, and LabeledFrame to resolve undefined names.

+ from sleap.instance import Instance, PredictedInstance
+ from sleap.skeleton import Skeleton
+ from sleap.labels import LabeledFrame

Also applies to: 1265-1265, 1266-1266, 1271-1271, 1342-1342, 1354-1354, 1406-1406, 1493-1493, 1514-1514, 1530-1530, 1542-1542, 1574-1574, 1678-1678, 1694-1694, 1780-1780, 1801-1801, 1802-1802, 1805-1805, 1862-1862, 1876-1876, 1914-1914, 1918-1918, 1924-1924, 1925-1925, 1926-1926, 1935-1935, 1971-1971, 1976-1976, 1980-1980


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.

Suggested change
_dummy_labeled_frame: Optional["LabeledFrame"] = None
from sleap.labels import LabeledFrame
_dummy_labeled_frame: Optional["LabeledFrame"] = None

roomrys added a commit that referenced this pull request Apr 12, 2024
* Add method to get single instance permutations

* Add method and (failing) test to get instance grouping

* Append a dummy instance for missing instances

* Update tests to accept a dummy instance

* Add initial InstanceGroup class

* Few extra tests for `InstanceGroup`

* Remember instance grouping after testing hypotheses

* Use reconsumable iterator for reprojected coords

* Only triangulate user instances, add fixture, update tests

* Normalize instance reprojection errors

* Add `locked`, `_dummy_instance`, `numpy`, and `update_points`

* Allow `PredictedPoint`s to be updated as well

* Add tests for new attributes and methods

* Add methods to create, add, replace, and remove instances

* Use PredictedInstance for new/dummy instances

* (3f -> 3e) Add `FrameGroup` class  (#1665)

* (3g -> 3f) Use frame group for triangulation (#1693)
roomrys added a commit that referenced this pull request Apr 18, 2024
* Update  methods to allow triangulating multiple instances at once

* Return instances and coords as a dictionary with cams

* Update get_instance_across_views to handle multiple frames

* [wip] Update calculate reprojected points to support multiple frames

* Finish support for multi-frame reprojection

* Remove code to put in next PR

* (3b -> 3a) Add method to get single instance permutations (#1586)

* Add method to get single instance permutations

* Append a dummy instance for missing instances

* Correct 'permutations' to 'products'

* (3c -> 3b) Add method to test instance grouping (#1599)

* (3d -> 3c) Add method for multi instance products (#1605)

* (3e -> 3a) Add `InstanceGroup` class (#1618)

* Add method to get single instance permutations

* Add method and (failing) test to get instance grouping

* Append a dummy instance for missing instances

* Update tests to accept a dummy instance

* Add initial InstanceGroup class

* Few extra tests for `InstanceGroup`

* Remember instance grouping after testing hypotheses

* Use reconsumable iterator for reprojected coords

* Only triangulate user instances, add fixture, update tests

* Normalize instance reprojection errors

* Add `locked`, `_dummy_instance`, `numpy`, and `update_points`

* Allow `PredictedPoint`s to be updated as well

* Add tests for new attributes and methods

* Add methods to create, add, replace, and remove instances

* Use PredictedInstance for new/dummy instances

* (3f -> 3e) Add `FrameGroup` class  (#1665)

* (3g -> 3f) Use frame group for triangulation (#1693)

* Only use user-`Instance`s for triangulation

* Remove unused code

* Use `LabeledFrame` class instead of dummy labeled frame

* Limit which methods can update `Labels.labeled_frames`

* Update cache when Labels. remove_session_video

* Remove RecordingSession.instance_groups

* [wip] Maintain cached FrameGroup dictionaries

* Add unique name (per FrameGroup) requirement for InstanceGroup

* Lint

* Fix remove_video bug

* Add RecordingSession.new_frame_group method

* Add TODO comments for later

* Fix RecordingSesssion.remove_video bug

* Remove FrameGroup._frame_idx_registry class attribute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
MultiView Stack This PR is part of the MultView stacked PRs.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant