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

Utility module updates #307

Merged
merged 15 commits into from
Aug 29, 2024
Merged

Utility module updates #307

merged 15 commits into from
Aug 29, 2024

Conversation

AntObi
Copy link
Collaborator

@AntObi AntObi commented Aug 29, 2024

New utility submodule and updated Contributing guide

Description

  • Added a Contributing.md file
  • Added a utilities module
  • Moved parse_formula from smact.properties into a separate function in smact.utils.composition
  • Updated parse_formula to handle non-integer stoichiometries
  • Added function comp_maker in smact.utils.composition which converts items in the list returned by smart_filter into a pymatgen Composition. Oxidation states are preserved if available.
  • Added function form_maker in smart.utils.composition which converts items in the list returned by smart_filter into a chemical formula.

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • This change requires a documentation update

How Has This Been Tested?

  • Verified parse_formula refactor doesn't break exisiting tests
  • Written tests to check that parse_formula works for decimal stoichiometries
  • Written tests for comp_maker and form_maker`

Test Configuration:

  • Python version: 3.10
  • Operating System: macOS

Reviewers

N/A

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules
  • I have checked my code and corrected any misspellings

Summary by CodeRabbit

  • New Features

    • Introduced a CONTRIBUTING.md file to guide contributors on best practices and workflows.
    • Added utility functions for parsing chemical formulas and creating compositions, enhancing data manipulation capabilities.
    • Established a new SMACT Utilities module for better organisation of utility functions.
    • Updated documentation to include the smact.utils submodule, improving accessibility.
  • Tests

    • Implemented a suite of unit tests for composition utilities to ensure functionality and accuracy.
  • Bug Fixes

    • Improved code modularity by removing redundant local functions in favour of imported utilities, enhancing maintainability.

@AntObi AntObi added enhancement python Pull requests that update Python code feature refactor labels Aug 29, 2024
Copy link
Contributor

coderabbitai bot commented Aug 29, 2024

Walkthrough

The changes introduce a CONTRIBUTING.md file to guide contributors on best practices for the SMACT project. The parse_formula function is refactored into a utility module, enhancing code modularity. New unit tests validate the functionality of composition utilities, and a utility file is created to handle chemical formula parsing and composition generation. Documentation for the utilities is also added, improving accessibility.

Changes

File(s) Change Summary
CONTRIBUTING.md Added a comprehensive guide for contributors, detailing the contribution process, guidelines for pull requests, and development requirements.
smact/properties.py Removed local parse_formula function; imported it from smact.utils.composition, improving code modularity and maintainability.
smact/tests/test_utils.py Introduced a suite of unit tests for parse_formula, comp_maker, and formula_maker, ensuring functionality and accuracy of composition utilities.
smact/utils/composition.py Added utility functions for parsing chemical formulas and creating compositions, including parse_formula, comp_maker, and formula_maker.
docs/smact.utils.composition.rst Introduced documentation for the SMACT Utilities Composition Module, detailing its functionalities and enhancing accessibility.
docs/smact.utils.rst Added documentation for the SMACT Utilities module, outlining its purpose and structure.
setup.py Added "smact.utils" to the packages list, ensuring the utilities module is included in the distribution setup.
smact/utils/__init__.py Introduced an __init__.py file for the utils module, establishing a clear organizational structure for utility functions.
docs/smact.rst Added smact.utils to the documentation structure, improving clarity and accessibility of the utilities within the SMACT framework.

Poem

In fields of code, I hop and play,
With functions new to light the way.
Parsing formulas, oh what a treat,
Contributions make our project sweet!
So join the fun, don’t be shy,
Together we’ll reach for the sky! 🐇✨


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.
    • @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 or @coderabbitai title 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

codecov bot commented Aug 29, 2024

Codecov Report

Attention: Patch coverage is 97.97980% with 2 lines in your changes missing coverage. Please review.

Project coverage is 76.55%. Comparing base (b6f4a7b) to head (83507d8).
Report is 16 commits behind head on develop.

Files with missing lines Patch % Lines
smact/utils/composition.py 95.74% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #307      +/-   ##
===========================================
+ Coverage    75.58%   76.55%   +0.96%     
===========================================
  Files           24       26       +2     
  Lines         2183     2273      +90     
===========================================
+ Hits          1650     1740      +90     
  Misses         533      533              

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

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

Outside diff range, codebase verification and nitpick comments (2)
CONTRIBUTING.md (2)

5-21: Minor stylistic improvements.

Consider the following changes for conciseness and consistency:

  • Use Oxford spelling: "summarised" → "summarized".
  • Remove "of" for conciseness: "all of the unit tests" → "all the unit tests".
- The steps for a new piece of work can be summarised as follows:
+ The steps for a new piece of work can be summarized as follows:

- ensure that all of the unit tests pass on your own machine.
+ ensure that all the unit tests pass on your own machine.
Tools
LanguageTool

[style] ~10-~10: Would you like to use the Oxford spelling “summarized”? The spelling ‘summarised’ is also correct.
Context: ...he steps for a new piece of work can be summarised as follows: 1. Push up or create [an i...

(OXFORD_SPELLING_Z_NOT_S)


[style] ~17-~17: Consider removing “of” to be more concise
Context: ...are finished with the work, ensure that all of the unit tests pass on your own machine....

(ALL_OF_THE)


22-31: Add a comma for clarity.

Consider adding a comma for clarity: "on GitHub look" → "on GitHub, look".

- For a general overview of using pull requests on GitHub look [in the GitHub docs](https://help.github.com/en/articles/about-pull-requests).
+ For a general overview of using pull requests on GitHub, look [in the GitHub docs](https://help.github.com/en/articles/about-pull-requests).
Tools
LanguageTool

[uncategorized] ~24-~24: Possible missing comma found.
Context: ...eral overview of using pull requests on GitHub look [in the GitHub docs](https://help....

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~26-~26: Possible missing comma found.
Context: ...t-pull-requests). When creating a pull request you should: - Ensure that the title su...

(AI_HYDRA_LEO_MISSING_COMMA)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b6f4a7b and 508f78a.

Files selected for processing (4)
  • CONTRIBUTING.md (1 hunks)
  • smact/properties.py (2 hunks)
  • smact/tests/test_utils.py (1 hunks)
  • smact/utils/composition.py (1 hunks)
Additional context used
LanguageTool
CONTRIBUTING.md

[style] ~10-~10: Would you like to use the Oxford spelling “summarized”? The spelling ‘summarised’ is also correct.
Context: ...he steps for a new piece of work can be summarised as follows: 1. Push up or create [an i...

(OXFORD_SPELLING_Z_NOT_S)


[style] ~17-~17: Consider removing “of” to be more concise
Context: ...are finished with the work, ensure that all of the unit tests pass on your own machine....

(ALL_OF_THE)


[uncategorized] ~24-~24: Possible missing comma found.
Context: ...eral overview of using pull requests on GitHub look [in the GitHub docs](https://help....

(AI_HYDRA_LEO_MISSING_COMMA)


[uncategorized] ~26-~26: Possible missing comma found.
Context: ...t-pull-requests). When creating a pull request you should: - Ensure that the title su...

(AI_HYDRA_LEO_MISSING_COMMA)

Additional comments not posted (11)
CONTRIBUTING.md (2)

1-3: LGTM!

The introduction is clear and concise.


33-50: LGTM!

The dev requirements section is clear and provides necessary information for setting up the development environment.

smact/tests/test_utils.py (4)

13-22: LGTM!

The setUp method is correctly initializing mock data for the tests.


24-49: LGTM!

The test_parse_formula method is comprehensive and covers various cases.


51-64: LGTM!

The test_comp_maker method is comprehensive and covers various cases.


66-76: LGTM!

The test_formula_maker method is comprehensive and covers various cases.

smact/utils/composition.py (3)

36-51: LGTM!

The _get_sym_dict function is correctly implemented.


54-80: LGTM!

The comp_maker function is correctly implemented.


83-95: LGTM!

The formula_maker function is correctly implemented.

smact/properties.py (2)

9-9: LGTM!

The import statement for parse_formula is correctly added to improve modularity and reusability.


Line range hint 67-105: LGTM!

The valence_electron_count function correctly uses the imported parse_formula to parse the compound formula.

Comment on lines 11 to 33
def parse_formula(formula: str) -> dict[str, int]:
"""Parse a formula into a dict of el:amt

Args:
formula (str): Chemical formula

Returns:
dict: Dictionary of element symbol: amount
"""
regex = r"\(([^\(\)]+)\)\s*([\.e\d]*)"
r = re.compile(regex)
m = re.search(r, formula)
if m:
factor = 1.0
if m.group(2) != "":
factor = float(m.group(2))
unit_sym_dict = _get_sym_dict(m.group(1), factor)
expanded_sym = "".join(
[f"{el}{amt}" for el, amt in unit_sym_dict.items()]
)
expanded_formula = formula.replace(m.group(), expanded_sym)
return parse_formula(expanded_formula)
return _get_sym_dict(formula, 1)
Copy link
Contributor

Choose a reason for hiding this comment

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

Correct the return type hint.

The return type hint should be dict[str, float] instead of dict[str, int] to accommodate non-integer stoichiometries.

-def parse_formula(formula: str) -> dict[str, int]:
+def parse_formula(formula: str) -> dict[str, float]:
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. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def parse_formula(formula: str) -> dict[str, int]:
"""Parse a formula into a dict of el:amt
Args:
formula (str): Chemical formula
Returns:
dict: Dictionary of element symbol: amount
"""
regex = r"\(([^\(\)]+)\)\s*([\.e\d]*)"
r = re.compile(regex)
m = re.search(r, formula)
if m:
factor = 1.0
if m.group(2) != "":
factor = float(m.group(2))
unit_sym_dict = _get_sym_dict(m.group(1), factor)
expanded_sym = "".join(
[f"{el}{amt}" for el, amt in unit_sym_dict.items()]
)
expanded_formula = formula.replace(m.group(), expanded_sym)
return parse_formula(expanded_formula)
return _get_sym_dict(formula, 1)
def parse_formula(formula: str) -> dict[str, float]:
"""Parse a formula into a dict of el:amt
Args:
formula (str): Chemical formula
Returns:
dict: Dictionary of element symbol: amount
"""
regex = r"\(([^\(\)]+)\)\s*([\.e\d]*)"
r = re.compile(regex)
m = re.search(r, formula)
if m:
factor = 1.0
if m.group(2) != "":
factor = float(m.group(2))
unit_sym_dict = _get_sym_dict(m.group(1), factor)
expanded_sym = "".join(
[f"{el}{amt}" for el, amt in unit_sym_dict.items()]
)
expanded_formula = formula.replace(m.group(), expanded_sym)
return parse_formula(expanded_formula)
return _get_sym_dict(formula, 1)

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

Outside diff range, codebase verification and nitpick comments (3)
smact/utils/composition.py (3)

1-1: Correct the typo in the docstring.

The word "functioms" should be corrected to "functions".

Apply this diff to fix the typo:

-"""Utility functioms for handling elements, species, formulas and composition"""
+"""Utility functions for handling elements, species, formulas and composition"""

56-82: Improve the docstring for clarity.

The docstring should specify that the function handles both two-element and three-element tuples.

Apply this diff to improve the docstring:

-    """Convert an output of smact.screening.smact_filer into a Pymatgen Compositions
+    """Convert an output of smact.screening.smact_filter into a Pymatgen Composition.

85-97: Improve the docstring for clarity.

The docstring should specify that the function uses comp_maker to create the Composition and then returns its reduced formula.

Apply this diff to improve the docstring:

-    """Convert an output of smact.screening.smact_filter into a formula.
+    """Convert an output of smact.screening.smact_filter into a chemical formula.
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 508f78a and 487247a.

Files selected for processing (5)
  • docs/smact.utils.composition.rst (1 hunks)
  • docs/smact.utils.rst (1 hunks)
  • setup.py (1 hunks)
  • smact/utils/init.py (1 hunks)
  • smact/utils/composition.py (1 hunks)
Files skipped from review due to trivial changes (3)
  • docs/smact.utils.composition.rst
  • docs/smact.utils.rst
  • smact/utils/init.py
Additional context used
GitHub Check: codecov/patch
smact/utils/composition.py

[warning] 50-51: smact/utils/composition.py#L50-L51
Added lines #L50 - L51 were not covered by tests

Additional comments not posted (2)
setup.py (1)

35-35: LGTM!

The addition of the smact.utils package to the packages list is necessary to include the new utilities module in the distribution setup.

smact/utils/composition.py (1)

13-13: Correct the return type hint.

The return type hint should be dict[str, float] instead of dict[str, int] to accommodate non-integer stoichiometries.

Apply this diff to fix the return type hint:

-def parse_formula(formula: str) -> dict[str, int]:
+def parse_formula(formula: str) -> dict[str, float]:

Likely invalid or redundant comment.

Comment on lines +38 to +51
def _get_sym_dict(formula: str, factor: float) -> dict[str, float]:
sym_dict: dict[str, float] = defaultdict(float)
regex = r"([A-Z][a-z]*)\s*([-*\.e\d]*)"
r = re.compile(regex)
for m in re.finditer(r, formula):
el = m.group(1)
amt = 1.0
if m.group(2).strip() != "":
amt = float(m.group(2))
sym_dict[el] += amt * factor
formula = formula.replace(m.group(), "", 1)
if formula.strip():
msg = f"{formula} is an invalid formula"
raise ValueError(msg)
Copy link
Contributor

Choose a reason for hiding this comment

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

Add tests for error handling.

The function raises a ValueError if the formula is invalid. Ensure that this error handling is covered by tests.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 50-51: smact/utils/composition.py#L50-L51
Added lines #L50 - L51 were not covered by tests

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 487247a and 83507d8.

Files selected for processing (1)
  • docs/smact.rst (1 hunks)
Files skipped from review due to trivial changes (1)
  • docs/smact.rst

@AntObi AntObi merged commit 7b1f4f1 into WMD-group:develop Aug 29, 2024
16 checks passed
@AntObi AntObi deleted the utils branch August 29, 2024 14:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement feature python Pull requests that update Python code refactor
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant