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

Add type annotations for io.vasp.inputs/optics #3740

Merged
merged 37 commits into from
Apr 21, 2024
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
a3ac1b5
some easy mypy fixes
DanielYang59 Apr 7, 2024
bedb74f
ruff check pymatgen/io/vasp --select ANN204 --unsafe-fixes --fix
janosh Apr 12, 2024
ca7cbfc
Merge branch 'master' into ruff-typing
DanielYang59 Apr 12, 2024
05c715d
Merge branch master into kpoints-tuple-type
DanielYang59 Apr 15, 2024
5439209
add type for io.vasp.help
DanielYang59 Apr 18, 2024
3c0194a
add timeout 60 sec for requests.get
DanielYang59 Apr 18, 2024
51714d2
Merge branch master into ruff-typing
DanielYang59 Apr 18, 2024
634239a
pre-commit auto-fixes
pre-commit-ci[bot] Apr 18, 2024
865bd01
add timeout 60 sec for requests.get
DanielYang59 Apr 18, 2024
1a1752a
fix default value of default_names
DanielYang59 Apr 18, 2024
f3aa520
finish poscar.from_str
DanielYang59 Apr 18, 2024
49c98c0
finish Poscar
DanielYang59 Apr 18, 2024
95dfe0a
finish Incar
DanielYang59 Apr 18, 2024
ad4ec38
temp save for potcarsingle
DanielYang59 Apr 18, 2024
5b866b3
put dunder methods close and to the top
DanielYang59 Apr 18, 2024
d75ca24
put properties close and to the top
DanielYang59 Apr 18, 2024
98601e2
put properties close and to the top
DanielYang59 Apr 18, 2024
b217092
replace str with PathLike
DanielYang59 Apr 18, 2024
f55d833
add types for optics
DanielYang59 Apr 18, 2024
1d18862
Merge branch 'master' into ruff-typing
DanielYang59 Apr 18, 2024
ff52da8
suppress some overload
DanielYang59 Apr 18, 2024
a02e225
remove None type from completely untyped classes
DanielYang59 Apr 18, 2024
8380b8c
pre-commit auto-fixes
pre-commit-ci[bot] Apr 18, 2024
0f169c0
fix type error outside io.vasp
DanielYang59 Apr 18, 2024
8f7cd58
Merge branch 'ruff-typing' of github.com:DanielYang59/pymatgen into r…
DanielYang59 Apr 18, 2024
c46a3cd
check for None in Incar init
DanielYang59 Apr 18, 2024
cee21ef
ruff fix
DanielYang59 Apr 18, 2024
465854f
Merge branch 'master' into ruff-typing
DanielYang59 Apr 19, 2024
aab17cd
Merge branch 'master' into ruff-typing
DanielYang59 Apr 19, 2024
16d2685
allow None
DanielYang59 Apr 19, 2024
555e609
Merge branch 'ruff-typing' of github.com:DanielYang59/pymatgen into r…
DanielYang59 Apr 19, 2024
fa9a610
Merge branch 'master' into ruff-typing
DanielYang59 Apr 19, 2024
e8055cd
fix types
DanielYang59 Apr 21, 2024
2954c80
replace `defaultdict` with specific type
DanielYang59 Apr 21, 2024
4c76814
revert accidental changes
DanielYang59 Apr 21, 2024
2945742
fix test
DanielYang59 Apr 21, 2024
2991771
fix tests
DanielYang59 Apr 21, 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 dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def gen_iupac_ordering():
def add_electron_affinities():
"""Update the periodic table data file with electron affinities."""

req = requests.get("https://wikipedia.org/wiki/Electron_affinity_(data_page)")
req = requests.get("https://wikipedia.org/wiki/Electron_affinity_(data_page)", timeout=60)
soup = BeautifulSoup(req.text, "html.parser")
table = None
for table in soup.find_all("table"):
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def __init__(self, existing_structures, structure_matcher=None, symprec=None):
structure matcher is used. A recommended value is 1e-5.
"""
self.symprec = symprec
self.structure_list = []
self.structure_list: list = []
self.existing_structures = existing_structures
if isinstance(structure_matcher, dict):
self.structure_matcher = StructureMatcher.from_dict(structure_matcher)
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def __init__(self, cif_string, transformations=None, primitive=True, extend_coll
"""
transformed_structures = []
lines = cif_string.split("\n")
structure_data = []
structure_data: list = []
read_data = False
for line in lines:
if re.match(r"^\s*data", line):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,7 @@ def __init__(self, permutations_safe_override=False, only_symbols=None):

self.minpoints = {}
self.maxpoints = {}
self.separations_cg = {}
self.separations_cg: dict = {}
Copy link
Member

Choose a reason for hiding this comment

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

can we make the types more specific? list/dict/set/... alone don't add any information for the reader. dict[str, CoordinationGeometry], list[Structure], etc. is more helpful

Copy link
Contributor Author

@DanielYang59 DanielYang59 Apr 21, 2024

Choose a reason for hiding this comment

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

can we make the types more specific? list/dict/set/... alone don't add any information for the reader. dict[str, CoordinationGeometry], list[Structure], etc. is more helpful

Yes this is very true. But in this PR I was working on adding types for io.vasp, sometimes mypy would complain about other unrelated modules (with need annotation for some line) which I haven't yet got time to look closer into. So in these case I just put a general type to stop mypy from complaining (if I look closely into every module, then the work can never be done).

But I would keep this in mind and try to more specific types :)

for cn in range(6, 21):
for cg in self.get_implemented_geometries(coordination=cn):
if only_symbols is not None and cg.ce_symbol not in only_symbols:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2085,7 +2085,7 @@ def __init__(self, coord_geoms=None):
coord_geoms: coordination geometries to be added to the chemical environment.
"""
if coord_geoms is None:
self.coord_geoms = {}
self.coord_geoms: dict = {}
else:
raise NotImplementedError(
"Constructor for ChemicalEnvironments with the coord_geoms argument is not yet implemented"
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/ewald.py
Original file line number Diff line number Diff line change
Expand Up @@ -540,7 +540,7 @@ def __init__(self, matrix, m_list, num_to_return=1, algo=ALGO_FAST):
if algo == EwaldMinimizer.ALGO_COMPLETE:
raise NotImplementedError("Complete algo not yet implemented for EwaldMinimizer")

self._output_lists = []
self._output_lists: list = []
# Tag that the recurse function looks at each level. If a method
# sets this to true it breaks the recursion and stops the search.
self._finished = False
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def __init__(self, lambda_table=None, alpha=-5):

# create Z and px
self.Z = 0
self._px = defaultdict(float)
self._px: defaultdict = defaultdict(float)
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
for s1, s2 in itertools.product(self.species, repeat=2):
value = math.exp(self.get_lambda(s1, s2))
self._px[s1] += value / 2
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/wulff.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ def __init__(self, normal, e_surf, normal_pt, dual_pt, index, m_ind_orig, miller
self.index = index
self.m_ind_orig = m_ind_orig
self.miller = miller
self.points = []
self.outer_lines = []
self.points: list = []
self.outer_lines: list = []


class WulffShape:
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/apps/battery/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def __init__(self, xaxis="capacity", hide_negative=False):
- frac_x: the atomic fraction of the working ion
hide_negative: If True only plot the voltage steps above zero.
"""
self._electrodes = {}
self._electrodes: dict = {}
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
self.xaxis = xaxis
self.hide_negative = hide_negative

Expand Down
2 changes: 1 addition & 1 deletion pymatgen/apps/borg/queen.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ def __init__(self, drone, rootpath=None, number_of_drones=1):
"""
self._drone = drone
self._num_drones = number_of_drones
self._data = []
self._data: list = []

if rootpath:
if number_of_drones > 1:
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/command_line/vampire_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,8 +131,8 @@ def __init__(

# Call Vampire
with subprocess.Popen(["vampire-serial"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as process:
stdout, stderr = process.communicate()
stdout = stdout.decode()
_stdout, stderr = process.communicate()
stdout: str = _stdout.decode()

if stderr:
van_helsing = stderr.decode()
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ def coincidents(self) -> list[Site]:
coincident_sites.append(self.sites[idx])
return coincident_sites

def __str__(self):
def __str__(self) -> str:
comp = self.composition
outs = [
f"Gb Summary ({comp.formula})",
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2860,7 +2860,7 @@ def from_str( # type: ignore[override]
elif fmt_low == "poscar":
from pymatgen.io.vasp import Poscar

struct = Poscar.from_str(input_string, default_names=False, read_velocities=False, **kwargs).structure
struct = Poscar.from_str(input_string, default_names=None, read_velocities=False, **kwargs).structure
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
elif fmt_low == "cssr":
from pymatgen.io.cssr import Cssr

Expand Down
4 changes: 2 additions & 2 deletions pymatgen/ext/cod.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ def get_structure_by_id(self, cod_id, **kwargs):
Returns:
A Structure.
"""
response = requests.get(f"http://{self.url}/cod/{cod_id}.cif")
response = requests.get(f"http://{self.url}/cod/{cod_id}.cif", timeout=60)
return Structure.from_str(response.text, fmt="cif", **kwargs)

@requires(which("mysql"), "mysql must be installed to use this query.")
Expand All @@ -112,7 +112,7 @@ def get_structure_by_formula(self, formula: str, **kwargs) -> list[dict[str, str
for line in text:
if line.strip():
cod_id, sg = line.split("\t")
response = requests.get(f"http://www.crystallography.net/cod/{cod_id.strip()}.cif")
response = requests.get(f"http://www.crystallography.net/cod/{cod_id.strip()}.cif", timeout=60)
try:
struct = Structure.from_str(response.text, fmt="cif", **kwargs)
structures.append({"structure": struct, "cod_id": int(cod_id), "sg": sg})
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/ext/matproj_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -1570,7 +1570,7 @@ def _check_get_download_info_url_by_task_id(self, prefix, task_ids) -> list[str]

@staticmethod
def _check_nomad_exist(url) -> bool:
response = requests.get(url=url)
response = requests.get(url=url, timeout=60)
if response.status_code != 200:
return False
content = json.loads(response.text)
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/abinit/abitimer.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,11 +85,11 @@ def walk(cls, top=".", ext=".abo"):
def __init__(self):
"""Initialize object."""
# List of files that have been parsed.
self._filenames = []
self._filenames: list = []
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved

# timers[filename][mpi_rank]
# contains the timer extracted from the file filename associated to the MPI rank mpi_rank.
self._timers = {}
self._timers: dict = {}
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved

def __iter__(self):
return iter(self._timers)
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/io/abinit/pseudos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1033,10 +1033,10 @@ class PseudoParser:

def __init__(self):
# List of files that have been parsed successfully.
self._parsed_paths = []
self._parsed_paths: list = []

# List of files that could not been parsed.
self._wrong_paths = []
self._wrong_paths: list = []

def scan_directory(self, dirname, exclude_exts=(), exclude_fnames=()):
"""
Expand Down Expand Up @@ -1228,14 +1228,14 @@ def __init__(self, filepath):
# In this way, we know that only the first two bound states (with f and n attributes)
# should be used for constructing an initial guess for the wave functions.

self.valence_states = {}
self.valence_states: dict = {}
for node in root.find("valence_states"):
attrib = AttrDict(node.attrib)
assert attrib.id not in self.valence_states
self.valence_states[attrib.id] = attrib

# Parse the radial grids
self.rad_grids = {}
self.rad_grids: dict = {}
for node in root.findall("radial_grid"):
grid_params = node.attrib
gid = grid_params["id"]
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/io/cp2k/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,15 +57,15 @@ def __init__(self, filename, verbose=False, auto_load=False):
# IO Info
self.filename = filename
self.dir = os.path.dirname(filename)
self.filenames = {}
self.filenames: dict = {}
self.parse_files()
self.data = {}
self.data: dict = {}

# Material properties/results
self.input = self.initial_structure = self.lattice = self.final_structure = self.composition = None
self.efermi = self.vbm = self.cbm = self.band_gap = None
self.structures = []
self.ionic_steps = []
self.structures: list = []
self.ionic_steps: list = []

# parse the basic run parameters always
self.parse_cp2k_params()
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/pwscf.py
Original file line number Diff line number Diff line change
Expand Up @@ -522,7 +522,7 @@ def __init__(self, filename):
filename (str): Filename.
"""
self.filename = filename
self.data = defaultdict(list)
self.data: defaultdict = defaultdict(list)
self.read_pattern(PWOutput.patterns)
for k, v in self.data.items():
if k == "energies":
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/qchem/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,8 +243,8 @@ def get_str(self) -> str:
"""Return a string representation of an entire input file."""
return str(self)

def __str__(self):
combined_list = []
def __str__(self) -> str:
combined_list: list = []
# molecule section
combined_list.extend((self.molecule_template(self.molecule), "", self.rem_template(self.rem), ""))
# opt section
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/io/vasp/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,11 @@
class VaspDoc:
"""A VASP documentation helper."""

def __init__(self):
def __init__(self) -> None:
"""Init for VaspDoc."""
self.url_template = "http://www.vasp.at/wiki/index.php/%s"

def print_help(self, tag):
def print_help(self, tag: str) -> None:
"""
Print the help for a TAG.

Expand All @@ -24,7 +24,7 @@ def print_help(self, tag):
"""
print(self.get_help(tag))

def print_jupyter_help(self, tag):
def print_jupyter_help(self, tag: str) -> None:
"""
Display HTML help in ipython notebook.

Expand All @@ -37,7 +37,7 @@ def print_jupyter_help(self, tag):
display(HTML(html_str))

@classmethod
def get_help(cls, tag, fmt="text"):
def get_help(cls, tag: str, fmt: str = "text") -> str:
"""
Get help on a VASP tag.

Expand All @@ -48,7 +48,7 @@ def get_help(cls, tag, fmt="text"):
Help text.
"""
tag = tag.upper()
response = requests.get(f"https://www.vasp.at/wiki/index.php/{tag}", verify=False)
response = requests.get(f"https://www.vasp.at/wiki/index.php/{tag}", verify=False, timeout=60)
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
soup = BeautifulSoup(response.text)
main_doc = soup.find(id="mw-content-text")
if fmt == "text":
Expand All @@ -60,14 +60,14 @@ def get_help(cls, tag, fmt="text"):
return output

@classmethod
def get_incar_tags(cls):
def get_incar_tags(cls) -> list[str]:
"""Returns: All incar tags."""
tags = []
for page in [
"https://www.vasp.at/wiki/index.php/Category:INCAR",
"https://www.vasp.at/wiki/index.php?title=Category:INCAR&pagefrom=ML+FF+LCONF+DISCARD#mw-pages",
]:
response = requests.get(page, verify=False)
response = requests.get(page, verify=False, timeout=60)
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
soup = BeautifulSoup(response.text)
for div in soup.findAll("div", {"class": "mw-category-group"}):
children = div.findChildren("li")
Expand Down
Loading
Loading