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

Avoid using eval, replace manual offset in enumerate and rename single letter variables #3739

Merged
merged 9 commits into from
Apr 7, 2024

Conversation

DanielYang59
Copy link
Contributor

@DanielYang59 DanielYang59 commented Apr 7, 2024

Summary

  • Replace eval with safer alternatives
  • Replace manual offset in enumerate with the start argument
  • Minor format tweaks

Copy link

coderabbitai bot commented Apr 7, 2024

Important

Auto Review Skipped

More than 25% of the files skipped due to max files limit. The review is being skipped to prevent a low-quality review.

26 files out of 83 files are above the max files limit of 50. Please upgrade to Pro plan to get higher limits.

Walkthrough

The recent updates across various components of the pymatgen library focus on enhancing code safety, efficiency, and readability. Notable improvements include the optimization of loop logic and conditionals, safer handling of dynamic expressions, and more precise and clear documentation. These changes collectively aim to refine the library's usability and maintainability, ensuring it remains a robust tool for materials science research.

Changes

Files Summary
.../analysis/magnetism/heisenberg.py - Adjusted loop logic and conditionals
- Simplified filename condition
- Optimized energy rounding and duplicate removal
- Replaced eval with literal_eval
.../electronic_structure/boltztrap2.py - Unified dosweight assignment based on spin polarization
- Simplified structure assignment
- Refined calculation and property access methods
.../io/vasp/inputs.py - Changed parameter type comparison and assignment methods
- Removed integer value handling for hashing
- Updated docstring for clarity

🐇✨
In the realm of pymatgen, where atoms dance,
CodeRabbit hopped through, improving at a glance.
Loops were tightened, and safety enhanced,
With every line, the code advanced.
🌟'Twas a leap for science, in every stance.
🐾📚

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

Actionable comments outside the diff hunks (3)
pymatgen/io/vasp/inputs.py (3)

Line range hint 322-322: The structure parameter in the __init__ method is critical and should be validated to ensure it's an instance of Structure. This validation enhances robustness and prevents potential runtime errors.

if not isinstance(structure, Structure):
    raise TypeError("The structure parameter must be an instance of pymatgen.core.structure.Structure")

Line range hint 2485-2485: The automatic_density method in the Kpoints class should include checks to ensure the structure parameter is valid and the kppa value is positive. These checks can prevent runtime errors and ensure the method's preconditions are met.

if not isinstance(structure, Structure):
    raise TypeError("The structure parameter must be an instance of pymatgen.core.structure.Structure")
if kppa <= 0:
    raise ValueError("The kppa value must be positive")

Line range hint 2485-2485: In the from_directory class method of the Potcar class, consider adding a check to ensure the directory exists and contains the expected POTCAR files. This check can prevent runtime errors when the directory is missing or incorrectly specified.

if not os.path.isdir(input_dir):
    raise FileNotFoundError(f"The specified directory {input_dir} does not exist")
Review Status

Configuration used: CodeRabbit UI

Commits Files that changed from the base of the PR and between a2ab944 and 5ca3aff.
Files selected for processing (3)
  • pymatgen/analysis/magnetism/heisenberg.py (5 hunks)
  • pymatgen/electronic_structure/boltztrap2.py (6 hunks)
  • pymatgen/io/vasp/inputs.py (4 hunks)
Additional comments not posted (19)
pymatgen/analysis/magnetism/heisenberg.py (3)

570-573: Ensure consistency in file extension handling.

The condition for appending ".json" to the filename is straightforward but consider encapsulating this logic into a utility function if similar patterns are used elsewhere in the codebase. This promotes DRY principles and simplifies maintenance if the logic for determining file extensions needs to change in the future.


731-732: Adjust the tolerance value for energy comparison.

The tolerance value for energy comparison is hardcoded as 6 (for 10^-6 eV/atom). Consider making this a configurable parameter of the HeisenbergScreener class to increase flexibility and adaptability to different precision requirements in future use cases.


926-926: Handle potential exceptions more gracefully in from_dict.

The from_dict method uses literal_eval to parse the ex_mat DataFrame from a JSON string. Consider adding error handling around this operation to catch and handle SyntaxError or other potential exceptions more gracefully. This could involve logging an error message and returning a default value or raising a custom exception with a more informative error message.

pymatgen/electronic_structure/boltztrap2.py (6)

111-111: Consider consolidating the assignment of dosweight to avoid repetition and improve maintainability.


172-172: The calculation of h for splitting projections based on spin polarization is repeated. Consider extracting this logic into a separate method to reduce duplication and improve code clarity.


210-210: The conditional assignment for structure is simplified here, which is a positive change for readability and maintainability.


223-223: The assignment of dosweight based on is_spin_polarized is repeated. It's advisable to centralize this logic to ensure consistency and ease future modifications.


264-264: The logic for handling projections based on spin polarization is duplicated. Consider creating a shared method to handle this logic to reduce code duplication.


1048-1050: The handling of property arrays based on doping and temperature conditions is well-implemented, ensuring flexibility and scalability for future extensions or modifications.

