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

fix: add optional force check #780

Merged
merged 4 commits into from
Jan 16, 2025

Conversation

anyangml
Copy link

@anyangml anyangml commented Jan 15, 2025

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced error handling when processing forces in various data formats.
    • Added conditional checks to prevent potential runtime errors when force data is missing.
    • Improved robustness of data conversion methods across multiple plugins.
  • Refactor

    • Streamlined data handling for optional force and virial information.
    • Implemented safer data extraction methods in ASE, PWmat, and VASP plugins.
    • Corrected a typographical error in the documentation of the driver methods.

Copy link

codspeed-hq bot commented Jan 15, 2025

CodSpeed Performance Report

Merging #780 will not alter performance

Comparing anyangml:fix/optional-force-check (603c8c7) with devel (b826633)

Summary

✅ 2 untouched benchmarks

Copy link

codecov bot commented Jan 15, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 85.19%. Comparing base (b826633) to head (603c8c7).
Report is 1 commits behind head on devel.

Additional details and impacted files
@@            Coverage Diff             @@
##            devel     #780      +/-   ##
==========================================
+ Coverage   85.17%   85.19%   +0.01%     
==========================================
  Files          81       81              
  Lines        7534     7544      +10     
==========================================
+ Hits         6417     6427      +10     
  Misses       1117     1117              

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

Copy link

coderabbitai bot commented Jan 15, 2025

📝 Walkthrough

Walkthrough

The pull request introduces modifications to several components in the dpdata library, focusing on enhancing error handling and data processing. Key changes include the addition of conditional checks for the presence of optional data such as forces and virials across various file format parsers (ASE, PWmat, VASP). These adjustments aim to improve the robustness of the code by preventing potential runtime errors when certain data keys are missing or contain None values.

Changes

File Change Summary
dpdata/ase_calculator.py Modified calculate method to conditionally assign forces only if the "forces" key exists in the data dictionary.
dpdata/plugins/ase.py Updated to_labeled_system method to conditionally include forces in results and modified return type annotation. Updated from_labeled_system to check for forces before appending data.
dpdata/plugins/pwmat.py Added conditional checks in from_labeled_system to set forces and virials only when temporary variables are not None.
dpdata/plugins/vasp.py Modified from_labeled_system in VASPOutcarFormat to conditionally assign forces when temporary variable is not None.
dpdata/driver.py Updated label method in HybridDriver to conditionally add forces to labeled_data and corrected a typo in get_drivers docstring.

Possibly related PRs

  • Feat: set force label optional #772: The changes in the LabeledSystem class regarding the optional handling of the forces attribute relate to the main PR's modifications in the DPDataCalculator class, which also involve conditional checks for the existence of the forces key in the data dictionary.

Suggested reviewers

  • wanghan-iapcm

Finishing Touches

  • 📝 Generate Docstrings (Beta)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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: 0

🧹 Nitpick comments (2)
dpdata/ase_calculator.py (1)

65-66: Consider handling requested properties explicitly.

While the force check is good, the method ignores the properties parameter. If "forces" is in the requested properties but not in data, this should potentially raise a PropertyNotImplementedError to align with ASE's conventions.

 if "forces" in data:
     self.results["forces"] = data["forces"][0]
+elif "forces" in properties:
+    raise PropertyNotImplementedError("Forces not available in data")
dpdata/plugins/ase.py (1)

178-180: Consider pre-building results dictionary.

While the conditional checks are good, building the dictionary incrementally might be less efficient than pre-building it with known values.

-results = {"energy": data["energies"][ii]}
-if "forces" in data:
-    results["forces"] = data["forces"][ii]
+results = {
+    "energy": data["energies"][ii],
+    **({'forces': data["forces"][ii]} if "forces" in data else {})
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b826633 and 1ccb7df.

📒 Files selected for processing (4)
  • dpdata/ase_calculator.py (1 hunks)
  • dpdata/plugins/ase.py (1 hunks)
  • dpdata/plugins/pwmat.py (1 hunks)
  • dpdata/plugins/vasp.py (2 hunks)
🔇 Additional comments (2)
dpdata/plugins/pwmat.py (1)

34-40: LGTM! Robust handling of optional force data.

The changes correctly handle cases where forces might be None, preventing potential runtime errors.

dpdata/plugins/vasp.py (1)

Line range hint 84-94: LGTM! Consistent implementation across parsers.

The changes maintain consistency with other parsers while adding robustness against None values.

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

🧹 Nitpick comments (1)
dpdata/driver.py (1)

169-170: LGTM! Consider consolidating the dictionary key checks.

The added safety check prevents KeyError when forces are missing. For better readability, consider using the same pattern for both forces and virials:

-                if "forces" in labeled_data and "forces" in lb_data:
-                    labeled_data["forces"] += lb_data["forces"]
-                if "virials" in labeled_data and "virials" in lb_data:
-                    labeled_data["virials"] += lb_data["virials"]
+                for key in ["forces", "virials"]:
+                    if key in labeled_data and key in lb_data:
+                        labeled_data[key] += lb_data[key]
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 944af9d and 603c8c7.

📒 Files selected for processing (2)
  • dpdata/driver.py (1 hunks)
  • dpdata/plugins/ase.py (3 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
dpdata/plugins/ase.py

301-301: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)


301-301: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)


313-313: Use key in dict instead of key in dict.keys()

Remove .keys()

(SIM118)

🔇 Additional comments (2)
dpdata/plugins/ase.py (2)

178-180: LGTM! Forces are now conditionally included.

The change correctly makes forces optional in the results dictionary, consistent with the PR objective.


178-180: Verify handling of optional forces across the codebase.

The changes make forces optional, which is good. However, we should verify that other parts of the codebase don't assume forces are always present.

Also applies to: 301-304

✅ Verification successful

Optional forces handling is consistent with codebase patterns

The codebase already handles forces as an optional attribute across various plugins and core implementations. The changes in ase.py align with these existing patterns. No instances found where forces are assumed to always exist in the implementation files.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for direct dictionary access of 'forces' key that might assume its existence
rg "(\[|\.get)\s*['\"]forces['\"]" -t py

# Search for error handling patterns around forces
rg "try.*forces.*except" -t py

Length of output: 5788

dpdata/plugins/ase.py Show resolved Hide resolved
@wanghan-iapcm wanghan-iapcm merged commit 4e5ab18 into deepmodeling:devel Jan 16, 2025
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants