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(data): Throw error when data's element is not present in input.json/type_map #4639

Merged
merged 5 commits into from
Mar 6, 2025

Conversation

Chengqian-Zhang
Copy link
Collaborator

@Chengqian-Zhang Chengqian-Zhang commented Mar 6, 2025

See issue #4519 .
When there are elements in the data that are not present in input.json, no error will be reported. For example, when element D is in type_map.raw, but D is not in type_map of input.json, the training process is normal. This error appears when self.mixed_type=True.

Summary by CodeRabbit

  • New Features

    • Introduced enhanced data validation to ensure the atom type mapping is complete and consistent. Users will now receive clear error notifications if there are discrepancies in the provided mapping.
  • Tests

    • Added a new test class to verify correct data initialization and validate that errors are raised appropriately for invalid atom type mappings.

@github-actions github-actions bot added the Python label Mar 6, 2025
Copy link
Contributor

coderabbitai bot commented Mar 6, 2025

📝 Walkthrough

Walkthrough

The changes add a validation step in the __init__ method of the DeepmdData class to ensure that every atom type declared in self.type_map is present in the provided type_map, raising a ValueError if not. In addition, new unit tests in the TestDataMixType class have been introduced to validate both successful initialization and error handling when an invalid type map is passed. An existing test was also updated to include this error check.

Changes

File Change Summary
deepmd/utils/data.py Added a validation step in the DeepmdData.__init__ method to check that all entries in self.type_map exist in the provided type_map; raises a ValueError if missing.
source/tests/tf/test_deepmd_data.py Introduced TestDataMixType with tests for proper initialization and error handling of the type map; modified an existing test to check for ValueError on invalid maps.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant DeepmdData.__init__

    Caller->>DeepmdData.__init__: Initialize with type_map & self.type_map
    DeepmdData.__init__->>DeepmdData.__init__: Check if type_map and self.type_map are non-empty
    DeepmdData.__init__->>DeepmdData.__init__: Validate each element in self.type_map against provided type_map
    alt Missing types found
        DeepmdData.__init__->>Caller: Raise ValueError with missing types
    else
        DeepmdData.__init__->>Caller: Proceed with initialization
    end
Loading

Possibly related PRs

  • docs: improve error message for inconsistent type maps #4074: The changes in the main PR, which introduce validation for the type_map in the DeepmdData class, are related to the enhancements made in the retrieved PR that improve error messaging for type map inconsistencies, as both address error handling related to type maps.

Suggested reviewers

  • njzjz
  • iProzd
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@Chengqian-Zhang
Copy link
Collaborator Author

Chengqian-Zhang commented Mar 6, 2025

image
This bug appends because there is no error reported in np.searchsorted method even when type_map and self.type_map are totally different.

@Chengqian-Zhang Chengqian-Zhang requested a review from njzjz March 6, 2025 11:02
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: 0

🧹 Nitpick comments (2)
source/tests/tf/test_deepmd_data.py (2)

455-458: Address unused variable warning.

The variable dd is assigned but never used, triggering a static analysis warning.

-    def test_init_type_map_error(self) -> None:
-        with self.assertRaises(ValueError):
-            dd = DeepmdData(self.data_name, type_map=["foo"])
+    def test_init_type_map_error(self) -> None:
+        with self.assertRaises(ValueError):
+            DeepmdData(self.data_name, type_map=["foo"])
🧰 Tools
🪛 Ruff (0.8.2)

457-457: Local variable dd is assigned to but never used

Remove assignment to unused variable dd

(F841)


180-183: Address unused variable warning in TestData class.

Similar to the other test, the variable dd is assigned but never used.

-    def test_init_type_map_error(self) -> None:
-        with self.assertRaises(ValueError):
-            dd = DeepmdData(self.data_name, type_map=["bar"])
+    def test_init_type_map_error(self) -> None:
+        with self.assertRaises(ValueError):
+            DeepmdData(self.data_name, type_map=["bar"])
🧰 Tools
🪛 Ruff (0.8.2)

182-182: Local variable dd is assigned to but never used

Remove assignment to unused variable dd

(F841)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 65812b8 and 534d620.

📒 Files selected for processing (2)
  • deepmd/utils/data.py (1 hunks)
  • source/tests/tf/test_deepmd_data.py (2 hunks)
🧰 Additional context used
🪛 Ruff (0.8.2)
source/tests/tf/test_deepmd_data.py

182-182: Local variable dd is assigned to but never used

Remove assignment to unused variable dd

(F841)


457-457: Local variable dd is assigned to but never used

Remove assignment to unused variable dd

(F841)

⏰ Context from checks skipped due to timeout of 90000ms (16)
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Test Python (5, 3.12)
  • GitHub Check: Test Python (4, 3.12)
  • GitHub Check: Test Python (4, 3.9)
  • GitHub Check: Test Python (3, 3.12)
  • GitHub Check: Test Python (3, 3.9)
  • GitHub Check: Test Python (2, 3.12)
  • GitHub Check: Test Python (2, 3.9)
  • GitHub Check: Test Python (1, 3.12)
  • GitHub Check: Test Python (1, 3.9)
  • GitHub Check: Analyze (python)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Test C++ (false)
  • GitHub Check: Test C++ (true)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
🔇 Additional comments (3)
deepmd/utils/data.py (1)

92-96: Well-implemented validation check.

This change adds proper validation to ensure all elements in self.type_map are present in the provided type_map. The error message clearly identifies which elements are missing, helping users quickly diagnose the issue.

source/tests/tf/test_deepmd_data.py (2)

180-183: Good addition of error handling test case.

Adding a test case that verifies the ValueError is raised when an incomplete type map is provided ensures the new validation in DeepmdData is working as expected.

🧰 Tools
🪛 Ruff (0.8.2)

182-182: Local variable dd is assigned to but never used

Remove assignment to unused variable dd

(F841)


385-454: Well-designed test class for mixed type testing.

This new test class properly sets up test data with mixed atom types and validates the behavior of DeepmdData when working with mixed types. The setup method is thorough in creating all necessary test files and data.

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

🧹 Nitpick comments (1)
source/tests/tf/test_deepmd_data.py (1)

385-461: Well-structured test class for mixed type scenario.

Good addition of the TestDataMixType class that specifically tests the behavior when handling mixed atom types. The setup method properly initializes test data including coordinates, boxes, and real atom types across multiple sets. The test methods appropriately verify both the successful initialization with a valid type map and error handling with an invalid type map.

One suggestion: consider adding a test case that verifies the error message content to ensure it provides clear guidance to users.

You could enhance the error test by verifying the specific error message:

 def test_init_type_map_error(self) -> None:
-    with self.assertRaises(ValueError):
+    with self.assertRaisesRegex(ValueError, "Some atom types.*not found in.*type_map"):
         DeepmdData(self.data_name, type_map=["foo"])
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 534d620 and 7ce0ea2.

📒 Files selected for processing (1)
  • source/tests/tf/test_deepmd_data.py (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (18)
  • GitHub Check: Build wheels for cp310-manylinux_aarch64
  • GitHub Check: Build wheels for cp311-win_amd64
  • GitHub Check: Build wheels for cp311-macosx_arm64
  • GitHub Check: Build wheels for cp311-macosx_x86_64
  • GitHub Check: Test C++ (false)
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Test C++ (true)
  • GitHub Check: Build wheels for cp311-manylinux_x86_64
  • GitHub Check: Analyze (python)
  • GitHub Check: Build C library (2.14, >=2.5.0rc0,<2.15, libdeepmd_c_cu11.tar.gz)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build C library (2.18, libdeepmd_c.tar.gz)
  • GitHub Check: Build C++ (clang, clang)
  • GitHub Check: Analyze (c-cpp)
  • GitHub Check: Build C++ (rocm, rocm)
  • GitHub Check: Build C++ (cuda120, cuda)
  • GitHub Check: Build C++ (cuda, cuda)
  • GitHub Check: Build C++ (cpu, cpu)
🔇 Additional comments (3)
source/tests/tf/test_deepmd_data.py (3)

180-183: Good addition of error test case.

This test verifies that a ValueError is thrown when an invalid type map (with only one type) is provided, which helps catch configuration errors early.


446-454: Thorough verification of type mapping properties.

The test properly verifies all relevant properties related to type mapping:

  1. enforce_type_map flag is correctly set
  2. type_map contents match expected values
  3. mixed_type is correctly set to True
  4. Type index mappings are correctly established

This ensures that the type mapping system works as intended.


455-458: Appropriate error test matches the existing TestData error test.

This test correctly verifies that an error is thrown when an invalid type map is provided, aligning with the similar test in the TestData class.

@njzjz
Copy link
Member

njzjz commented Mar 6, 2025

This bug appends because there is no error reported in np.searchsorted method even when type_map and self.type_map are totally different.

There is another np.searchsorted that may also be critical. cc @iProzd

idx_type_map = sorter[
np.searchsorted(full_type_map, origin_type_map, sorter=sorter)
]

@njzjz njzjz linked an issue Mar 6, 2025 that may be closed by this pull request
@njzjz njzjz enabled auto-merge March 6, 2025 11:56
Copy link

codecov bot commented Mar 6, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 84.64%. Comparing base (65812b8) to head (7ce0ea2).
Report is 1 commits behind head on devel.

Additional details and impacted files
@@            Coverage Diff             @@
##            devel    #4639      +/-   ##
==========================================
- Coverage   84.78%   84.64%   -0.14%     
==========================================
  Files         688      688              
  Lines       66091    66094       +3     
  Branches     3539     3539              
==========================================
- Hits        56032    55944      -88     
- Misses       8918     9013      +95     
+ Partials     1141     1137       -4     

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

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@njzjz njzjz added this pull request to the merge queue Mar 6, 2025
Merged via the queue into deepmodeling:devel with commit e4eb01f Mar 6, 2025
60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] No error reported when data's element is not present in input.json
3 participants