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

Merge develop into master branch #306

Merged
merged 50 commits into from
Aug 30, 2024
Merged

Merge develop into master branch #306

merged 50 commits into from
Aug 30, 2024

Conversation

AntObi
Copy link
Collaborator

@AntObi AntObi commented Aug 27, 2024

Merging develop branch updates into master branch

Description

N/A

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)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Test suite updates

Test Configuration:

  • Python version:
  • Operating System:

Reviewers

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

Summary by CodeRabbit

  • New Features

    • Introduced a script to calculate and display the Valence Electron Count (VEC) for chemical compounds.
    • Added new functions to retrieve elemental data from external sources, enhancing data handling capabilities.
    • Expanded the Element class with additional properties for more detailed elemental information.
    • Introduced a dedicated utilities module for handling chemical formulas and compositions.
    • Enhanced the smact_filter and smact_validity functions with updated default settings for oxidation states.
    • Updated contact information and added a contributing guide in the README.
  • Bug Fixes

    • Updated import paths in notebooks to align with Python's best practices, ensuring compatibility with recent versions.
  • Tests

    • Added a new test function to validate the VEC calculation, improving test coverage and reliability.
    • Introduced unit tests for composition-related utilities to ensure proper functionality.
  • Documentation

    • Added a comprehensive guide for contributors to streamline the onboarding process.
    • Enhanced documentation structure to include new utilities, improving accessibility for users.

@AntObi AntObi added enhancement WIP Work in progress labels Aug 27, 2024
Copy link
Contributor

coderabbitai bot commented Aug 27, 2024

Walkthrough

The changes encompass updates to the .pre-commit-config.yaml for hook configurations, enhancements in the smact module by adding new attributes and functions for elemental data handling, and the introduction of a new script for calculating valence electron counts. Additionally, a new test function has been added to verify the functionality of the valence electron count feature, ensuring comprehensive coverage of the new capabilities. New documentation files and a contributing guide have also been introduced.

Changes

Files Change Summary
.pre-commit-config.yaml Updated nbQA version from 1.6.1 to 1.8.7; changed nbqa-pyupgrade argument from --py38-plus to --py39-plus; minor formatting fix in isort arguments.
examples/Crystal_Space/1_reduction.ipynb Updated import statement for Iterable from typing to collections.abc.
examples/vec_example.py Introduced a new script to calculate and display the Valence Electron Count (VEC) for "Fe2O3".
smact/__init__.py Added five new attributes to the Element class: mendeleev, AtomicWeight, MeltingT, num_valence, and num_valence_modified.
smact/data_loader.py Added functions lookup_element_magpie_data and lookup_element_valence_data for retrieving elemental data from CSV files.
smact/properties.py Introduced a new function, valence_electron_count, to calculate VEC for given chemical compounds.
smact/tests/test_core.py Added a new test function, test_valence_electron_count, to validate the functionality of the valence_electron_count function.
CONTRIBUTING.md New file added to guide contributors on the workflow and best practices for the project.
docs/smact.rst Updated documentation to include the new smact.utils submodule.
docs/smact.utils.* New documentation files for the smact.utils module and its composition functionalities.
setup.py Added "smact.utils" to the list of packages for distribution.
smact/tests/test_utils.py New test suite added for validating composition-related utilities.
smact/utils/__init__.py New file added to serve as a container for utility functions in the SMACT project.
smact/utils/composition.py New file containing utility functions for parsing chemical formulas and creating compositions.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Script
    participant Properties
    participant DataLoader

    User->>Script: Request VEC for "Fe2O3"
    Script->>Properties: Call valence_electron_count("Fe2O3")
    Properties->>DataLoader: Retrieve valence data for "Fe2O3"
    DataLoader-->>Properties: Return valence data
    Properties-->>Script: Return calculated VEC
    Script-->>User: Display VEC
Loading

🐇 "In code we hop, with joy we play,
New features bloom, brightening the day.
With VEC in hand, we leap and cheer,
For elemental wonders, oh so near!
From data to tests, our journey's begun,
Together we code, and oh, what fun!" 🌼


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 27, 2024

Codecov Report

Attention: Patch coverage is 97.63314% with 4 lines in your changes missing coverage. Please review.

Project coverage is 76.46%. Comparing base (149297e) to head (a7946c9).
Report is 51 commits behind head on master.

Files with missing lines Patch % Lines
smact/data_loader.py 93.10% 2 Missing ⚠️
smact/utils/composition.py 95.45% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #306      +/-   ##
==========================================
+ Coverage   75.47%   76.46%   +0.99%     
==========================================
  Files          24       26       +2     
  Lines        2361     2265      -96     
==========================================
- Hits         1782     1732      -50     
+ Misses        579      533      -46     

☔ 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: 2

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 149297e and b6f4a7b.

Files ignored due to path filters (2)
  • smact/data/element_valence_modified.csv is excluded by !**/*.csv
  • smact/data/magpie.csv is excluded by !**/*.csv
Files selected for processing (7)
  • .pre-commit-config.yaml (2 hunks)
  • examples/Crystal_Space/1_reduction.ipynb (1 hunks)
  • examples/vec_example.py (1 hunks)
  • smact/init.py (3 hunks)
  • smact/data_loader.py (2 hunks)
  • smact/properties.py (2 hunks)
  • smact/tests/test_core.py (2 hunks)
Files skipped from review due to trivial changes (2)
  • examples/Crystal_Space/1_reduction.ipynb
  • examples/vec_example.py
Additional context used
Ruff
smact/properties.py

1-1: csv imported but unused

Remove unused import: csv

(F401)


211-211: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

smact/__init__.py

168-171: Use ternary operator num_valence_modified = valence_data["NValence"] if valence_data else None instead of if-else-block

Replace if-else-block with num_valence_modified = valence_data["NValence"] if valence_data else None

(SIM108)

Additional comments not posted (15)
.pre-commit-config.yaml (2)

7-7: LGTM!

The formatting correction improves readability and ensures the arguments are correctly separated.

The code changes are approved.


19-23: LGTM!

Updating the nbQA version and altering the arguments for the nbqa-pyupgrade hook ensures compatibility with newer Python standards and potentially includes additional features or bug fixes.

The code changes are approved.

smact/properties.py (1)

196-199: Use raise ... from None for raising exceptions.

To distinguish exceptions raised in the get_element_valence function from errors in exception handling, use raise ... from None.

Apply this diff to improve exception handling:

-        except NameError:
+        except NameError as e:
             raise ValueError(
-                f"Valence data not found for element: {element}"
-            ) from None
+                f"Valence data not found for element: {element}"
+            ) from e

Likely invalid or redundant comment.

smact/tests/test_core.py (1)

94-110: LGTM!

The test cases are comprehensive and ensure the robustness of the valence_electron_count function.

The code changes are approved.

smact/__init__.py (7)

76-76: LGTM!

The attribute mendeleev is correctly added and documented.

The code changes are approved.


78-78: LGTM!

The attribute AtomicWeight is correctly added and documented.

The code changes are approved.


80-80: LGTM!

The attribute MeltingT is correctly added and documented.

The code changes are approved.


82-82: LGTM!

The attribute num_valence is correctly added and documented.

The code changes are approved.


84-84: LGTM!

The attribute num_valence_modified is correctly added and documented.

The code changes are approved.


155-161: LGTM!

The data retrieval and initialization for magpie_data are correctly implemented.

The code changes are approved.


207-211: LGTM!

The attribute setting is correctly implemented.

The code changes are approved.

smact/data_loader.py (4)

829-895: LGTM!

The data initialization and caching for _element_magpie_data are correctly implemented.

The code changes are approved.


897-906: LGTM!

The data retrieval and warning mechanism are correctly implemented.

The code changes are approved.


909-947: LGTM!

The data initialization and caching for _element_valence_data are correctly implemented.

The code changes are approved.


948-957: LGTM!

