Skip to content

Commit

Permalink
ruff 0.4.3 auto-fixes (#3808)
Browse files Browse the repository at this point in the history
* ruff auto-fixes

* PascalCase class name mpl_figure
  • Loading branch information
janosh authored May 4, 2024
1 parent c43af9b commit a16ac39
Show file tree
Hide file tree
Showing 18 changed files with 53 additions and 63 deletions.
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ ci:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.4.2
rev: v0.4.3
hooks:
- id: ruff
args: [--fix, --unsafe-fixes]
Expand Down Expand Up @@ -47,7 +47,7 @@ repos:
- id: blacken-docs

- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.39.0
rev: v0.40.0
hooks:
- id: markdownlint
# MD013: line too long
Expand All @@ -64,6 +64,6 @@ repos:
args: [--drop-empty-cells, --keep-output]

- repo: https://github.com/RobertCraigie/pyright-python
rev: v1.1.360
rev: v1.1.361
hooks:
- id: pyright
2 changes: 1 addition & 1 deletion pymatgen/analysis/eos.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
__author__ = "Kiran Mathew, gmatteo"
__credits__ = "Cormac Toher"

logger = logging.getLogger(__file__)
logger = logging.getLogger(__name__)


class EOSBase(ABC):
Expand Down
10 changes: 4 additions & 6 deletions pymatgen/analysis/transition_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,12 +235,10 @@ def from_dir(cls, root_dir, relaxation_dirs=None, **kwargs) -> Self:

# Setup the search sequence for the OUTCARs for the terminal
# directories.
terminal_dirs = []
if relaxation_dirs is not None:
terminal_dirs.append(relaxation_dirs)
terminal_dirs.append((neb_dirs[0][1], neb_dirs[-1][1]))
terminal_dirs.append([os.path.join(root_dir, d) for d in ["start", "end"]])
terminal_dirs.append([os.path.join(root_dir, d) for d in ["initial", "final"]])
terminal_dirs = [] if relaxation_dirs is None else [relaxation_dirs]
terminal_dirs += [(neb_dirs[0][1], neb_dirs[-1][1])]
terminal_dirs += [[os.path.join(root_dir, folder) for folder in ["start", "end"]]]
terminal_dirs += [[os.path.join(root_dir, folder) for folder in ["initial", "final"]]]

for idx, neb_dir in neb_dirs:
outcar = glob(f"{neb_dir}/OUTCAR*")
Expand Down
4 changes: 1 addition & 3 deletions pymatgen/core/sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,9 +229,7 @@ def __lt__(self, other):
return True
if self.species.average_electroneg > other.species.average_electroneg:
return False
if self.species_string < other.species_string:
return True
return False
return self.species_string < other.species_string

def __str__(self) -> str:
return f"{self.coords} {self.species_string}"
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/electronic_structure/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3976,7 +3976,7 @@ def plot_fermi_surface(
if transparency_factor is None:
transparency_factor = [1] * n_surfaces

fig = mlab_figure if mlab_figure else None
fig = mlab_figure or None

if kpoints_dict is None:
kpoints_dict = {}
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/abinit/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
if TYPE_CHECKING:
from typing_extensions import Self

logger = logging.getLogger(__file__)
logger = logging.getLogger(__name__)


# List of Abinit variables used to specify the structure.
Expand Down
16 changes: 9 additions & 7 deletions pymatgen/io/abinit/pseudos.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,13 +140,15 @@ def to_str(self, verbose=0) -> str:
"""String representation."""

lines: list[str] = []
lines.append(f"<{type(self).__name__}: {self.basename}>")
lines.append(" summary: " + self.summary.strip())
lines.append(f" number of valence electrons: {self.Z_val}")
lines.append(f" maximum angular momentum: {l2str(self.l_max)}")
lines.append(f" angular momentum for local part: {l2str(self.l_local)}")
lines.append(f" XC correlation: {self.xc}")
lines.append(f" supports spin-orbit: {self.supports_soc}")
lines += (
f"<{type(self).__name__}: {self.basename}>",
" summary: " + self.summary.strip(),
f" number of valence electrons: {self.Z_val}",
f" maximum angular momentum: {l2str(self.l_max)}",
f" angular momentum for local part: {l2str(self.l_local)}",
f" XC correlation: {self.xc}",
f" supports spin-orbit: {self.supports_soc}",
)

if self.isnc:
lines.append(f" radius for non-linear core correction: {self.nlcc_radius}")
Expand Down
5 changes: 1 addition & 4 deletions pymatgen/io/aims/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,10 +289,7 @@ def __eq__(self, other: object) -> bool:
if self.filename != other.filename:
return False

if self.elf_type != other.elf_type:
return False

return True
return self.elf_type == other.elf_type

def __post_init__(self) -> None:
"""Check the inputted variables to make sure they are correct
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/io/ase.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,18 @@ def __init__(self, *args, **kwargs):
class MSONAtoms(Atoms, MSONable):
"""A custom subclass of ASE Atoms that is MSONable, including `.as_dict()` and `.from_dict()` methods."""

def as_dict(atoms: Atoms) -> dict[str, Any]:
def as_dict(self: Atoms) -> dict[str, Any]:
# Normally, we would want to this to be a wrapper around atoms.todict() with @module and
# @class key-value pairs inserted. However, atoms.todict()/atoms.fromdict() is not meant
# to be used in a round-trip fashion and does not work properly with constraints.
# See ASE issue #1387.
atoms_no_info = atoms.copy()
atoms_no_info = self.copy()
atoms_no_info.info = {}
return {
"@module": "pymatgen.io.ase",
"@class": "MSONAtoms",
"atoms_json": encode(atoms_no_info),
"atoms_info": jsanitize(atoms.info, strict=True),
"atoms_info": jsanitize(self.info, strict=True),
}

@classmethod
Expand Down
8 changes: 5 additions & 3 deletions pymatgen/io/feff/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -605,9 +605,11 @@ def get_str(self, sort_keys: bool = False, pretty: bool = False) -> str:
# no cross terms for orientation averaged spectrum
beam_energy_list[2] = str(0)
lines.append([self._stringify_val(beam_energy_list)])
lines.append([self._stringify_val(self[key]["ANGLES"])])
lines.append([self._stringify_val(self[key]["MESH"])])
lines.append([self._stringify_val(self[key]["POSITION"])])
lines += (
[self._stringify_val(self[key]["ANGLES"])],
[self._stringify_val(self[key]["MESH"])],
[self._stringify_val(self[key]["POSITION"])],
)
else:
lines.append([key, self._stringify_val(self[key])])
if pretty:
Expand Down
7 changes: 2 additions & 5 deletions pymatgen/io/lobster/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,14 +157,11 @@ def __getitem__(self, key) -> Any:
return self.data[normalized_key]

def __contains__(self, key) -> bool:
"""Implements getitem from dict to avoid problems with cases."""
"""Implements getitem from dict to avoid problems with different key casing."""
normalized_key = next((k for k in self if key.strip().lower() == k.lower()), key)

key_is_unknown = normalized_key.lower() not in map(str.lower, Lobsterin.AVAILABLE_KEYWORDS)
if key_is_unknown or normalized_key not in self.data:
return False

return True
return not key_is_unknown and normalized_key in self.data

def __delitem__(self, key):
new_key = next((key_here for key_here in self if key.strip().lower() == key_here.lower()), key)
Expand Down
27 changes: 13 additions & 14 deletions pymatgen/io/pwmat/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ def get_virial(self) -> np.ndarray | None:
Returns:
np.ndarray | None: Virial tensor of shape=(9,)
"""
virial_tensor = []
virial_tensor: list[float] = []
aim_content = "LATTICE"
aim_idx = ListLocator.locate_all_lines(strs_lst=self.strs_lst, content=aim_content)[0]

Expand All @@ -344,9 +344,7 @@ def get_virial(self) -> np.ndarray | None:
for tmp_idx in [aim_idx + 1, aim_idx + 2, aim_idx + 3]:
# tmp_str_lst = ['0.120972E+02', '0.483925E+01', '0.242063E+01']
tmp_str_lst = self.strs_lst[tmp_idx].split()[-3:]
virial_tensor.append(float(tmp_str_lst[0]))
virial_tensor.append(float(tmp_str_lst[1]))
virial_tensor.append(float(tmp_str_lst[2]))
virial_tensor += (float(tmp_str_lst[0]), float(tmp_str_lst[1]), float(tmp_str_lst[2]))

return np.array(virial_tensor)

Expand Down Expand Up @@ -441,17 +439,18 @@ def get_str(self) -> str:
lattice = Lattice(-lattice.matrix)

lines: list[str] = []
lines.append(f"\t{self.structure.num_sites} atoms\n")
lines.append("Lattice vector\n")
for ii in range(3):
lines.append(f"{lattice.matrix[ii][0]:>15f}{lattice.matrix[ii][1]:>15f}{lattice.matrix[ii][2]:>15f}\n")
lines += (f"\t{self.structure.num_sites} atoms\n", "Lattice vector\n")
for idx in range(3):
lines.append(f"{lattice.matrix[idx][0]:>15f}{lattice.matrix[idx][1]:>15f}{lattice.matrix[idx][2]:>15f}\n")
lines.append("Position, move_x, move_y, move_z\n")
for ii in range(self.structure.num_sites):
lines.append(f"{int(self.structure.species[ii].Z):>4d}")
lines.append(f"{self.structure.frac_coords[ii][0]:>15f}")
lines.append(f"{self.structure.frac_coords[ii][1]:>15f}")
lines.append(f"{self.structure.frac_coords[ii][2]:>15f}")
lines.append(" 1 1 1\n")
for site_idx in range(len(self.structure)):
lines += (
f"{int(self.structure.species[site_idx].Z):>4d}",
f"{self.structure.frac_coords[site_idx][0]:>15f}",
f"{self.structure.frac_coords[site_idx][1]:>15f}",
f"{self.structure.frac_coords[site_idx][2]:>15f}",
" 1 1 1\n",
)
if "magmom" in self.structure.sites[0].properties:
lines.append("MAGNETIC\n")
for _, tmp_site in enumerate(self.structure.sites):
Expand Down
8 changes: 2 additions & 6 deletions pymatgen/io/xcrysden.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,13 @@ def to_str(self, atom_symbol: bool = True) -> str:
"""
lines: list[str] = []

lines.append("CRYSTAL")
lines.append("# Primitive lattice vectors in Angstrom")
lines.append("PRIMVEC")
lines.extend(("CRYSTAL", "# Primitive lattice vectors in Angstrom", "PRIMVEC"))
cell = self.structure.lattice.matrix
for i in range(3):
lines.append(f" {cell[i][0]:.14f} {cell[i][1]:.14f} {cell[i][2]:.14f}")

cart_coords = self.structure.cart_coords
lines.append("# Cartesian coordinates in Angstrom.")
lines.append("PRIMCOORD")
lines.append(f" {len(cart_coords)} 1")
lines.extend(("# Cartesian coordinates in Angstrom.", "PRIMCOORD", f" {len(cart_coords)} 1"))

for site, coord in zip(self.structure, cart_coords):
sp = site.specie.symbol if atom_symbol else f"{site.specie.Z}"
Expand Down
1 change: 1 addition & 0 deletions pymatgen/util/provenance.py
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,7 @@ def __str__(self):
)

def __eq__(self, other: object) -> bool:
"""Check for equality between two StructureNL objects."""
needed_attrs = ("structure", "authors", "projects", "references", "remarks", "data", "history", "created_at")

if not all(hasattr(other, attr) for attr in needed_attrs):
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/util/testing/aims.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def compare_files(test_name: str, work_dir: Path, ref_dir: Path) -> None:
"""
for file in glob(f"{work_dir / test_name}/*in"):
with open(file) as test_file:
test_lines = [line.strip() for line in test_file.readlines() if len(line.strip()) > 0 and line[0] != "#"]
test_lines = [line.strip() for line in test_file if len(line.strip()) > 0 and line[0] != "#"]

with gzip.open(f"{ref_dir / test_name / Path(file).name}.gz", "rt") as ref_file:
ref_lines = [line.strip() for line in ref_file.readlines() if len(line.strip()) > 0 and line[0] != "#"]
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/vis/structure_vtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import os
import subprocess
import time
from typing import TYPE_CHECKING
from typing import TYPE_CHECKING, ClassVar

import numpy as np
from monty.dev import requires
Expand Down Expand Up @@ -880,7 +880,7 @@ def make_movie(structures, output_filename="movie.mp4", zoom=1.0, fps=20, bitrat
class MultiStructuresVis(StructureVis):
"""Visualization for multiple structures."""

DEFAULT_ANIMATED_MOVIE_OPTIONS = dict(
DEFAULT_ANIMATED_MOVIE_OPTIONS: ClassVar = dict(
time_between_frames=0.1,
looping_type="restart",
number_of_loops=1,
Expand Down
4 changes: 2 additions & 2 deletions tests/analysis/test_interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import numpy as np
import pytest
from matplotlib.figure import Figure as mpl_figure
from matplotlib.figure import Figure as MplFigure
from numpy.testing import assert_allclose
from pandas import DataFrame
from plotly.graph_objects import Figure
Expand Down Expand Up @@ -392,7 +392,7 @@ def test_labels(self):
def test_plot(self):
for ir in self.irs:
fig = ir.plot(backend="matplotlib")
assert fig, isinstance(fig, mpl_figure)
assert fig, isinstance(fig, MplFigure)

fig = ir.plot(backend="plotly")
assert isinstance(fig, Figure)
Expand Down
2 changes: 1 addition & 1 deletion tests/analysis/test_molecule_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def test_get_rmsd(self):
def test_group_molecules(self):
mol_matcher = MoleculeMatcher(tolerance=0.001)
with open(f"{TEST_DIR}/mol_list.txt") as file:
filename_list = [line.strip() for line in file.readlines()]
filename_list = [line.strip() for line in file]
mol_list = [Molecule.from_file(f"{TEST_DIR}/{file}") for file in filename_list]
mol_groups = mol_matcher.group_molecules(mol_list)
filename_groups = [[filename_list[mol_list.index(m)] for m in g] for g in mol_groups]
Expand Down

0 comments on commit a16ac39

Please sign in to comment.