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

Support PIMD for LAMMPS #263

Merged
merged 7 commits into from
Oct 6, 2024
Merged

Conversation

zjgemi
Copy link
Collaborator

@zjgemi zjgemi commented Sep 30, 2024

Summary by CodeRabbit

Release Notes

  • New Features

    • Introduced new parameters for LAMMPS input file generation, enhancing flexibility in handling PIMD tasks.
    • Added a function to merge multiple trajectory and model deviation files into consolidated outputs.
    • Enhanced testing capabilities with new templates for PIMD simulations.
  • Bug Fixes

    • Minor corrections in documentation strings for clarity.
  • Tests

    • Added new tests to ensure the functionality of merging PIMD files is working as expected.
    • Included tests to validate the PIMD template integration within the existing test framework.

Signed-off-by: zjgemi <liuxin_zijian@163.com>
Copy link

coderabbitai bot commented Sep 30, 2024

📝 Walkthrough

Walkthrough

The changes involve enhancements to the dpgen2 library, particularly in the handling of LAMMPS input files for molecular dynamics simulations. New optional parameters related to Path Integral Molecular Dynamics (PIMD) have been introduced across various functions and classes, facilitating dynamic naming of trajectory and model deviation files. Additionally, a new function for merging PIMD files has been added, along with corresponding tests to ensure functionality. Overall, these modifications improve the flexibility and structure of input and output file handling.

Changes

Files Change Summary
dpgen2/constants.py Added variables lmp_pimd_traj_name and lmp_pimd_model_devi_name for dynamic naming of PIMD trajectory and model deviation files.
dpgen2/exploration/task/lmp/lmp_input.py Introduced optional parameter pimd_bead in make_lmp_input function, modifying logic to select appropriate model deviation and trajectory file names based on this parameter. Updated string formatting to include new variables.
dpgen2/exploration/task/lmp_template_task_group.py Added pimd_bead parameter to set_lmp method and modified related functions to utilize this parameter for file naming.
dpgen2/exploration/task/make_task_group_from_config.py Added pimd_bead argument to several task group argument functions, with minor documentation corrections.
dpgen2/exploration/task/npt_task_group.py Updated set_md method to include pimd_bead parameter, passing it to the _make_lmp_task method.
dpgen2/op/run_lmp.py Introduced a new function merge_pimd_files to consolidate multiple trajectory and model deviation files. Updated execute method to call this new function post-LAMMPS command execution.
tests/op/test_run_lmp.py Added TestMergePIMDFiles class with a method test_merge_pimd_files to test the functionality of merging PIMD files, ensuring proper cleanup of test artifacts.
tests/exploration/test_lmp_templ_task_group.py Introduced new variables in_lmp_pimd_template and expected_lmp_pimd_template for PIMD simulations, and added a new test method test_lmp_pimd to validate the PIMD template functionality.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant LmpTemplateTaskGroup
    participant LmpInput
    participant RunLmp
    participant MergePIMDFiles

    User->>LmpTemplateTaskGroup: set_lmp(numb_models, lmp_template_fname, pimd_bead)
    LmpTemplateTaskGroup->>LmpInput: make_lmp_input(pimd_bead)
    LmpInput->>RunLmp: execute()
    RunLmp->>MergePIMDFiles: merge_pimd_files()
    MergePIMDFiles-->>RunLmp: Merged files
    RunLmp-->>User: Execution complete
Loading

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

@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

🧹 Outside diff range and nitpick comments (12)
dpgen2/constants.py (2)

15-15: LGTM! Consider adding a comment for clarity.

The addition of lmp_pimd_traj_name is consistent with the existing naming conventions and supports the PR objective of implementing PIMD for LAMMPS. The use of a placeholder allows for dynamic naming, which is beneficial for PIMD simulations.

Consider adding a brief comment to explain the purpose of the placeholder:

# %s placeholder for PIMD bead index or other identifiers
lmp_pimd_traj_name = "traj.%s.dump"

18-18: LGTM! Consider adding a comment for consistency.

The addition of lmp_pimd_model_devi_name is well-aligned with the existing naming conventions and supports the PR objective of implementing PIMD for LAMMPS. The use of a placeholder is consistent with the lmp_pimd_traj_name constant.

For consistency with the previous suggestion, consider adding a brief comment:

# %s placeholder for PIMD bead index or other identifiers
lmp_pimd_model_devi_name = "model_devi.%s.out"
dpgen2/exploration/task/npt_task_group.py (1)

52-52: LGTM! Consider adding documentation for the new parameter.

The addition of the pimd_bead parameter is well-implemented and consistent with the PR objective of supporting PIMD for LAMMPS. The optional nature and default value maintain backward compatibility.

Consider adding a brief description of the pimd_bead parameter in the method's docstring to improve code documentation.

Also applies to: 76-76

dpgen2/op/run_lmp.py (2)

Line range hint 198-208: LGTM! Consider adding a comment for clarity.

The changes look good and align with the PR objectives. The addition of merge_pimd_files() and the handling of electronic temperature data enhance the functionality of the execute method.

Consider adding a brief comment explaining the purpose of merge_pimd_files() for better code readability. For example:

# Merge PIMD trajectory and model deviation files
merge_pimd_files()

363-375: Good implementation. Consider adding error handling and cleanup.

The merge_pimd_files function effectively merges trajectory and model deviation files. The use of glob and sorting ensures all relevant files are processed in a consistent order.

Consider the following improvements:

  1. Add error handling for file operations:
def merge_pimd_files():
    try:
        # ... existing code ...
    except IOError as e:
        logging.error(f"Error merging PIMD files: {e}")
        raise
  1. Add an option to clean up original files after successful merging:
def merge_pimd_files(cleanup=False):
    # ... existing code ...
    if cleanup:
        for file in traj_files + model_devi_files:
            os.remove(file)
  1. Consider using with statements for file operations to ensure proper closure:
with open(lmp_traj_name, "w") as f:
    for traj_file in sorted(traj_files):
        with open(traj_file, "r") as f2:
            f.write(f2.read())
dpgen2/exploration/task/make_task_group_from_config.py (2)

50-50: LGTM! Consider clarifying the documentation.

The addition of the pimd_bead argument is well-implemented and aligns with the PR objective of supporting PIMD for LAMMPS. The argument is correctly defined as optional with a default value of None.

Consider expanding the documentation string to provide more context about PIMD and when this argument should be used. For example:

doc_pimd_bead = "Bead index for Path Integral Molecular Dynamics (PIMD) simulations. Set to None for non-PIMD simulations."

Also applies to: 112-118


128-128: LGTM! Ensure consistency in documentation improvement.

The addition of the pimd_bead argument to the lmp_template_task_group_args function is consistent with the changes made in npt_task_group_args. The implementation is correct and maintains backward compatibility.

If you decide to expand the documentation for pimd_bead in the npt_task_group_args function as suggested earlier, make sure to apply the same improvement here for consistency.

Also applies to: 170-176

dpgen2/exploration/task/lmp_template_task_group.py (3)

50-50: Add docstring for set_lmp method to include pimd_bead parameter

The set_lmp method now includes a new optional parameter pimd_bead. Updating the docstring to reflect this change will enhance code readability and maintainability by clearly documenting the purpose and usage of this parameter.


155-161: Add pimd_bead parameter to revise_lmp_input_model docstring

The function revise_lmp_input_model now includes an optional pimd_bead parameter. Updating the docstring will help users understand the role of this parameter in modifying the LAMMPS input lines for PIMD simulations.


180-184: Add pimd_bead parameter to revise_lmp_input_dump and update docstring

The function revise_lmp_input_dump now accepts an optional pimd_bead parameter to adjust the trajectory file naming for PIMD simulations. Updating the function's docstring will clarify this new parameter's purpose and usage.

dpgen2/exploration/task/lmp/lmp_input.py (1)

54-54: Consider updating the function documentation to include pimd_bead parameter

The new optional parameter pimd_bead has been added to make_lmp_input. Please update the function's docstring to include this parameter and explain its usage.

