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

Refactor LossViewer to use matplotlib #1899

Merged
merged 57 commits into from
Aug 26, 2024

Conversation

eberrigan
Copy link
Contributor

@eberrigan eberrigan commented Aug 9, 2024

Description

In a downstream branch #1841, we upgrade all of the dependencies to use Python 3.10. However, QtCharts is problematic--it is missing libraries in updated PySide6

We are only using QtCharts in the LossViewer, so, in this PR, we replace QtCharts with matplotlib. A LossPlot class that subclasses MplCanvas is added to handle the plotting functionality previously mixed into LossViewer. The unused duplicate of the LossViewer in training_monitor.py is removed. To maintain scope, the refactored LossViewer re-uses same logic and only replaces QtCharts with matplotlib.


⚠️ In testing the refactored LossViewer, we came across a "leaked semaphore" error that seemed to occur only for (a?) bottom-up model(s?) on (a?) Mac M2(s?). This issue will be further investigated, but has been deemed unrelated to the refactoring in this PR as it was replicated on the base develop branch as well (and seems more likely to be model/configuration related).

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?

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

Summary by CodeRabbit

  • New Features

    • Introduced Matplotlib-based charting functionality for improved graph rendering in the GUI.
    • Added methods for better management of scatter and line plots within the visualization canvas.
    • Enhanced visual representation of training metrics with a new plotting mechanism.
    • Integrated log-scale functionality for the y-axis to improve data visualization.
  • Bug Fixes

    • Resolved issues related to the previous charting library (QtCharts) not functioning properly.
  • Refactor

    • Enhanced plotting capabilities and streamlined the visualization process by switching to Matplotlib.
    • Improved initialization and management of chart series for training and validation losses.

Copy link

coderabbitai bot commented Aug 9, 2024

Walkthrough

The recent changes enhance the Sleap application's graphical representation by integrating Matplotlib as the primary plotting framework while retaining QtCharts functionality. This transition includes the introduction of a new LossPlot class and updates to the LossViewer for improved management and visualization of training metrics.

Changes

Files Change Summary
sleap/gui/widgets/monitor.py Introduced LossPlot class for plotting training/validation loss with Matplotlib; refactored LossViewer methods for better data handling and visualization.
sleap/nn/training.py, sleap/gui/widgets/mpl.py Changed Matplotlib backend from "Qt5Agg" to "QtAgg" in both setup_visualization and mpl.py, enhancing compatibility.
sleap/gui/app.py Removed a blank line; no functional changes.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LossViewer
    participant LossPlot

    User->>LossViewer: Request to visualize loss data
    LossViewer->>LossPlot: Create LossPlot instance
    LossPlot-->>LossViewer: Return plot
    LossViewer->>LossPlot: Add training/validation loss data
    LossPlot-->>LossViewer: Update visualization
    LossViewer->>User: Display updated loss chart
Loading

Poem

In the garden, data blooms bright,
With LossPlot, a new delight!
From Qt's grasp, we've set it free,
Now plots dance in harmony.
Hoppity hop, let graphs take flight,
Visual magic, pure and bright! 🐇✨


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.
    • @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 as 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.

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

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.

coderabbitai[bot]

This comment was marked as spam.

@roomrys roomrys marked this pull request as ready for review August 23, 2024 05:16
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: 1

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 99b1716 and 9abeb64.

Files selected for processing (3)
  • sleap/gui/app.py (1 hunks)
  • sleap/gui/widgets/monitor.py (8 hunks)
  • sleap/gui/widgets/mpl.py (1 hunks)
Files skipped from review due to trivial changes (1)
  • sleap/gui/app.py
Additional context used
Ruff
sleap/gui/widgets/monitor.py

837-838: Use a single if statement instead of nested if statements

(SIM102)

Additional comments not posted (4)
sleap/gui/widgets/mpl.py (2)

9-9: LGTM: Import statement updated for new backend.

The import statement for FigureCanvasQTAgg has been updated to align with the QtAgg backend. This change is appropriate for compatibility with PySide 6.


12-12: LGTM: Backend configuration updated to QtAgg.

The Matplotlib backend has been set to QtAgg, which is consistent with the import update and should improve compatibility with PySide 6.

sleap/gui/widgets/monitor.py (2)

21-493: LGTM: LossPlot class implementation.

The LossPlot class is well-structured and effectively encapsulates the logic for plotting loss data using Matplotlib. The methods for initializing series, setting up axes, and managing plot updates are clear and appropriate for the intended functionality.


Line range hint 495-928: LGTM: LossViewer class refactoring.

The refactoring of the LossViewer class to use the LossPlot class improves the clarity and modularity of the code. The integration of Matplotlib enhances the visual representation of training metrics.

Tools
Ruff

837-838: Use a single if statement instead of nested if statements

(SIM102)

Comment on lines +837 to +838
if which == "val_loss":
if self.best_val_y is None or y < self.best_val_y:
Copy link

Choose a reason for hiding this comment

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

Simplify nested if statement.

The nested if statement can be simplified to improve readability.

Apply this diff to simplify the condition:

- if which == "val_loss":
-     if self.best_val_y is None or y < self.best_val_y:
+ if which == "val_loss" and (self.best_val_y is None or y < self.best_val_y):
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
if which == "val_loss":
if self.best_val_y is None or y < self.best_val_y:
if which == "val_loss" and (self.best_val_y is None or y < self.best_val_y):
Tools
Ruff

837-838: Use a single if statement instead of nested if statements

(SIM102)

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

Outside diff range, codebase verification and nitpick comments (3)
sleap/gui/widgets/monitor.py (3)

Line range hint 586-619: Extract ZMQ port initialization to a separate method.

The initialization of ZMQ ports is embedded within the constructor. Consider extracting this logic into a separate method for clarity and maintainability.

Here's a suggestion to refactor the ZMQ port initialization:

def initialize_zmq_ports(self, zmq_ports):
    zmq_ports = zmq_ports or dict()
    zmq_ports["publish_port"] = zmq_ports.get("publish_port", 9001)
    zmq_ports["controller_port"] = zmq_ports.get("controller_port", 9000)
    return zmq_ports

# Usage in __init__
self.zmq_ports = self.initialize_zmq_ports(zmq_ports)

Line range hint 658-750: Extract layout setup to a separate method.

The layout setup logic is embedded within the reset method. Consider extracting this logic into a separate method for clarity and maintainability.

Here's a suggestion to refactor the layout setup:

def setup_layout(self):
    layout = QtWidgets.QVBoxLayout()
    layout.addWidget(self.canvas)

    if self.show_controller:
        control_layout = QtWidgets.QHBoxLayout()
        # Add control elements to control_layout
        layout.addLayout(control_layout)

    wid = QtWidgets.QWidget()
    wid.setLayout(layout)
    self.setCentralWidget(wid)

# Usage in reset
self.setup_layout()

Line range hint 802-876: Extract free port finding logic to a utility function.

The logic for finding a free port is embedded within the setup_zmq method. Consider extracting this logic into a utility function for reuse and clarity.

Here's a suggestion to refactor the free port finding logic:

def find_free_port(port: int, zmq_context: zmq.Context, max_attempts: int = 10):
    attempts = 0
    while not is_port_free(port=port, zmq_context=zmq_context):
        if attempts >= max_attempts:
            raise RuntimeError(
                f"Could not find free port after {max_attempts} attempts."
            )
        port = select_zmq_port(zmq_context=zmq_context)
        attempts += 1
    return port

# Usage in setup_zmq
self.zmq_ports["publish_port"] = find_free_port(
    port=self.zmq_ports["publish_port"], zmq_context=self.ctx
)
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 9abeb64 and 3269576.

Files selected for processing (1)
  • sleap/gui/widgets/monitor.py (8 hunks)
Additional context used
Ruff
sleap/gui/widgets/monitor.py

928-929: Use a single if statement instead of nested if statements

(SIM102)

Additional comments not posted (25)
sleap/gui/widgets/monitor.py (25)

121-137: LGTM!

The log_scale property is well-implemented and correctly toggles the y-axis scale.


177-208: LGTM!

The _set_title_space method is well-implemented and effectively calculates the title space.


210-225: LGTM!

The _setup_x_axis method is well-implemented and correctly configures the x-axis.


227-247: LGTM!

The _set_up_y_axis method is well-implemented and correctly configures the y-axis.


249-274: LGTM!

The _setup_legend method is well-implemented and effectively configures the legend.


276-292: LGTM!

The _setup_major_gridlines method is well-implemented and effectively configures the gridlines and spines.


294-309: LGTM!

The _add_midpoint_gridlines method is well-implemented and effectively adds midpoint gridlines.


311-326: LGTM!

The set_data_on_scatter method is well-implemented and correctly sets data on scatter plots.


327-342: LGTM!

The add_data_to_plot method is well-implemented and correctly adds data to line plots.


343-359: LGTM!

The calculate_xlim method is well-implemented and correctly calculates x-axis limits.


361-393: LGTM!

The calculate_ylim method is well-implemented and correctly calculates y-axis limits.


395-417: LGTM!

The resize_axes method is well-implemented and correctly resizes axes to fit data.


419-422: LGTM!

The redraw_plot method is well-implemented and correctly redraws the plot.


750-765: LGTM!

The log_scale property is well-implemented and correctly toggles the y-axis scale.


767-781: LGTM!

The ignore_outliers property is well-implemented and correctly manages outlier handling.


783-785: LGTM!

The toggle_ignore_outliers method is well-implemented and correctly toggles outlier handling.


787-789: LGTM!

The toggle_log_scale method is well-implemented and correctly toggles the y-axis scale.


Line range hint 791-800: LGTM!

The set_batches_to_show method is well-implemented and correctly manages the number of batches to display.


Line range hint 878-884: LGTM!

The cancel method is well-implemented and correctly manages the cancel action.


Line range hint 886-896: LGTM!

The stop method is well-implemented and correctly manages the stop action.


Line range hint 898-936: Simplify nested if statement for val_loss.

The nested if statement for val_loss can be simplified to improve readability.

Apply this diff to simplify the condition:

- if which == "val_loss":
-     if self.best_val_y is None or y < self.best_val_y:
+ if which == "val_loss" and (self.best_val_y is None or y < self.best_val_y):
Tools
Ruff

928-929: Use a single if statement instead of nested if statements

(SIM102)


938-952: LGTM!

The _set_data_on_scatter method is well-implemented and correctly sets data on scatter plots.


953-967: LGTM!

The _add_data_to_plot method is well-implemented and correctly adds data to line plots.


968-971: LGTM!

The _redraw_plot method is well-implemented and correctly redraws the plot.


973-982: LGTM!

The _resize_axes method is well-implemented and correctly resizes axes to fit data.

sleap/gui/widgets/monitor.py Outdated Show resolved Hide resolved
sleap/gui/widgets/monitor.py Outdated Show resolved Hide resolved
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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 3269576 and c1af1ee.

Files selected for processing (1)
  • sleap/gui/widgets/monitor.py (8 hunks)
Additional context used
Ruff
sleap/gui/widgets/monitor.py

928-929: Use a single if statement instead of nested if statements

(SIM102)

Additional comments not posted (5)
sleap/gui/widgets/monitor.py (5)

22-445: Well-structured LossPlot class for Matplotlib integration.

The LossPlot class is well-structured and effectively encapsulates the functionality required for plotting training and validation loss curves using Matplotlib. The methods are well-organized, and the class properties are used effectively to manage state.


Line range hint 586-1028: Effective integration of LossPlot in LossViewer.

The refactoring of the LossViewer class to use the new LossPlot class for Matplotlib plotting is effectively done. The methods related to data handling, ZMQ integration, and GUI controls are well-implemented. The use of properties for managing plot settings like log_scale and ignore_outliers is a good practice.

Tools
Ruff

928-929: Use a single if statement instead of nested if statements

(SIM102)


953-967: Ensure separation of concerns in _add_data_to_plot.

The method _add_data_to_plot correctly handles adding data to line plots and ensures it does not interact with scatter plots. This separation of concerns is crucial for maintaining clarity and correctness in the plotting logic.


938-952: Correct implementation of _set_data_on_scatter.

The method _set_data_on_scatter is well-implemented, focusing solely on scatter plots and ensuring no interaction with line plots. This method effectively manages the data setting for scatter plots, which is essential for the correct visualization of batch and best validation losses.


789-789: Ensure propagation of log scale setting in toggle_log_scale.

The method toggle_log_scale effectively toggles the log scale setting. It is crucial to ensure that this setting is correctly propagated to the LossPlot instance to maintain consistency in the plot appearance.

@roomrys roomrys requested a review from talmo August 24, 2024 20:52
Otherwise we get an unnecessary teminal message:
UserWarning: Attempting to set identical bottom == top == 3.0 results in singular transformations; automatically expanding.
  self.axes.set_ylim(y_min, y_max)
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: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between c1af1ee and a4c2905.

Files selected for processing (1)
  • sleap/gui/widgets/monitor.py (8 hunks)
Additional context used
Ruff
sleap/gui/widgets/monitor.py

929-930: Use a single if statement instead of nested if statements

(SIM102)

Additional comments not posted (2)
sleap/gui/widgets/monitor.py (2)

22-199: Comprehensive review of LossPlot class.

The LossPlot class is well-structured and encapsulates all functionalities related to the plotting of training and validation loss curves using Matplotlib. The methods are well-organized, and the use of properties for log_scale and handling of outliers is appropriate.

  • Initialization and Setup: The constructor and setup methods (__init__, _setup_x_axis, _setup_y_axis, _setup_legend, _setup_major_gridlines) are correctly implemented. The use of properties to handle attributes like log_scale and ignore_outliers is a good practice, ensuring that changes to these attributes are handled consistently.
  • Data Handling: Methods like set_data_on_scatter and add_data_to_plot are clear and concise, appropriately checking the type of plot before adding data.
  • Axes and Gridlines Management: The methods handling axes adjustments (resize_axes, _calculate_xlim, _calculate_ylim) and gridline setup are crucial for ensuring the plot scales correctly with incoming data. The implementation here handles these aspects well, with considerations for log scale and outlier handling.
  • Redrawing and Title Updates: The redraw_plot and update_runtime_title methods ensure that the plot updates are efficient and that runtime information is displayed accurately.

Overall, the LossPlot class is a robust implementation for the plotting needs of the LossViewer and integrates well with the existing architecture. The use of Matplotlib is effectively leveraged to enhance the visualization capabilities.


Line range hint 587-1020: Detailed review of LossViewer class.

The LossViewer class handles the GUI and integration of the LossPlot for displaying training metrics. The class is well-structured, and the methods are appropriately segmented to handle different aspects of the GUI and data handling.

  • Initialization and Reset: The constructor and reset method are well-implemented, ensuring that the LossPlot is correctly instantiated and configured. The handling of ZMQ for communication is robust, providing a solid foundation for receiving training data.
  • Data Handling and Plotting: The methods add_datapoint, _set_data_on_scatter, and _add_data_to_plot effectively manage the data received during training and ensure it is plotted correctly. The separation of scatter and line plot handling is a good practice.
  • GUI Components: The setup of GUI components like checkboxes and buttons is done well, providing necessary controls to the user for adjusting plot settings.
  • Runtime Updates: The method update_runtime and associated helper methods ensure that the plot's title and other runtime information are updated accurately based on the training progress.

Overall, the LossViewer class effectively integrates the LossPlot and manages the GUI components necessary for displaying training metrics. The class is a key part of the application's functionality, allowing users to monitor training progress interactively.

Tools
Ruff

929-930: Use a single if statement instead of nested if statements

(SIM102)

@talmo talmo merged commit c88412c into develop Aug 26, 2024
8 checks passed
@talmo talmo deleted the elizabeth/Refactor-`LossViewer`-to-use-matplotlib branch August 26, 2024 15:08
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.

3 participants