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

Fix fixable ruff rules #4015

Merged
merged 33 commits into from
Aug 28, 2024
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
317ebd9
fix RUF017
DanielYang59 Aug 25, 2024
dbb52e6
fix B018: useless expressions
DanielYang59 Aug 25, 2024
7d03f14
NEED confirm: fix TRY004 type error
DanielYang59 Aug 25, 2024
53f89f0
fix PGH003: bare # type: ignore
DanielYang59 Aug 25, 2024
be99826
fix FBT003 boolean-positional-value-in-call
DanielYang59 Aug 25, 2024
79c0c87
fix PYI024 collections-named-tuple
DanielYang59 Aug 25, 2024
9fd02e0
relocate io.aims test file and rename test dir
DanielYang59 Aug 25, 2024
ee394be
NEED CONFIRM: relocate io.aims test helper functions
DanielYang59 Aug 25, 2024
381571e
add __init__.py
DanielYang59 Aug 25, 2024
f1bba42
try to fix helper function path
DanielYang59 Aug 25, 2024
8057ff6
pre-commit auto-fixes
pre-commit-ci[bot] Aug 25, 2024
e0af132
clean up pyproject.toml
DanielYang59 Aug 25, 2024
27550eb
relocate type check import
DanielYang59 Aug 25, 2024
cf24f12
use relative import, TODO how to use abs import in this case?
DanielYang59 Aug 25, 2024
101c558
fix NPY201
DanielYang59 Aug 25, 2024
735cb62
turn of paradox box of S101
DanielYang59 Aug 25, 2024
2751e64
Revert "turn of paradox box of S101"
DanielYang59 Aug 26, 2024
b466559
tweak type and docstring
DanielYang59 Aug 26, 2024
7b5cc69
fix PD011, got a lot false pos in cp2k keywords
DanielYang59 Aug 26, 2024
9cfd546
ignore PD011 as too many false pos https://github.com/astral-sh/ruff/…
DanielYang59 Aug 26, 2024
993b92c
one missing pd011
DanielYang59 Aug 26, 2024
6da15fa
fix usage of pytest raise message PT011
DanielYang59 Aug 27, 2024
b2685a5
fix B009 get attribute
DanielYang59 Aug 27, 2024
09f7692
fix B018, attr test
DanielYang59 Aug 27, 2024
e5938f6
use np array to avoid RUF005 error
DanielYang59 Aug 27, 2024
01be529
fix RUF005 with np array
DanielYang59 Aug 27, 2024
6b42af3
fix typo in hasattr use
DanielYang59 Aug 27, 2024
ae52433
NEED CONFIRM: turn on SSL certificate check
DanielYang59 Aug 27, 2024
8fdd1c5
replace http with https, there're many other cases might need test an…
DanielYang59 Aug 27, 2024
6de9a21
Revert "replace http with https, there're many other cases might need…
DanielYang59 Aug 27, 2024
81b4f76
Move to another PR, Revert "NEED CONFIRM: turn on SSL certificate check"
DanielYang59 Aug 27, 2024
ef9a46c
rename _SpinMode to SpinModeTuple
DanielYang59 Aug 28, 2024
8f5f519
use list comprehension over function tool to flat list of lists
DanielYang59 Aug 28, 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
4 changes: 3 additions & 1 deletion dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

from __future__ import annotations

import functools
import json
import operator
import re
from collections import defaultdict
from itertools import product
Expand Down Expand Up @@ -217,7 +219,7 @@ def gen_iupac_ordering():
([17], range(6, 1, -1)),
] # At -> F

order = sum((list(product(x, y)) for x, y in order), []) # noqa: RUF017
order = functools.reduce(operator.iadd, (list(product(x, y)) for x, y in order), [])
iupac_ordering_dict = dict(
zip([Element.from_row_and_group(row, group) for group, row in order], range(len(order)), strict=True)
)
Expand Down
20 changes: 11 additions & 9 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -206,18 +206,18 @@ ignore = [
"D212", # Multi-line docstring summary should start at the first line
"FBT001", # Boolean-typed positional argument in function definition
"FBT002", # Boolean default positional argument in function
"NPY201", # TODO: enable after migration to NumPy 2.0
"PD011", # (A lot of false positive on non-Pandas objects)
"PERF203", # Use of try-except in for/while loop
"PERF401", # Replace "for" loops with list comprehension
"PLR0911", # Too many return statements
"PLR0912", # Too many branches
"PLR0913", # Too many arguments
"PLR0915", # Too many statements
"PLR1702", # Too many nested blocks
"PLR2004", # Magic-value-comparison TODO fix these
"PLR2004", # Magic-value-comparison TODO: fix these
"PLW2901", # Outer for loop variable overwritten by inner assignment target
"PT013", # Incorrect import of pytest
"S101", # Use of "assert"
"S101", # Use of "assert" TODO: fix these
"S110", # Log for try-except-pass
"S112", # Log for try-except-continue
"S311", # Use random module for cryptographic purposes
Expand All @@ -238,10 +238,14 @@ isort.known-first-party = ["pymatgen"]
docstring-code-format = true

[tool.ruff.lint.per-file-ignores]
"__init__.py" = ["F401"]
# PLR2004: magic-value-comparison
# PLR6301: no-self-use
"tests/**" = ["ANN201", "D", "PLR0124", "PLR2004", "PLR6301"]
"__init__.py" = ["F401"] # unused-import
"tests/**" = [
"ANN201", # missing-return-type-undocumented-public-function
"D", # pydocstyle
"PLR0124", # comparison-with-itself
"PLR2004", # magic-value-comparison
"PLR6301", # no-self-use
]
"src/pymatgen/analysis/*" = ["D"]
"src/pymatgen/io/*" = ["D"]
"dev_scripts/*" = ["D"]
Expand All @@ -264,13 +268,11 @@ omit = [
[tool.coverage.report]
exclude_also = [
"@deprecated",
"@np.deprecate",
"def __repr__",
"except ImportError:",
"if TYPE_CHECKING:",
"if self.debug:",
"if settings.DEBUG",
"if typing.TYPE_CHECKING:",
"pragma: no cover",
"raise NotImplementedError",
"show_plot",
Expand Down
4 changes: 3 additions & 1 deletion src/pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

from __future__ import annotations

import functools
import itertools
import operator
import os
from typing import TYPE_CHECKING

Expand Down Expand Up @@ -300,7 +302,7 @@ def find_adsorption_sites(
sites = [site + distance * np.asarray(self.mvec) for site in sites]

ads_sites[key] = sites
ads_sites["all"] = sum(ads_sites.values(), []) # noqa: RUF017
ads_sites["all"] = functools.reduce(operator.iadd, ads_sites.values(), [])
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
return ads_sites

def symm_reduce(self, coords_set, threshold=1e-6):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,7 @@


def _is_ox(structure):
for elem in structure.composition:
try:
elem.oxi_state # noqa: B018
except AttributeError:
return False
return True
return all(hasattr(elem, "oxi_state") for elem in structure.composition)


class RLSVolumePredictor:
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/cli/pmg.py
Original file line number Diff line number Diff line change
Expand Up @@ -441,10 +441,10 @@ def main():
args = parser.parse_args()

try:
args.func # noqa: B018
except AttributeError:
_ = args.func
except AttributeError as exc:
parser.print_help()
raise SystemExit("Please specify a command.")
raise SystemExit("Please specify a command.") from exc
return args.func(args)


Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/electronic_structure/boltztrap2.py
Original file line number Diff line number Diff line change
Expand Up @@ -800,8 +800,8 @@ def compute_properties_doping(self, doping, temp_r=None) -> None:
self.nelect + dop_car,
temp,
self.dosweight,
True, # noqa: FBT003
False, # noqa: FBT003
refine=True,
try_center=False,
)

N, L0, L1, L2, Lm11 = BL.fermiintegrals(
Expand Down
14 changes: 10 additions & 4 deletions src/pymatgen/electronic_structure/dos.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@

import numpy as np
from monty.json import MSONable
from packaging import version
from scipy.constants import value as _constant
from scipy.ndimage import gaussian_filter1d
from scipy.signal import hilbert
Expand All @@ -18,6 +19,9 @@
from pymatgen.electronic_structure.core import Orbital, OrbitalType, Spin
from pymatgen.util.coord import get_linear_interpolated_value

if version.parse(np.__version__) < version.parse("2.0.0"):
np.trapezoid = np.trapz # noqa: NPY201

if TYPE_CHECKING:
from collections.abc import Sequence
from typing import Any, Literal
Expand Down Expand Up @@ -916,7 +920,9 @@ def get_band_filling(

# Only integrate up to Fermi level
energies = dos.energies - dos.efermi
return np.trapz(dos_densities[energies < 0], x=energies[energies < 0]) / np.trapz(dos_densities, x=energies)
return np.trapezoid(dos_densities[energies < 0], x=energies[energies < 0]) / np.trapezoid(
dos_densities, x=energies
)

def get_band_center(
self,
Expand Down Expand Up @@ -1112,7 +1118,7 @@ def get_n_moment(
p = energies

# Take the nth moment
return np.trapz(p**n * dos_densities, x=energies) / np.trapz(dos_densities, x=energies)
return np.trapezoid(p**n * dos_densities, x=energies) / np.trapezoid(dos_densities, x=energies)

def get_hilbert_transform(
self,
Expand Down Expand Up @@ -1337,8 +1343,8 @@ def get_dos_fp_similarity(
vec1 = np.array([pt[col] for pt in fp1_dict.values()]).flatten()
vec2 = np.array([pt[col] for pt in fp2_dict.values()]).flatten()
else:
vec1 = fp1_dict[fp1[2][pt]][col] # type: ignore # noqa:PGH003
vec2 = fp2_dict[fp2[2][pt]][col] # type: ignore # noqa:PGH003
vec1 = fp1_dict[fp1[2][pt]][col]
vec2 = fp2_dict[fp2[2][pt]][col]

if not normalize and metric == "tanimoto":
rescale = np.linalg.norm(vec1) ** 2 + np.linalg.norm(vec2) ** 2 - np.dot(vec1, vec2)
Expand Down
8 changes: 4 additions & 4 deletions src/pymatgen/entries/mixing_scheme.py
Original file line number Diff line number Diff line change
Expand Up @@ -292,8 +292,8 @@ def get_adjustments(self, entry, mixing_state_data: pd.DataFrame | None = None):
)

# Verify that the entry is included in the mixing state data
if (entry.entry_id not in mixing_state_data["entry_id_1"].values) and ( # noqa: PD011
entry.entry_id not in mixing_state_data["entry_id_2"].values # noqa: PD011
if (entry.entry_id not in mixing_state_data["entry_id_1"].to_numpy()) and (
entry.entry_id not in mixing_state_data["entry_id_2"].to_numpy()
):
raise CompatibilityError(
f"WARNING! Discarding {run_type} entry {entry.entry_id} for {entry.formula} "
Expand All @@ -303,8 +303,8 @@ def get_adjustments(self, entry, mixing_state_data: pd.DataFrame | None = None):
)

# Verify that the entry's energy has not been modified since mixing state data was generated
if (entry.energy_per_atom not in mixing_state_data["energy_1"].values) and ( # noqa: PD011
entry.energy_per_atom not in mixing_state_data["energy_2"].values # noqa: PD011
if (entry.energy_per_atom not in mixing_state_data["energy_1"].to_numpy()) and (
entry.energy_per_atom not in mixing_state_data["energy_2"].to_numpy()
):
raise CompatibilityError(
f"WARNING! Discarding {run_type} entry {entry.entry_id} for {entry.formula} "
Expand Down
12 changes: 9 additions & 3 deletions src/pymatgen/io/abinit/abiobjects.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@
from __future__ import annotations

import abc
from collections import namedtuple
from collections.abc import Iterable
from enum import Enum, unique
from pprint import pformat
from typing import TYPE_CHECKING, cast
from typing import TYPE_CHECKING, NamedTuple, cast

import numpy as np
from monty.collections import AttrDict
Expand Down Expand Up @@ -339,7 +338,14 @@ class DefaultVariable:
DEFAULT = DefaultVariable()


class SpinMode(namedtuple("SpinMode", "mode nsppol nspinor nspden"), AbivarAble, MSONable): # noqa: PYI024
class _SpinMode(NamedTuple):
DanielYang59 marked this conversation as resolved.
Show resolved Hide resolved
mode: str
nsppol: int
nspinor: int
nspden: int


class SpinMode(_SpinMode, AbivarAble, MSONable):
"""
Different configurations of the electron density as implemented in abinit:
One can use as_spinmode to construct the object via SpinMode.as_spinmode
Expand Down
8 changes: 4 additions & 4 deletions src/pymatgen/io/abinit/pseudos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1401,7 +1401,7 @@ def plot_densities(self, ax: plt.Axes = None, **kwargs):
for idx, density_name in enumerate(["ae_core_density", "pseudo_core_density"]):
rden = getattr(self, density_name)
label = "$n_c$" if idx == 1 else r"$\tilde{n}_c$"
ax.plot(rden.mesh, rden.mesh * rden.values, label=label, lw=2) # noqa: PD011
ax.plot(rden.mesh, rden.mesh * rden.values, label=label, lw=2)

ax.legend(loc="best")

Expand Down Expand Up @@ -1429,10 +1429,10 @@ def plot_waves(self, ax: plt.Axes = None, fontsize=12, **kwargs):
# ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1))

for state, rfunc in self.pseudo_partial_waves.items():
ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label=f"PS-WAVE: {state}") # noqa: PD011
ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label=f"PS-WAVE: {state}")

for state, rfunc in self.ae_partial_waves.items():
ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label=f"AE-WAVE: {state}") # noqa: PD011
ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, lw=2, label=f"AE-WAVE: {state}")

ax.legend(loc="best", shadow=True, fontsize=fontsize)

Expand All @@ -1458,7 +1458,7 @@ def plot_projectors(self, ax: plt.Axes = None, fontsize=12, **kwargs):
# ax.annotate("$r_c$", xy=(self.paw_radius + 0.1, 0.1))

for state, rfunc in self.projector_functions.items():
ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, label=f"TPROJ: {state}") # noqa: PD011
ax.plot(rfunc.mesh, rfunc.mesh * rfunc.values, label=f"TPROJ: {state}")

ax.legend(loc="best", shadow=True, fontsize=fontsize)

Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/io/aims/sets/bs.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ def get_parameter_updates(
dict: The updated for the parameters for the output section of FHI-aims
"""
if isinstance(structure, Molecule):
raise ValueError("BandStructures can not be made for non-periodic systems") # noqa: TRY004
Copy link
Contributor Author

@DanielYang59 DanielYang59 Aug 25, 2024

Choose a reason for hiding this comment

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

ValueError changed to TypeError, tests seem to pass.

raise TypeError("BandStructures can not be made for non-periodic systems")

updated_outputs = prev_parameters.get("output", [])
updated_outputs += prepare_band_input(structure, self.k_point_density)
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/io/cp2k/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ def __eq__(self, other: object) -> bool:
return NotImplemented
if self.name.upper() == other.name.upper():
v1 = [val.upper() if isinstance(val, str) else val for val in self.values]
v2 = [val.upper() if isinstance(val, str) else val for val in other.values] # noqa: PD011
v2 = [val.upper() if isinstance(val, str) else val for val in other.values]
if v1 == v2 and self.units == other.units:
return True
return False
Expand Down
10 changes: 5 additions & 5 deletions src/pymatgen/io/cp2k/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,12 +177,12 @@ def spin_polarized(self) -> bool:
@property
def charge(self) -> float:
"""Charge from the input file."""
return self.input["FORCE_EVAL"]["DFT"].get("CHARGE", Keyword("", 0)).values[0] # noqa: PD011
return self.input["FORCE_EVAL"]["DFT"].get("CHARGE", Keyword("", 0)).values[0]

@property
def multiplicity(self) -> int:
"""The spin multiplicity from input file."""
return self.input["FORCE_EVAL"]["DFT"].get("Multiplicity", Keyword("")).values[0] # noqa: PD011
return self.input["FORCE_EVAL"]["DFT"].get("Multiplicity", Keyword("")).values[0]

@property
def is_molecule(self) -> bool:
Expand Down Expand Up @@ -691,9 +691,9 @@ def parse_cell_params(self):
cell = self.input["force_eval"]["subsys"]["cell"]
if cell.get("abc"):
return [
[cell["abc"].values[0], 0, 0], # noqa: PD011
[0, cell["abc"].values[1], 0], # noqa: PD011
[0, 0, cell["abc"].values[2]], # noqa: PD011
[cell["abc"].values[0], 0, 0],
[0, cell["abc"].values[1], 0],
[0, 0, cell["abc"].values[2]],
]
return [
list(cell.get("A").values),
Expand Down
8 changes: 4 additions & 4 deletions src/pymatgen/io/cp2k/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -988,7 +988,7 @@ def activate_motion(
if not self.check("MOTION"):
self.insert(Section("MOTION", subsections={}))

run_type = self["global"].get("run_type", Keyword("run_type", "energy")).values[0].upper() # noqa: PD011
run_type = self["global"].get("run_type", Keyword("run_type", "energy")).values[0].upper()
run_type = {"GEOMETRY_OPTIMIZATION": "GEO_OPT", "MOLECULAR_DYNAMICS": "MD"}.get(run_type, run_type)

self["MOTION"].insert(Section("PRINT", subsections={}))
Expand Down Expand Up @@ -1296,7 +1296,7 @@ def modify_dft_print_iters(self, iters, add_last="no"):
no: do not explicitly include the last iteration
"""
assert add_last.lower() in ["no", "numeric", "symbolic"]
run_type = self["global"].get("run_type", Keyword("run_type", "energy")).values[0].upper() # noqa: PD011
run_type = self["global"].get("run_type", Keyword("run_type", "energy")).values[0].upper()
if run_type not in ["ENERGY_FORCE", "ENERGY", "WAVEFUNCTION_OPTIMIZATION", "WFN_OPT"] and self.check(
"FORCE_EVAL/DFT/PRINT"
):
Expand All @@ -1322,8 +1322,8 @@ def validate(self):
for val in self["force_eval"]["subsys"].subsections.values():
if (
val.name.upper() == "KIND"
and val["POTENTIAL"].values[0].upper() == "ALL" # noqa: PD011
and self["force_eval"]["dft"]["qs"]["method"].values[0].upper() != "GAPW" # noqa: PD011
and val["POTENTIAL"].values[0].upper() == "ALL"
and self["force_eval"]["dft"]["qs"]["method"].values[0].upper() != "GAPW"
):
raise Cp2kValidationError("All electron basis sets require GAPW method")

Expand Down
Loading