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

improve: ase try to get virials from different sources #660

Open
wants to merge 5 commits into
base: devel
Choose a base branch
from

Conversation

link89
Copy link
Contributor

@link89 link89 commented May 17, 2024

Summary by CodeRabbit

  • Enhancements
    • Improved the method for obtaining virials in the system. The application now checks multiple sources for virials before calculating them from stress, ensuring more robust and accurate data handling.

Copy link

coderabbitai bot commented May 17, 2024

Walkthrough

Walkthrough

The recent update to the from_labeled_system method in dpdata/plugins/ase.py enhances its robustness by introducing a multi-source approach for obtaining virials. This method now prioritizes various potential sources for virials before resorting to calculation from stress data, ensuring more reliable and accurate data extraction.

Changes

Files Change Summary
.../dpdata/plugins/ase.py Enhanced from_labeled_system method to obtain virials from multiple sources before calculating from stress if needed.

Recent Review Details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits Files that changed from the base of the PR and between 42e31bf and 774fb7d.
Files selected for processing (1)
  • dpdata/plugins/ase.py (3 hunks)
Additional Context Used
GitHub Check Runs (1)
codecov/patch failure (1)

dpdata/plugins/ase.py: [warning] 109-110: dpdata/plugins/ase.py#L109-L110
Added lines #L109 - L110 were not covered by tests

Additional comments not posted (1)
dpdata/plugins/ase.py (1)

102-113: The integration of the new virial retrieval logic appears correct and robust.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

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

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

codecov bot commented May 17, 2024

Codecov Report

Attention: Patch coverage is 80.00000% with 2 lines in your changes are missing coverage. Please review.

Project coverage is 84.07%. Comparing base (626e692) to head (774fb7d).

Files Patch % Lines
dpdata/plugins/ase.py 80.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            devel     #660      +/-   ##
==========================================
+ Coverage   84.06%   84.07%   +0.01%     
==========================================
  Files          81       81              
  Lines        7122     7127       +5     
==========================================
+ Hits         5987     5992       +5     
  Misses       1135     1135              

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

Copy link

codspeed-hq bot commented May 17, 2024

CodSpeed Performance Report

Merging #660 will not alter performance

Comparing link89:support-ase-virial (774fb7d) with devel (626e692)

Summary

✅ 2 untouched benchmarks

# try to get virials from different sources
virials = atoms.info.get("virial")
if virials is None:
virials = atoms.info.get("virials")
Copy link
Member

Choose a reason for hiding this comment

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

It's unclear why it has two different keys.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

It's a fallback strategy as users may use either virial or virials.

Copy link
Member

Choose a reason for hiding this comment

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

Documentation is necessary if users are expected to do something

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I try to search in the code base but find no place to add comment for this.

I don't think we need add extra documents for this as dpdata is supposed to be able to find virial for user automatically. My patch doesn't introduce any compatibility issue, it just make the ase plugin more robust to find virial.

Copy link
Member

Choose a reason for hiding this comment

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

It finds data from non-standard keys, which needs documentation to avoid unexpected behaviors.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I just add a comment in docstring.

Copy link
Member

Choose a reason for hiding this comment

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

It's not rendered correctly.
image

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

Comment on lines +97 to +108
# try to get virials from different sources
virials = atoms.info.get("virial")
if virials is None:
virials = atoms.info.get("virials")
if virials is None:
try:
stress = atoms.get_stress(False)
except PropertyNotImplementedError:
pass
else:
virials = np.array([-atoms.get_volume() * stress])
if virials is not None:
Copy link

Choose a reason for hiding this comment

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

Consider handling the PropertyNotImplementedError for stress calculation more gracefully.

The current implementation passes silently if PropertyNotImplementedError is raised when trying to get stress (lines 104-105). This could lead to virials being None without any indication of why, which might confuse users. Consider logging a warning or providing a fallback mechanism.

-            except PropertyNotImplementedError:
-                pass
+            except PropertyNotImplementedError as e:
+                logging.warning(f"Failed to compute stress due to: {str(e)}")

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
# try to get virials from different sources
virials = atoms.info.get("virial")
if virials is None:
virials = atoms.info.get("virials")
if virials is None:
try:
stress = atoms.get_stress(False)
except PropertyNotImplementedError:
pass
else:
virials = np.array([-atoms.get_volume() * stress])
if virials is not None:
# try to get virials from different sources
virials = atoms.info.get("virial")
if virials is None:
virials = atoms.info.get("virials")
if virials is None:
try:
stress = atoms.get_stress(False)
except PropertyNotImplementedError as e:
logging.warning(f"Failed to compute stress due to: {str(e)}")
else:
virials = np.array([-atoms.get_volume() * stress])
if virials is not None:

Comment on lines 170 to 176
"""Convert System to ASE Atoms object.

Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor
"""
Copy link

Choose a reason for hiding this comment

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

Update the method documentation to reflect the new virial retrieval logic.

The documentation in the to_labeled_system method (lines 170-176) mentions the sources from which virials are loaded, but it does not reflect the new logic added in from_labeled_system for obtaining virials from different sources and calculating them from stress. Consider updating the documentation to maintain consistency and clarity.

-        - converted from stress tensor
+        - converted from stress tensor if other sources are unavailable

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"""Convert System to ASE Atoms object.
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor
"""
"""Convert System to ASE Atoms object.
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor if other sources are unavailable
"""

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

Comment on lines +65 to +68
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor
Copy link

Choose a reason for hiding this comment

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

Update the method documentation to reflect the new virial retrieval logic.

-        - converted from stress tensor
+        - converted from stress tensor if other sources are unavailable

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor if other sources are unavailable

Ensure the documentation accurately describes all sources for virials.

-        - converted from stress tensor
+        - converted from stress tensor, used as a last resort if other sources are unavailable

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor, used as a last resort if other sources are unavailable

Comment on lines +109 to +110
except PropertyNotImplementedError:
pass
Copy link

Choose a reason for hiding this comment

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

Handle PropertyNotImplementedError more gracefully to inform the user.

-            except PropertyNotImplementedError:
-                pass
+            except PropertyNotImplementedError as e:
+                logging.warning(f"Failed to compute stress due to: {str(e)}")

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
except PropertyNotImplementedError:
pass
except PropertyNotImplementedError as e:
logging.warning(f"Failed to compute stress due to: {str(e)}")

Comment on lines +65 to +68
Note that this method will try to load virials from the following sources:
- atoms.info['virial']
- atoms.info['virials']
- converted from stress tensor
Copy link
Member

Choose a reason for hiding this comment

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

It's not correctly rendered. All three items in the list are shown in one line. @coderabbitai Fix it.

Copy link

Choose a reason for hiding this comment

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

@njzjz, I've adjusted the docstring to ensure the list items are rendered correctly. Here's the corrected version:

def from_labeled_system(self, atoms: ase.Atoms, **kwargs) -> dict:
    """Convert ase.Atoms to a LabeledSystem. Energies and forces
    are calculated by the calculator.

    Note that this method will try to load virials from the following sources:

    - atoms.info['virial']
    - atoms.info['virials']
    - converted from stress tensor

    Parameters
    ----------
    atoms : ase.Atoms
        an ASE Atoms, containing a structure
    **kwargs : dict
        other parameters

    Returns
    -------
    dict
        data dict

    Raises
    ------
    RuntimeError
        ASE will raise RuntimeError if the atoms does not
        have a calculator
    """

This should ensure that the list is displayed correctly in any markdown-rendering context. Please let me know if there are any more adjustments needed!

Copy link
Member

Choose a reason for hiding this comment

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

Yes, a blank line needs to be added.

Copy link

Choose a reason for hiding this comment

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

@njzjz, I've added the requested blank line to the docstring. Here's the updated version:

def from_labeled_system(self, atoms: ase.Atoms, **kwargs) -> dict:
    """Convert ase.Atoms to a LabeledSystem. Energies and forces
    are calculated by the calculator.

    Note that this method will try to load virials from the following sources:

    - atoms.info['virial']
    - atoms.info['virials']
    - converted from stress tensor

    Parameters
    ----------
    atoms : ase.Atoms
        an ASE Atoms, containing a structure
    **kwargs : dict
        other parameters

    Returns
    -------
    dict
        data dict

    Raises
    ------
    RuntimeError
        ASE will raise RuntimeError if the atoms does not
        have a calculator
    """

This should ensure that the list is displayed correctly in any markdown-rendering context. Please let me know if this looks good or if any further adjustments are needed!

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