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 numb_fparam & numb_aparam to dipole & polar fitting #4405

Merged
merged 2 commits into from
Nov 23, 2024

Conversation

njzjz
Copy link
Member

@njzjz njzjz commented Nov 22, 2024

Fix #4396. Fix #4397. Fix #4398. Throw errors for TF.

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new parameters numb_fparam and numb_aparam for improved fitting configurations in both dipole and polar fitting classes.
    • Added methods to retrieve the values of the new parameters and enhanced input requirement management.
  • Documentation

    • Updated training documentation to clarify the handling of new parameters and their limitations in the TensorFlow backend.
  • Bug Fixes

    • Updated test configurations to reflect the new parameter structure, ensuring consistency across tests for dipole and polar models.

Fix deepmodeling#4396. Fix deepmodeling#4397. Fix deepmodeling#4398. Throw errors for TF.

Signed-off-by: Jinzhe Zeng <jinzhe.zeng@rutgers.edu>
Copy link
Contributor

@Copilot Copilot AI left a comment

Choose a reason for hiding this comment

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

Copilot reviewed 5 out of 7 changed files in this pull request and generated 1 suggestion.

Files not reviewed (2)
  • deepmd/tf/fit/polar.py: Evaluated as low risk
  • deepmd/utils/argcheck.py: Evaluated as low risk

deepmd/tf/fit/dipole.py Outdated Show resolved Hide resolved
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Signed-off-by: Jinzhe Zeng <jinzhe.zeng@rutgers.edu>
Copy link
Contributor

coderabbitai bot commented Nov 22, 2024

📝 Walkthrough
📝 Walkthrough

Walkthrough

The pull request introduces modifications to the DipoleFittingSeA and PolarFittingSeA classes, adding two new parameters, numb_fparam and numb_aparam, to their constructors. These parameters are validated and included in the serialization process. New methods for retrieving these parameters and a property for input requirements have also been added. Additionally, updates were made to the fitting_polar and fitting_dipole functions in argcheck.py to incorporate the new parameters. Documentation and test files have been adjusted to reflect these changes.

Changes

File Change Summary
deepmd/tf/fit/dipole.py Added numb_fparam and numb_aparam to DipoleFittingSeA constructor; updated serialize, added input_requirement, get_numb_fparam, and get_numb_aparam methods.
deepmd/tf/fit/polar.py Added numb_fparam and numb_aparam to PolarFittingSeA constructor; updated serialize, added input_requirement, get_numb_fparam, and get_numb_aparam methods in GlobalPolarFittingSeA.
deepmd/utils/argcheck.py Updated fitting_polar and fitting_dipole functions to include numb_fparam and numb_aparam.
doc/model/train-fitting-tensor.md Updated documentation to reflect changes regarding tensorial properties and parameter support.
source/tests/consistent/model/test_dipole.py Updated data property to include numb_fparam.
source/tests/consistent/model/test_polar.py Updated data property to include numb_fparam.
source/tests/consistent/model/test_property.py Updated data property to include numb_fparam.

Assessment against linked issues

Objective Addressed Explanation
Add numb_fparam argument to property fitting (##4396)
Add numb_fparam argument to polar fitting (##4397)
Add numb_fparam argument to dipole fitting (##4398)

Possibly related PRs

Suggested labels

Python, Docs

Suggested reviewers

  • wanghan-iapcm
  • anyangml

📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 42e9f98 and b4d1418.

📒 Files selected for processing (1)
  • deepmd/tf/fit/dipole.py (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • deepmd/tf/fit/dipole.py

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

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

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

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@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

🧹 Outside diff range and nitpick comments (5)
source/tests/consistent/model/test_dipole.py (1)

65-65: Consider adding more test cases for better coverage.

The test suite would benefit from additional test cases to validate:

  1. Error handling for invalid numb_fparam values (> 0)
  2. Different valid numb_fparam values
  3. The new numb_aparam parameter mentioned in PR objectives

Here's a suggested approach to add these test cases:

def test_invalid_numb_fparam(self):
    """Test that ValueError is raised when numb_fparam > 0."""
    invalid_data = self.data.copy()
    invalid_data["fitting_net"]["numb_fparam"] = 1
    with self.assertRaises(ValueError):
        self.pass_data_to_cls(self.dp_class, invalid_data)

def test_numb_aparam(self):
    """Test configuration with numb_aparam parameter."""
    data_with_aparam = self.data.copy()
    data_with_aparam["fitting_net"]["numb_aparam"] = 0
    model = self.pass_data_to_cls(self.dp_class, data_with_aparam)
    self.assertEqual(model.get_numb_aparam(), 0)
doc/model/train-fitting-tensor.md (1)

250-250: Enhance the documentation of TensorFlow backend limitations

While the note about TensorFlow's limitations is accurate, consider enhancing it to be more helpful to users:

  1. Make it more prominent by moving it to a warning/caution block
  2. Add context about why these parameters aren't supported
  3. Provide guidance on alternatives if available

Consider updating the note like this:

-The TensorFlow backend does not support {ref}`numb_fparam <model[standard]/fitting_net[dipole]/numb_fparam>` and {ref}`numb_aparam <model[standard]/fitting_net[dipole]/numb_aparam>`.
+:::{warning}
+The TensorFlow backend does not support {ref}`numb_fparam <model[standard]/fitting_net[dipole]/numb_fparam>` and {ref}`numb_aparam <model[standard]/fitting_net[dipole]/numb_aparam>`. Attempting to use these parameters with TensorFlow will raise a ValueError. If you need these parameters, consider using PyTorch or other supported backends.
+:::
deepmd/tf/fit/dipole.py (1)

439-463: LGTM with a minor docstring enhancement suggestion

The implementation of the input_requirement property and parameter getters is correct. Consider enhancing the docstrings for the getter methods to include return type hints:

     def get_numb_fparam(self) -> int:
-        """Get the number of frame parameters."""
+        """Get the number of frame parameters.
+        
+        Returns
+        -------
+        int
+            The number of frame parameters
+        """
         return self.numb_fparam

     def get_numb_aparam(self) -> int:
-        """Get the number of atomic parameters."""
+        """Get the number of atomic parameters.
+        
+        Returns
+        -------
+        int
+            The number of atomic parameters
+        """
         return self.numb_aparam
deepmd/tf/fit/polar.py (2)

163-174: Consider improving error messages for parameter validation.

While the validation logic is correct, the error messages could be more descriptive to help users understand why these parameters are not supported.

Consider updating the error messages to be more specific:

-            raise ValueError("numb_fparam is not supported in the dipole fitting")
+            raise ValueError("Frame parameters (numb_fparam) are not supported in polar fitting as they may affect the rotational invariance of the polarizability tensor")
-            raise ValueError("numb_aparam is not supported in the dipole fitting")
+            raise ValueError("Atomic parameters (numb_aparam) are not supported in polar fitting as they may affect the rotational invariance of the polarizability tensor")

822-828: Consider adding validation in getter methods.

The getter methods get_numb_fparam and get_numb_aparam are implemented correctly, but they might benefit from additional validation to maintain consistency with the constructor's validation.

Consider updating the methods to include validation:

def get_numb_fparam(self) -> int:
    """Get the number of frame parameters."""
+   if self.numb_fparam > 0:
+       raise ValueError("Frame parameters are not supported in polar fitting")
    return self.numb_fparam

def get_numb_aparam(self) -> int:
    """Get the number of atomic parameters."""
+   if self.numb_aparam > 0:
+       raise ValueError("Atomic parameters are not supported in polar fitting")
    return self.numb_aparam
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7bd2e5a and 42e9f98.

📒 Files selected for processing (7)
  • deepmd/tf/fit/dipole.py (6 hunks)
  • deepmd/tf/fit/polar.py (6 hunks)
  • deepmd/utils/argcheck.py (3 hunks)
  • doc/model/train-fitting-tensor.md (1 hunks)
  • source/tests/consistent/model/test_dipole.py (1 hunks)
  • source/tests/consistent/model/test_polar.py (1 hunks)
  • source/tests/consistent/model/test_property.py (1 hunks)
🔇 Additional comments (13)
source/tests/consistent/model/test_property.py (1)

60-60: LGTM! Verify consistency across test files.

The addition of numb_fparam: 0 to the fitting_net configuration aligns with the PR objectives and matches the validation requirements.

Let's verify if similar changes are applied consistently in the related test files:

✅ Verification successful

Changes are consistently applied across test files

The verification shows that numb_fparam: 0 is consistently added in all relevant test files:

  • test_property.py
  • test_polar.py
  • test_dos.py
  • test_dipole.py

The implementation is uniform across the test suite, which aligns with the PR objectives to add numb_fparam support.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if numb_fparam is consistently added across test files
# Expected: Should find similar changes in test_dipole.py and test_polar.py

# Search for numb_fparam in test files
rg -A 5 "numb_fparam" "source/tests/consistent/model/test_*.py"

# Search for fitting_net dictionary definitions
ast-grep --pattern 'fitting_net = {$$$}' "source/tests/consistent/model/test_*.py"
ast-grep --pattern '"fitting_net": {$$$}' "source/tests/consistent/model/test_*.py"

Length of output: 488


Script:

#!/bin/bash
# Let's first find the test files and then search within them
# Find test files in the model directory
fd "test_.*\.py$" source/tests/consistent/model/

# Search for numb_fparam in these files
rg "numb_fparam" source/tests/consistent/model/

# Search for fitting_net dictionary definitions
rg -A 5 "fitting_net.*=.*{" source/tests/consistent/model/
rg -A 5 "\"fitting_net\".*:.*{" source/tests/consistent/model/

Length of output: 1092

source/tests/consistent/model/test_polar.py (1)

65-65: LGTM! Consider adding test cases for non-zero numb_fparam.

The addition of numb_fparam to the test data aligns with the PR objectives. However, the current test only covers the case where numb_fparam is 0.

Let's verify if there are any test cases for non-zero values:

source/tests/consistent/model/test_dipole.py (1)

65-65: LGTM! The addition of numb_fparam aligns with PR objectives.

The change correctly adds the numb_fparam parameter to the dipole fitting configuration with a default value of 0.

deepmd/tf/fit/dipole.py (4)

32-34: LGTM: Import addition is appropriate

The addition of DataRequirementItem import is necessary for implementing the new input_requirement property.


57-60: LGTM: Constructor parameters properly documented and added

The numb_fparam and numb_aparam parameters are well-documented in the class docstring and appropriately added to the constructor with default values.

Also applies to: 85-86


396-397: LGTM: Serialization properly updated

The numb_fparam and numb_aparam parameters are correctly included in the serialized output.


122-125: Verify: Parameter validation seems to contradict PR objectives

The PR aims to add numb_fparam & numb_aparam support, but the implementation raises ValueError if these parameters are greater than 0. This seems to contradict the PR objectives. Please verify if this is intentional or if the validation should be removed.

deepmd/tf/fit/polar.py (4)

62-65: LGTM: Parameter documentation is clear and consistent.

The new parameters numb_fparam and numb_aparam are well-documented in the class docstring and properly added to the constructor with appropriate default values.

Also applies to: 96-97


589-590: LGTM: Proper serialization of new parameters.

The new parameters are correctly included in the serialization method, maintaining backward compatibility.


37-39: LGTM: Clean import of DataRequirementItem.

The import of DataRequirementItem is properly placed and follows the project's import style.


804-820: Verify the input requirements implementation.

The input_requirement property correctly constructs the data requirements based on numb_fparam and numb_aparam. However, since these parameters are not supported (as per the validation in the constructor), this property will always return an empty list.

deepmd/utils/argcheck.py (2)

Line range hint 1598-1627: LGTM: Parameters added correctly to polar fitting

The addition of numb_fparam and numb_aparam parameters to the polar fitting configuration is implemented correctly with proper documentation and default values.


1668-1690: LGTM: Parameters added consistently to dipole fitting

The addition of numb_fparam and numb_aparam parameters to the dipole fitting configuration matches the implementation in polar fitting, maintaining consistency across the codebase.

deepmd/tf/fit/dipole.py Outdated Show resolved Hide resolved
Copy link

codecov bot commented Nov 22, 2024

Codecov Report

Attention: Patch coverage is 70.37037% with 16 lines in your changes missing coverage. Please review.

Project coverage is 84.63%. Comparing base (7bd2e5a) to head (b4d1418).
Report is 4 commits behind head on devel.

Files with missing lines Patch % Lines
deepmd/tf/fit/polar.py 60.00% 10 Missing ⚠️
deepmd/tf/fit/dipole.py 76.00% 6 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4405      +/-   ##
==========================================
- Coverage   84.64%   84.63%   -0.02%     
==========================================
  Files         614      614              
  Lines       57007    57061      +54     
  Branches     3486     3487       +1     
==========================================
+ Hits        48254    48293      +39     
- Misses       7627     7644      +17     
+ Partials     1126     1124       -2     

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


🚨 Try these New Features:

@wanghan-iapcm wanghan-iapcm added this pull request to the merge queue Nov 23, 2024
Merged via the queue into deepmodeling:devel with commit 2ce3276 Nov 23, 2024
60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
2 participants