The data retrieval and warning mechanism are correctly implemented.

The code changes are approved.

@@ -1,3 +1,6 @@
import csv
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unused import.

The csv module is imported but not used in the file.

Apply this diff to remove the unused import:

-import csv
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
import csv
Tools
Ruff

1-1: csv imported but unused

Remove unused import: csv

(F401)

Comment on lines 167 to 171
valence_data = data_loader.lookup_element_valence_data(symbol)
if valence_data:
num_valence_modified = valence_data["NValence"]
else:
num_valence_modified = None
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider using a ternary operator for conciseness.

Replace the if-else block with a ternary operator for the num_valence_modified attribute.

Apply this diff to use a ternary operator:

-        valence_data = data_loader.lookup_element_valence_data(symbol)
-        if valence_data:
-            num_valence_modified = valence_data["NValence"]
-        else:
-            num_valence_modified = None
+        num_valence_modified = valence_data["NValence"] if valence_data else None
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
valence_data = data_loader.lookup_element_valence_data(symbol)
if valence_data:
num_valence_modified = valence_data["NValence"]
else:
num_valence_modified = None
valence_data = data_loader.lookup_element_valence_data(symbol)
num_valence_modified = valence_data["NValence"] if valence_data else None
Tools
Ruff

168-171: Use ternary operator num_valence_modified = valence_data["NValence"] if valence_data else None instead of if-else-block

Replace if-else-block with num_valence_modified = valence_data["NValence"] if valence_data else None

(SIM108)

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

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

5-21: Improve readability.

Consider using Oxford spelling and removing "of" for conciseness.

- 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 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: Improve readability.

Consider adding a comma for clarity.

- 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)

smact/properties.py (2)

Line range hint 9-28: Improve documentation and use a more specific exception.

  • Improve the docstring to provide more details about the function's behaviour.
  • Use a more specific exception instead of a generic Exception.

Improve the docstring.

 def eneg_mulliken(element: Union[smact.Element, str]) -> float:
     """Get Mulliken electronegativity from the IE and EA.
     Arguments:
         symbol (smact.Element or str): Element object or symbol
     Returns:
         mulliken (float): Mulliken electronegativity
     """

Use a more specific exception.

 def eneg_mulliken(element: Union[smact.Element, str]) -> float:
     if type(element) == str:
         element = smact.Element(element)
     elif type(element) != smact.Element:
-        raise Exception(f"Unexpected type: {type(element)}")
+        raise TypeError(f"Unexpected type: {type(element)}")
     mulliken = (element.ionpot + element.e_affinity) / 2.0
     return mulliken
Tools
Ruff

1-1: csv imported but unused

Remove unused import: csv

(F401)


2-2: re imported but unused

Remove unused import: re

(F401)


3-3: collections.defaultdict imported but unused

Remove unused import: collections.defaultdict

(F401)


Line range hint 29-73: Improve documentation and use type hints.

  • Improve the docstring to provide more details about the function's behaviour.
  • Use type hints for the arguments and return value.

Improve the docstring.

 def band_gap_Harrison(
     anion: str,
     cation: str,
     verbose: bool = False,
     distance: Optional[Union[float, str]] = None,
 ) -> float:
     """
     Estimates the band gap from elemental data.
     The band gap is estimated using the principles outlined in
     Harrison's 1980 work "Electronic Structure and the Properties of
     Solids: The Physics of the Chemical Bond".
     Args:
         Anion (str): Element symbol of the dominant anion in the system
         Cation (str): Element symbol of the the dominant cation in the system
         Distance (float or str): Nuclear separation between anion and cation
                i.e. sum of ionic radii
         verbose (bool) : An optional True/False flag. If True, additional
         information is printed to the standard output. [Defult: False]
     Returns :
         Band_gap (float): Band gap in eV
     """

Use type hints for the arguments and return value.

 def band_gap_Harrison(
     anion: str,
     cation: str,
     verbose: bool = False,
     distance: Optional[Union[float, str]] = None,
 ) -> float:
Tools
Ruff

1-1: csv imported but unused

Remove unused import: csv

(F401)


2-2: re imported but unused

Remove unused import: re

(F401)


3-3: collections.defaultdict imported but unused

Remove unused import: collections.defaultdict

(F401)

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between b6f4a7b and 7b1f4f1.

Files selected for processing (9)
  • CONTRIBUTING.md (1 hunks)
  • docs/smact.rst (1 hunks)
  • docs/smact.utils.composition.rst (1 hunks)
  • docs/smact.utils.rst (1 hunks)
  • setup.py (1 hunks)
  • smact/properties.py (2 hunks)
  • smact/tests/test_utils.py (1 hunks)
  • smact/utils/init.py (1 hunks)
  • smact/utils/composition.py (1 hunks)
Files skipped from review due to trivial changes (4)
  • docs/smact.rst
  • docs/smact.utils.composition.rst
  • docs/smact.utils.rst
  • smact/utils/init.py
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)

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

Ruff
smact/properties.py

1-1: csv imported but unused

Remove unused import: csv

(F401)


2-2: re imported but unused

Remove unused import: re

(F401)


3-3: collections.defaultdict imported but unused

Remove unused import: collections.defaultdict

(F401)


202-202: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

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

1-3: LGTM!

The introduction is clear and concise.


33-50: LGTM!

The dev requirements section is clear and provides detailed instructions.

setup.py (1)

35-35: LGTM!

The modification ensures that the smact.utils module is included in the package distribution.

smact/tests/test_utils.py (3)

24-49: LGTM!

The test function is comprehensive and covers various cases.


51-64: LGTM!

The test function is comprehensive and covers various cases.


66-76: LGTM!

The test function is comprehensive and covers various cases.

Comment on lines 13 to 35
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

Choose a reason for hiding this comment

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

Improve efficiency and documentation.

  • Compile the regular expressions once and reuse them.
  • Improve the docstring to provide more details about the function's behaviour.

Compile the regular expressions once and reuse them.

 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)
+    r = re.compile(r"\(([^\(\)]+)\)\s*([\.e\d]*)")
     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)

Improve the docstring.

 def parse_formula(formula: str) -> dict[str, float]:
-    """Parse a formula into a dict of el:amt
+    """Parse a chemical formula into a dictionary of elements and their amounts.
     Args:
         formula (str): Chemical formula
     Returns:
         dict: Dictionary of element symbol: amount
     """

Comment on lines +38 to +53
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)

return sym_dict
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve efficiency and documentation.

  • Compile the regular expressions once and reuse them.
  • Improve the docstring to provide more details about the function's behaviour.

Compile the regular expressions once and reuse them.

 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)
+    r = re.compile(r"([A-Z][a-z]*)\s*([-*\.e\d]*)")
     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)
     return sym_dict

Improve the docstring.

 def _get_sym_dict(formula: str, factor: float) -> dict[str, float]:
+    """Convert a chemical formula into a dictionary of elements and their amounts.
+    Args:
+        formula (str): Chemical formula
+        factor (float): Multiplication factor for the amounts
+    Returns:
+        dict: Dictionary of element symbol: amount
+    Raises:
+        ValueError: If the formula is invalid
+    """
     sym_dict: dict[str, float] = defaultdict(float)
Tools
GitHub Check: codecov/patch

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

Comment on lines 56 to 82
def comp_maker(
smact_filter_output: tuple[str, int, int] | tuple[str, int]
) -> Composition:
"""Convert an output of smact.screening.smact_filer into a Pymatgen Compositions

Args:
smact_filter_output (tuple[str, int, int]|tuple[str, int]): An item in the list returned from smact_filter

Returns:
composition (pymatgen.core.Composition): An instance of the Composition class
"""
if len(smact_filter_output) == 2:
form = []
for el, ammt in zip(smact_filter_output[0], smact_filter_output[-1]):
form.append(el)
form.append(ammt)
form = "".join(str(e) for e in form)
else:
form = {}
for el, ox, ammt in zip(
smact_filter_output[0],
smact_filter_output[1],
smact_filter_output[2],
):
sp = unparse_spec((el, ox))
form[sp] = ammt
return Composition(form)
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve documentation and simplify the function.

  • Improve the docstring to provide more details about the function's behaviour.
  • Simplify the function using a dictionary comprehension.

Improve the docstring.

 def comp_maker(
     smact_filter_output: tuple[str, int, int] | tuple[str, int]
 ) -> Composition:
-    """Convert an output of smact.screening.smact_filer into a Pymatgen Compositions
+    """Convert an output of smact.screening.smact_filter into a Pymatgen Composition.
     Args:
         smact_filter_output (tuple[str, int, int]|tuple[str, int]): An item in the list returned from smact_filter
     Returns:
         composition (pymatgen.core.Composition): An instance of the Composition class
     """

Simplify the function using a dictionary comprehension.

 def comp_maker(
     smact_filter_output: tuple[str, int, int] | tuple[str, int]
 ) -> Composition:
     if len(smact_filter_output) == 2:
         form = []
         for el, ammt in zip(smact_filter_output[0], smact_filter_output[-1]):
             form.append(el)
             form.append(ammt)
         form = "".join(str(e) for e in form)
     else:
-        form = {}
-        for el, ox, ammt in zip(
-            smact_filter_output[0],
-            smact_filter_output[1],
-            smact_filter_output[2],
-        ):
-            sp = unparse_spec((el, ox))
-            form[sp] = ammt
+        form = {
+            unparse_spec((el, ox)): ammt
+            for el, ox, ammt in zip(
+                smact_filter_output[0],
+                smact_filter_output[1],
+                smact_filter_output[2],
+            )
+        }
     return Composition(form)

Comment on lines 85 to 97
def formula_maker(
smact_filter_output: tuple[str, int, int] | tuple[str, int]
) -> str:
"""Convert an output of smact.screening.smact_filter into a formula.

Args:
smact_filter_output (tuple[str, int, int]|tuple[str, int]): An item in the list returned from smact_filter

Returns:
formula (str): A formula

"""
return comp_maker(smact_filter_output).reduced_formula
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve documentation.

Improve the docstring to provide more details about the function's behaviour.

Improve the docstring.

 def formula_maker(
     smact_filter_output: tuple[str, int, int] | tuple[str, int]
 ) -> str:
-    """Convert an output of smact.screening.smact_filter into a formula.
+    """Convert an output of smact.screening.smact_filter into a chemical formula.
     Args:
         smact_filter_output (tuple[str, int, int]|tuple[str, int]): An item in the list returned from smact_filter
     Returns:
         formula (str): A chemical formula
     """

Committable suggestion was skipped due to low confidence.

Comment on lines 166 to 208
def valence_electron_count(compound: str) -> float:
"""
Calculate the Valence Electron Count (VEC) for a given compound.

This function parses the input compound, extracts the elements and their
stoichiometries, and calculates the VEC using the valence electron data
from SMACT's Element class.

Args:
compound (str): Chemical formula of the compound (e.g., "Fe2O3").

Returns:
float: Valence Electron Count (VEC) for the compound.

Raises:
ValueError: If an element in the compound is not found in the valence data.
"""

def get_element_valence(element: str) -> int:
try:
return smact.Element(element).num_valence_modified
except NameError:
raise ValueError(
f"Valence data not found for element: {element}"
) from None

element_stoich = parse_formula(compound)

total_valence = 0
total_stoich = 0
for element, stoich in element_stoich.items():
try:
valence = get_element_valence(element)
total_valence += stoich * valence
total_stoich += stoich
except TypeError:
raise ValueError(f"No valence information for element {element}")

if total_stoich == 0:
return 0.0

vec = total_valence / total_stoich
return vec
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve documentation, readability, and error handling.

  • Improve the docstring to provide more details about the function's behaviour.
  • Move the nested function get_element_valence outside to improve readability.
  • Improve the error handling by using raise ... from None.

Improve the docstring.

 def valence_electron_count(compound: str) -> float:
     """
-    Calculate the Valence Electron Count (VEC) for a given compound.
+    Calculate the Valence Electron Count (VEC) for a given chemical compound.
     This function parses the input compound, extracts the elements and their
     stoichiometries, and calculates the VEC using the valence electron data
     from SMACT's Element class.
     Args:
         compound (str): Chemical formula of the compound (e.g., "Fe2O3").
     Returns:
         float: Valence Electron Count (VEC) for the compound.
     Raises:
         ValueError: If an element in the compound is not found in the valence data.
     """

Move the nested function get_element_valence outside.

+def get_element_valence(element: str) -> int:
+    try:
+        return smact.Element(element).num_valence_modified
+    except NameError:
+        raise ValueError(
+            f"Valence data not found for element: {element}"
+        ) from None
+
 def valence_electron_count(compound: str) -> float:
-    def get_element_valence(element: str) -> int:
-        try:
-            return smact.Element(element).num_valence_modified
-        except NameError:
-            raise ValueError(
-                f"Valence data not found for element: {element}"
-            ) from None
     element_stoich = parse_formula(compound)
     total_valence = 0
     total_stoich = 0
     for element, stoich in element_stoich.items():
         try:
             valence = get_element_valence(element)
             total_valence += stoich * valence
             total_stoich += stoich
         except TypeError:
-            raise ValueError(f"No valence information for element {element}")
+            raise ValueError(f"No valence information for element {element}") from None
     if total_stoich == 0:
         return 0.0
     vec = total_valence / total_stoich
     return vec
Tools
Ruff

202-202: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Comment on lines 1 to 3
import csv
import re
from collections import defaultdict
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove unused imports.

The csv, re, and collections.defaultdict modules are imported but not used in the file.

Apply this diff to remove the unused imports:

-import csv
-import re
-from collections import defaultdict
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
import csv
import re
from collections import defaultdict
Tools
Ruff

1-1: csv imported but unused

Remove unused import: csv

(F401)


2-2: re imported but unused

Remove unused import: re

(F401)


3-3: collections.defaultdict imported but unused

Remove unused import: collections.defaultdict

(F401)

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 7b1f4f1 and d440b16.

Files selected for processing (6)
  • docs/conf.py (1 hunks)
  • setup.py (2 hunks)
  • smact/init.py (5 hunks)
  • smact/properties.py (2 hunks)
  • smact/screening.py (6 hunks)
  • smact/utils/composition.py (1 hunks)
Files skipped from review due to trivial changes (1)
  • docs/conf.py
Files skipped from review as they are similar to previous changes (2)
  • setup.py
  • smact/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

Ruff
smact/properties.py

199-199: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

Additional comments not posted (7)
smact/utils/composition.py (4)

12-35: Approve changes but consider previous suggestions.

The function correctly parses chemical formulas. However, consider applying the previously suggested improvements to compile the regular expressions once and enhance the docstring for better clarity.

The code changes are approved.


37-53: Approve changes but consider previous suggestions.

The function correctly converts chemical formulas into dictionaries. However, consider applying the previously suggested improvements to compile the regular expressions once and enhance the docstring for better clarity.

The code changes are approved.

Tools
GitHub Check: codecov/patch

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


56-82: Approve changes but consider previous suggestions.

The function correctly converts outputs into Pymatgen compositions. However, consider applying the previously suggested improvements to enhance the docstring and simplify the function using a dictionary comprehension.

The code changes are approved.


85-97: Approve changes but consider previous suggestions.

The function correctly converts outputs into chemical formulas. However, consider applying the previously suggested improvements to enhance the docstring for better clarity.

The code changes are approved.

smact/properties.py (1)

163-205: Approve changes but consider previous suggestions.

The function correctly calculates the Valence Electron Count (VEC) for chemical compounds. However, consider applying the previously suggested improvements to enhance the docstring, improve error handling, and move the nested function outside for better readability.

The code changes are approved.

Tools
Ruff

199-199: Within an except clause, raise exceptions with raise ... from err or raise ... from None to distinguish them from errors in exception handling

(B904)

smact/screening.py (2)

Line range hint 324-392: Approve changes but ensure clear documentation.

The function correctly applies tests for chemical compositions. Ensure that the documentation clearly explains the new default oxidation states and provides guidance for users transitioning from earlier versions.

The code changes are approved.


Line range hint 437-502: Approve changes but ensure clear documentation.

The function correctly checks the validity of compositions. Ensure that the documentation clearly explains the new default oxidation states and provides guidance for users transitioning from earlier versions.

The code changes are approved.

@AntObi AntObi added bug docs dependencies Pull requests that update a dependency file python Pull requests that update Python code feature refactor and removed WIP Work in progress labels Aug 30, 2024
@AntObi AntObi changed the title [WIP] Merge develop into master branch Merge develop into master branch Aug 30, 2024
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between d440b16 and 4dc7117.

Files selected for processing (2)
  • README.md (1 hunks)
  • requirements.txt (5 hunks)
Additional context used
LanguageTool
README.md

[grammar] ~125-~125: The pronoun ‘they’ must be used with a non-third-person form of a verb.
Context: ...n the issue tracker, especially if they helps us improve the docs! For other queries ...

(NON3PRS_VERB)


[style] ~128-~128: Consider a different adverb to strengthen your wording.
Context: ...ctively. ### Code contributions We are always looking for ways to make SMACT better a...

(ALWAYS_CONSTANTLY)

Markdownlint
README.md

127-127: Expected: setext; Actual: atx
Heading style

(MD003, heading-style)


125-125: null
Bare URL used

(MD034, no-bare-urls)


125-125: null
Bare URL used

(MD034, no-bare-urls)

Additional comments not posted (5)
requirements.txt (4)

39-39: Updated dependency: multiprocess

The version of multiprocess has been incremented from 0.70.15 to 0.70.16. This appears to be a minor update, likely involving bug fixes or small improvements. Verify that this update does not introduce any issues with existing multiprocessing implementations in the project.


35-35: Updated dependency: monty

The version of monty has been updated significantly from 2023.11.3 to 2024.7.30. Ensure that this version is compatible with other dependencies and the project's current codebase.


115-116: Added dependency: typing-extensions

The addition of typing-extensions==4.12.2 suggests an enhancement in type hinting capabilities, possibly for compatibility with newer Python features. Confirm that this addition aligns with the project's Python version and coding standards.

Verification successful

Compatibility of typing-extensions==4.12.2 with Python 3.9+

The project requires Python version 3.9 or higher, as specified in setup.py. The typing-extensions==4.12.2 package is compatible with Python 3.9 and above, according to its release notes and PyPI page. Therefore, the addition aligns with the project's requirements and standards. No issues found.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for compatibility of typing-extensions with the project's Python version.

# Test: Search for compatibility notes for typing-extensions 4.12.2.
rg --type markdown -A 5 $'typing-extensions 4.12.2 compatibility'

Length of output: 66


Script:

#!/bin/bash
# Search for the Python version specified in common configuration files.
rg --type toml 'python' -A 3
rg --type py 'python_requires' -A 3

Length of output: 121


Script:

#!/bin/bash
# Check for compatibility notes for typing-extensions 4.12.2 in the repository.
rg 'typing-extensions' -A 5

Length of output: 535


75-75: Updated dependency: pymatgen

The version of pymatgen has been updated from 2023.11.12 to 2024.5.1. Given the importance of this package in materials science projects, it's crucial to ensure that the new version integrates well with the project's modules that depend on pymatgen.

README.md (1)

133-133: Reference to contributing guide added

A new line directing contributors to the CONTRIBUTING.md guide has been added. This is a positive change as it provides clear guidance on how to contribute to the project. Ensure that the CONTRIBUTING.md file is up-to-date and accessible.

Verification successful

Reference to contributing guide verified

The CONTRIBUTING.md file exists in the repository, confirming the review comment's suggestion to ensure its accessibility. The file is present and accessible as intended.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the existence and accessibility of the CONTRIBUTING.md file.

# Test: Check if the CONTRIBUTING.md file exists and is accessible.
fd 'CONTRIBUTING.md'

Length of output: 36

README.md Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 4dc7117 and a7946c9.

Files selected for processing (1)
  • README.md (1 hunks)
Additional context used
LanguageTool
README.md

[style] ~128-~128: Consider a different adverb to strengthen your wording.
Context: ...ctively. ### Code contributions We are always looking for ways to make SMACT better a...

(ALWAYS_CONSTANTLY)

Markdownlint
README.md

127-127: Expected: setext; Actual: atx
Heading style

(MD003, heading-style)


125-125: null
Bare URL used

(MD034, no-bare-urls)


125-125: null
Bare URL used

(MD034, no-bare-urls)

Additional comments not posted (1)
README.md (1)

133-133: Reference to the contributing guide added.

The addition of a reference to the contributing guide in the "Code contributions" section is a useful update for potential contributors. It directs them to more detailed information on how to contribute effectively.

The code changes are approved.

@@ -122,14 +122,15 @@ Development notes
-----------------

### Bugs, features and questions
Please use the [Issue Tracker](https://github.com/WMD-group/smact/issues) to report bugs or request features in the first instance. While we hope that most questions can be answered by searching [the docs](https://smact.readthedocs.io/en/latest/), we welcome new questions on the issue tracker, especially if they helps us improve the docs! For other queries about any aspect of the code, please contact either Dan Davies (author) or Anthony Onwuli (maintainer) by e-mail: d.w.davies@imperial.ac.uk or [email protected] respectively.
Please use the [Issue Tracker](https://github.com/WMD-group/smact/issues) to report bugs or request features in the first instance. While we hope that most questions can be answered by searching [the docs](https://smact.readthedocs.io/en/latest/), we welcome new questions on the issue tracker, especially if they help us improve the docs! For other queries about any aspect of the code, please contact either Aron Walsh on behalf of The SMACT Developers (author) or Anthony Onwuli (maintainer) by e-mail: a.walsh@imperial.ac.uk or [email protected] respectively.
Copy link
Contributor

Choose a reason for hiding this comment

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

Correct grammatical error in the issue tracker sentence.

The previous comment by coderabbitai[bot] highlighted a grammatical error that still needs correction. The verb form should be 'help' instead of 'helps' to agree with the plural subject 'they'.

Apply this diff to correct the grammar:

- especially if they helps us improve the docs!
+ especially if they help us improve the docs!
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
Please use the [Issue Tracker](https://github.com/WMD-group/smact/issues) to report bugs or request features in the first instance. While we hope that most questions can be answered by searching [the docs](https://smact.readthedocs.io/en/latest/), we welcome new questions on the issue tracker, especially if they help us improve the docs! For other queries about any aspect of the code, please contact either Aron Walsh on behalf of The SMACT Developers (author) or Anthony Onwuli (maintainer) by e-mail: [email protected] or [email protected] respectively.
Please use the [Issue Tracker](https://github.com/WMD-group/smact/issues) to report bugs or request features in the first instance. While we hope that most questions can be answered by searching [the docs](https://smact.readthedocs.io/en/latest/), we welcome new questions on the issue tracker, especially if they help us improve the docs! For other queries about any aspect of the code, please contact either Aron Walsh on behalf of The SMACT Developers (author) or Anthony Onwuli (maintainer) by e-mail: [email protected] or [email protected] respectively.
Tools
Markdownlint

125-125: null
Bare URL used

(MD034, no-bare-urls)


125-125: null
Bare URL used

(MD034, no-bare-urls)

@AntObi AntObi merged commit 2fc6a8a into master Aug 30, 2024
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug dependencies Pull requests that update a dependency file docs enhancement feature python Pull requests that update Python code refactor
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants