Skip to content

Cp2kOutput.parse_initial_structure() use regex for line matching to allow arbitrary white space between Atom/Kind/Element/... #3810

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

Merged
merged 3 commits into from
May 6, 2024

Conversation

janosh
Copy link
Member

@janosh janosh commented May 6, 2024

closes #3809

@janosh janosh added io Input/output functionality fix Bug fix PRs cp2k CP2K quantum chemistry package labels May 6, 2024
@janosh janosh requested review from shyuep and mkhorton as code owners May 6, 2024 15:34
@janosh janosh enabled auto-merge (squash) May 6, 2024 15:35
Copy link

coderabbitai bot commented May 6, 2024

Walkthrough

The recent updates to the pymatgen/io/cp2k/outputs.py focus on refining the parsing process of initial structures from CP2K output files. This includes better regex pattern management, clearer variable naming, and enhanced data handling, aimed at improving the reliability and readability of the code.

Changes

File Path Change Summary
.../cp2k/outputs.py Refactored parsing logic for initial structures, updated variable names, improved regex and data handling.

Assessment against linked issues

Objective Addressed Explanation
Correct string matching and parsing in CP2K output parser [#3809] The refactoring includes improvements in regex patterns, which likely address the matching issue.
Prevent infinite loop in parse_initial_structure [#3809] The changes in variable and loop handling should prevent the previously encountered infinite loops.

Recent Review Details

Configuration used: .coderabbit.yaml
Review profile: CHILL

Commits Files that changed from the base of the PR and between a16ac39 and 945dc77.
Files ignored due to path filters (1)
  • tests/files/io/cp2k/cp2k.out is excluded by !**/*.out
Files selected for processing (1)
  • pymatgen/io/cp2k/outputs.py (3 hunks)

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

@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: 6

@@ -318,8 +318,7 @@ def parse_structures(self, trajectory_file=None, lattice_file=None):

def parse_initial_structure(self):
"""Parse the initial structure from the main cp2k output file."""
pattern = re.compile(r"- Atoms:\s+(\d+)")
patterns = {"num_atoms": pattern}
patterns = {"num_atoms": re.compile(r"- Atoms:\s+(\d+)")}
Copy link

Choose a reason for hiding this comment

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

Refactor the regex pattern to handle arbitrary whitespace between tokens.

- patterns = {"num_atoms": re.compile(r"- Atoms:\s+(\d+)")}
+ patterns = {"num_atoms": re.compile(r"- Atoms:\s*\+(\d+)")}

This change ensures that the regex correctly matches the expected format even if the whitespace varies, addressing the core issue that led to the infinite loop.


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
patterns = {"num_atoms": re.compile(r"- Atoms:\s+(\d+)")}
patterns = {"num_atoms": re.compile(r"- Atoms:\s*\+(\d+)")}

@@ -331,7 +330,7 @@ def parse_initial_structure(self):
with zopen(self.filename, mode="rt") as file:
while True:
line = file.readline()
if "Atom Kind Element X Y Z Z(eff) Mass" in line:
if re.search(r"Atom\s+Kind\s+Element\s+X\s+Y\s+Z\s+Z\(eff\)\s+Mass", line):
Copy link

Choose a reason for hiding this comment

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

Ensure robust handling of empty lines during file parsing.

- if line == []:
+ if not line.strip():

Using line.strip() is more robust as it checks for lines that are effectively empty (only whitespace) and not just strictly empty lists.


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
if re.search(r"Atom\s+Kind\s+Element\s+X\s+Y\s+Z\s+Z\(eff\)\s+Mass", line):
if not line.strip():

@@ -340,36 +339,33 @@ def parse_initial_structure(self):
break

lattice = self.parse_cell_params()
gs = {}
ghost_atoms = {}
Copy link

Choose a reason for hiding this comment

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

Initialize ghost_atoms dictionary more explicitly.

- ghost_atoms = {}
+ ghost_atoms = dict()

Using dict() for dictionary initialization is more explicit and aligns with Python's clear coding practices.


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
ghost_atoms = {}
ghost_atoms = dict()

Comment on lines +344 to +346
for val in self.data["atomic_kind_info"].values():
ghost_atoms[val["kind_number"]] = val["pseudo_potential"].upper() == "NONE"

Copy link

Choose a reason for hiding this comment

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

Optimize the loop for setting ghost atom properties.

- for val in self.data["atomic_kind_info"].values():
-     ghost_atoms[val["kind_number"]] = val["pseudo_potential"].upper() == "NONE"
+ ghost_atoms = {val["kind_number"]: val["pseudo_potential"].upper() == "NONE" for val in self.data["atomic_kind_info"].values()}

This change uses a dictionary comprehension to make the code more concise and potentially more efficient by reducing the overhead of loop execution.


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
for val in self.data["atomic_kind_info"].values():
ghost_atoms[val["kind_number"]] = val["pseudo_potential"].upper() == "NONE"
ghost_atoms = {val["kind_number"]: val["pseudo_potential"].upper() == "NONE" for val in self.data["atomic_kind_info"].values()}

Comment on lines +347 to +351
for coord in coord_table:
for key, val in self.data["atomic_kind_info"].items():
if int(val["kind_number"]) == int(coord[1]):
val["element"] = coord[2]
self.data["atomic_kind_list"].append(key)
Copy link

Choose a reason for hiding this comment

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

Refactor nested loops for clarity and efficiency.

- for coord in coord_table:
-     for key, val in self.data["atomic_kind_info"].items():
-         if int(val["kind_number"]) == int(coord[1]):
-             val["element"] = coord[2]
-             self.data["atomic_kind_list"].append(key)
-             break
+ for coord in coord_table:
+     kind_number = int(coord[1])
+     if kind_number in self.data["atomic_kind_info"]:
+         val = self.data["atomic_kind_info"][kind_number]
+         val["element"] = coord[2]
+         self.data["atomic_kind_list"].append(kind_number)

This refactoring avoids the inner loop by directly accessing the dictionary with the kind number, which is more efficient and clearer.


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
for coord in coord_table:
for key, val in self.data["atomic_kind_info"].items():
if int(val["kind_number"]) == int(coord[1]):
val["element"] = coord[2]
self.data["atomic_kind_list"].append(key)
for coord in coord_table:
kind_number = int(coord[1])
if kind_number in self.data["atomic_kind_info"]:
val = self.data["atomic_kind_info"][kind_number]
val["element"] = coord[2]
self.data["atomic_kind_list"].append(kind_number)

Comment on lines +356 to +358
species=[coord[2] for coord in coord_table],
coords=[[float(i[4]), float(i[5]), float(i[6])] for i in coord_table],
site_properties={"ghost": [gs.get(int(i[1])) for i in coord_table]},
site_properties={"ghost": [ghost_atoms.get(int(i[1])) for i in coord_table]},
Copy link

Choose a reason for hiding this comment

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

Ensure consistent use of variable names in list comprehensions.

- species=[coord[2] for coord in coord_table],
- coords=[[float(i[4]), float(i[5]), float(i[6])] for i in coord_table],
- site_properties={"ghost": [ghost_atoms.get(int(i[1])) for i in coord_table]},
+ species=[coord[2] for coord in coord_table],
+ coords=[[float(coord[4]), float(coord[5]), float(coord[6])] for coord in coord_table],
+ site_properties={"ghost": [ghost_atoms.get(int(coord[1])) for coord in coord_table]},

This change corrects the variable used in the list comprehensions to be consistent, improving readability and reducing the chance of errors.


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
species=[coord[2] for coord in coord_table],
coords=[[float(i[4]), float(i[5]), float(i[6])] for i in coord_table],
site_properties={"ghost": [gs.get(int(i[1])) for i in coord_table]},
site_properties={"ghost": [ghost_atoms.get(int(i[1])) for i in coord_table]},
species=[coord[2] for coord in coord_table],
coords=[[float(coord[4]), float(coord[5]), float(coord[6])] for coord in coord_table],
site_properties={"ghost": [ghost_atoms.get(int(coord[1])) for coord in coord_table]},

@janosh janosh merged commit ad19ffb into master May 6, 2024
@janosh janosh deleted the fix-gh-3809 branch May 6, 2024 15:46
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
cp2k CP2K quantum chemistry package fix Bug fix PRs io Input/output functionality
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Error in CP2K output parser structure parsing
1 participant