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

Allow max tracking args for Kalman filter #1986

Open
wants to merge 8 commits into
base: develop
Choose a base branch
from

Conversation

eberrigan
Copy link
Contributor

@eberrigan eberrigan commented Oct 8, 2024

Description

Replicating the Error

  • target_instance_count not present in GUI but is present as argument in make_tracker_by_name

    sleap/sleap/nn/tracking.py

    Lines 836 to 872 in 1339f0d

    @classmethod
    def make_tracker_by_name(
    cls,
    # Tracker options
    tracker: str = "flow",
    similarity: str = "instance",
    match: str = "greedy",
    track_window: int = 5,
    robust: float = 1.0,
    min_new_track_points: int = 0,
    min_match_points: int = 0,
    # Optical flow options
    img_scale: float = 1.0,
    of_window_size: int = 21,
    of_max_levels: int = 3,
    save_shifted_instances: bool = False,
    # Pre-tracking options to cull instances
    target_instance_count: int = 0,
    pre_cull_to_target: bool = False,
    pre_cull_iou_threshold: Optional[float] = None,
    # Post-tracking options to connect broken tracks
    post_connect_single_breaks: bool = False,
    # TODO: deprecate these post-tracking cleaning options
    clean_instance_count: int = 0,
    clean_iou_threshold: Optional[float] = None,
    # Kalman filter options
    kf_init_frame_count: int = 0,
    kf_node_indices: Optional[list] = None,
    # Max tracking options
    max_tracks: Optional[int] = None,
    max_tracking: bool = False,
    # Object keypoint similarity options
    oks_errors: Optional[list] = None,
    oks_score_weighting: bool = False,
    oks_normalization: str = "all",
    **kwargs,
    ) -> BaseTracker:
Software versions:
SLEAP: 1.4.1a2
TensorFlow: 2.9.2
Numpy: 1.22.4
Python: 3.9.20
OS: macOS-14.5-arm64-arm-64bit
.
.
.
Using already trained model for centroid: /Users/elizabethberrigan/repos/sleap/tests/data/models/minimal_instance.UNet.centroid/training_config.json
Using already trained model for centered_instance: /Users/elizabethberrigan/repos/sleap/tests/data/models/minimal_instance.UNet.centered_instance/training_config.json
Command line call:
sleap-track /Users/elizabethberrigan/repos/sleap/tests/data/tracks/clip.2node.slp --only-labeled-frames -m /Users/elizabethberrigan/repos/sleap/tests/data/models/minimal_instance.UNet.centroid/training_config.json -m /Users/elizabethberrigan/repos/sleap/tests/data/models/minimal_instance.UNet.centered_instance/training_config.json --batch_size 4 --tracking.tracker flow --tracking.similarity instance --tracking.match greedy --tracking.track_window 5 --tracking.kf_init_frame_count 10 --tracking.kf_node_indices 0,1,2 --tracking.post_connect_single_breaks 1 --controller_port 9000 --publish_port 9001 -o /Users/elizabethberrigan/repos/sleap/tests/data/tracks/predictions/clip.2node.slp.241003_221743.predictions.slp --verbosity json --no-empty-frames

Started inference at: 2024-10-03 22:17:47.149775
Args:
{
│   'data_path': '/Users/elizabethberrigan/repos/sleap/tests/data/tracks/clip.2node.slp',
│   'models': [
│   │   '/Users/elizabethberrigan/repos/sleap/tests/data/models/minimal_instance.UNet.centroid/training_config.json',
│   │   '/Users/elizabethberrigan/repos/sleap/tests/data/models/minimal_instance.UNet.centered_instance/training_config.json'
│   ],
│   'frames': '',
│   'only_labeled_frames': True,
│   'only_suggested_frames': False,
Traceback (most recent call last):
  File "/Users/elizabethberrigan/miniforge3/envs/sleap_v1.4.1a2/bin/sleap-track", line 33, in <module>
    sys.exit(load_entry_point('sleap==1.4.1a2', 'console_scripts', 'sleap-track')())
  File "/Users/elizabethberrigan/miniforge3/envs/sleap_v1.4.1a2/lib/python3.9/site-packages/sleap/nn/inference.py", line 5467, in main
    tracker = _make_tracker_from_cli(args)
  File "/Users/elizabethberrigan/miniforge3/envs/sleap_v1.4.1a2/lib/python3.9/site-packages/sleap/nn/inference.py", line 5401, in _make_tracker_from_cli
    tracker = Tracker.make_tracker_by_name(**policy_args["tracking"])
  File "/Users/elizabethberrigan/miniforge3/envs/sleap_v1.4.1a2/lib/python3.9/site-packages/sleap/nn/tracking.py", line 916, in make_tracker_by_name
    raise ValueError("Kalman filter requires target instance count.")
ValueError: Kalman filter requires target instance count.
│   'output': '/Users/elizabethberrigan/repos/sleap/tests/data/tracks/predictions/clip.2node.slp.241003_221743.predictions.slp',
│   'no_empty_frames': True,
│   'verbosity': 'json',
│   'video.dataset': None,
│   'video.input_format': 'channels_last',
│   'video.index': '',
│   'cpu': False,
Process return code: 1
  • Same error when max_tracking is set

    (sleap_v1.4.1a2) C:\repos\sleap>sleap-label
    Saving config: C:\Users\eb/.sleap/1.4.1a2/preferences.yaml
    
    Software versions:
    SLEAP: 1.4.1a2
    TensorFlow: 2.7.0
    Numpy: 1.21.6
    Python: 3.7.12
    OS: Windows-10-10.0.22621-SP0
    .
    .
    .
    
    Using already trained model for centroid: C:/repos/sleap/tests/data/models/minimal_instance.UNet.centroid/training_config.json
    Using already trained model for centered_instance: C:/repos/sleap/tests/data/models/minimal_instance.UNet.centered_instance/training_config.json
    Command line call:
    sleap-track C:/repos/sleap/tests/data/tracks/clip.2node.slp --video.index 0 --frames 1499 -m C:/repos/sleap/tests/data/models/minimal_instance.UNet.centroid/training_config.json -m C:/repos/sleap/tests/data/models/minimal_instance.UNet.centered_instance/training_config.json --batch_size 4 --tracking.tracker flowmaxtracks --max_instances 2 --tracking.max_tracks 2 --tracking.similarity instance --tracking.match greedy --tracking.track_window 5 --tracking.kf_init_frame_count 10 --tracking.kf_node_indices 0,1 --tracking.post_connect_single_breaks 1 --controller_port 9000 --publish_port 9001 --tracking.max_tracking 1 -o C:/repos/sleap/tests/data/tracks\predictions\clip.2node.slp.241004_091302.predictions.slp --verbosity json --no-empty-frames
    
    Started inference at: 2024-10-04 09:13:06.788183
    Args:
    {
        'data_path': 'C:/repos/sleap/tests/data/tracks/clip.2node.slp',
        'models': [
            'C:/repos/sleap/tests/data/models/minimal_instance.UNet.centroid/training_config.json',
            'C:/repos/sleap/tests/data/models/minimal_instance.UNet.centered_instance/training_config.json'
        ],
        'frames': '1499',
        'only_labeled_frames': False,
        'only_suggested_frames': False,
        'output': 'C:/repos/sleap/tests/data/tracks\\predictions\\clip.2node.slp.241004_091302.predictions.slp',
        'no_empty_frames': True,
        'verbosity': 'json',
        'video.dataset': None,
        'video.input_format': 'channels_last',
        'video.index': '0',
        'cpu': False,
        'first_gpu': False,
        'last_gpu': False,
        'gpu': 'auto',
        'max_edge_length_ratio': 0.25,
        'dist_penalty_weight': 1.0,
        'batch_size': 4,
        'open_in_gui': False,
        'peak_threshold': 0.2,
        'max_instances': 2,
        'tracking.tracker': 'flowmaxtracks',
        'tracking.max_tracking': True,
        'tracking.max_tracks': 2,
        'tracking.target_instance_count': None,
        'tracking.pre_cull_to_target': None,
        'tracking.pre_cull_iou_threshold': None,
        'tracking.post_connect_single_breaks': 1,
        'tracking.clean_instance_count': None,
        'tracking.clean_iou_threshold': None,
        'tracking.similarity': 'instance',
        'tracking.match': 'greedy',
        'tracking.robust': None,
        'tracking.track_window': 5,
        'tracking.min_new_track_points': None,
    Traceback (most recent call last):
      File "C:\Users\eb\Miniforge3\envs\sleap_v1.4.1a2\Scripts\sleap-track-script.py", line 33, in <module>
        sys.exit(load_entry_point('sleap==1.4.1a2', 'console_scripts', 'sleap-track')())
      File "C:\Users\eb\Miniforge3\envs\sleap_v1.4.1a2\lib\site-packages\sleap\nn\inference.py", line 5467, in main
        tracker = _make_tracker_from_cli(args)
      File "C:\Users\eb\Miniforge3\envs\sleap_v1.4.1a2\lib\site-packages\sleap\nn\inference.py", line 5401, in _make_tracker_from_cli
        tracker = Tracker.make_tracker_by_name(**policy_args["tracking"])
      File "C:\Users\eb\Miniforge3\envs\sleap_v1.4.1a2\lib\site-packages\sleap\nn\tracking.py", line 916, in make_tracker_by_name
        raise ValueError("Kalman filter requires target instance count.")
    ValueError: Kalman filter requires target instance count.
        'tracking.min_match_points': None,
        'tracking.img_scale': None,
        'tracking.of_window_size': None,
        'tracking.of_max_levels': None,
        'tracking.save_shifted_instances': None,
        'tracking.kf_node_indices': [0, 1],
        'tracking.kf_init_frame_count': 10
    Process return code: 1

Tracing the Error

  • Tracker.make_tracker_by_name does take target_instance_count as an argument and it is set to 0 by default.

  • kf_init_frame_count is set to 10 while target_instance_count remains 0, producing the error "Kalman filter requires target instance count."

    sleap/sleap/nn/tracking.py

    Lines 957 to 958 in 1339f0d

    elif kf_init_frame_count and not target_instance_count:
    raise ValueError("Kalman filter requires target instance count.")

    • We want it to run these lines instead, which requires target_instance_count and kf_init_frame_count

      sleap/sleap/nn/tracking.py

      Lines 947 to 954 in 1339f0d

      if target_instance_count and kf_init_frame_count:
      kalman_obj = KalmanTracker.make_tracker(
      init_tracker=tracker_obj,
      init_frame_count=kf_init_frame_count,
      node_indices=kf_node_indices,
      instance_count=target_instance_count,
      instance_iou_threshold=pre_cull_iou_threshold,
      )
  • Called here (args parsed from CLI):

    sleap/sleap/nn/tracking.py

    Lines 1564 to 1570 in 1339f0d

    Tracker.add_cli_parser_args(parser)
    args = parser.parse_args()
    tracker_args = {key: val for key, val in vars(args).items() if val is not None}
    tracker = Tracker.make_tracker_by_name(**tracker_args)

  • presence of max_tracking does change the tracker candidate. Is this a problem?? Will CLI behavior be different than GUI behavior?

  • Related: If we want to cull, we need to add pre_cull_to_target option to the GUI. Right now, nothing will lead to the pre-cull function through the GUI

    sleap/sleap/nn/tracking.py

    Lines 922 to 930 in 1339f0d

    pre_cull_function = None
    if target_instance_count and pre_cull_to_target:
    def pre_cull_function(inst_list):
    cull_frame_instances(
    inst_list,
    instance_count=target_instance_count,
    iou_threshold=pre_cull_iou_threshold,
    )

  • Getting the following error for flowmaxtracks only (not simplemaxtracks).

  • This is not being caught in our tests.

  • More tests need to be added since we didn't catch the args for using the Kalman filter not to be present in the GUI.

  • Codecov results from first push

Using already trained model for centroid: C:/repos/sleap/tests/data/tracks\models\241007_145636.centroid.n=1500\training_config.json
Using already trained model for centered_instance: C:/repos/sleap/tests/data/tracks\models\241007_154651.centered_instance.n=1500\training_config.json
Command line call:
sleap-track C:/repos/sleap/tests/data/tracks/clip.2node.slp --video.index 0 --frames 627,-682 -m C:/repos/sleap/tests/data/tracks\models\241007_145636.centroid.n=1500\training_config.json -m C:/repos/sleap/tests/data/tracks\models\241007_154651.centered_instance.n=1500\training_config.json --batch_size 4 --tracking.tracker flowmaxtracks --tracking.max_tracks 2 --tracking.similarity instance --tracking.match hungarian --tracking.track_window 5 --tracking.kf_init_frame_count 10 --tracking.kf_node_indices 0,1 --tracking.oks_errors  --tracking.oks_score_weighting 0 --tracking.post_connect_single_breaks 1 --controller_port 9000 --publish_port 9001 --tracking.max_tracking 1 -o C:/repos/sleap/tests/data/tracks\predictions\clip.2node.slp.241007_205530.predictions.slp --verbosity json --no-empty-frames

Started inference at: 2024-10-07 20:55:35.535014
Args:
{
    'data_path': 'C:/repos/sleap/tests/data/tracks/clip.2node.slp',
    'models': [
        'C:/repos/sleap/tests/data/tracks\\models\\241007_145636.centroid.n=1500\\training_config.json',
        'C:/repos/sleap/tests/data/tracks\\models\\241007_154651.centered_instance.n=1500\\training_config.json'
    ],
    'frames': '627,-682',
    'only_labeled_frames': False,
    'only_suggested_frames': False,
    'output': 'C:/repos/sleap/tests/data/tracks\\predictions\\clip.2node.slp.241007_205530.predictions.slp',
    'no_empty_frames': True,
    'verbosity': 'json',
    'video.dataset': None,
    'video.input_format': 'channels_last',
    'video.index': '0',
    'cpu': False,
    'first_gpu': False,
    'last_gpu': False,
    'gpu': 'auto',
    'max_edge_length_ratio': 0.25,
    'dist_penalty_weight': 1.0,
    'batch_size': 4,
    'open_in_gui': False,
    'peak_threshold': 0.2,
    'max_instances': None,
    'tracking.tracker': 'flowmaxtracks',
    'tracking.max_tracking': True,
    'tracking.max_tracks': 2,
    'tracking.target_instance_count': None,
    'tracking.pre_cull_to_target': None,
    'tracking.pre_cull_iou_threshold': None,
2024-10-07 20:55:37.291379: I tensorflow/core/platform/cpu_feature_guard.cc:151] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
    'tracking.post_connect_single_breaks': 1,
    'tracking.clean_instance_count': None,
    'tracking.clean_iou_threshold': None,
    'tracking.similarity': 'instance',
    'tracking.match': 'hungarian',
    'tracking.robust': None,
    'tracking.track_window': 5,
    'tracking.min_new_track_points': None,
    'tracking.min_match_points': None,
2024-10-07 20:55:37.799106: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1525] Created device /job:localhost/replica:0/task:0/device:GPU:0 with 5957 MB memory:  -> device: 0, name: NVIDIA GeForce RTX 2070 SUPER, pci bus id: 0000:01:00.0, compute capability: 7.5
    'tracking.img_scale': None,
    'tracking.of_window_size': None,
    'tracking.of_max_levels': None,
    'tracking.save_shifted_instances': None,
    'tracking.kf_node_indices': [0, 1],
    'tracking.kf_init_frame_count': 10,
    'tracking.oks_errors': None,
    'tracking.oks_score_weighting': 0,
    'tracking.oks_normalization': None
}

INFO:sleap.nn.inference:Auto-selected GPU 0 with 6744 MiB of free memory.
2024-10-07 20:55:43.684523: I tensorflow/stream_executor/cuda/cuda_dnn.cc:366] Loaded cuDNN version 8201
Versions:
Exception in thread Thread-3:
Traceback (most recent call last):
  File "C:\Users\eb\Miniforge3\envs\sleap_dev\lib\threading.py", line 926, in _bootstrap_inner
    self.run()
  File "C:\Users\eb\Miniforge3\envs\sleap_dev\lib\threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "c:\repos\sleap\sleap\nn\inference.py", line 2627, in _object_builder
    t=frame_ind,
  File "c:\repos\sleap\sleap\nn\tracking.py", line 1433, in track
    tracked_instances = self.init_tracker.track(untracked_instances, img, t)
  File "c:\repos\sleap\sleap\nn\tracking.py", line 714, in track
    img=img,
  File "c:\repos\sleap\sleap\nn\tracking.py", line 434, in get_candidates
    ref_instances, ref_img, ref_t, img, t
  File "c:\repos\sleap\sleap\nn\tracking.py", line 191, in get_shifted_instances
    max_levels=self.of_max_levels,
  File "c:\repos\sleap\sleap\nn\tracking.py", line 330, in flow_shift_instances
    0.01,
cv2.error: OpenCV(4.6.0) :-1: error: (-5:Bad argument) in function 'calcOpticalFlowPyrLK'
> Overload resolution failed:
>  - prevImg is not a numpy array, neither a scalar
>  - Expected Ptr<cv::UMat> for argument 'prevImg'

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?

#1447
#1583, #1980

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

    • Introduced a max_tracking feature for enhanced control over the number of active tracks.
    • Updated logic to limit the number of tracks processed, improving tracking efficiency.
  • Bug Fixes

    • Adjusted deprecated target_instance_count usage to ensure compatibility with new tracking attributes.
  • Documentation

    • Updated method signatures to reflect changes in tracking parameters.

Copy link

coderabbitai bot commented Oct 8, 2024

Walkthrough

The changes in this pull request primarily affect the sleap/nn/tracking.py file, focusing on the Tracker and FlowMaxTracksCandidateMaker classes. A new property max_tracking has been added to the Tracker class, facilitating maximum tracking functionality. The target_instance_count attribute is marked for deprecation, with adjustments made to various methods to accommodate the new max_tracks attribute. Logic for limiting track processing based on max_tracks has been implemented, enhancing the overall tracking capabilities and preparing the codebase for future updates.

Changes

File Path Change Summary
sleap/nn/tracking.py - Added max_tracking property to Tracker class.
- Deprecated target_instance_count attribute with adjusted usage.
- Updated FlowMaxTracksCandidateMaker to limit tracks based on max_tracks.
- Enhanced track method in Tracker to handle max_tracking.
- Modified final_pass method for flexible connection logic.
- Updated make_tracker_by_name method to reflect changes in parameters.

