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

Reformat docstrings to Google style and add type annotations #3694

Merged
merged 42 commits into from
Mar 22, 2024
Merged
Show file tree
Hide file tree
Changes from 34 commits
Commits
Show all changes
42 commits
Select commit Hold shift + click to select a range
537886e
add type hint and revise docstring
DanielYang59 Mar 18, 2024
92b2285
add type hint and revise docstring, multiple mypy error
DanielYang59 Mar 18, 2024
1e9e45f
Merge branch 'materialsproject:master' into format-docstr-google
DanielYang59 Mar 18, 2024
0fe0ce9
add type hint, multiple mypy error
DanielYang59 Mar 18, 2024
76c9109
Merge branch 'format-docstr-google' of github.com:DanielYang59/pymatg…
DanielYang59 Mar 18, 2024
8805824
revert del of ununsed ctx
DanielYang59 Mar 18, 2024
1c3fe34
add type annotations
DanielYang59 Mar 18, 2024
57a1cf0
add type annotations
DanielYang59 Mar 18, 2024
5022fce
reformat docstring and add type hints
DanielYang59 Mar 18, 2024
2ec9d47
change return set to list
DanielYang59 Mar 18, 2024
fadb4ae
fix typo
DanielYang59 Mar 18, 2024
7662eaa
add TODO tag
DanielYang59 Mar 19, 2024
9d691a5
Merge branch 'format-docstr-google' of github.com:DanielYang59/pymatg…
DanielYang59 Mar 19, 2024
3a392e4
pre-commit auto-fixes
pre-commit-ci[bot] Mar 19, 2024
f5d7be7
fix typo
DanielYang59 Mar 19, 2024
cea79f4
Merge branch 'format-docstr-google' of github.com:DanielYang59/pymatg…
DanielYang59 Mar 19, 2024
d0296f2
fix mypy error in graphs
DanielYang59 Mar 19, 2024
de593af
reformat docstring
DanielYang59 Mar 19, 2024
955d4ef
recovert description
DanielYang59 Mar 19, 2024
e1eeb7f
format docstring
DanielYang59 Mar 19, 2024
1ac8dc1
rename arg: to args:
DanielYang59 Mar 19, 2024
4ee61f3
ruff fixes
DanielYang59 Mar 19, 2024
64295f4
mypy fixes
DanielYang59 Mar 19, 2024
7f95153
fix mypy errors
DanielYang59 Mar 19, 2024
7eb0798
remove type annotation
DanielYang59 Mar 19, 2024
25edb99
remove description indentation
DanielYang59 Mar 19, 2024
a458052
fix return list ordering
DanielYang59 Mar 19, 2024
3612f27
pre-commit auto-fixes
pre-commit-ci[bot] Mar 19, 2024
f9376b3
replace rst styled :: with :
DanielYang59 Mar 20, 2024
d1d5241
replace return: with returns:
DanielYang59 Mar 20, 2024
929ebca
docstring format tweaks
DanielYang59 Mar 20, 2024
9918a4a
Merge branch 'master' into format-docstr-google
DanielYang59 Mar 20, 2024
4c4c466
fixed type error
DanielYang59 Mar 22, 2024
0070169
lint fix
DanielYang59 Mar 22, 2024
795f958
ruff format
DanielYang59 Mar 22, 2024
26a2c8c
fix mypy errors
janosh Mar 22, 2024
06edd23
get_connected_sites remove debug TODO
janosh Mar 22, 2024
0d31af7
remove TODO tag
DanielYang59 Mar 22, 2024
ccf42e3
remove blank line above Args: if no summary line
janosh Mar 22, 2024
3cc5c84
recover comment
DanielYang59 Mar 22, 2024
e056e43
sort optional dep
DanielYang59 Mar 22, 2024
f5691b5
add type-extension
DanielYang59 Mar 22, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ jobs:
- name: ruff
run: |
ruff --version
ruff .
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
ruff check .
ruff format --check .

- name: mypy
Expand Down
14 changes: 8 additions & 6 deletions pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,19 +344,21 @@ def as_dict(self) -> dict[str, Any]:
return dct

@classmethod
def from_dict(cls, dct) -> TransformedStructure:
def from_dict(cls, dct: dict) -> TransformedStructure:
"""Creates a TransformedStructure from a dict."""
struct = Structure.from_dict(dct)
return cls(struct, history=dct["history"], other_parameters=dct.get("other_parameters"))

def to_snl(self, authors, **kwargs) -> StructureNL:
"""Generate SNL from TransformedStructure.
def to_snl(self, authors: list[str], **kwargs) -> StructureNL:
"""
Generate a StructureNL from TransformedStructure.

:param authors: List of authors
:param **kwargs: All kwargs supported by StructureNL.
Args:
authors (List[str]): List of authors contributing to the generated StructureNL.
**kwargs (Any): All kwargs supported by StructureNL.

Returns:
StructureNL
StructureNL: The generated StructureNL object.
"""
if self.other_parameters:
warn("Data in TransformedStructure.other_parameters discarded during type conversion to SNL")
Expand Down
46 changes: 28 additions & 18 deletions pymatgen/analysis/bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from __future__ import annotations

import logging
import warnings

import networkx as nx
from monty.json import MSONable
Expand Down Expand Up @@ -48,7 +49,7 @@ def __init__(

Args:
molecule_entry (dict): Entry for the principle molecule. Should have the keys mentioned above.
fragment_entries (list of dicts): List of fragment entries. Each should have the keys mentioned above.
fragment_entries (list[dict]): Fragment entries. Each should have the keys mentioned above.
allow_additional_charge_separation (bool): If True, consider larger than normal charge separation
among fragments. Defaults to False. See the definition of self.expected_charges below for more
specific information.
Expand Down Expand Up @@ -98,7 +99,7 @@ def __init__(
self.fragment_and_process(bonds)
# If multibreak, loop through pairs of ring bonds.
if multibreak:
print(
warnings.warn(
"Breaking pairs of ring bonds. WARNING: Structure changes much more likely, meaning dissociation values"
" are less reliable! This is a bad idea!"
)
Expand All @@ -120,6 +121,7 @@ def fragment_and_process(self, bonds):
try:
frags = self.mol_graph.split_molecule_subgraphs(bonds, allow_reverse=True)
frag_success = True

except MolGraphSplitError:
# If split is unsuccessful, then we have encountered a ring bond
if len(bonds) == 1:
Expand Down Expand Up @@ -152,23 +154,23 @@ def fragment_and_process(self, bonds):
pb_mol = bb.pybel_mol
smiles = pb_mol.write("smi").split()[0]
specie = nx.get_node_attributes(self.mol_graph.graph, "specie")
print(
warnings.warn(
f"Missing ring opening fragment resulting from the breakage of {specie[bonds[0][0]]} "
f"{specie[bonds[0][1]]} bond {bonds[0][0]} {bonds[0][1]} which would yield a "
f"molecule with this SMILES string: {smiles}"
)
elif len(good_entries) == 1:
# If we have only one good entry, format it and add it to the list that will eventually return:
# If we have only one good entry, format it and add it to the list that will eventually return
self.bond_dissociation_energies += [self.build_new_entry(good_entries, bonds)]
else:
# We shouldn't ever encounter more than one good entry.
raise RuntimeError("There should only be one valid ring opening fragment! Exiting...")
elif len(bonds) == 2:
raise RuntimeError("Should only be trying to break two bonds if multibreak is true! Exiting...")
else:
print("No reason to try and break more than two bonds at once! Exiting...")
raise ValueError
raise ValueError("No reason to try and break more than two bonds at once! Exiting...")
frag_success = False

if frag_success:
# If the principle did successfully split, then we aren't dealing with a ring bond.
# As above, we begin by making sure we haven't already encountered an identical pair of fragments:
Expand Down Expand Up @@ -203,14 +205,14 @@ def fragment_and_process(self, bonds):
smiles = pb_mol.write("smi").split()[0]
for charge in self.expected_charges:
if charge not in frag1_charges_found:
print(f"Missing {charge=} for fragment {smiles}")
warnings.warn(f"Missing {charge=} for fragment {smiles}")
if len(frag2_charges_found) < len(self.expected_charges):
bb = BabelMolAdaptor(frags[1].molecule)
pb_mol = bb.pybel_mol
smiles = pb_mol.write("smi").split()[0]
for charge in self.expected_charges:
if charge not in frag2_charges_found:
print(f"Missing {charge=} for fragment {smiles}")
warnings.warn(f"Missing {charge=} for fragment {smiles}")
# Now we attempt to pair fragments with the right total charge, starting with only fragments with no
# structural change:
for frag1 in frag1_entries[0]: # 0 -> no structural change
Expand Down Expand Up @@ -241,7 +243,7 @@ def fragment_and_process(self, bonds):
self.bond_dissociation_energies += [self.build_new_entry([frag1, frag2], bonds)]
n_entries_for_this_frag_pair += 1

def search_fragment_entries(self, frag):
def search_fragment_entries(self, frag) -> list:
"""
Search all fragment entries for those isomorphic to the given fragment.
We distinguish between entries where both initial and final molgraphs are isomorphic to the
Expand All @@ -263,13 +265,14 @@ def search_fragment_entries(self, frag):
final_entries += [entry]
return [entries, initial_entries, final_entries]

def filter_fragment_entries(self, fragment_entries):
def filter_fragment_entries(self, fragment_entries: list) -> None:
"""
Filter the fragment entries.

:param fragment_entries:
Args:
fragment_entries (List): Fragment entries to be filtered.
"""
self.filtered_entries = []
self.filtered_entries: list = []
for entry in fragment_entries:
# Check and make sure that PCM dielectric is consistent with principle:
if "pcm_dielectric" in self.molecule_entry:
Expand Down Expand Up @@ -305,8 +308,9 @@ def filter_fragment_entries(self, fragment_entries):
else:
entry["structure_change"] = "bond_change"
found_similar_entry = False

# Check for uniqueness
for ii, filtered_entry in enumerate(self.filtered_entries):
for idx, filtered_entry in enumerate(self.filtered_entries):
if filtered_entry["formula_pretty"] == entry["formula_pretty"] and (
filtered_entry["initial_molgraph"].isomorphic_to(entry["initial_molgraph"])
and filtered_entry["final_molgraph"].isomorphic_to(entry["final_molgraph"])
Expand All @@ -316,19 +320,23 @@ def filter_fragment_entries(self, fragment_entries):
# If two entries are found that pass the above similarity check, take the one with the lower
# energy:
if entry["final_energy"] < filtered_entry["final_energy"]:
self.filtered_entries[ii] = entry
self.filtered_entries[idx] = entry
# Note that this will essentially choose between singlet and triplet entries assuming both have
# the same structural details
break
if not found_similar_entry:
self.filtered_entries += [entry]

def build_new_entry(self, frags, bonds):
def build_new_entry(self, frags: list, bonds: list) -> list:
"""
Simple function to format a bond dissociation entry that will eventually be returned to the user.
Build a new entry for bond dissociation that will be returned to the user.

:param frags:
:param bonds:
Args:
frags (list): Fragments involved in the bond dissociation.
bonds (list): Bonds broken in the dissociation process.

Returns:
list: Formatted bond dissociation entries.
"""
specie = nx.get_node_attributes(self.mol_graph.graph, "specie")
if len(frags) == 2:
Expand All @@ -348,6 +356,7 @@ def build_new_entry(self, frags, bonds):
frags[1]["initial_molecule"]["spin_multiplicity"],
frags[1]["final_energy"],
]

else:
new_entry = [
self.molecule_entry["final_energy"] - frags[0]["final_energy"],
Expand All @@ -360,4 +369,5 @@ def build_new_entry(self, frags, bonds):
frags[0]["initial_molecule"]["spin_multiplicity"],
frags[0]["final_energy"],
]

return new_entry
12 changes: 7 additions & 5 deletions pymatgen/analysis/chemenv/connectivity/connectivity_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,10 @@ def __init__(self, multiple_environments_choice=None):
"""
Constructor for the ConnectivityFinder.

:param multiple_environments_choice: defines the procedure to apply when
the environment of a given site is described as a "mix" of more than one
coordination environments.
Args:
multiple_environments_choice: defines the procedure to apply when
the environment of a given site is described as a "mix" of more than one
coordination environments.
"""
self.setup_parameters(multiple_environments_choice=multiple_environments_choice)

Expand All @@ -35,8 +36,9 @@ def get_structure_connectivity(self, light_structure_environments):
Get the structure connectivity from the coordination environments provided
as an input.

:param light_structure_environments: LightStructureEnvironments with the
relevant coordination environments in the structure
Args:
light_structure_environments: LightStructureEnvironments with the
relevant coordination environments in the structure

Returns:
a StructureConnectivity object describing the connectivity of
Expand Down
Loading
Loading