tests/op/test_run_lmp.py (1)

337-339: Replace bare assert statements with unittest assertions

Using self.assertEqual instead of bare assert statements provides more informative error messages and better integration with the unittest framework.

Apply this diff to make the changes:

-        assert len(s) == 4
+        self.assertEqual(len(s), 4)
-        assert model_devi.shape[0] == 4
+        self.assertEqual(model_devi.shape[0], 4)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 7b8e942 and db0e577.

📒 Files selected for processing (7)
  • dpgen2/constants.py (1 hunks)
  • dpgen2/exploration/task/lmp/lmp_input.py (5 hunks)
  • dpgen2/exploration/task/lmp_template_task_group.py (3 hunks)
  • dpgen2/exploration/task/make_task_group_from_config.py (4 hunks)
  • dpgen2/exploration/task/npt_task_group.py (3 hunks)
  • dpgen2/op/run_lmp.py (3 hunks)
  • tests/op/test_run_lmp.py (3 hunks)
🔇 Additional comments (16)
dpgen2/constants.py (1)

Line range hint 1-39: Summary: PIMD support added with minimal impact

The changes to this file are focused and minimal, adding two new constants (lmp_pimd_traj_name and lmp_pimd_model_devi_name) to support Path Integral Molecular Dynamics (PIMD) for LAMMPS. These additions are consistent with existing naming conventions and do not modify any existing constants, which reduces the risk of breaking changes.

The use of placeholders in the new constants allows for dynamic naming, which is likely necessary for PIMD simulations. This flexibility aligns well with the PR objective of supporting PIMD for LAMMPS.

dpgen2/exploration/task/npt_task_group.py (2)

136-136: LGTM! Consistent implementation of the PIMD feature.

The addition of the pimd_bead parameter to the make_lmp_input function call is consistent with the changes in the set_md method and correctly implements the PIMD feature.


Line range hint 1-139: Overall, the changes look good and align with the PR objective.

The implementation of PIMD support in the NPTTaskGroup class is well-executed. The changes are minimal, focused, and maintain backward compatibility. The new pimd_bead parameter is consistently used across the class methods.

dpgen2/op/run_lmp.py (1)

Line range hint 1-375: Overall, the changes enhance PIMD support as intended.

The modifications to the RunLmp class and the addition of the merge_pimd_files function successfully implement support for Path Integral Molecular Dynamics (PIMD) in LAMMPS simulations. These changes align well with the PR objectives and integrate seamlessly with the existing codebase.

Key improvements:

  1. Dynamic merging of trajectory and model deviation files.
  2. Enhanced handling of electronic temperature data.

The changes are localized and don't introduce any apparent conflicts with other parts of the file.

To ensure the changes don't introduce any unintended side effects, please run the following verification script:

dpgen2/exploration/task/make_task_group_from_config.py (2)

Line range hint 181-281: Verify if pimd_bead argument is needed for customized LMP template.

The pimd_bead argument has been added to npt_task_group_args and lmp_template_task_group_args, but not to customized_lmp_template_task_group_args.

Please confirm if this is intentional or if the pimd_bead argument should be added to this function as well for consistency. If it should be added, consider updating the function similar to the other two:

def customized_lmp_template_task_group_args():
    # ... existing code ...
    doc_pimd_bead = "Bead index for PIMD, None for non-PIMD"
    
    return [
        # ... existing arguments ...
        Argument(
            "pimd_bead",
            str,
            optional=True,
            default=None,
            doc=doc_pimd_bead,
        ),
    ]

Line range hint 1-281: Summary: PIMD support added successfully, minor improvements suggested

The changes to add support for Path Integral Molecular Dynamics (PIMD) in LAMMPS have been implemented correctly in the npt_task_group_args and lmp_template_task_group_args functions. The new pimd_bead argument is properly defined and documented, maintaining backward compatibility.

Key points:

  1. The implementation is consistent with the PR objective.
  2. Minor improvements to the documentation have been suggested.
  3. Verification is needed for the customized_lmp_template_task_group_args function to ensure consistency across all relevant functions.