Poem

🐇 In the meadow where tracks align,
A new path opens, oh so fine!
With max_tracking guiding the way,
We hop and skip, come what may.
Old counts fade, new limits rise,
In our world, the future lies! 🌼


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4a8db98 and 2db959d.

📒 Files selected for processing (1)
  • sleap/nn/tracking.py (9 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • sleap/nn/tracking.py

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>, please review it.
    • 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 gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @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.
    • @coderabbitai help me debug CodeRabbit configuration file.

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 using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration 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.

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: 8

🧹 Outside diff range and nitpick comments (2)
sleap/nn/tracking.py (2)

969-970: Clarify the exception message for missing required parameters.

The ValueError message could be more explicit by naming the parameters:

raise ValueError("Kalman filter requires `max_tracks` or `target_instance_count` to be set.")

This helps users understand which parameters need to be provided.


1403-1403: Remove unused **kwargs parameter from the track method.

The track method includes **kwargs in its signature, but kwargs is not used within the method. Consider removing it to simplify the method and prevent confusion.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between fff8761 and 4a8db98.

📒 Files selected for processing (1)
  • sleap/nn/tracking.py (9 hunks)
🧰 Additional context used

@@ -574,7 +574,7 @@ class Tracker(BaseTracker):
max_tracking: bool = False # To enable maximum tracking.

cleaner: Optional[Callable] = None # TODO: deprecate
target_instance_count: int = 0
target_instance_count: int = 0 # TODO: deprecate
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Refactor to remove dependency on deprecated target_instance_count.

The attribute target_instance_count is marked for deprecation but is still being defined and used. Consider refactoring the code to eliminate its usage and replace it with max_tracks wherever applicable to clean up the codebase and avoid confusion.

Comment on lines 827 to 831
elif (self.target_instance_count or self.max_tracks) and self.post_connect_single_breaks:
if not self.target_instance_count:
# If target_instance_count is not set, use max_tracks instead
# target_instance_count not available in the GUI
self.target_instance_count = self.max_tracks
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid using deprecated target_instance_count in logic.

The code assigns self.target_instance_count from self.max_tracks, despite target_instance_count being marked for deprecation. Refactor the logic to use self.max_tracks directly, removing reliance on the deprecated attribute.

@@ -850,7 +855,7 @@
of_max_levels: int = 3,
save_shifted_instances: bool = False,
# Pre-tracking options to cull instances
target_instance_count: int = 0,
target_instance_count: int = 0, # TODO: deprecate target_instance_count
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove deprecated parameter target_instance_count from method signature.

The parameter target_instance_count in the make_tracker_by_name method is marked for deprecation but remains in the signature. To streamline the API and prevent future confusion, consider removing it and updating any dependent code to use max_tracks.

@@ -940,11 +946,17 @@
pre_cull_function=pre_cull_function,
max_tracking=max_tracking,
max_tracks=max_tracks,
target_instance_count=target_instance_count,
target_instance_count=target_instance_count, # TODO: deprecate target_instance_count
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Eliminate passing deprecated target_instance_count to the constructor.

When creating tracker_obj, the deprecated target_instance_count is still being passed. Update the constructor and related logic to rely solely on max_tracks, removing the need for the deprecated parameter.

Comment on lines +953 to +958
# Kalman filter requires deprecated target_instance_count
if (max_tracks or target_instance_count) and kf_init_frame_count:
if not target_instance_count:
# If target_instance_count is not set, use max_tracks instead
# target_instance_count not available in the GUI
target_instance_count = max_tracks
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Update Kalman filter implementation to use max_tracks instead of deprecated target_instance_count.

The Kalman filter initialization depends on target_instance_count, which is marked for deprecation. Modify the Kalman filter code to use max_tracks exclusively, ensuring future maintainability and consistency.

@@ -1369,6 +1381,8 @@
if init_tracker.pre_cull_function is None:
init_tracker.pre_cull_function = cull_function

print(f"Using {init_tracker.get_name()} to track {init_frame_count} frames for Kalman filters.")
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix syntax error due to extra parenthesis in print statement.

There is an extra closing parenthesis at the end of the print statement:

print(f"Using {init_tracker.get_name()} to track {init_frame_count} frames for Kalman filters.)"

Remove the extra parenthesis to correct the syntax error.

Apply this diff:

-print(f"Using {init_tracker.get_name()} to track {init_frame_count} frames for Kalman filters.)"
+print(f"Using {init_tracker.get_name()} to track {init_frame_count} frames for Kalman filters.")

connect_single_track_breaks(frames, self.target_instance_count)
print("Connecting single track breaks.")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use logging instead of print statements for better practice.

The print statement for status messages can be replaced with the logging module to provide configurable logging levels and outputs.

Apply this diff:

+import logging
...
+logger = logging.getLogger(__name__)
...
-print("Connecting single track breaks.")
+logger.info("Connecting single track breaks.")

Committable suggestion was skipped due to low confidence.

@@ -1420,7 +1435,7 @@
# Initialize the Kalman filters
self.kalman_tracker.init_filters(self.init_set.instances)

# print(f"Kalman filters initialized (frame {t})")
print(f"Kalman filters initialized (frame {t})")
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use logging instead of print statements for initialization messages.

Replace the print statement with the logging module to improve flexibility and control over log outputs.

Apply this diff:

+import logging
...
+logger = logging.getLogger(__name__)
...
-print(f"Kalman filters initialized (frame {t})")
+logger.info(f"Kalman filters initialized (frame {t})")

Committable suggestion was skipped due to low confidence.

Copy link

codecov bot commented Oct 8, 2024

Codecov Report

Attention: Patch coverage is 33.33333% with 8 lines in your changes missing coverage. Please review.

Project coverage is 75.46%. Comparing base (7ed1229) to head (2db959d).
Report is 56 commits behind head on develop.

Files with missing lines Patch % Lines
sleap/nn/tracking.py 33.33% 8 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #1986      +/-   ##
===========================================
+ Coverage    73.30%   75.46%   +2.15%     
===========================================
  Files          134      133       -1     
  Lines        24087    24642     +555     
===========================================
+ Hits         17658    18596     +938     
+ Misses        6429     6046     -383     

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

@eberrigan eberrigan changed the title Elizabeth/set kalman filter args equal to max tracking args Allow max tracking args for Kalman filter Oct 8, 2024
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