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

Use Self type in Method Signatures #3705

Merged
merged 84 commits into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
84 commits
Select commit Hold shift + click to select a range
4355dec
add some Self type annotations
DanielYang59 Mar 24, 2024
7130241
add more Self and type annotations
DanielYang59 Mar 24, 2024
b7cc248
add more Self and type annotations
DanielYang59 Mar 24, 2024
a467a2e
pre-commit auto-fixes
pre-commit-ci[bot] Mar 24, 2024
ae6f09a
add more Self and type annotations
DanielYang59 Mar 24, 2024
4fb2035
Merge branch 'use-self-type' of github.com:DanielYang59/pymatgen into…
DanielYang59 Mar 24, 2024
e0c1366
format docstring to google style
DanielYang59 Mar 24, 2024
cc49d0b
add more Self types
DanielYang59 Mar 24, 2024
1938cb9
TEMP FIX for normalized repr
DanielYang59 Mar 24, 2024
2e7921f
add more Self types
DanielYang59 Mar 24, 2024
b06bc89
remove encoding for binary
DanielYang59 Mar 24, 2024
48a8fd5
use `Attributes` over `Parameters`
DanielYang59 Mar 24, 2024
2adde29
add Self return type to __new__ and __enter__ methods
janosh Mar 24, 2024
296fe08
use `Self` for multi-line def
DanielYang59 Mar 24, 2024
5994121
Merge branch 'use-self-type' of https://github.com/DanielYang59/pymat…
DanielYang59 Mar 24, 2024
5b58fbc
`mypy` fixes in core
DanielYang59 Mar 24, 2024
13dbbd9
`mypy` fixes in core
DanielYang59 Mar 24, 2024
949af29
move `mypy` fixes
DanielYang59 Mar 24, 2024
0eda046
Merge branch 'master' into use-self-type
DanielYang59 Mar 24, 2024
bd08e71
add Note tag
DanielYang59 Mar 24, 2024
91ae376
Merge branch 'use-self-type' of https://github.com/DanielYang59/pymat…
DanielYang59 Mar 24, 2024
11a53c4
remove unused arg properties from core.ion
DanielYang59 Mar 24, 2024
493bc75
fix mypy error
DanielYang59 Mar 24, 2024
0aba332
fix unit test for reaction energy calc
DanielYang59 Mar 24, 2024
47a7c22
fix unit test for core.units
DanielYang59 Mar 24, 2024
6a705d2
remove ERROR = UnitError
DanielYang59 Mar 24, 2024
ea76e15
google-style doc string return type format
janosh Mar 24, 2024
b528903
replace deprecated utcnow
DanielYang59 Mar 25, 2024
86a2d9f
fix missing datetime import
DanielYang59 Mar 25, 2024
fa05c87
replace `app = lines.append`
DanielYang59 Mar 25, 2024
6d789e5
slab type hints
janosh Mar 25, 2024
e8b6eb7
relocate Slab import
DanielYang59 Mar 25, 2024
df224a9
fix vector in adsorption
DanielYang59 Mar 25, 2024
b12eadb
Merge branch 'master' into use-self-type
DanielYang59 Mar 25, 2024
1263036
use time for time count
DanielYang59 Mar 25, 2024
5a75503
revert datetime utc
DanielYang59 Mar 25, 2024
7df2bfe
switch to `time`
DanielYang59 Mar 25, 2024
bd72454
switch to `datetime` for utc time for now
DanielYang59 Mar 25, 2024
b8f1a32
Merge branch 'master' into pr/DanielYang59/3705
janosh Mar 25, 2024
da7fded
take some coderabbitai suggestions
DanielYang59 Mar 26, 2024
1595cf2
ignore some mypy override errors
DanielYang59 Mar 26, 2024
3381b53
Merge branch 'master' into use-self-type
DanielYang59 Mar 26, 2024
6f397bb
Merge branch 'master' into use-self-type
DanielYang59 Mar 26, 2024
f96ccfb
fix type ufloat
DanielYang59 Mar 26, 2024
8583e39
fix BaseLammpsGenerator missing fields inputfile and data (did this a…
janosh Mar 27, 2024
42ade92
Merge branch 'master' into pr/DanielYang59/3705
janosh Mar 27, 2024
3bb711d
`mypy` fixes
DanielYang59 Mar 27, 2024
48abd6f
`mypy` fixes
DanielYang59 Mar 27, 2024
5923a55
more `mypy` fixes
DanielYang59 Mar 27, 2024
bc47741
mypy fixes
janosh Mar 27, 2024
7b82274
fix unit test
DanielYang59 Mar 27, 2024
1d11b0e
fix unit test
DanielYang59 Mar 27, 2024
6973596
reapply fix for voronoi
DanielYang59 Mar 27, 2024
1a9878d
fix mypy and voronoi unit test
DanielYang59 Mar 27, 2024
d8f4877
fix unit test for voronoi
DanielYang59 Mar 27, 2024
8e10c9d
more `mypy` fixes
DanielYang59 Mar 27, 2024
13e1eed
one more `mypy` fix
DanielYang59 Mar 27, 2024
d69e1ad
pre-commit auto-fixes
pre-commit-ci[bot] Mar 27, 2024
f9a0b65
fix number import name
DanielYang59 Mar 27, 2024
2d5e0bb
fix lammps generator
DanielYang59 Mar 27, 2024
5d88bc3
avoid self type hard-coding
DanielYang59 Mar 27, 2024
934934a
mypy fix
DanielYang59 Mar 28, 2024
cf16f8b
`sourcery` fix
DanielYang59 Mar 28, 2024
4d76b1f
Merge branch 'master' into use-self-type
DanielYang59 Mar 28, 2024
5cd6072
`sourcery` fix
DanielYang59 Mar 28, 2024
3efde4c
Merge branch 'use-self-type' of github.com:DanielYang59/pymatgen into…
DanielYang59 Mar 28, 2024
8cdbed9
`sourcery` fix
DanielYang59 Mar 28, 2024
fdf428d
`mypy` fix
DanielYang59 Mar 28, 2024
b0d63cd
suppress `mypy` error
DanielYang59 Mar 28, 2024
96f285a
`mypy` and `sourcery` fix
DanielYang59 Mar 28, 2024
3b293bf
`mypy` fixes
DanielYang59 Mar 28, 2024
7312432
fix unit tests
DanielYang59 Mar 28, 2024
7e426bd
`mypy` fixes
DanielYang59 Mar 28, 2024
f9107fb
`mypy` fixes
DanielYang59 Mar 28, 2024
fb49e75
suppress `mypy` error in xcfunc
DanielYang59 Mar 28, 2024
5e22d01
fix `mypy` error
DanielYang59 Mar 28, 2024
cfd77ab
fix `mypy` error
DanielYang59 Mar 28, 2024
a1e8eb0
refactor date parsing in AirssProvider to use std lib datetime instea…
janosh Mar 29, 2024
8137931
fix TestKpoints check kpts_shift
janosh Mar 29, 2024
4bbee19
fix mypy error in sets.py: cast(Sequence[Sequence[float]], kpoints)
janosh Mar 29, 2024
8bdb484
refactor
janosh Mar 29, 2024
6d06bef
fix mypy confusing keyword and positional args in Lattice.from_parame…
janosh Mar 29, 2024
5c309e3
remove now unused mypy ignore in Cssr.from_str
janosh Mar 29, 2024
2fe3b93
fix bad refactor in 8bdb4845fd
janosh Mar 29, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
26 changes: 13 additions & 13 deletions dev_scripts/potcar_scrambler.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import shutil
import warnings
from glob import glob
from typing import TYPE_CHECKING

import numpy as np
from monty.os.path import zpath
Expand All @@ -14,6 +15,9 @@
from pymatgen.io.vasp.sets import _load_yaml_config
from pymatgen.util.testing import VASP_IN_DIR

if TYPE_CHECKING:
from typing_extensions import Self


class PotcarScrambler:
"""
Expand All @@ -34,26 +38,22 @@ class PotcarScrambler:
from existing POTCAR `input_filename`
"""

def __init__(self, potcars: Potcar | PotcarSingle):
if isinstance(potcars, PotcarSingle):
self.PSP_list = [potcars]
else:
self.PSP_list = potcars
def __init__(self, potcars: Potcar | PotcarSingle) -> None:
self.PSP_list = [potcars] if isinstance(potcars, PotcarSingle) else potcars
self.scrambled_potcars_str = ""
for psp in self.PSP_list:
scrambled_potcar_str = self.scramble_single_potcar(psp)
self.scrambled_potcars_str += scrambled_potcar_str
return

def _rand_float_from_str_with_prec(self, input_str: str, bloat: float = 1.5):
def _rand_float_from_str_with_prec(self, input_str: str, bloat: float = 1.5) -> float:
n_prec = len(input_str.split(".")[1])
bd = max(1, bloat * abs(float(input_str)))
return round(bd * np.random.rand(1)[0], n_prec)

def _read_fortran_str_and_scramble(self, input_str: str, bloat: float = 1.5):
input_str = input_str.strip()

if input_str.lower() in ("t", "f", "true", "false"):
if input_str.lower() in {"t", "f", "true", "false"}:
return bool(np.random.randint(2))

if input_str.upper() == input_str.lower() and input_str[0].isnumeric():
Expand All @@ -68,7 +68,7 @@ def _read_fortran_str_and_scramble(self, input_str: str, bloat: float = 1.5):
except ValueError:
return input_str

def scramble_single_potcar(self, potcar: PotcarSingle):
def scramble_single_potcar(self, potcar: PotcarSingle) -> str:
"""
Scramble the body of a POTCAR, retain the PSCTR header information.

Expand Down Expand Up @@ -124,20 +124,20 @@ def scramble_single_potcar(self, potcar: PotcarSingle):
)
return scrambled_potcar_str

def to_file(self, filename: str):
def to_file(self, filename: str) -> None:
with zopen(filename, mode="wt") as file:
file.write(self.scrambled_potcars_str)

@classmethod
def from_file(cls, input_filename: str, output_filename: str | None = None):
def from_file(cls, input_filename: str, output_filename: str | None = None) -> Self:
psp = Potcar.from_file(input_filename)
psp_scrambled = cls(psp)
if output_filename:
psp_scrambled.to_file(output_filename)
return psp_scrambled


def generate_fake_potcar_libraries():
def generate_fake_potcar_libraries() -> None:
"""
To test the `_gen_potcar_summary_stats` function in `pymatgen.io.vasp.inputs`,
need a library of fake POTCARs which do not violate copyright
Expand Down Expand Up @@ -173,7 +173,7 @@ def generate_fake_potcar_libraries():
break


def potcar_cleanser():
def potcar_cleanser() -> None:
"""
Function to replace copyrighted POTCARs used in io.vasp.sets testing
with dummy POTCARs that have scrambled PSP and kinetic energy values
Expand Down
12 changes: 6 additions & 6 deletions dev_scripts/regen_libxcfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,16 +50,16 @@ def write_libxc_docs_json(xc_funcs, json_path):
xc_funcs = deepcopy(xc_funcs)

# Remove XC_FAMILY from Family and XC_ from Kind to make strings more human-readable.
for d in xc_funcs.values():
d["Family"] = d["Family"].replace("XC_FAMILY_", "", 1)
d["Kind"] = d["Kind"].replace("XC_", "", 1)
for dct in xc_funcs.values():
dct["Family"] = dct["Family"].replace("XC_FAMILY_", "", 1)
dct["Kind"] = dct["Kind"].replace("XC_", "", 1)

# Build lightweight version with a subset of keys.
for num, d in xc_funcs.items():
xc_funcs[num] = {key: d[key] for key in ("Family", "Kind", "References")}
for num, dct in xc_funcs.items():
xc_funcs[num] = {key: dct[key] for key in ("Family", "Kind", "References")}
# Descriptions are optional
for opt in ("Description 1", "Description 2"):
desc = d.get(opt)
desc = dct.get(opt)
if desc is not None:
xc_funcs[num][opt] = desc

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ def __repr__(self):
]
)

def as_dict(self):
def as_dict(self) -> dict:
"""Returns: MSONable dict."""
return {
"@module": type(self).__module__,
Expand Down
14 changes: 8 additions & 6 deletions pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
if TYPE_CHECKING:
from collections.abc import Sequence

from typing_extensions import Self

from pymatgen.alchemy.filters import AbstractStructureFilter


Expand Down Expand Up @@ -212,7 +214,7 @@ def write_vasp_input(
**kwargs: All keyword args supported by the VASP input set.
"""
vasp_input_set(self.final_structure, **kwargs).write_input(output_dir, make_dir_if_not_present=create_directory)
with open(f"{output_dir}/transformations.json", mode="w") as file:
with open(f"{output_dir}/transformations.json", mode="w", encoding="utf-8") as file:
json.dump(self.as_dict(), file)

def __str__(self) -> str:
Expand Down Expand Up @@ -267,7 +269,7 @@ def from_cif_str(
transformations: list[AbstractTransformation] | None = None,
primitive: bool = True,
occupancy_tolerance: float = 1.0,
) -> TransformedStructure:
) -> Self:
"""Generates TransformedStructure from a cif string.

Args:
Expand Down Expand Up @@ -311,7 +313,7 @@ def from_poscar_str(
cls,
poscar_string: str,
transformations: list[AbstractTransformation] | None = None,
) -> TransformedStructure:
) -> Self:
"""Generates TransformedStructure from a poscar string.

Args:
Expand Down Expand Up @@ -339,12 +341,12 @@ def as_dict(self) -> dict[str, Any]:
dct["@module"] = type(self).__module__
dct["@class"] = type(self).__name__
dct["history"] = jsanitize(self.history)
dct["last_modified"] = str(datetime.datetime.utcnow())
dct["last_modified"] = str(datetime.datetime.now(datetime.timezone.utc))
dct["other_parameters"] = jsanitize(self.other_parameters)
return dct

@classmethod
def from_dict(cls, dct: dict) -> TransformedStructure:
def from_dict(cls, dct: dict) -> Self:
"""Creates a TransformedStructure from a dict."""
struct = Structure.from_dict(dct)
return cls(struct, history=dct["history"], other_parameters=dct.get("other_parameters"))
Expand Down Expand Up @@ -376,7 +378,7 @@ def to_snl(self, authors: list[str], **kwargs) -> StructureNL:
return StructureNL(self.final_structure, authors, history=history, **kwargs)

@classmethod
def from_snl(cls, snl: StructureNL) -> TransformedStructure:
def from_snl(cls, snl: StructureNL) -> Self:
"""Create TransformedStructure from SNL.

Args:
Expand Down
34 changes: 18 additions & 16 deletions pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
if TYPE_CHECKING:
from collections.abc import Sequence

from typing_extensions import Self

__author__ = "Shyue Ping Ong, Will Richards"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
Expand All @@ -42,7 +44,7 @@ def __init__(
transformations=None,
extend_collection: int = 0,
ncores: int | None = None,
):
) -> None:
"""Initializes a transmuter from an initial list of
pymatgen.alchemy.materials.TransformedStructure.

Expand Down Expand Up @@ -71,7 +73,16 @@ def __getitem__(self, index):
def __getattr__(self, name):
return [getattr(x, name) for x in self.transformed_structures]

def undo_last_change(self):
def __len__(self):
return len(self.transformed_structures)

def __str__(self):
output = ["Current structures", "------------"]
for x in self.transformed_structures:
output.append(str(x.final_structure))
return "\n".join(output)

def undo_last_change(self) -> None:
"""Undo the last transformation in the TransformedStructure.

Raises:
Expand All @@ -80,7 +91,7 @@ def undo_last_change(self):
for x in self.transformed_structures:
x.undo_last_change()

def redo_next_change(self):
def redo_next_change(self) -> None:
"""Redo the last undone transformation in the TransformedStructure.

Raises:
Expand All @@ -89,9 +100,6 @@ def redo_next_change(self):
for x in self.transformed_structures:
x.redo_next_change()

def __len__(self):
return len(self.transformed_structures)

def append_transformation(self, transformation, extend_collection=False, clear_redo=True):
"""Appends a transformation to all TransformedStructures.

Expand Down Expand Up @@ -178,12 +186,6 @@ def add_tags(self, tags):
"""
self.set_parameter("tags", tags)

def __str__(self):
output = ["Current structures", "------------"]
for x in self.transformed_structures:
output.append(str(x.final_structure))
return "\n".join(output)

def append_transformed_structures(self, trafo_structs_or_transmuter):
"""Method is overloaded to accept either a list of transformed structures
or transmuter, it which case it appends the second transmuter"s
Expand All @@ -201,7 +203,7 @@ def append_transformed_structures(self, trafo_structs_or_transmuter):
self.transformed_structures.extend(trafo_structs_or_transmuter)

@classmethod
def from_structures(cls, structures, transformations=None, extend_collection=0):
def from_structures(cls, structures, transformations=None, extend_collection=0) -> Self:
"""Alternative constructor from structures rather than
TransformedStructures.

Expand Down Expand Up @@ -256,7 +258,7 @@ def __init__(self, cif_string, transformations=None, primitive=True, extend_coll
super().__init__(transformed_structures, transformations, extend_collection)

@classmethod
def from_filenames(cls, filenames, transformations=None, primitive=True, extend_collection=False):
def from_filenames(cls, filenames, transformations=None, primitive=True, extend_collection=False) -> Self:
"""Generates a TransformedStructureCollection from a cif, possibly
containing multiple structures.

Expand All @@ -269,7 +271,7 @@ def from_filenames(cls, filenames, transformations=None, primitive=True, extend_
"""
cif_files = []
for filename in filenames:
with open(filename) as file:
with open(filename, encoding="utf-8") as file:
cif_files.append(file.read())
return cls(
"\n".join(cif_files),
Expand Down Expand Up @@ -308,7 +310,7 @@ def from_filenames(cls, poscar_filenames, transformations=None, extend_collectio
"""
trafo_structs = []
for filename in poscar_filenames:
with open(filename) as file:
with open(filename, encoding="utf-8") as file:
trafo_structs.append(TransformedStructure.from_poscar_str(file.read(), []))
return StandardTransmuter(trafo_structs, transformations, extend_collection=extend_collection)
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved

Expand Down