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

Aadi/pymotmetrics #22

Merged
merged 10 commits into from
Apr 22, 2024
Merged

Aadi/pymotmetrics #22

merged 10 commits into from
Apr 22, 2024

Conversation

aaprasad
Copy link
Contributor

@aaprasad aaprasad commented Nov 10, 2023

  • Implement pymotmetrics for calculating clearmot metrics on biogtr

Summary by CodeRabbit

  • New Features

    • Introduced data classes for better data handling and representation in tracking applications.
    • Added new functionality for tracking inference using the GTR Model.
    • Enhanced dataset functionality for microscopy and cell tracking with improved data handling.
    • Implemented a new TrackQueue class for managing tracking operations over sliding windows.
  • Enhancements

    • Improved model performance with updated methods for data loading, logger initialization, and checkpoint handling.
    • Enhanced evaluation metrics computation and added new functions for tracking evaluation using Py-MOTMetrics.
    • Updated visualization functions to handle more detailed annotations and video saving options.
  • Bug Fixes

    • Corrected data access methods in dataset management to enhance stability and performance.
    • Fixed issues in inference functions to ensure accurate tracking and data handling.
  • Documentation

    • Updated docstrings across various modules for better clarity and consistency.
  • Refactor

    • Major refactoring in dataset classes to utilize new data structures and improve data handling.
    • Refactored inference and model components to align with new data handling structures.
  • Tests

    • Extended testing suite to cover new data structures, models, and dataset functionalities.
    • Updated existing tests to align with refactored codebase and new functionalities.
  • Dependencies

    • Updated environment configurations to support new versions and additional dependencies.

@aaprasad aaprasad changed the base branch from main to aadi-refactor-tracker November 10, 2023 06:27
Co-authored-by: aaprasad <aaprasad.ucsd.edu>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link
Contributor

coderabbitai bot commented Apr 22, 2024

Important

Auto Review Skipped

Auto reviews are disabled on base/target branches other than the default branch. Please add the base/target branch pattern to the list of additional branches to be reviewed in the settings.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

The recent updates focus on enhancing the biogtr project, primarily improving data handling with new structures like Frame and Instance. Changes span from refining data loading, processing, and tracking inferences to optimizing model functionality and evaluation metrics. These modifications aim to streamline workflows, boost performance, and enhance clarity across various modules, making the system more robust and user-friendly for tracking tasks in biological imaging.

Changes

Files Changes
.gitignore, environment.yml, environment_cpu.yml Updated to include new directories, dependencies, and version changes.
biogtr/config.py, biogtr/models/..., biogtr/training/... Major enhancements in configuration handling, model operations, and training processes.
biogtr/data_structures.py, biogtr/datasets/... Introduced new data structures and updated dataset handling for improved data management.
biogtr/inference/... Enhanced inference capabilities with new classes and refined tracking logic.
tests/... Expanded testing to cover new functionalities and data structures.
biogtr/visualize.py, biogtr/training/configs/base.yaml Visual enhancements and configuration updates for better usability and performance.

🐰✨
In the warren of code, beneath the moon's glow,
A rabbit hopped, with changes in tow.
Frames and Instances, neatly aligned,
Tracking and metrics, redefined.
Through fields of data, it leaps with grace,
Celebrating each commit, in cyberspace. 🌌
🐰✨


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.

@aaprasad aaprasad marked this pull request as ready for review April 22, 2024 20:26
@aaprasad
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

@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: 13

Actionable comments outside the diff hunks (2)
biogtr/datasets/microscopy_dataset.py (1)

Line range hint 86-86: Replace lambda with a function definition for better readability and maintainability.

-            parser = lambda x: data_utils.parse_synthetic(x, source=source)
+            def parser(x):
+                return data_utils.parse_synthetic(x, source=source)

Using explicit function definitions instead of lambda expressions can improve readability, especially when the function is non-trivial or used in multiple places.

biogtr/datasets/data_utils.py (1)

Line range hint 342-342: Replace the bare except with more specific exception handling.

Using a bare except clause can catch unexpected exceptions, making debugging difficult. It is recommended to catch specific exceptions to avoid hiding bugs. For example:

-            except Exception as e:
+            except IndexError as e:

This change ensures that only specific, anticipated errors are caught, making the code more robust and maintainable.

Comment on lines 75 to 78
if not isinstance(crop, torch.Tensor):
self._features = torch.tensor(features)
else:
self._features = features
Copy link
Contributor

Choose a reason for hiding this comment

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

There is a potential bug in the conditional check for crop. It checks if crop is not a tensor twice, which seems to be a copy-paste error. The second check should be for features.

- if not isinstance(crop, torch.Tensor):
+ if not isinstance(features, torch.Tensor):

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
if not isinstance(crop, torch.Tensor):
self._features = torch.tensor(features)
else:
self._features = features
if not isinstance(features, torch.Tensor):
self._features = torch.tensor(features)
else:
self._features = features

biogtr/data_structures.py Show resolved Hide resolved
Comment on lines 695 to 698
try:
self._video = video_filename
except ValueError:
self._video = video_filename
Copy link
Contributor