Overall, the changes look good and are ready for merge after addressing the minor suggestions and verifying the consistency across all functions.

dpgen2/exploration/task/lmp_template_task_group.py (5)

14-15: Approved: Importing new constants for PIMD support

The addition of lmp_pimd_model_devi_name alongside lmp_model_devi_name correctly imports the necessary constants to support Path Integral Molecular Dynamics (PIMD).


64-67: Pass pimd_bead consistently to input revision functions

Passing self.pimd_bead to both revise_lmp_input_model and revise_lmp_input_dump ensures consistent handling of PIMD-specific file naming. This modification appropriately extends the functionality to support PIMD configurations.


171-175: Approved: Updated pair_style configuration with PIMD support

The modifications to lmp_lines[idx] correctly incorporate the pimd_bead parameter into the model deviation file naming for the pair_style command. This ensures accurate output file generation during simulations.


56-56: Initialize self.pimd_bead before using it

Ensure that self.pimd_bead is initialized before it is used in subsequent method calls. Although it is assigned here, an explicit check or documentation can prevent potential issues if set_lmp is called without pimd_bead.

You can verify the initialization with the following script:

✅ Verification successful

self.pimd_bead is properly initialized before usage

The verification confirms that self.pimd_bead is assigned before it is used in subsequent method calls. No instances of using self.pimd_bead before its initialization were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check if `self.pimd_bead` is used before assignment in the class.

# Test: Search for usages of `self.pimd_bead` in methods other than `set_lmp`.
# Expect: No usages before assignment in `set_lmp`.
rg --python -A 2 'self\.pimd_bead' dpgen2/exploration/task/lmp_template_task_group.py

Length of output: 478


Script:

#!/bin/bash
# Description: Check if `self.pimd_bead` is used before assignment in the class.

# Search for the assignment of `self.pimd_bead`
rg 'self\.pimd_bead\s*=' dpgen2/exploration/task/lmp_template_task_group.py

# Search for usages of `self.pimd_bead` excluding the assignment line
rg -C 2 'self\.pimd_bead' dpgen2/exploration/task/lmp_template_task_group.py | grep -v 'self\.pimd_bead\s*='

Length of output: 709


166-170: Ensure correct string formatting with pimd_bead in file naming

When constructing model_devi_file_name, verify that lmp_pimd_model_devi_name expects a string formatter compatible with pimd_bead. This will prevent potential runtime errors if pimd_bead is None or not the expected type.

Use the following script to check the usage:

✅ Verification successful

String formatting for lmp_pimd_model_devi_name is correct

The lmp_pimd_model_devi_name includes a %s format specifier, ensuring compatibility with pimd_bead.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the definition of `lmp_pimd_model_devi_name` and its formatting.

# Test: Confirm that `lmp_pimd_model_devi_name` includes a format specifier.
# Expect: The constant includes a `%s` or similar for string formatting.
rg --python 'lmp_pimd_model_devi_name\s*=\s*' dpgen2/constants.py

Length of output: 478


Script:

#!/bin/bash
# Description: Check the definition of `lmp_pimd_model_devi_name` and its formatting.

# Test: Confirm that `lmp_pimd_model_devi_name` includes a format specifier.
# Expect: The constant includes a `%s` or similar for string formatting.
rg 'lmp_pimd_model_devi_name\s*=\s*["\'].*%s.*["\']' dpgen2/constants.py

Length of output: 93


Script:

#!/bin/bash
# Description: Check the definition of `lmp_pimd_model_devi_name` and its formatting.

# Test: Confirm that `lmp_pimd_model_devi_name` includes a format specifier.
# Expect: The constant includes a `%s` or similar for string formatting.
rg 'lmp_pimd_model_devi_name\s*=\s*["'"'"'].*%s.*["'"'"']' dpgen2/constants.py

Length of output: 125

dpgen2/exploration/task/lmp/lmp_input.py (5)

15-17: Imported new constants for PIMD support

The constants lmp_pimd_model_devi_name and lmp_pimd_traj_name are correctly imported to support Path Integral Molecular Dynamics (PIMD) features.


104-108: Conditional assignment of model_devi_file_name based on pimd_bead

The logic for assigning model_devi_file_name correctly handles the presence of pimd_bead.


111-114: Ensure correct pair_style syntax for DeepMD version < 1

The pair_style command is updated to include model_devi_file_name, which is appropriate for DeepMD versions earlier than 1.0.


128-131: Updated pair_style command for DeepMD version ≥ 1

The pair_style command correctly incorporates model_devi_file_name and keywords for DeepMD versions 1.0 and above.


140-142: Conditional assignment of lmp_traj_file_name based on pimd_bead

The logic for assigning lmp_traj_file_name handles pimd_bead correctly, ensuring the appropriate trajectory file name is used.

dpgen2/exploration/task/lmp_template_task_group.py Outdated Show resolved Hide resolved
dpgen2/exploration/task/lmp/lmp_input.py Show resolved Hide resolved
tests/op/test_run_lmp.py Show resolved Hide resolved
Copy link

codecov bot commented Sep 30, 2024

Codecov Report

Attention: Patch coverage is 96.77419% with 1 line in your changes missing coverage. Please review.

Project coverage is 83.72%. Comparing base (7b8e942) to head (13ab3aa).
Report is 2 commits behind head on master.

Files with missing lines Patch % Lines
dpgen2/exploration/task/lmp/lmp_input.py 75.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #263      +/-   ##
==========================================
+ Coverage   83.65%   83.72%   +0.06%     
==========================================
  Files         104      104              
  Lines        5990     6015      +25     
==========================================
+ Hits         5011     5036      +25     
  Misses        979      979              

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

wanghan-iapcm and others added 3 commits October 2, 2024 15:19
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Copy link

@wanghan-iapcm wanghan-iapcm left a comment

Choose a reason for hiding this comment

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

Could you please provide UT for pimd_bead in exploration/test_lmp_templ_task_group.py

@zjgemi
Copy link
Collaborator Author

zjgemi commented Oct 3, 2024

Could you please provide UT for pimd_bead in exploration/test_lmp_templ_task_group.py

Done.

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

📥 Commits

Files that changed from the base of the PR and between 679035f and 13ab3aa.

📒 Files selected for processing (1)
  • tests/exploration/test_lmp_templ_task_group.py (3 hunks)
🔇 Additional comments (7)
tests/exploration/test_lmp_templ_task_group.py (7)

200-236: Verify the consistency of the timestep value

In the in_lmp_pimd_template, the timestep is set to 0.001 (line 233), whereas in the other templates it is 0.002000. Please verify if this change is intentional and appropriate for PIMD simulations.


261-261: Ensure proper file naming with model_devi.${ibead}.out

In expected_lmp_pimd_template, the pair_style includes out_file model_devi.${ibead}.out (line 261). Confirm that ${ibead} will be correctly expanded during runtime to distinguish output files for different beads.


267-267: Confirm the dump file naming convention

The dump command specifies traj.${ibead}.dump (line 267). Ensure that this naming convention correctly stores separate trajectory files for each bead and that ${ibead} is properly resolved.


296-297: Initialize PIMD template file correctly

The PIMD template file lmp.pimd.template is created and written successfully.


303-303: Ensure cleanup of PIMD template file in tearDown

The os.remove(self.lmp_pimd_template_fname) statement properly removes the PIMD template file after tests.


426-426: Verify the usage of pimd_bead parameter

The parameter pimd_bead="${ibead}" (line 426) is passed to set_lmp. Confirm that this parameter is correctly utilized within the task group setup and that ${ibead} is properly expanded during task execution.


208-208: ⚠️ Potential issue

Check the variable ibead definition for correctness

The definition variable ibead uloop 4 pad may need verification. Ensure that the usage of uloop and pad aligns with LAMMPS variable definitions for intended looping over beads in PIMD simulations.

@wanghan-iapcm wanghan-iapcm merged commit 850eb22 into deepmodeling:master Oct 6, 2024
9 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