-
Notifications
You must be signed in to change notification settings - Fork 102
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
Refactor LossViewer
to use matplotlib
#1899
Conversation
…ssViewer` (untested)
WalkthroughThe 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 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
Poem
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? TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Additionally, you can add CodeRabbit Configuration File (
|
There was a problem hiding this 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
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 nestedif
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 theQtAgg
backend. This change is appropriate for compatibility with PySide 6.
12-12
: LGTM: Backend configuration updated toQtAgg
.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 theLossPlot
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 nestedif
statements(SIM102)
if which == "val_loss": | ||
if self.best_val_y is None or y < self.best_val_y: |
There was a problem hiding this comment.
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.
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 nestedif
statements(SIM102)
There was a problem hiding this 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
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 nestedif
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 forval_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 nestedif
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.
There was a problem hiding this 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
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 nestedif
statements(SIM102)
Additional comments not posted (5)
sleap/gui/widgets/monitor.py (5)
22-445
: Well-structuredLossPlot
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 ofLossPlot
inLossViewer
.The refactoring of the
LossViewer
class to use the newLossPlot
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 likelog_scale
andignore_outliers
is a good practice.Tools
Ruff
928-929: Use a single
if
statement instead of nestedif
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 intoggle_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 theLossPlot
instance to maintain consistency in the plot appearance.
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)
There was a problem hiding this 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
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 nestedif
statements(SIM102)
Additional comments not posted (2)
sleap/gui/widgets/monitor.py (2)
22-199
: Comprehensive review ofLossPlot
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 forlog_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 likelog_scale
andignore_outliers
is a good practice, ensuring that changes to these attributes are handled consistently.- Data Handling: Methods like
set_data_on_scatter
andadd_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
andupdate_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 theLossViewer
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 ofLossViewer
class.The
LossViewer
class handles the GUI and integration of theLossPlot
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 theLossPlot
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 theLossPlot
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 nestedif
statements(SIM102)
* Remove no-op code from #1498 * Add options to set background color when exporting video (#1328) * implement #921 * simplified form / refractor * Add test function and update cli docs * Improve test function to check background color * Improve comments * Change background options to lowercase * Use coderabbitai suggested `fill` --------- Co-authored-by: Shrivaths Shyam <52810689+shrivaths16@users.noreply.github.com> Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Increase range on batch size (#1513) * Increase range on batch size * Set maximum to a factor of 2 * Set default callable for `match_lists_function` (#1520) * Set default for `match_lists_function` * Move test code to official tests * Check using expected values * Allow passing in `Labels` to `app.main` (#1524) * Allow passing in `Labels` to `app.main` * Load the labels object through command * Add warning when unable to switch back to CPU mode * Replace (broken) `--unrag` with `--ragged` (#1539) * Fix unrag always set to true in sleap-export * Replace unrag with ragged * Fix typos * Add function to create app (#1546) * Refactor `AddInstance` command (#1561) * Refactor AddInstance command * Add staticmethod wrappers * Return early from set_visible_nodes * Import DLC with uniquebodyparts, add Tracks (#1562) * Import DLC with uniquebodyparts, add Tracks * add tests * correct tests * Make the hdf5 videos store as int8 format (#1559) * make the hdf5 video dataset type as proper int8 by padding with zeros * add gzip compression * Scale new instances to new frame size (#1568) * Fix typehinting in `AddInstance` * brought over changes from my own branch * added suggestions * Ensured google style comments --------- Co-authored-by: roomrys <38435167+roomrys@users.noreply.github.com> Co-authored-by: sidharth srinath <sidhumani22@gmail.com> * Fix package export (#1619) Add check for empty videos * Add resize/scroll to training GUI (#1565) * Make resizable training GUI and add adaptive scroll bar * Set a maximum window size --------- Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * support loading slp files with non-compound types and str in metadata (#1566) Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * change inference pipeline option to tracking-only (#1666) change inference pipeline none option to tracking-only * Add ABL:AOC 2023 Workshop link (#1673) * Add ABL:AOC 2023 Workshop link * Trigger website build * Graceful failing with seeking errors (#1712) * Don't try to seek to faulty last frame on provider initialization * Catch seeking errors and pass * Lint * Fix IndexError for hdf5 file import for single instance analysis files (#1695) * Fix hdf5 read for single instance analysis files * Add test * Small test files * removing unneccessary fixtures * Replace imgaug with albumentations (#1623) What's the worst that could happen? * Initial commit * Fix augmentation * Update more deps requirements * Use pip for installing albumentations and avoid reinstalling OpenCV * Update other conda envs * Fix out of bounds albumentations issues and update dependencies (#1724) * Install albumentations using conda-forge in environment file * Conda install albumentations * Add ndx-pose to pypi requirements * Keep out of bounds points * Black * Add ndx-pose to conda install in environment file * Match environment file without cuda * Ordered dependencies * Add test * Delete comments * Add conda packages to mac environment file * Order dependencies in pypi requirements * Add tests with zeroes and NaNs for augmentation * Back * Black * Make comment one line * Add todo for later * Black * Update to new TensorFlow conda package (#1726) * Build conda package locally * Try 2.8.4 * Merge develop into branch to fix dependencies * Change tensorflow version to 2.7.4 in where conda packages are used * Make tensorflow requirements in pypi looser * Conda package has TensorFlow 2.7.0 and h5py and numpy installed via conda * Change tensorflow version in `environment_no_cuda.yml` to test using CI * Test new sleap/tensorflow package * Reset build number * Bump version * Update mac deps * Update to Arm64 Mac runners * pin `importlib-metadata` * Pin more stuff on mac * constrain `opencv` version due to new qt dependencies * Update more mac stuff * Patches to get to green * More mac skipping --------- Co-authored-by: Talmo Pereira <talmo@salk.edu> Co-authored-by: Talmo Pereira <talmo@princeton.edu> * Fix CI on macosx-arm64 (#1734) * Build conda package locally * Try 2.8.4 * Merge develop into branch to fix dependencies * Change tensorflow version to 2.7.4 in where conda packages are used * Make tensorflow requirements in pypi looser * Conda package has TensorFlow 2.7.0 and h5py and numpy installed via conda * Change tensorflow version in `environment_no_cuda.yml` to test using CI * Test new sleap/tensorflow package * Reset build number * Bump version * Update mac deps * Update to Arm64 Mac runners * pin `importlib-metadata` * Pin more stuff on mac * constrain `opencv` version due to new qt dependencies * Update more mac stuff * Patches to get to green * More mac skipping * Re-enable mac tests * Handle GPU re-init * Fix mac build CI * Widen tolerance for movenet correctness test * Fix build ci * Try for manual build without upload * Try to reduce training CI time * Rework actions * Fix miniforge usage * Tweaks * Fix build ci * Disable manual build * Try merging CI coverage * GPU/CPU usage in tests * Lint * Clean up * Fix test skip condition * Remove scratch test --------- Co-authored-by: eberrigan <berri104@gmail.com> * Add option to export to CSV via sleap-convert and API (#1730) * Add csv as a format option * Add analysis to format * Add csv suffix to output path * Add condition for csv analysis file * Add export function to Labels class * delete print statement * lint * Add `analysis.csv` as parametrize input for `sleap-convert` tests * test `export_csv` method added to `Labels` class * black formatting * use `Path` to construct filename * add `analysis.csv` to cli guide for `sleap-convert` --------- Co-authored-by: Talmo Pereira <talmo@salk.edu> * Only propagate Transpose Tracks when propagate is checked (#1748) Fix always-propagate transpose tracks issue * View Hyperparameter nonetype fix (#1766) Pass config getter argument to fetch hyperparameters * Adding ragged metadata to `info.json` (#1765) Add ragged metadata to info.json file * Add batch size to GUI for inference (#1771) * Fix conda builds (#1776) * test conda packages in a test environment as part of CI * do not test sleap import using conda build * use github environment variables to define build path for each OS in the matrix and add print statements for testing * figure out paths one OS at a time * github environment variables work in subsequent steps not current step * use local builds first * print env info * try simple environment creation * try conda instead of mamba * fix windows build path * fix windows build path * add comment to reference pull request * remove test stage from conda build for macs and test instead by creating the environment in a workflow * test workflow by pushing to current branch * test conda package on macos runner * Mac build does not need nvidia channel * qudida and albumentations are conda installed now * add comment with original issue * use python 3.9 * use conda match specifications syntax * make print statements more readable for troubleshooting python versioning * clean up build file * update version for pre-release * add TODO * add tests for conda packages before uploading * update ci comments and branches * remove macos test of pip wheel since python 3.9 is not supported by setup-python action * Upgrade build actions for release (#1779) * update `build.yml` so it matches updates from `build_manual.yml` * test `build.yml` without uploading * test again using build_manual.yml * build pip wheel with Ubuntu and turn off caching so build.yml exactly matches build_manual.yml * `build.yml` on release only and upload * testing caching * `use-only-tar-bz2: true` makes environment unsolvable, change it back * Update .github/workflows/build_manual.yml Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Update .github/workflows/build.yml Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * bump pre-release version * fix version for pre-release * run build and upload on release! * try setting `CACHE_NUMBER` to 1 with `use-only-tar-bz2` set to true * increasing the cache number to reset the cache does work when `use-only-tar-bz2` is set to true * publish and upload on release only --------- Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Add ZMQ support via GUI and CLI (#1780) * Add ZMQ support via GUI and CLI, automatic port handler, separate utils module for the functions * Change menu name to match deleting predictions beyond max instance (#1790) Change menu and function names * Fix website build and remove build cache across workflows (#1786) * test with build_manual on push * comment out caching in build manual * remove cache step from builad manual since environment resolves when this is commented out * comment out cache in build ci * remove cache from build on release * remove cache from website build * test website build on push * add name to checkout step * update checkout to v4 * update checkout to v4 in build ci * remove cache since build ci works without it * update upload-artifact to v4 in build ci * update second chechout to v4 in build ci * update setup-python to v5 in build ci * update download-artifact to v4 in build ci * update checkout to v4 in build ci * update checkout to v4 in website build * update setup-miniconda to v3.0.3 in website build * update actions-gh-pages to v4 in website build * update actions checkout and setup-python in ci * update checkout action in ci to v4 * pip install lxml[html_clean] because of error message during action * add error message to website to explain why pip install lxml[html_clean] * remove my branch for pull request * Bump to 1.4.1a1 (#1791) * bump versions to 1.4.1a1 * we can change the version on the installation page since this will be merged into the develop branch and not main * Fix windows conda package upload and build ci (#1792) * windows OS is 2022 not 2019 on runner * upload windows conda build manually but not pypi build * remove comment and run build ci * change build manual back so that it doesn't upload * remove branch from build manual * update installation docs for 1.4.1a1 * Fix zmq inference (#1800) * Ensure that we always pass in the zmq_port dict to LossViewer * Ensure zmq_ports has correct keys inside LossViewer * Use specified controller and publish ports for first attempted addresses * Add test for ports being set in LossViewer * Add max attempts to find unused port * Fix find free port loop and add for controller port also * Improve code readablility and reuse * Improve error message when unable to find free port * Set selected instance to None after removal (#1808) * Add test that selected instance set to None after removal * Set selected instance to None after removal * Add `InstancesList` class to handle backref to `LabeledFrame` (#1807) * Add InstancesList class to handle backref to LabeledFrame * Register structure/unstructure hooks for InstancesList * Add tests for the InstanceList class * Handle case where instance are passed in but labeled_frame is None * Add tests relevant methods in LabeledFrame * Delegate setting frame to InstancesList * Add test for PredictedInstance.frame after complex merge * Add todo comment to not use Instance.frame * Add rtest for InstasnceList.remove * Use normal list for informative `merged_instances` * Add test for copy and clear * Add copy and clear methods, use normal lists in merge method * Bump to v1.4.1a2 (#1835) bump to 1.4.1a2 * Updated trail length viewing options (#1822) * updated trail length optptions * Updated trail length options in the view menu * Updated `prefs` to include length info from `preferences.yaml` * Added trail length as method of `MainWindow` * Updated trail length documentation * black formatting --------- Co-authored-by: Keya Loding <keya@Keyas-MacBook-Air.local> * Handle case when no frame selection for trail overlay (#1832) * Menu option to open preferences directory and update to util functions to pathlib (#1843) * Add menu to view preferences directory and update to pathlib * text formatting * Add `Keep visualizations` checkbox to training GUI (#1824) * Renamed save_visualizations to view_visualizations for clarity * Added Delete Visualizations button to the training pipeline gui, exposed del_viz_predictions config option to the user * Reverted view_ back to save_ and changed new training checkbox to Keep visualization images after training. * Fixed keep_viz config option state override bug and updated keep_viz doc description * Added test case for reading training CLI argument correctly * Removed unnecessary testing code * Creating test case to check for viz folder * Finished tests to check CLI argument reading and viz directory existence * Use empty string instead of None in cli args test * Use keep_viz_images false in most all test configs (except test to override config) --------- Co-authored-by: roomrys <38435167+roomrys@users.noreply.github.com> * Allowing inference on multiple videos via `sleap-track` (#1784) * implementing proposed code changes from issue #1777 * comments * configuring output_path to support multiple video inputs * fixing errors from preexisting test cases * Test case / code fixes * extending test cases for mp4 folders * test case for output directory * black and code rabbit fixes * code rabbit fixes * as_posix errors resolved * syntax error * adding test data * black * output error resolved * edited for push to dev branch * black * errors fixed, test cases implemented * invalid output test and invalid input test * deleting debugging statements * deleting print statements * black * deleting unnecessary test case * implemented tmpdir * deleting extraneous file * fixing broken test case * fixing test_sleap_track_invalid_output * removing support for multiple slp files * implementing talmo's comments * adding comments * Add object keypoint similarity method (#1003) * Add object keypoint similarity method * fix max_tracking * correct off-by-one error * correct off-by-one error * Generate suggestions using max point displacement threshold (#1862) * create function max_point_displacement, _max_point_displacement_video. Add to yaml file. Create test for new function . . . will need to edit * remove unnecessary for loop, calculate proper displacement, adjusted tests accordingly * Increase range for displacement threshold * Fix frames not found bug * Return the latter frame index * Lint --------- Co-authored-by: roomrys <38435167+roomrys@users.noreply.github.com> * Added Three Different Cases for Adding a New Instance (#1859) * implemented paste with offset * right click and then default will paste the new instance at the location of the cursor * modified the logics for creating new instance * refined the logic * fixed the logic for right click * refined logics for adding new instance at a specific location * Remove print statements * Comment code * Ensure that we choose a non nan reference node * Move OOB nodes to closest in-bounds position --------- Co-authored-by: roomrys <38435167+roomrys@users.noreply.github.com> * Allow csv and text file support on sleap track (#1875) * initial changes * csv support and test case * increased code coverage * Error fixing, black, deletion of (self-written) unused code * final edits * black * documentation changes * documentation changes * Fix GUI crash on scroll (#1883) * Only pass wheelEvent to children that can handle it * Add test for wheelEvent * Fix typo to allow rendering videos with mp4 (Mac) (#1892) Fix typo to allow rendering videos with mp4 * Do not apply offset when double clicking a `PredictedInstance` (#1888) * Add offset argument to newInstance and AddInstance * Apply offset of 10 for Add Instance menu button (Ctrl + I) * Add offset for docks Add Instance button * Make the QtVideoPlayer context menu unit-testable * Add test for creating a new instance * Add test for "New Instance" button in `InstancesDock` * Fix typo in docstring * Add docstrings and typehinting * Remove unused imports and sort imports * Refactor video writer to use imageio instead of skvideo (#1900) * modify `VideoWriter` to use imageio with ffmpeg backend * check to see if ffmpeg is present * use the new check for ffmpeg * import imageio.v2 * add imageio-ffmpeg to environments to test * using avi format for now * remove SKvideo videowriter * test `VideoWriterImageio` minimally * add more documentation for ffmpeg * default mp4 for ffmpeg should be mp4 * print using `IMAGEIO` when using ffmpeg * mp4 for ffmpeg * use mp4 ending in test * test `VideoWriterImageio` with avi file extension * test video with odd size * remove redundant filter since imageio-ffmpeg resizes automatically * black * remove unused import * use logging instead of print statement * import cv2 is needed for resize * remove logging * Use `Video.from_filename` when structuring videos (#1905) * Use Video.from_filename when structuring videos * Modify removal_test_labels to have extension in filename * Use | instead of + in key commands (#1907) * Use | instead of + in key commands * Lint * Replace QtDesktop widget in preparation for PySide6 (#1908) * Replace to-be-depreciated QDesktopWidget * Remove unused imports and sort remaining imports * Remove unsupported |= operand to prepare for PySide6 (#1910) Fixes TypeError: unsupported operand type(s) for |=: 'int' and 'Option' * Use positional argument for exception type (#1912) traceback.format_exception has changed it's first positional argument's name from etype to exc in python 3.7 to 3.10 * Replace all Video structuring with Video.cattr() (#1911) * Remove unused AsyncVideo class (#1917) Remove unused AsyncVideo * Refactor `LossViewer` to use matplotlib (#1899) * use updated syntax for QtAgg backend of matplotlib * start add features to `MplCanvas` to replace QtCharts features in `LossViewer` (untested) * remove QtCharts imports and replace with MplCanvas * remove QtCharts imports and replace with MplCanvas * start using MplCanvas in LossViwer instead of QtCharts (untested) * use updated syntax * Uncomment all commented out QtChart * Add debug code * Refactor monitor to use LossViewer._init_series method * Add monitor only debug code * Add methods for setting up axes and legend * Add the matplotlib canvas to the widget * Resize axis with data (no log support yet) * Try using PathCollection for "batch" * Get "batch" plotting with ax.scatter (no log support yet) * Add log support * Add a _resize_axis method * Modify init_series to work for ax.plot as well * Use matplotlib to plot epoch_loss line * Add method _add_data_to_scatter * Add _add_data_to_plot method * Add docstring to _resize_axes * Add matplotlib plot for val_loss * Add matplotlib scatter for val_loss_best * Avoid errors with setting log scale before any positive values * Add x and y axes labels * Set title (removing html tags) * Add legend * Adjust positioning of plot * Lint * Leave MplCanvas unchanged * Removed unused training_monitor.LossViewer * Resize fonts * Move legend outside of plot * Add debug code for montitor aesthetics * Use latex formatting to bold parts of title * Make axes aesthetic * Add midpoint grid lines * Set initial limits on x and y axes to be 0+ * Ensure x axis minimum is always resized to 0+ * Adjust plot to account for plateau patience title * Add debug code for plateau patience title line * Lint * Set thicker line width * Remove unused import * Set log axis on initialization * Make tick labels smaller * Move plot down a smidge * Move ylabel left a bit * Lint * Add class LossPlot * Refactor LossViewer to use LossPlot * Remove QtCharts code * Remove debug codes * Allocate space for figure items based on item's size * Refactor LossPlot to use underscores for internal methods * Ensure y_min, y_max not equal 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) --------- Co-authored-by: roomrys <lmaree@ucsd.edu> Co-authored-by: roomrys <38435167+roomrys@users.noreply.github.com> * Refactor `LossViewer` to use underscores for internal method names (#1919) Refactor LossViewer to use underscores for internal method names * Manually handle `Instance.from_predicted` structuring when not `None` (#1930) * Use `tf.math.mod` instead of `%` (#1931) * Option for Max Stride to be 128 (#1941) Co-authored-by: Max Weinberg <maxweinberg85@gmail.com> * Add discussion comment workflow (#1945) * Add a bot to autocomment on workflow * Use github markdown warning syntax * Add a multiline warning * Change happy coding to happy SLEAPing Co-authored-by: Talmo Pereira <talmo@salk.edu> --------- Co-authored-by: roomrys <lmaree@ucsd.edu> Co-authored-by: Talmo Pereira <talmo@salk.edu> * Add comment on issue workflow (#1946) * Add workflow to test conda packages (#1935) * Add missing imageio-ffmpeg to meta.ymls (#1943) * Update installation docs 1.4.1 (#1810) * [wip] Updated installation docs * Add tabs for different OS installations * Move installation methods to tabs * Use tabs.css * FIx styling error (line under last tab in terminal hint) * Add installation instructions before TOC * Replace mamba with conda * Lint * Find good light colors not switching when change dark/light themes * Get color scheme switching with dark/light toggle button * Upgrade website build dependencies * Remove seemingly unneeded dependencies from workflow * Add myst-nb>=0.16.0 lower bound * Trigger dev website build * Fix minor typo in css * Add miniforge and one-liner installs for package managers --------- Co-authored-by: roomrys <lmaree@ucsd.edu> Co-authored-by: Talmo Pereira <talmo@salk.edu> * Add imageio dependencies for pypi wheel (#1950) Add imagio dependencies for pypi wheel Co-authored-by: roomrys <lmaree@ucsd.edu> * Do not always color skeletons table black (#1952) Co-authored-by: roomrys <lmaree@ucsd.edu> * Remove no module named work error (#1956) * Do not always color skeletons table black * Remove offending (possibly unneeded) line that causes the no module named work error to print in terminal * Remove offending (possibly unneeded) line that causes the no module named work error to print in terminal * Remove accidentally added changes * Add (failing) test to ensure menu-item updates with state change * Reconnect callback for menu-item (using lambda) * Add (failing) test to ensure menu-item updates with state change Do not assume inital state * Reconnect callback for menu-item (using lambda) --------- Co-authored-by: roomrys <lmaree@ucsd.edu> * Add `normalized_instance_similarity` method (#1939) * Add normalize function * Expose normalization function * Fix tests * Expose object keypoint sim function * Fix tests * Handle skeleton decoding internally (#1961) * Reorganize (and add) imports * Add (and reorganize) imports * Modify decode_preview_image to return bytes if specified * Implement (minimally tested) replace_jsonpickle_decode * Add support for using idx_to_node map i.e. loading from Labels (slp file) * Ignore None items in reduce_list * Convert large function to SkeletonDecoder class * Update SkeletonDecoder.decode docstring * Move decode_preview_image to SkeletonDecoder * Use SkeletonDecoder instead of jsonpickle in tests * Remove unused imports * Add test for decoding dict vs tuple pystates * Handle skeleton encoding internally (#1970) * start class `SkeletonEncoder` * _encoded_objects need to be a dict to add to * add notebook for testing * format * fix type in docstring * finish classmethod for encoding Skeleton as a json string * test encoded Skeleton as json string by decoding it * add test for decoded encoded skeleton * update jupyter notebook for easy testing * constraining attrs in dev environment to make sure decode format is always the same locally * encode links first then encode source then target then type * save first enconding statically as an input to _get_or_assign_id so that we do not always get py/id * save first encoding statically * first encoding is passed to _get_or_assign_id * use first_encoding variable to determine if we should assign a py/id * add print statements for debugging * update notebook for easy testing * black * remove comment * adding attrs constraint to show this passes for certain attrs version only * add import * switch out jsonpickle.encode * oops remove import * can attrs be unconstrained? * forgot comma * pin attrs for testing * test Skeleton from json, template, with symmetries, and template * use SkeletonEncoder.encode * black * try removing None values in EdgeType reduced * Handle case when nodes are replaced by integer indices from caller * Remove prototyping notebook * Remove attrs pins * Remove sort keys (which flips the neccessary ordering of our py/ids) * Do not add extra indents to encoded file * Only append links after fully encoded (fat-finger) * Remove outdated comment * Lint --------- Co-authored-by: Talmo Pereira <talmo@salk.edu> Co-authored-by: roomrys <38435167+roomrys@users.noreply.github.com> * Pin ndx-pose<0.2.0 (#1978) * Pin ndx-pose<0.2.0 * Typo * Sort encoded `Skeleton` dictionary for backwards compatibility (#1975) * Add failing test to check that encoded Skeleton is sorted * Sort Skeleton dictionary before encoding * Remove unused import * Disable comment bot for now * Fix COCO Dataset Loading for Invisible Keypoints (#2035) Update coco.py # Fix COCO Dataset Loading for Invisible Keypoints ## Issue When loading COCO datasets, keypoints marked as invisible (flag=0) are currently skipped and later placed randomly within the instance's bounding box. However, in COCO format, these keypoints may still have valid coordinate information that should be preserved (see toy_dataset for expected vs. current behavior). ## Changes Modified the COCO dataset loading logic to: - Check if invisible keypoints (flag=0) have non-zero coordinates - If coordinates are (0,0), skip the point (existing behavior) - If coordinates are not (0,0), create the point at those coordinates but mark it as not visible - Maintain existing behavior for visible (flag=2) and labeled * Lint * Add tracking score as seekbar header options (#2047) * Add `tracking_score` as a constructor arg for `PredictedInstance` * Add `tracking_score` to ID models * Add fixture with tracking scores * Add tracking score to seekbar header * Add bonsai guide for sleap docs (#2050) * [WIP] Add bonsai guide page * Add more information to the guide with images * add branch for website build * Typos * fix links * Include suggestions * Add more screenshots and refine the doc * Remove branch from website workflow * Completed documentation edits from PR made by reviewer + review bot. --------- Co-authored-by: Shrivaths Shyam <52810689+shrivaths16@users.noreply.github.com> Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Don't mark complete on instance scaling (#2049) * Add check for instances with track assigned before training ID models (#2053) * Add menu item for deleting instances beyond frame limit (#1797) * Add menu item for deleting instances beyond frame limit * Add test function to test the instances returned * typos * Update docstring * Add frame range form * Extend command to use frame range --------- Co-authored-by: Talmo Pereira <talmo@salk.edu> * Highlight instance box on hover (#2055) * Make node marker and label sizes configurable via preferences (#2057) * Make node marker and label sizes configurable via preferences * Fix test * Enable touchpad pinch to zoom (#2058) * Fix import PySide2 -> qtpy (#2065) * Fix import PySide2 -> qtpy * Remove unnecessary print statements. * Add channels for pip conda env (#2067) * Add channels for pypi conda env * Trigger dev website build * Separate the video name and its filepath columns in `VideoTablesModel` (#2052) * add option to show video names with filepath * add doc * new feature added successfully * delete unnecessary code * remove attributes from video object * Update dataviews.py * remove all properties * delete toggle option * remove video show * fix the order of the columns * remove options * Update sleap/gui/dataviews.py Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Update sleap/gui/dataviews.py Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * use pathlib instead of substrings * Update dataviews.py Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Use Path instead of pathlib.Path and sort imports and remove unused imports * Use item.filename instead of getattr --------- Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Make status bar dependent on UI mode (#2063) * remove bug for dark mode * fix toggle case --------- Co-authored-by: Liezl Maree <38435167+roomrys@users.noreply.github.com> * Bump version to 1.4.1 (#2062) * Bump version to 1.4.1 * Trigger conda/pypi builds (no upload) * Trigger website build * Add dev channel to installation instructions --------- Co-authored-by: Talmo Pereira <talmo@salk.edu> * Add -c sleap/label/dev channel for win/linux - also trigger website build --------- Co-authored-by: Scott Yang <67733409+scott-yj-yang@users.noreply.github.com> Co-authored-by: Shrivaths Shyam <52810689+shrivaths16@users.noreply.github.com> Co-authored-by: getzze <getzze@gmail.com> Co-authored-by: Lili Karashchuk <krchtchk@gmail.com> Co-authored-by: Sidharth Srinath <69165889+ssrinath22@users.noreply.github.com> Co-authored-by: sidharth srinath <sidhumani22@gmail.com> Co-authored-by: Talmo Pereira <talmo@salk.edu> Co-authored-by: KevinZ0217 <96039456+KevinZ0217@users.noreply.github.com> Co-authored-by: Elizabeth <106755962+eberrigan@users.noreply.github.com> Co-authored-by: Talmo Pereira <talmo@princeton.edu> Co-authored-by: eberrigan <berri104@gmail.com> Co-authored-by: vaibhavtrip29 <82742234+vaibhavtrip29@users.noreply.github.com> Co-authored-by: Keya Loding <117320751+keyaloding@users.noreply.github.com> Co-authored-by: Keya Loding <keya@Keyas-MacBook-Air.local> Co-authored-by: Hajin Park <hajin1819@gmail.com> Co-authored-by: Elise Davis <elisemdavis02@gmail.com> Co-authored-by: gqcpm <63070177+gqcpm@users.noreply.github.com> Co-authored-by: Andrew Park <hep003@ucsd.edu> Co-authored-by: roomrys <lmaree@ucsd.edu> Co-authored-by: MweinbergUmass <143860933+MweinbergUmass@users.noreply.github.com> Co-authored-by: Max Weinberg <maxweinberg85@gmail.com> Co-authored-by: DivyaSesh <64513125+gitttt-1234@users.noreply.github.com> Co-authored-by: Felipe Parodi <53239931+felipe-parodi@users.noreply.github.com> Co-authored-by: croblesMed <carlosrobles00001@gmail.com>
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 updatedPySide6
We are only using
QtCharts
in theLossViewer
, so, in this PR, we replaceQtCharts
withmatplotlib
. ALossPlot
class that subclassesMplCanvas
is added to handle the plotting functionality previously mixed intoLossViewer
. The unused duplicate of theLossViewer
in training_monitor.py is removed. To maintain scope, the refactoredLossViewer
re-uses same logic and only replacesQtCharts
withmatplotlib
.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
Does this address any currently open issues?
Outside contributors checklist
Thank you for contributing to SLEAP!
❤️
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Bug Fixes
Refactor