Choose a reason for hiding this comment

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

The exception handling in the video setter seems unnecessary because the assignment operation does not raise an exception. Consider removing the try-except block.

- try:
  self._video = video_filename
- except ValueError:
-   self._video = video_filename

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
try:
self._video = video_filename
except ValueError:
self._video = video_filename
self._video = video_filename

biogtr/config.py Show resolved Hide resolved
biogtr/config.py Show resolved Hide resolved
Comment on lines 102 to 124
def forward(self, frames: list[Frame], query_frame: int = None):
"""Execute forward pass of GTR Model to get asso matrix.

Args:
instances: List of dicts from chunk containing crops of objects + gt label info
all_instances: List of dicts containing crops of objects + gt label info. Used for stitching together full trajectory
frames: List of Frames from chunk containing crops of objects + gt label info
query_frame: Frame index used as query for self attention. Only used in sliding inference where query frame is the last frame in the window.

Returns:
An N_T x N association matrix
"""
# Extract feature representations with pre-trained encoder.
for frame in instances:
if (frame["num_detected"] > 0).item():
z = self.visual_encoder(frame["crops"])
frame["features"] = z
for frame in frames:
if frame.has_instances():
if not frame.has_features():
crops = frame.get_crops()
z = self.visual_encoder(crops)

for i, z_i in enumerate(z):
frame.instances[i].features = z_i

# Extract association matrix with transformer.
if self.transformer.return_embedding:
asso_preds, emb = self.transformer(instances, query_frame=query_frame)
else:
asso_preds = self.transformer(instances, query_frame=query_frame)
asso_preds, emb = self.transformer(frames, query_frame=query_frame)

return (asso_preds, emb) if self.transformer.return_embedding else asso_preds
return asso_preds, emb
Copy link
Contributor

Choose a reason for hiding this comment

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

Refactor the forward method to improve readability and performance.

-        for frame in frames:
-            if frame.has_instances():
-                if not frame.has_features():
-                    crops = frame.get_crops()
-                    z = self.visual_encoder(crops)
-                    for i, z_i in enumerate(z):
-                        frame.instances[i].features = z_i
+        for frame in filter(lambda f: f.has_instances() and not f.has_features(), frames):
+            crops = frame.get_crops()
+            features = self.visual_encoder(crops)
+            for instance, feature in zip(frame.instances, features):
+                instance.features = feature

This refactoring uses Python's built-in filter function to streamline the checks for frames that have instances but not features, reducing the depth of nested conditions. It also pairs instances with their corresponding features directly using zip, enhancing clarity and reducing the risk of indexing errors.


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
def forward(self, frames: list[Frame], query_frame: int = None):
"""Execute forward pass of GTR Model to get asso matrix.
Args:
instances: List of dicts from chunk containing crops of objects + gt label info
all_instances: List of dicts containing crops of objects + gt label info. Used for stitching together full trajectory
frames: List of Frames from chunk containing crops of objects + gt label info
query_frame: Frame index used as query for self attention. Only used in sliding inference where query frame is the last frame in the window.
Returns:
An N_T x N association matrix
"""
# Extract feature representations with pre-trained encoder.
for frame in instances:
if (frame["num_detected"] > 0).item():
z = self.visual_encoder(frame["crops"])
frame["features"] = z
for frame in frames:
if frame.has_instances():
if not frame.has_features():
crops = frame.get_crops()
z = self.visual_encoder(crops)
for i, z_i in enumerate(z):
frame.instances[i].features = z_i
# Extract association matrix with transformer.
if self.transformer.return_embedding:
asso_preds, emb = self.transformer(instances, query_frame=query_frame)
else:
asso_preds = self.transformer(instances, query_frame=query_frame)
asso_preds, emb = self.transformer(frames, query_frame=query_frame)
return (asso_preds, emb) if self.transformer.return_embedding else asso_preds
return asso_preds, emb
def forward(self, frames: list[Frame], query_frame: int = None):
"""Execute forward pass of GTR Model to get asso matrix.
Args:
frames: List of Frames from chunk containing crops of objects + gt label info
query_frame: Frame index used as query for self attention. Only used in sliding inference where query frame is the last frame in the window.
Returns:
An N_T x N association matrix
"""
# Extract feature representations with pre-trained encoder.
for frame in filter(lambda f: f.has_instances() and not f.has_features(), frames):
crops = frame.get_crops()
features = self.visual_encoder(crops)
for instance, feature in zip(frame.instances, features):
instance.features = feature
asso_preds, emb = self.transformer(frames, query_frame=query_frame)
return asso_preds, emb

biogtr/models/gtr_runner.py Show resolved Hide resolved
Comment on lines +112 to +142
def pose_bbox(points: np.ndarray, bbox_size: Union[tuple[int], int]) -> torch.Tensor:
"""Calculate bbox around instance pose.

Args:
instance: a labeled instance in a frame,
padding: the amount to pad around the pose crop
im_shape: the size of the original image in (w,h)
bbox_size: size of bbox either an int indicating square bbox or in (x,y)

Returns:
Bounding box in [y1, x1, y2, x2] format.
"""
w, h = im_shape
if isinstance(bbox_size, int):
bbox_size = (bbox_size, bbox_size)
# print(points)
minx = np.nanmin(points[:, 0], axis=-1)
miny = np.nanmin(points[:, -1], axis=-1)
minpoints = np.array([minx, miny]).T

points = torch.Tensor([[p.x, p.y] for p in instance.points])
maxx = np.nanmax(points[:, 0], axis=-1)
maxy = np.nanmax(points[:, -1], axis=-1)
maxpoints = np.array([maxx, maxy]).T

min_x = max(torch.nanmin(points[:, 0]) - padding, 0)
min_y = max(torch.nanmin(points[:, 1]) - padding, 0)
max_x = min(torch.nanmax(points[:, 0]) + padding, w)
max_y = min(torch.nanmax(points[:, 1]) + padding, h)
c = (minpoints + maxpoints) / 2

bbox = torch.Tensor([min_y, min_x, max_y, max_x])
bbox = torch.Tensor(
[
c[-1] - bbox_size[-1] / 2,
c[0] - bbox_size[0] / 2,
c[-1] + bbox_size[-1] / 2,
c[0] + bbox_size[0] / 2,
]
)
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using explicit indexing for clarity.

-    c = (minpoints + maxpoints) / 2
-    bbox = torch.Tensor(
-        [
-            c[-1] - bbox_size[-1] / 2,
-            c[0] - bbox_size[0] / 2,
-            c[-1] + bbox_size[-1] / 2,
-            c[0] + bbox_size[0] / 2,
-        ]
-    )
+    cx, cy = (minpoints + maxpoints) / 2
+    height, width = bbox_size
+    bbox = torch.Tensor([cy - height / 2, cx - width / 2, cy + height / 2, cx + width / 2])

This change makes the code easier to understand and maintain by explicitly naming the dimensions and coordinates.


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
def pose_bbox(points: np.ndarray, bbox_size: Union[tuple[int], int]) -> torch.Tensor:
"""Calculate bbox around instance pose.
Args:
instance: a labeled instance in a frame,
padding: the amount to pad around the pose crop
im_shape: the size of the original image in (w,h)
bbox_size: size of bbox either an int indicating square bbox or in (x,y)
Returns:
Bounding box in [y1, x1, y2, x2] format.
"""
w, h = im_shape
if isinstance(bbox_size, int):
bbox_size = (bbox_size, bbox_size)
# print(points)
minx = np.nanmin(points[:, 0], axis=-1)
miny = np.nanmin(points[:, -1], axis=-1)
minpoints = np.array([minx, miny]).T
points = torch.Tensor([[p.x, p.y] for p in instance.points])
maxx = np.nanmax(points[:, 0], axis=-1)
maxy = np.nanmax(points[:, -1], axis=-1)
maxpoints = np.array([maxx, maxy]).T
min_x = max(torch.nanmin(points[:, 0]) - padding, 0)
min_y = max(torch.nanmin(points[:, 1]) - padding, 0)
max_x = min(torch.nanmax(points[:, 0]) + padding, w)
max_y = min(torch.nanmax(points[:, 1]) + padding, h)
c = (minpoints + maxpoints) / 2
bbox = torch.Tensor([min_y, min_x, max_y, max_x])
bbox = torch.Tensor(
[
c[-1] - bbox_size[-1] / 2,
c[0] - bbox_size[0] / 2,
c[-1] + bbox_size[-1] / 2,
c[0] + bbox_size[0] / 2,
]
)
def pose_bbox(points: np.ndarray, bbox_size: Union[tuple[int], int]) -> torch.Tensor:
"""Calculate bbox around instance pose.
Args:
instance: a labeled instance in a frame,
bbox_size: size of bbox either an int indicating square bbox or in (x,y)
Returns:
Bounding box in [y1, x1, y2, x2] format.
"""
if isinstance(bbox_size, int):
bbox_size = (bbox_size, bbox_size)
# print(points)
minx = np.nanmin(points[:, 0], axis=-1)
miny = np.nanmin(points[:, -1], axis=-1)
minpoints = np.array([minx, miny]).T
maxx = np.nanmax(points[:, 0], axis=-1)
maxy = np.nanmax(points[:, -1], axis=-1)
maxpoints = np.array([maxx, maxy]).T
cx, cy = (minpoints + maxpoints) / 2
height, width = bbox_size
bbox = torch.Tensor([cy - height / 2, cx - width / 2, cy + height / 2, cx + width / 2])

For some reason it screws up `test_training` by causing a device error
"""

Copy link
Contributor

Choose a reason for hiding this comment

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

Investigate and resolve the root cause of the device error instead of commenting out code.

Commenting out code is a temporary solution that can lead to technical debt. It's important to investigate the root cause of the device error mentioned and resolve it properly to ensure the robustness of the test suite.

biogtr/datasets/eval_dataset.py Show resolved Hide resolved
@aaprasad aaprasad merged commit ec6d359 into aadi-refactor-tracker Apr 22, 2024
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant