Skip to content

Commit 1367746

Browse files
DanielYang59janosh
andauthored
pyright fixes (#3777)
* enable pyright * fix electronic_structure.plotters * update pre-commit * finish `electronic_structure` * fix `core.surface/tensors/tracjectory` * fix unit test * fix core.surface * add DEBUG tag * fix core.interface * fix command_line * fix some analysis * fix some analysis * fix more analysis * fix np.empty * fix more analysis * fix chemenv.utils * finish chemenv * revert changes that break tests * Revert "revert changes that break tests" This reverts commit de34eda. * fix unit test * remove tag * remove TODO tag * try downgrade pyright * Revert "try downgrade pyright" This reverts commit 079ebca. * add venv path for pyright * Revert "add venv path for pyright" This reverts commit f9a3aeb. * skip pyright in pre-commit * increase `requests` timeout from 60s to 600s * skip tests/ext/test_cod.py in CI * fix plot_slab weird way to calc zorder * internal types --------- Co-authored-by: Janosh Riebesell <[email protected]>
1 parent 7e2f16c commit 1367746

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+390
-208
lines changed

.github/workflows/lint.yml

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ jobs:
2222

2323
- name: Install dependencies
2424
run: |
25-
pip install --upgrade ruff mypy
25+
pip install --upgrade ruff mypy pyright
2626
2727
- name: ruff
2828
run: |
@@ -31,7 +31,7 @@ jobs:
3131
ruff format --check .
3232
3333
- name: mypy
34-
run: |
35-
mypy --version
36-
rm -rf .mypy_cache
37-
mypy ${{ github.event.repository.name }}
34+
run: mypy ${{ github.event.repository.name }}
35+
36+
- name: pyright
37+
run: pyright

.pre-commit-config.yaml

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@ exclude: ^(docs|tests/files|cmd_line|tasks.py)
22

33
ci:
44
autoupdate_schedule: monthly
5-
skip: [mypy]
5+
skip: [mypy, pyright]
66
autofix_commit_msg: pre-commit auto-fixes
77
autoupdate_commit_msg: pre-commit autoupdate
88

99
repos:
1010
- repo: https://github.com/astral-sh/ruff-pre-commit
11-
rev: v0.3.7
11+
rev: v0.4.1
1212
hooks:
1313
- id: ruff
1414
args: [--fix, --unsafe-fixes]
@@ -35,7 +35,7 @@ repos:
3535
additional_dependencies: [tomli] # needed to read pyproject.toml below py3.11
3636

3737
- repo: https://github.com/MarcoGorelli/cython-lint
38-
rev: v0.16.0
38+
rev: v0.16.2
3939
hooks:
4040
- id: cython-lint
4141
args: [--no-pycodestyle]
@@ -62,3 +62,8 @@ repos:
6262
hooks:
6363
- id: nbstripout
6464
args: [--drop-empty-cells, --keep-output]
65+
66+
- repo: https://github.com/RobertCraigie/pyright-python
67+
rev: v1.1.359
68+
hooks:
69+
- id: pyright

dev_scripts/update_pt_data.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -234,7 +234,7 @@ def gen_iupac_ordering():
234234
def add_electron_affinities():
235235
"""Update the periodic table data file with electron affinities."""
236236

237-
req = requests.get("https://wikipedia.org/wiki/Electron_affinity_(data_page)", timeout=60)
237+
req = requests.get("https://wikipedia.org/wiki/Electron_affinity_(data_page)", timeout=600)
238238
soup = BeautifulSoup(req.text, "html.parser")
239239
table = None
240240
for table in soup.find_all("table"):

pymatgen/analysis/adsorption.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -680,19 +680,19 @@ def plot_slab(
680680
sites = list(reversed(sites))
681681
coords = np.array(reversed(coords))
682682
# Draw circles at sites and stack them accordingly
683-
for n, coord in enumerate(coords):
684-
radius = sites[n].species.elements[0].atomic_radius * scale
685-
ax.add_patch(patches.Circle(coord[:2] - lattice_sum * (repeat // 2), radius, color="w", zorder=2 * n))
686-
color = color_dict[sites[n].species.elements[0].symbol]
683+
for idx, coord in enumerate(coords):
684+
radius = sites[idx].species.elements[0].atomic_radius * scale
685+
ax.add_patch(patches.Circle(coord[:2] - lattice_sum * (repeat // 2), radius, color="w", zorder=2 * idx))
686+
color = color_dict[sites[idx].species.elements[0].symbol]
687687
ax.add_patch(
688688
patches.Circle(
689689
coord[:2] - lattice_sum * (repeat // 2),
690690
radius,
691691
facecolor=color,
692-
alpha=alphas[n],
692+
alpha=alphas[idx],
693693
edgecolor="k",
694694
lw=0.3,
695-
zorder=2 * n + 1,
695+
zorder=2 * idx + 1,
696696
)
697697
)
698698
# Adsorption sites
@@ -714,7 +714,7 @@ def plot_slab(
714714
codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]
715715
vertices = [(np.array(vert) + corner).tolist() for vert in vertices]
716716
path = Path(vertices, codes)
717-
patch = patches.PathPatch(path, facecolor="none", lw=2, alpha=0.5, zorder=2 * n + 2)
717+
patch = patches.PathPatch(path, facecolor="none", lw=2, alpha=0.5, zorder=2 * len(coords) + 2)
718718
ax.add_patch(patch)
719719
ax.set_aspect("equal")
720720
center = corner + lattice_sum / 2.0

pymatgen/analysis/bond_dissociation.py

Lines changed: 11 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,9 @@ def fragment_and_process(self, bonds):
118118
bonds (list): bonds to process.
119119
"""
120120
# Try to split the principle:
121+
fragments: list[MoleculeGraph] = []
121122
try:
122-
frags = self.mol_graph.split_molecule_subgraphs(bonds, allow_reverse=True)
123+
fragments = self.mol_graph.split_molecule_subgraphs(bonds, allow_reverse=True)
123124
frag_success = True
124125

125126
except MolGraphSplitError:
@@ -166,7 +167,7 @@ def fragment_and_process(self, bonds):
166167
# We shouldn't ever encounter more than one good entry.
167168
raise RuntimeError("There should only be one valid ring opening fragment! Exiting...")
168169
elif len(bonds) == 2:
169-
raise RuntimeError("Should only be trying to break two bonds if multibreak is true! Exiting...")
170+
raise RuntimeError("Should only be trying to break two bonds if multibreak=True! Exiting...")
170171
else:
171172
raise ValueError("No reason to try and break more than two bonds at once! Exiting...")
172173
frag_success = False
@@ -176,19 +177,19 @@ def fragment_and_process(self, bonds):
176177
# As above, we begin by making sure we haven't already encountered an identical pair of fragments:
177178
frags_done = False
178179
for frag_pair in self.done_frag_pairs:
179-
if frag_pair[0].isomorphic_to(frags[0]):
180-
if frag_pair[1].isomorphic_to(frags[1]):
180+
if frag_pair[0].isomorphic_to(fragments[0]):
181+
if frag_pair[1].isomorphic_to(fragments[1]):
181182
frags_done = True
182183
break
183-
elif frag_pair[1].isomorphic_to(frags[0]) and frag_pair[0].isomorphic_to(frags[1]):
184+
elif frag_pair[1].isomorphic_to(fragments[0]) and frag_pair[0].isomorphic_to(fragments[1]):
184185
frags_done = True
185186
break
186187
if not frags_done:
187188
# If we haven't, we save this pair and search for the relevant fragment entries:
188-
self.done_frag_pairs += [frags]
189+
self.done_frag_pairs += [fragments]
189190
n_entries_for_this_frag_pair = 0
190-
frag1_entries = self.search_fragment_entries(frags[0])
191-
frag2_entries = self.search_fragment_entries(frags[1])
191+
frag1_entries = self.search_fragment_entries(fragments[0])
192+
frag2_entries = self.search_fragment_entries(fragments[1])
192193
frag1_charges_found = []
193194
frag2_charges_found = []
194195
# We then check for our expected charges of each fragment:
@@ -200,14 +201,14 @@ def fragment_and_process(self, bonds):
200201
frag2_charges_found += [frag2["initial_molecule"]["charge"]]
201202
# If we're missing some of either, tell the user:
202203
if len(frag1_charges_found) < len(self.expected_charges):
203-
bb = BabelMolAdaptor(frags[0].molecule)
204+
bb = BabelMolAdaptor(fragments[0].molecule)
204205
pb_mol = bb.pybel_mol
205206
smiles = pb_mol.write("smi").split()[0]
206207
for charge in self.expected_charges:
207208
if charge not in frag1_charges_found:
208209
warnings.warn(f"Missing {charge=} for fragment {smiles}")
209210
if len(frag2_charges_found) < len(self.expected_charges):
210-
bb = BabelMolAdaptor(frags[1].molecule)
211+
bb = BabelMolAdaptor(fragments[1].molecule)
211212
pb_mol = bb.pybel_mol
212213
smiles = pb_mol.write("smi").split()[0]
213214
for charge in self.expected_charges:

pymatgen/analysis/bond_valence.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -268,6 +268,7 @@ def get_valences(self, structure: Structure):
268268
valences.append(vals)
269269

270270
# make variables needed for recursion
271+
attrib = []
271272
if structure.is_ordered:
272273
n_sites = np.array(list(map(len, equi_sites)))
273274
valence_min = np.array(list(map(min, valences)))
@@ -324,7 +325,6 @@ def _recurse(assigned=None):
324325
else:
325326
n_sites = np.array([len(sites) for sites in equi_sites])
326327
tmp = []
327-
attrib = []
328328
for idx, n_site in enumerate(n_sites):
329329
for _ in valences[idx]:
330330
tmp.append(n_site)

pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
import abc
1111
import os
12-
from typing import TYPE_CHECKING, ClassVar
12+
from typing import TYPE_CHECKING
1313

1414
import numpy as np
1515
from monty.json import MSONable
@@ -31,6 +31,8 @@
3131
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
3232

3333
if TYPE_CHECKING:
34+
from typing import ClassVar
35+
3436
from typing_extensions import Self
3537

3638
__author__ = "David Waroquiers"
@@ -256,6 +258,7 @@ def equivalent_site_index_and_transform(self, psite):
256258
Equivalent site in the unit cell, translations and symmetry transformation.
257259
"""
258260
# Get the index of the site in the unit cell of which the PeriodicSite psite is a replica.
261+
isite = 0
259262
try:
260263
isite = self.structure_environments.structure.index(psite)
261264
except ValueError:
@@ -283,6 +286,8 @@ def equivalent_site_index_and_transform(self, psite):
283286
# that gets back the site to the unit cell (Translation III)
284287
# TODO: check that these tolerances are needed, now that the structures are refined before analyzing envs
285288
tolerances = [1e-8, 1e-7, 1e-6, 1e-5, 1e-4]
289+
d_this_site2 = (0, 0, 0)
290+
sym_trafo = None
286291
for tolerance in tolerances:
287292
for sym_op in self.symops:
288293
new_site = PeriodicSite(

pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,6 +808,9 @@ def edges(self, sites, permutation=None, input="sites"):
808808
coords = [site.coords for site in sites]
809809
elif input == "coords":
810810
coords = sites
811+
else:
812+
raise RuntimeError("Invalid input for edges.")
813+
811814
# if permutation is None:
812815
# coords = [site.coords for site in sites]
813816
# else:

pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -775,6 +775,7 @@ def compute_structure_environments(
775775

776776
to_add_from_hints = []
777777
nb_sets_info = {}
778+
cn = 0
778779

779780
for cn, nb_sets in struct_envs.neighbors_sets[isite].items():
780781
if cn not in all_cns:
@@ -1534,8 +1535,7 @@ def coordination_geometry_symmetry_measures_separation_plane(
15341535
algos = []
15351536
perfect2local_maps = []
15361537
local2perfect_maps = []
1537-
if testing:
1538-
separation_permutations = []
1538+
separation_permutations = []
15391539
nplanes = 0
15401540
for npoints in range(
15411541
separation_plane_algo.minimum_number_of_points,
@@ -1793,9 +1793,10 @@ def _cg_csm_separation_plane(
17931793
plane_found = False
17941794
permutations = []
17951795
permutations_symmetry_measures = []
1796-
if testing:
1797-
separation_permutations = []
1796+
separation_permutations = []
17981797
dist_tolerances = dist_tolerances or DIST_TOLERANCES
1798+
algo = ""
1799+
17991800
for dist_tolerance in dist_tolerances:
18001801
algo = "NOT_FOUND"
18011802
separation = local_plane.indices_separate(self.local_geometry._coords, dist_tolerance)

pymatgen/analysis/chemenv/coordination_environments/structure_environments.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2230,6 +2230,7 @@ def __str__(self):
22302230
if len(self.coord_geoms) == 0:
22312231
out += " => No coordination in it <=\n"
22322232
return out
2233+
mp_symbol = ""
22332234
for key in self.coord_geoms:
22342235
mp_symbol = key
22352236
break

0 commit comments

Comments
 (0)