pymatgen/io/vasp/inputs.py (10)

Line range hint 322-322: Consider adding type hints to the __init__ method parameters for clarity and better code documentation.


Line range hint 2485-2485: The as_dict method should include all relevant attributes of the Poscar class to ensure a complete representation when converting to a dictionary. Currently, it seems some attributes might not be included.


Line range hint 2485-2485: The __setitem__ method in the Incar class should include validation for the keys and values being set, especially since INCAR files have specific requirements for different parameters. This validation can prevent common errors and ensure the generated INCAR file is valid.


Line range hint 2485-2485: The from_dict class method should handle potential mismatches or missing keys gracefully, providing default values or warnings to inform the user, rather than potentially raising a KeyError.


Line range hint 2485-2485: In the Kpoints class, consider adding a method to validate the k-point mesh settings, especially for automatic schemes. This validation can help catch common configuration errors early.


Line range hint 2485-2485: In the PotcarSingle class, the method from_symbol_and_functional should handle cases where the specified functional or symbol does not exist more gracefully, perhaps by providing a list of valid options or suggesting alternatives.


Line range hint 2485-2485: The verify_potcar method in the PotcarSingle class should include more detailed logging or warnings when a POTCAR does not pass validation. This information can help users diagnose and fix issues with their POTCAR files.


Line range hint 2485-2485: The Potcar class should include a method to validate the compatibility of PotcarSingle objects it contains, ensuring they all use the same functional. This validation can prevent common configuration errors in VASP simulations.


Line range hint 2485-2485: The VaspInput class should include a method to validate the completeness and compatibility of its components (Incar, Kpoints, Poscar, Potcar). This validation can ensure that the VASP input set is correctly configured before running simulations.


Line range hint 2485-2485: In the run_vasp method of the VaspInput class, consider adding error handling for cases where the VASP executable is not found or fails to run. This handling can improve the user experience by providing clearer error messages and potential solutions.

pymatgen/analysis/magnetism/heisenberg.py Show resolved Hide resolved
@DanielYang59 DanielYang59 marked this pull request as draft April 7, 2024 09:36
Copy link
Member

@janosh janosh left a comment

Choose a reason for hiding this comment

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

looks good to me.

sorry for hijacking this PR but i'd be interested to get your opinion on these variable renames. single-letter variables are a pet peeve of mine for hurting code readability so been trying to get rid of them for a while

@DanielYang59 DanielYang59 changed the title Avoid using eval Avoid using eval, replace manual offset in enumerate and rename single letter variables Apr 7, 2024
@DanielYang59
Copy link
Contributor Author

DanielYang59 commented Apr 7, 2024

sorry for hijacking this PR

No worries at all. I'm going off topic a bit too (Just cannot resist the pulse to change them, I understand that).

but i'd be interested to get your opinion on these variable renames. single-letter variables are a pet peeve of mine for hurting code readability so been trying to get rid of them for a while

I would fully support such improvements, which makes the code much more readable (especially without reading the full code block).

But for some simple cases, I sometimes think it might not be necessary

  • Very simple and widely accepted cases like i/j for index, k/v for key/value
  • Where the var is immediately returned (mostly list comprehensions like [idx for idx, site in enumerate(structure) if condition])

For some cases, using a more detailed var name is much better

  • When similar name could occur, which could be very confusing, for example the core.surface I'm currently cleaning up, I need to guess c stands for cluster or c-coordinate
  • When the var name is carried for a long distance (I would easily forget what it stands for if it needs to go dozens lines forward)
  • When people don't want to read the full code block

@DanielYang59 DanielYang59 marked this pull request as ready for review April 7, 2024 10:19
@DanielYang59 DanielYang59 requested a review from JaGeo as a code owner April 7, 2024 10:19
@DanielYang59
Copy link
Contributor Author

@janosh Please review. Thanks!

@janosh janosh added linting Linting and quality assurance security Security issues or fixes labels Apr 7, 2024
@janosh janosh merged commit 2a3608f into materialsproject:master Apr 7, 2024
22 checks passed
@janosh
Copy link
Member

janosh commented Apr 7, 2024

ruff has had limited auto-typing ability for a while.

i just ran

ruff check . --select ANN204 --unsafe-fixes
Found 674 errors.
[*] 550 fixable with the --fix option.

would you be interested in submitting a PR with those changes as a followup to #3705?

@DanielYang59 DanielYang59 deleted the avoid-eval branch April 7, 2024 11:44
@DanielYang59
Copy link
Contributor Author

ruff has had limited auto-typing ability for a while.

i just ran

ruff check . --select ANN204 --unsafe-fixes
Found 674 errors.
[*] 550 fixable with the --fix option.

would you be interested in submitting a PR with those changes as a followup to #3705?

Wow this sounds very interesting (always amazed how much you know about all kinds of stuff). I would have a go at this after I finish cleaning up core.surface. Thanks for the useful input.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
linting Linting and quality assurance security Security issues or fixes
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants