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

Enable more ruff rules including A, DTZ, PGH and more #3871

Merged
merged 50 commits into from
Jun 21, 2024
Merged
Show file tree
Hide file tree
Changes from 38 commits
Commits
Show all changes
50 commits
Select commit Hold shift + click to select a range
88e6e38
enable ruff rule `PGH`
DanielYang59 Jun 9, 2024
5aae5d0
revert change in lobster.inputs test
DanielYang59 Jun 9, 2024
0cca4db
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 9, 2024
a8dcb88
fix some PathLike-related issues
DanielYang59 Jun 9, 2024
8003545
more PGH003 fixes
DanielYang59 Jun 9, 2024
bdd03ca
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 9, 2024
29891d0
more PGH003 fixes
DanielYang59 Jun 9, 2024
7561745
Merge branch 'pgh-ruff-rules' of https://github.com/DanielYang59/pyma…
DanielYang59 Jun 9, 2024
19231be
fix unit test
DanielYang59 Jun 9, 2024
b19a177
more fixes for analysis module
DanielYang59 Jun 9, 2024
ea2b642
finish all PGH
DanielYang59 Jun 9, 2024
bce41f6
add more ruff rules
DanielYang59 Jun 9, 2024
7fac0b4
fix some `DTZ` datetime errors
DanielYang59 Jun 9, 2024
6752d77
fix `A001`
DanielYang59 Jun 9, 2024
b1aa5bb
fix `TRY004`
DanielYang59 Jun 9, 2024
5b8a654
fix more `TRY` errors
DanielYang59 Jun 9, 2024
a6ec759
tweak format
DanielYang59 Jun 9, 2024
d5609f6
tweak rule selections
DanielYang59 Jun 9, 2024
c1986cc
tweak pyproject.toml
DanielYang59 Jun 9, 2024
ae68a47
disable NPY rule for this PR
DanielYang59 Jun 9, 2024
7e0dc6a
revert datetime utc replacement for now
DanielYang59 Jun 9, 2024
217369e
pre-commit auto-fixes
pre-commit-ci[bot] Jun 9, 2024
0f8788a
reapply DTZ005 fixes
DanielYang59 Jun 9, 2024
c231f45
Merge branch 'pgh-ruff-rules' of https://github.com/DanielYang59/pyma…
DanielYang59 Jun 9, 2024
bdd1f04
fix DTZ007
DanielYang59 Jun 9, 2024
0ea568e
fix PLR0124: compare with itself
DanielYang59 Jun 9, 2024
50e9b7d
fix unit test
DanielYang59 Jun 9, 2024
59d851b
suppress or fix `A002`
DanielYang59 Jun 9, 2024
2ca4ca9
fix errors that don't show locally
DanielYang59 Jun 9, 2024
3ed29b9
replace `match.group(x)` with `match[x]`
DanielYang59 Jun 9, 2024
f4d3ec5
correct err code
DanielYang59 Jun 9, 2024
e0e0fe3
more group(x) changes
DanielYang59 Jun 9, 2024
3a29aad
relocate no planned ruff families
DanielYang59 Jun 9, 2024
3b85706
reverse rule selection
DanielYang59 Jun 9, 2024
411babc
enable rule family `D` for `pymatgen/viz`
DanielYang59 Jun 9, 2024
0999bc2
restore assert x == x in __eq__ tests and ignore ruff PLR0124 in test…
janosh Jun 9, 2024
a6afae9
cif -> CIF in doc str
janosh Jun 9, 2024
0c71b06
snake_case var names
janosh Jun 9, 2024
9dfa60e
revert deletion of test for __eq__
DanielYang59 Jun 10, 2024
ebfb9d5
replace `[0:x]` slicing with `[:x]`
DanielYang59 Jun 10, 2024
a994dae
replace one more [0:x] slicing
DanielYang59 Jun 10, 2024
47d72f3
replace multi-line `dict()` with `{}`
DanielYang59 Jun 10, 2024
1fea2f4
split xcfunc tests
DanielYang59 Jun 11, 2024
59832d2
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 11, 2024
7b74fd1
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 13, 2024
249cc93
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 18, 2024
935b3f0
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 18, 2024
6fbe87d
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 19, 2024
aaebd50
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 20, 2024
3922127
Merge branch 'master' into pgh-ruff-rules
DanielYang59 Jun 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
6 changes: 3 additions & 3 deletions dev_scripts/chemenv/get_plane_permutations_optimized.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def random_permutations_iterator(initial_permutation, n_permutations):
sym_measures = [c["symmetry_measure"] for c in csms]
prt1(string="Continuous symmetry measures", printing_volume=printing_volume)
prt1(string=sym_measures, printing_volume=printing_volume)
csms_with_recorded_permutation = [] # type: ignore
csms_with_recorded_permutation: list = []
explicit_permutations = []
for icsm, csm in enumerate(csms):
found = False
Expand Down Expand Up @@ -308,7 +308,6 @@ def random_permutations_iterator(initial_permutation, n_permutations):
all_planes_point_indices += algo.other_plane_points

# Setup of the permutations to be used for this algorithm

indices = list(range(cg.coordination_number))
if permutations_setup_type == "all":
perms_iterator = itertools.permutations(indices)
Expand Down Expand Up @@ -400,7 +399,8 @@ def random_permutations_iterator(initial_permutation, n_permutations):
else:
perms_used[some_perm] = 1
tcurrent = time.process_time()
time_left = (n_permutations - idx_perm) * (tcurrent - t0) / idx_perm # type: ignore
assert n_permutations is not None
time_left = (n_permutations - idx_perm) * (tcurrent - t0) / idx_perm
time_left = f"{time_left:.1f}"
idx_perm += 1
print(
Expand Down
22 changes: 11 additions & 11 deletions dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,24 +30,24 @@ def parse_oxi_state():
oxi_data = re.sub("[\n\r]", "", oxi_data)
patt = re.compile("<tr>(.*?)</tr>", re.MULTILINE)

for m in patt.finditer(oxi_data):
line = m.group(1)
for match in patt.finditer(oxi_data):
line = match[1]
line = re.sub("</td>", "", line)
line = re.sub("(<td>)+", "<td>", line)
line = re.sub("</*a[^>]*>", "", line)
el = None
oxi_states = []
common_oxi = []
for tok in re.split("<td>", line.strip()):
m2 = re.match(r"<b>([A-Z][a-z]*)</b>", tok)
if m2:
el = m2.group(1)
match2 = re.match(r"<b>([A-Z][a-z]*)</b>", tok)
if match2:
el = match2[1]
else:
m3 = re.match(r"(<b>)*([\+\-]\d)(</b>)*", tok)
if m3:
oxi_states += [int(m3.group(2))]
if m3.group(1):
common_oxi += [int(m3.group(2))]
match3 = re.match(r"(<b>)*([\+\-]\d)(</b>)*", tok)
if match3:
oxi_states += [int(match3[2])]
if match3[1]:
common_oxi += [int(match3[2])]
if el in data:
del data[el]["Max oxidation state"]
del data[el]["Min oxidation state"]
Expand Down Expand Up @@ -79,7 +79,7 @@ def parse_ionic_radii():
ionic_radii = {}
for tok_idx in range(3, len(tokens)):
if match := re.match(r"^\s*([0-9\.]+)", tokens[tok_idx]):
ionic_radii[int(header[tok_idx])] = float(match.group(1))
ionic_radii[int(header[tok_idx])] = float(match[1])

if el in data:
data[el][f"Ionic_radii{suffix}"] = ionic_radii
Expand Down
4 changes: 2 additions & 2 deletions docs/apidoc/conf.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def __init__(self, structure_matcher: dict | StructureMatcher | None = None, sym
self.symprec = symprec
self.structure_list: dict[str, list[Structure]] = defaultdict(list)
if not isinstance(structure_matcher, (dict, StructureMatcher, type(None))):
raise ValueError(f"{structure_matcher=} must be a dict, StructureMatcher or None")
raise TypeError(f"{structure_matcher=} must be a dict, StructureMatcher or None")
if isinstance(structure_matcher, dict):
self.structure_matcher = StructureMatcher.from_dict(structure_matcher)
else:
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -270,10 +270,10 @@ def from_cif_str(
primitive: bool = True,
occupancy_tolerance: float = 1.0,
) -> Self:
"""Generate TransformedStructure from a cif string.
"""Generate TransformedStructure from a CIF string.

Args:
cif_string (str): Input cif string. Should contain only one
cif_string (str): Input CIF string. Should contain only one
structure. For CIFs containing multiple structures, please use
CifTransmuter.
transformations (list[Transformation]): Sequence of transformations
Expand Down Expand Up @@ -302,7 +302,7 @@ def from_cif_str(
source = "uploaded cif"
source_info = {
"source": source,
"datetime": str(datetime.datetime.now()),
"datetime": str(datetime.datetime.now(tz=datetime.timezone.utc)),
"original_file": raw_str,
"cif_data": cif_dict[cif_keys[0]],
}
Expand Down Expand Up @@ -330,7 +330,7 @@ def from_poscar_str(
struct = poscar.structure
source_info = {
"source": "POSCAR",
"datetime": str(datetime.datetime.now()),
"datetime": str(datetime.datetime.now(tz=datetime.timezone.utc)),
"original_file": raw_str,
}
return cls(struct, transformations, history=[source_info])
Expand Down
16 changes: 7 additions & 9 deletions pymatgen/alchemy/transmuters.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,10 +121,10 @@ def append_transformation(self, transformation, extend_collection=False, clear_r
describes whether the transformation altered the structure
"""
if self.ncores and transformation.use_multiprocessing:
with Pool(self.ncores) as p:
with Pool(self.ncores) as pool:
# need to condense arguments into single tuple to use map
z = ((ts, transformation, extend_collection, clear_redo) for ts in self.transformed_structures)
trafo_new_structs = p.map(_apply_transformation, z, 1)
trafo_new_structs = pool.map(_apply_transformation, z, 1)
self.transformed_structures = []
for ts in trafo_new_structs:
self.transformed_structures.extend(ts)
Expand Down Expand Up @@ -223,19 +223,17 @@ def from_structures(cls, structures, transformations=None, extend_collection=0)


class CifTransmuter(StandardTransmuter):
"""Generate a Transmuter from a cif string, possibly containing multiple
structures.
"""
"""Generate a Transmuter from a CIF string, possibly containing multiple structures."""

def __init__(self, cif_string, transformations=None, primitive=True, extend_collection=False):
"""Generate a Transmuter from a cif string, possibly
"""Generate a Transmuter from a CIF string, possibly
containing multiple structures.

Args:
cif_string: A string containing a cif or a series of CIFs
cif_string: A string containing a CIF or a series of CIFs
transformations: New transformations to be applied to all
structures
primitive: Whether to generate the primitive cell from the cif.
primitive: Whether to generate the primitive cell from the CIF.
extend_collection: Whether to use more than one output structure
from one-to-many transformations. extend_collection can be a
number, which determines the maximum branching for each
Expand All @@ -262,7 +260,7 @@ def from_filenames(cls, filenames, transformations=None, primitive=True, extend_
containing multiple structures.

Args:
filenames: List of strings of the cif files
filenames: List of strings of the CIF files
transformations: New transformations to be applied to all
structures
primitive: Same meaning as in __init__.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -483,7 +483,7 @@ def compute_periodicity_cycle_basis(self) -> None:
for current_delta in this_cycle_deltas:
this_cycle_deltas_new.append(current_delta + delta)
this_cycle_deltas = this_cycle_deltas_new
all_deltas.extend(this_cycle_deltas) # type: ignore
all_deltas.extend(this_cycle_deltas)
all_deltas = get_linearly_independent_vectors(all_deltas)
if len(all_deltas) == 3:
return
Expand All @@ -501,7 +501,7 @@ def compute_periodicity_cycle_basis(self) -> None:
current_delta = get_delta(n1, n2, e1data)
delta = get_delta(n2, n1, e2data)
current_delta += delta
all_deltas.append(current_delta) # type: ignore
all_deltas.append(current_delta)
else:
raise ValueError("Should not be here ...")
all_deltas = get_linearly_independent_vectors(all_deltas)
Expand Down Expand Up @@ -770,7 +770,7 @@ def _edgedictkey_to_edgekey(key):
except ValueError:
return key
else:
raise ValueError("Edge key in a dict of dicts representation of a graph should be either a str or an int.")
raise TypeError("Edge key in a dict of dicts representation of a graph should be either a str or an int.")

@staticmethod
def _retuplify_edgedata(edata):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ def set_structure_environments(self, structure_environments):
"""
self.structure_environments = structure_environments
if not isinstance(self.structure_environments.voronoi, DetailedVoronoiContainer):
raise ValueError('Voronoi Container not of type "DetailedVoronoiContainer"')
raise TypeError('Voronoi Container not of type "DetailedVoronoiContainer"')
self.prepare_symmetries()

def prepare_symmetries(self):
Expand Down Expand Up @@ -512,7 +512,7 @@ class SimplestChemenvStrategy(AbstractChemenvStrategy):
DEFAULT_ANGLE_CUTOFF = 0.3
DEFAULT_CONTINUOUS_SYMMETRY_MEASURE_CUTOFF = 10
DEFAULT_ADDITIONAL_CONDITION = AbstractChemenvStrategy.AC.ONLY_ACB
STRATEGY_OPTIONS: ClassVar[dict[str, dict]] = dict( # type: ignore
STRATEGY_OPTIONS: ClassVar[dict[str, dict]] = dict(
distance_cutoff=dict(
type=DistanceCutoffFloat,
internal="_distance_cutoff",
Expand Down Expand Up @@ -598,7 +598,7 @@ def angle_cutoff(self, angle_cutoff):
self._angle_cutoff = AngleCutoffFloat(angle_cutoff)

@property
def additional_condition(self):
def additional_condition(self) -> AdditionalConditionInt:
"""Additional condition for this strategy."""
return self._additional_condition

Expand Down Expand Up @@ -897,7 +897,7 @@ class SimpleAbundanceChemenvStrategy(AbstractChemenvStrategy):

DEFAULT_MAX_DIST = 2.0
DEFAULT_ADDITIONAL_CONDITION = AbstractChemenvStrategy.AC.ONLY_ACB
STRATEGY_OPTIONS: ClassVar[dict[str, dict]] = dict( # type: ignore
STRATEGY_OPTIONS: ClassVar[dict[str, dict]] = dict(
surface_calculation_type={},
additional_condition=dict(
type=AdditionalConditionInt,
Expand Down Expand Up @@ -1057,7 +1057,7 @@ def __eq__(self, other: object) -> bool:
if not isinstance(other, type(self)):
return NotImplemented

return self._additional_condition == other.additional_condition # type: ignore
return self._additional_condition == other.additional_condition # type: ignore[has-type]

def as_dict(self):
"""
Expand Down Expand Up @@ -1347,7 +1347,7 @@ def angle_sumn(self, nb_set):
def __eq__(self, other: object) -> bool:
if not hasattr(other, "aa"):
return NotImplemented
return self.aa == other.aa # type: ignore
return self.aa == other.aa

def as_dict(self):
"""MSONable dict."""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@ def faces(self, sites, permutation=None):
coords = [site.coords for site in sites] if permutation is None else [sites[ii].coords for ii in permutation]
return [[coords[ii] for ii in face] for face in self._faces]

def edges(self, sites, permutation=None, input="sites"):
def edges(self, sites, permutation=None, input="sites"): # noqa: A002
"""Get the list of edges of this coordination geometry. Each edge is given as a
list of its end vertices coordinates.
"""
Expand Down Expand Up @@ -1144,7 +1144,7 @@ def is_a_valid_coordination_geometry(
# TODO give a more helpful error message that suggests possible reasons and solutions
raise RuntimeError("Should not be here!")

def pretty_print(self, type="implemented_geometries", maxcn=8, additional_info=None):
def pretty_print(self, type="implemented_geometries", maxcn=8, additional_info=None): # noqa: A002
"""Get a string with a list of the Coordination Geometries.

Args:
Expand Down
13 changes: 8 additions & 5 deletions pymatgen/analysis/chemenv/utils/scripts_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
from __future__ import annotations

import re
from typing import TYPE_CHECKING

import numpy as np

from pymatgen.analysis.chemenv.coordination_environments.chemenv_strategies import (
AbstractChemenvStrategy,
SimpleAbundanceChemenvStrategy,
SimplestChemenvStrategy,
TargetedPenaltiedAbundanceChemenvStrategy,
Expand All @@ -32,6 +32,9 @@
except ImportError:
StructureVis = None # type: ignore[misc]

if TYPE_CHECKING:
from typing import Any

__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__credits__ = "Geoffroy Hautier"
Expand All @@ -40,10 +43,10 @@
__email__ = "david.waroquiers@gmail.com"
__date__ = "Feb 20, 2016"

strategies_class_lookup: dict[str, AbstractChemenvStrategy] = {
"SimplestChemenvStrategy": SimplestChemenvStrategy, # type: ignore
"SimpleAbundanceChemenvStrategy": SimpleAbundanceChemenvStrategy, # type: ignore
"TargetedPenaltiedAbundanceChemenvStrategy": TargetedPenaltiedAbundanceChemenvStrategy, # type: ignore
strategies_class_lookup: dict[str, Any] = {
"SimplestChemenvStrategy": SimplestChemenvStrategy,
"SimpleAbundanceChemenvStrategy": SimpleAbundanceChemenvStrategy,
"TargetedPenaltiedAbundanceChemenvStrategy": TargetedPenaltiedAbundanceChemenvStrategy,
}


Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/chempot_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ def get_plot(
default_min_limit=self.default_min_limit,
formal_chempots=self.formal_chempots,
)
fig = cpd.get_plot(elements=elems, label_stable=label_stable) # type: ignore
fig = cpd.get_plot(elements=elems, label_stable=label_stable) # type: ignore[arg-type]
else:
fig = self._get_3d_plot(
elements=elems,
Expand All @@ -211,7 +211,7 @@ def _get_domains(self) -> dict[str, np.ndarray]:
interior_point = np.min(self.lims, axis=1) + 1e-1
hs_int = HalfspaceIntersection(hs_hyperplanes, interior_point)

domains = {entry.reduced_formula: [] for entry in entries} # type: ignore
domains: dict[str, list] = {entry.reduced_formula: [] for entry in entries}

for intersection, facet in zip(hs_int.intersections, hs_int.dual_facets):
for v in facet:
Expand Down Expand Up @@ -585,7 +585,7 @@ def get_chempot_axis_title(element) -> str:

return axes_layout

@property # type: ignore
@property
@lru_cache(maxsize=1) # noqa: B019
def domains(self) -> dict[str, np.ndarray]:
"""Mapping of formulas to array of domain boundary points."""
Expand Down
Loading