Skip to content

Conversation

@anyangml
Copy link
Contributor

@anyangml anyangml commented Jun 4, 2025

This PR should fix #831

Summary by CodeRabbit

  • New Features

    • Enhanced support for additional data fields, allowing handling and persistence of "fparam" and "aparam" in labeled systems.
  • Tests

    • Added tests to verify correct handling and round-trip persistence of the new "fparam" and "aparam" fields in labeled systems.

njzjz and others added 2 commits March 20, 2025 11:30
<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

- **Chores**
- Updated developer tooling configurations to use a newer linting hook
version.
- **Refactor**
- Streamlined structure processing so that magnetic data is included
only when defined, resulting in cleaner output.
- Optimized coordinate adjustments with vectorized operations for
improved performance.
- **Tests**
- Cleaned up test data by removing redundant magnetic moment fields from
atomic position entries.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@anyangml anyangml changed the base branch from master to devel June 4, 2025 10:44
@codspeed-hq
Copy link

codspeed-hq bot commented Jun 4, 2025

CodSpeed Performance Report

Merging #832 will not alter performance

Comparing anyangml:fix/fparam-to-mixed (13d1dad) with devel (10fca12)

Summary

✅ 2 untouched benchmarks

@codecov
Copy link

codecov bot commented Jun 4, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.36%. Comparing base (35a0af0) to head (13d1dad).
⚠️ Report is 54 commits behind head on devel.

Additional details and impacted files
@@            Coverage Diff             @@
##            devel     #832      +/-   ##
==========================================
+ Coverage   85.33%   85.36%   +0.02%     
==========================================
  Files          82       82              
  Lines        7515     7528      +13     
==========================================
+ Hits         6413     6426      +13     
  Misses       1102     1102              

☔ 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.

@coderabbitai
Copy link

coderabbitai bot commented Jun 4, 2025

📝 Walkthrough

Walkthrough

The to_system_data function in dpdata/deepmd/mixed.py was updated to support partitioning and handling of optional "fparam" and "aparam" fields when processing mixed DeepMD datasets. Corresponding tests were added to verify correct persistence and loading of these fields. No changes were made to public APIs or function signatures.

Changes

File(s) Change Summary
dpdata/deepmd/mixed.py Updated to_system_data to correctly partition and assign optional "fparam" and "aparam" fields if present.
tests/test_deepmd_mixed.py Added TestMixedSystemWithFparamAparam to test persistence and integrity of "fparam" and "aparam" fields.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant System (dpdata)
    participant FileSystem

    User->>System (dpdata): Save MultiSystem with fparam/aparam
    System (dpdata)->>FileSystem: Write set.XXX/fparam.npy, aparam.npy

    User->>System (dpdata): Load MultiSystem from DeepMD mixed format
    System (dpdata)->>FileSystem: Read set.XXX/fparam.npy, aparam.npy
    System (dpdata)->>System (dpdata): Partition fparam/aparam per system
    System (dpdata)-->>User: Return MultiSystem with correct fparam/aparam shapes
Loading

Assessment against linked issues

Objective Addressed Explanation
Correctly partition and assign fparam (and aparam) fields when loading/saving MultiSystems (#831)
Ensure no shape mismatch errors for fparam/aparam in DeepMD mixed format (#831)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Possibly related PRs

Suggested reviewers

  • wanghan-iapcm
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 08aefba and c04d685.

📒 Files selected for processing (5)
  • .github/workflows/benchmark.yml (1 hunks)
  • .github/workflows/test.yml (1 hunks)
  • .pre-commit-config.yaml (1 hunks)
  • dpdata/abacus/stru.py (2 hunks)
  • dpdata/deepmd/mixed.py (2 hunks)
🧰 Additional context used
🪛 GitHub Check: codecov/patch
dpdata/deepmd/mixed.py

[warning] 62-63: dpdata/deepmd/mixed.py#L62-L63
Added lines #L62 - L63 were not covered by tests


[warning] 65-66: dpdata/deepmd/mixed.py#L65-L66
Added lines #L65 - L66 were not covered by tests

🔇 Additional comments (6)
.github/workflows/benchmark.yml (1)

16-16: Upgrade astral-sh/setup-uv to v6
Bumping the UV action to v6 aligns this workflow with the test pipeline and unlocks caching improvements. Please verify that v6 still supports the same inputs (enable-cache, cache-dependency-glob).

.pre-commit-config.yaml (1)

24-24: Update ruff pre-commit hook to v0.11.11
This patch release may include new rules or fixes—rerun the full pre-commit suite to catch any unexpected lint diffs.

.github/workflows/test.yml (1)

21-21: Sync astral-sh/setup-uv action to v6
Keeping the setup-uv action version consistent across workflows; confirm that caching parameters (enable-cache, cache-dependency-glob, cache-suffix) are still supported in v6.

dpdata/abacus/stru.py (2)

317-317: LGTM! Good typo fix.

The function name correction from get_carteisan_coords to get_cartesian_coords improves code readability and correctness.


381-381: LGTM! Consistent function call update.

The function call was correctly updated to match the fixed function name.

dpdata/deepmd/mixed.py (1)

30-31: LGTM! Proper handling of optional fields.

The use of data.get() with default None is the correct approach for handling optional fields.

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 (3)
tests/test_deepmd_mixed.py (3)

473-474: Consider using more realistic test data dimensions.

The random arrays for fparam and aparam use arbitrary dimensions (2 and 3 respectively). Consider using dimensions that reflect realistic use cases or documenting why these specific dimensions were chosen.

-        tmp_data["fparam"] = np.random.random([nframes, 2])
-        tmp_data["aparam"] = np.random.random([nframes, natoms, 3])
+        # Using common fparam dimension (e.g., temperature, pressure)
+        tmp_data["fparam"] = np.random.random([nframes, 2])  
+        # Using common aparam dimension (e.g., atomic charge, mass, polarizability)
+        tmp_data["aparam"] = np.random.random([nframes, natoms, 3])  

458-458: Add class docstring for better documentation.

Static analysis correctly identifies missing docstring. Consider adding a brief description of what this test class validates.

 class TestMixedSystemWithFparamAparam(unittest.TestCase, CompLabeledSys, IsNoPBC):
+    """Test persistence of fparam and aparam fields in DeepMD mixed format."""
     def setUp(self):
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 458-458: Missing class docstring

(C0115)


487-494: Add method docstrings for test clarity.

Both test methods would benefit from brief docstrings explaining their purpose.

     def test_fparam_exists(self):
+        """Test that fparam field is preserved during save/load cycle."""
         self.assertTrue("fparam" in self.system_1.data)
         
     def test_aparam_exists(self):
+        """Test that aparam field is preserved during save/load cycle."""
         self.assertTrue("aparam" in self.system_1.data)

Also applies to: 496-503

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 487-487: Missing function or method docstring

(C0116)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c04d685 and d379d2b.

📒 Files selected for processing (2)
  • dpdata/deepmd/mixed.py (2 hunks)
  • tests/test_deepmd_mixed.py (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • dpdata/deepmd/mixed.py
🧰 Additional context used
🪛 Pylint (3.3.7)
tests/test_deepmd_mixed.py

[convention] 458-458: Missing class docstring

(C0115)


[convention] 487-487: Missing function or method docstring

(C0116)


[convention] 496-496: Missing function or method docstring

(C0116)

🪛 GitHub Actions: Python package
tests/test_deepmd_mixed.py

[error] 479-479: NotImplementedError: DeePMDMixedFormat doesn't support LabeledSystem.from - raised in multiple tests during setup when initializing dpdata.LabeledSystem

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

♻️ Duplicate comments (1)
tests/test_deepmd_mixed.py (1)

526-538: Critical issue: Test will fail due to missing loading support.

Based on the past review comments, the pipeline fails with NotImplementedError: DeePMDMixedFormat doesn't support LabeledSystem.from when trying to load from the mixed format. This test cannot pass until the underlying implementation is fixed.

The test logic itself is well-structured, but it requires the implementation of loading support in the mixed format handler before it can run successfully.

🧹 Nitpick comments (2)
tests/test_deepmd_mixed.py (2)

463-465: Add class docstring per coding standards.

The test class is missing a docstring explaining its purpose.

+class TestMixedSystemWithFparamAparam(
+    unittest.TestCase, CompLabeledMultiSys, MultiSystems, MSAllIsNoPBC
+):
+    """Test mixed DeepMD format with optional fparam and aparam fields."""
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 463-463: Missing class docstring

(C0115)


[refactor] 463-463: Too many instance attributes (12/7)

(R0902)


557-561: Add method docstring.

The test method is missing a docstring explaining what it tests.

+def test_len(self):
+    """Test that the number of systems is correctly preserved."""
🧰 Tools
🪛 Pylint (3.3.7)

[convention] 557-557: Missing function or method docstring

(C0116)


[convention] 561-561: Missing function or method docstring

(C0116)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f49dbd and 64f6df0.

📒 Files selected for processing (1)
  • tests/test_deepmd_mixed.py (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
tests/test_deepmd_mixed.py (3)
dpdata/data_type.py (2)
  • Axis (15-21)
  • DataType (35-131)
dpdata/system.py (8)
  • MultiSystems (1360-1729)
  • System (55-1111)
  • register_data_type (1094-1111)
  • LabeledSystem (1159-1357)
  • copy (429-431)
  • get_nframes (417-419)
  • get_nframes (1495-1497)
  • formula (611-620)
tests/comp_sys.py (2)
  • MultiSystems (174-183)
  • MSAllIsNoPBC (207-213)
🪛 Pylint (3.3.7)
tests/test_deepmd_mixed.py

[error] 18-21: Unable to import 'dpdata.data_type'

(E0401)


[convention] 463-463: Missing class docstring

(C0115)


[refactor] 463-463: Too many instance attributes (12/7)

(R0902)


[refactor] 466-466: Too many local variables (19/15)

(R0914)


[convention] 557-557: Missing function or method docstring

(C0116)


[convention] 561-561: Missing function or method docstring

(C0116)


[convention] 565-565: Missing function or method docstring

(C0116)


[convention] 571-571: Missing function or method docstring

(C0116)


[convention] 586-586: Missing function or method docstring

(C0116)

🔇 Additional comments (4)
tests/test_deepmd_mixed.py (4)

18-21: Import statements look good.

The imports for Axis and DataType are appropriate for defining new data types in the test.

🧰 Tools
🪛 Pylint (3.3.7)

[error] 18-21: Unable to import 'dpdata.data_type'

(E0401)


472-489: Well-structured data type registration.

The definition and registration of new optional data types follows the proper pattern using DataType with appropriate shapes and the required=False flag.


571-584: Comprehensive fparam validation.

The test properly verifies both the existence of fparam fields and their numerical integrity after the save/load cycle.

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 571-571: Missing function or method docstring

(C0116)


586-599: Comprehensive aparam validation.

The test properly verifies both the existence of aparam fields and their numerical integrity after the save/load cycle, following the same pattern as the fparam test.

🧰 Tools
🪛 Pylint (3.3.7)

[convention] 586-586: Missing function or method docstring

(C0116)

@iProzd iProzd requested review from iProzd and njzjz June 4, 2025 13:12
Copy link
Member

Choose a reason for hiding this comment

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

Please check other files in this directory to see how we support ANY new keys with the plugin system.

if labels:
dtypes = dpdata.system.LabeledSystem.DTYPES
else:
dtypes = dpdata.system.System.DTYPES
for dtype in dtypes:
if dtype.name in (
"atom_numbs",

Copy link
Contributor Author

@anyangml anyangml Jun 5, 2025

Choose a reason for hiding this comment

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

Please check other files in this directory to see how we support ANY new keys with the plugin system.

@njzjz I am not quite following. Are you suggesting that there are missing changes need to be added, or you want the feature to be implemented using a different approach. This PR only fix the fparam bug in mixed systems.

Copy link
Member

Choose a reason for hiding this comment

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

fparam is implemented with plugins, so I don't suggest handling it specially. Ideally, we should handle any registered data type.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

fparam is implemented with plugins, so I don't suggest handling it specially. Ideally, we should handle any registered data type.

If I understand correctly, you are suggesting refactoring the temp_idx logic into comp.py, not only for fparam but also include all the other dtypes?

temp_idx = np.arange(all_real_atom_types_concat.shape[0])[
(all_real_atom_types_concat == all_real_atom_types_concat[0]).all(-1)
]
rest_idx = np.arange(all_real_atom_types_concat.shape[0])[
(all_real_atom_types_concat != all_real_atom_types_concat[0]).any(-1)
]
temp_data = data.copy()
temp_data["atom_names"] = data["atom_names"].copy()
temp_data["atom_numbs"] = temp_atom_numbs
temp_data["atom_types"] = all_real_atom_types_concat[0]
all_real_atom_types_concat = all_real_atom_types_concat[rest_idx]
temp_data["cells"] = all_cells_concat[temp_idx]
all_cells_concat = all_cells_concat[rest_idx]
temp_data["coords"] = all_coords_concat[temp_idx]
all_coords_concat = all_coords_concat[rest_idx]
if labels:
if all_eners_concat is not None and all_eners_concat.size > 0:
temp_data["energies"] = all_eners_concat[temp_idx]
all_eners_concat = all_eners_concat[rest_idx]
if all_forces_concat is not None and all_forces_concat.size > 0:
temp_data["forces"] = all_forces_concat[temp_idx]
all_forces_concat = all_forces_concat[rest_idx]
if all_virs_concat is not None and all_virs_concat.size > 0:
temp_data["virials"] = all_virs_concat[temp_idx]
all_virs_concat = all_virs_concat[rest_idx]
data_list.append(temp_data)

That probably be done in a separate PR as a refactor. This PR only aims to fix the bug.

@anyangml anyangml closed this Jun 10, 2025
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.

[BUG] MultiSystems load fparam shape mismatch

3 participants