Skip to content

Commit

Permalink
enable ruff PLR0402 PLR1714 PLR5501 in pyproject.toml and auto-fix
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Apr 13, 2024
1 parent e2e11a8 commit f055827
Show file tree
Hide file tree
Showing 10 changed files with 142 additions and 150 deletions.
19 changes: 9 additions & 10 deletions pymatgen/analysis/chemenv/connectivity/connected_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,17 +241,16 @@ def __init__(
if links_data is None:
edge_data = None

elif (env_node1, env_node2, key) in links_data:
edge_data = links_data[(env_node1, env_node2, key)]
elif (env_node2, env_node1, key) in links_data:
edge_data = links_data[(env_node2, env_node1, key)]
elif (env_node1, env_node2) in links_data:
edge_data = links_data[(env_node1, env_node2)]
elif (env_node2, env_node1) in links_data:
edge_data = links_data[(env_node2, env_node1)]
else:
if (env_node1, env_node2, key) in links_data:
edge_data = links_data[(env_node1, env_node2, key)]
elif (env_node2, env_node1, key) in links_data:
edge_data = links_data[(env_node2, env_node1, key)]
elif (env_node1, env_node2) in links_data:
edge_data = links_data[(env_node1, env_node2)]
elif (env_node2, env_node1) in links_data:
edge_data = links_data[(env_node2, env_node1)]
else:
edge_data = None
edge_data = None

if edge_data:
self._connected_subgraph.add_edge(env_node1, env_node2, key, **edge_data)
Expand Down
85 changes: 40 additions & 45 deletions pymatgen/electronic_structure/cohp.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,57 +772,52 @@ def from_file(
# LMTO COHPs have 5 significant figures
avg_data[i].update({spin: np.array([round_to_sigfigs(a, 5) for a in avg], dtype=float)})
avg_cohp = Cohp(efermi, energies, avg_data["COHP"], icohp=avg_data["ICOHP"])
elif not are_multi_center_cobis:
avg_cohp = Cohp(
efermi,
energies,
cohp_data["average"]["COHP"],
icohp=cohp_data["average"]["ICOHP"],
are_coops=are_coops,
are_cobis=are_cobis,
are_multi_center_cobis=are_multi_center_cobis,
)
del cohp_data["average"]
else:
if not are_multi_center_cobis:
avg_cohp = Cohp(
efermi,
energies,
cohp_data["average"]["COHP"],
icohp=cohp_data["average"]["ICOHP"],
are_coops=are_coops,
are_cobis=are_cobis,
are_multi_center_cobis=are_multi_center_cobis,
)
del cohp_data["average"]
else:
# only include two-center cobis in average
# do this for both spin channels
cohp = {}
cohp[Spin.up] = np.array(
[np.array(c["COHP"][Spin.up]) for c in cohp_file.cohp_data.values() if len(c["sites"]) <= 2]
# only include two-center cobis in average
# do this for both spin channels
cohp = {}
cohp[Spin.up] = np.array(
[np.array(c["COHP"][Spin.up]) for c in cohp_file.cohp_data.values() if len(c["sites"]) <= 2]
).mean(axis=0)
try:
cohp[Spin.down] = np.array(
[np.array(c["COHP"][Spin.down]) for c in cohp_file.cohp_data.values() if len(c["sites"]) <= 2]
).mean(axis=0)
except KeyError:
pass
try:
icohp = {}
icohp[Spin.up] = np.array(
[np.array(c["ICOHP"][Spin.up]) for c in cohp_file.cohp_data.values() if len(c["sites"]) <= 2]
).mean(axis=0)
try:
cohp[Spin.down] = np.array(
[np.array(c["COHP"][Spin.down]) for c in cohp_file.cohp_data.values() if len(c["sites"]) <= 2]
icohp[Spin.down] = np.array(
[np.array(c["ICOHP"][Spin.down]) for c in cohp_file.cohp_data.values() if len(c["sites"]) <= 2]
).mean(axis=0)
except KeyError:
pass
try:
icohp = {}
icohp[Spin.up] = np.array(
[np.array(c["ICOHP"][Spin.up]) for c in cohp_file.cohp_data.values() if len(c["sites"]) <= 2]
).mean(axis=0)
try:
icohp[Spin.down] = np.array(
[
np.array(c["ICOHP"][Spin.down])
for c in cohp_file.cohp_data.values()
if len(c["sites"]) <= 2
]
).mean(axis=0)
except KeyError:
pass
except KeyError:
icohp = None
avg_cohp = Cohp(
efermi,
energies,
cohp,
icohp=icohp,
are_coops=are_coops,
are_cobis=are_cobis,
are_multi_center_cobis=are_multi_center_cobis,
)
except KeyError:
icohp = None
avg_cohp = Cohp(
efermi,
energies,
cohp,
icohp=icohp,
are_coops=are_coops,
are_cobis=are_cobis,
are_multi_center_cobis=are_multi_center_cobis,
)

cohp_dict = {
key: Cohp(
Expand Down
5 changes: 2 additions & 3 deletions pymatgen/io/aims/sets/bs.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ def prepare_band_input(structure: Structure, density: float = 20):
current_segment["length"] += 1
lines_and_labels.append(current_segment)
current_segment = None
else:
if current_segment is not None:
current_segment["length"] += 1
elif current_segment is not None:
current_segment["length"] += 1

bands = []
for segment in lines_and_labels:
Expand Down
93 changes: 46 additions & 47 deletions pymatgen/io/vasp/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ def _parse(self, stream, parse_dos, parse_eigen, parse_projected_eigen):
# The start event tells us when we have entered blocks
if tag == "calculation":
parsed_header = True
elif tag == "eigenvalues_kpoints_opt" or tag == "projected_kpoints_opt":
elif tag in ("eigenvalues_kpoints_opt", "projected_kpoints_opt"):
in_kpoints_opt = True
else: # event == "end":
# The end event happens when we have read a block, so have
Expand Down Expand Up @@ -411,7 +411,7 @@ def _parse(self, stream, parse_dos, parse_eigen, parse_projected_eigen):
self.eigenvalues = self._parse_eigen(elem)
elif parse_projected_eigen and tag == "projected" and not in_kpoints_opt:
self.projected_eigenvalues, self.projected_magnetisation = self._parse_projected_eigen(elem)
elif tag == "eigenvalues_kpoints_opt" or tag == "projected_kpoints_opt":
elif tag in ("eigenvalues_kpoints_opt", "projected_kpoints_opt"):
in_kpoints_opt = False
if self.kpoints_opt_props is None:
self.kpoints_opt_props = KpointOptProps()
Expand Down Expand Up @@ -1615,54 +1615,53 @@ def __init__(
or (tag == "dos" and elem.attrib.get("comment") == "kpoints_opt")
):
in_kpoints_opt = True
else: # if event == "end":
if not parsed_header:
if tag == "generator":
self.generator = self._parse_params(elem)
elif tag == "incar":
self.incar = self._parse_params(elem)
elif tag == "kpoints":
self.kpoints, self.actual_kpoints, self.actual_kpoints_weights = self._parse_kpoints(elem)
elif tag == "parameters":
self.parameters = self._parse_params(elem)
elif tag == "atominfo":
self.atomic_symbols, self.potcar_symbols = self._parse_atominfo(elem)
self.potcar_spec = [
{"titel": p, "hash": None, "summary_stats": {}} for p in self.potcar_symbols
]
parsed_header = True
elif tag == "i" and elem.attrib.get("name") == "efermi":
if in_kpoints_opt:
if self.kpoints_opt_props is None:
self.kpoints_opt_props = KpointOptProps()
self.kpoints_opt_props.efermi = float(elem.text)
in_kpoints_opt = False
else:
self.efermi = float(elem.text)
elif tag == "eigenvalues" and not in_kpoints_opt:
self.eigenvalues = self._parse_eigen(elem)
elif parse_projected_eigen and tag == "projected" and not in_kpoints_opt:
self.projected_eigenvalues, self.projected_magnetisation = self._parse_projected_eigen(elem)
elif tag == "eigenvalues_kpoints_opt" or tag == "projected_kpoints_opt":
elif not parsed_header:
if tag == "generator":
self.generator = self._parse_params(elem)
elif tag == "incar":
self.incar = self._parse_params(elem)
elif tag == "kpoints":
self.kpoints, self.actual_kpoints, self.actual_kpoints_weights = self._parse_kpoints(elem)
elif tag == "parameters":
self.parameters = self._parse_params(elem)
elif tag == "atominfo":
self.atomic_symbols, self.potcar_symbols = self._parse_atominfo(elem)
self.potcar_spec = [
{"titel": p, "hash": None, "summary_stats": {}} for p in self.potcar_symbols
]
parsed_header = True
elif tag == "i" and elem.attrib.get("name") == "efermi":
if in_kpoints_opt:
if self.kpoints_opt_props is None:
self.kpoints_opt_props = KpointOptProps()
self.kpoints_opt_props.efermi = float(elem.text)
in_kpoints_opt = False
# projected_kpoints_opt includes occupation information whereas
# eigenvalues_kpoints_opt doesn't.
self.kpoints_opt_props.eigenvalues = self._parse_eigen(elem.find("eigenvalues"))
if tag == "eigenvalues_kpoints_opt":
(
self.kpoints_opt_props.kpoints,
self.kpoints_opt_props.actual_kpoints,
self.kpoints_opt_props.actual_kpoints_weights,
) = self._parse_kpoints(elem.find("kpoints"))
elif parse_projected_eigen: # and tag == "projected_kpoints_opt": (implied)
(
self.kpoints_opt_props.projected_eigenvalues,
self.kpoints_opt_props.projected_magnetisation,
) = self._parse_projected_eigen(elem)
elif tag == "structure" and elem.attrib.get("name") == "finalpos":
self.final_structure = self._parse_structure(elem)
else:
self.efermi = float(elem.text)
elif tag == "eigenvalues" and not in_kpoints_opt:
self.eigenvalues = self._parse_eigen(elem)
elif parse_projected_eigen and tag == "projected" and not in_kpoints_opt:
self.projected_eigenvalues, self.projected_magnetisation = self._parse_projected_eigen(elem)
elif tag in ("eigenvalues_kpoints_opt", "projected_kpoints_opt"):
if self.kpoints_opt_props is None:
self.kpoints_opt_props = KpointOptProps()
in_kpoints_opt = False
# projected_kpoints_opt includes occupation information whereas
# eigenvalues_kpoints_opt doesn't.
self.kpoints_opt_props.eigenvalues = self._parse_eigen(elem.find("eigenvalues"))
if tag == "eigenvalues_kpoints_opt":
(
self.kpoints_opt_props.kpoints,
self.kpoints_opt_props.actual_kpoints,
self.kpoints_opt_props.actual_kpoints_weights,
) = self._parse_kpoints(elem.find("kpoints"))
elif parse_projected_eigen: # and tag == "projected_kpoints_opt": (implied)
(
self.kpoints_opt_props.projected_eigenvalues,
self.kpoints_opt_props.projected_magnetisation,
) = self._parse_projected_eigen(elem)
elif tag == "structure" and elem.attrib.get("name") == "finalpos":
self.final_structure = self._parse_structure(elem)
self.vasp_version = self.generator["version"]
if parse_potcar_file:
self.update_potcar_spec(parse_potcar_file)
Expand Down
7 changes: 3 additions & 4 deletions pymatgen/io/vasp/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -1114,11 +1114,10 @@ def calculate_ng(

if custom_encut is not None:
encut = custom_encut
elif self.incar.get("ENCUT", 0) > 0:
encut = self.incar["ENCUT"] # get the ENCUT val
else:
if self.incar.get("ENCUT", 0) > 0:
encut = self.incar["ENCUT"] # get the ENCUT val
else:
encut = max(i_species.enmax for i_species in self.get_vasp_input()["POTCAR"])
encut = max(i_species.enmax for i_species in self.get_vasp_input()["POTCAR"])

# PREC=Normal is VASP default
PREC = self.incar.get("PREC", "Normal") if custom_prec is None else custom_prec
Expand Down
15 changes: 7 additions & 8 deletions pymatgen/phonon/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,15 +205,14 @@ def get_plot(
ax.set_xlim(xlim)
if ylim:
ax.set_ylim(ylim)
elif invert_axes:
_ylim = ax.get_ylim()
relevant_x = [p[1] for p in all_pts if _ylim[0] < p[0] < _ylim[1]] or ax.get_xlim()
ax.set_xlim((min(relevant_x), max(relevant_x)))
else:
if invert_axes:
_ylim = ax.get_ylim()
relevant_x = [p[1] for p in all_pts if _ylim[0] < p[0] < _ylim[1]] or ax.get_xlim()
ax.set_xlim((min(relevant_x), max(relevant_x)))
else:
_xlim = ax.get_xlim()
relevant_y = [p[1] for p in all_pts if _xlim[0] < p[0] < _xlim[1]] or ax.get_ylim()
ax.set_ylim((min(relevant_y), max(relevant_y)))
_xlim = ax.get_xlim()
relevant_y = [p[1] for p in all_pts if _xlim[0] < p[0] < _xlim[1]] or ax.get_ylim()
ax.set_ylim((min(relevant_y), max(relevant_y)))

if invert_axes:
ax.axhline(0, linewidth=2, color="black", linestyle="--")
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/vis/structure_vtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -988,7 +988,7 @@ def apply_tags(self):
tags = {}
for tag in self.tags:
istruct = tag.get("istruct", "all")
if istruct != "all" and istruct != self.istruct:
if istruct not in ("all", self.istruct):
continue
site_index = tag["site_index"]
color = tag.get("color", [0.5, 0.5, 0.5])
Expand Down
61 changes: 32 additions & 29 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,35 +23,38 @@ repair-wheel-command = "delocate-wheel --require-archs {delocate_archs} -w {dest
target-version = "py39"
line-length = 120
lint.select = [
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"D", # pydocstyle
"E", # pycodestyle error
"EXE", # flake8-executable
"F", # pyflakes
"FA", # flake8-future-annotations
"FBT003", # boolean-positional-value-in-call
"FLY", # flynt
"I", # isort
"ICN", # flake8-import-conventions
"ISC", # flake8-implicit-str-concat
"PD", # pandas-vet
"PERF", # perflint
"PIE", # flake8-pie
"PL", # pylint
"PT", # flake8-pytest-style
"PYI", # flakes8-pyi
"Q", # flake8-quotes
"RET", # flake8-return
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"SIM", # flake8-simplify
"SLOT", # flake8-slots
"TCH", # flake8-type-checking
"TID", # flake8-tidy-imports
"UP", # pyupgrade
"W", # pycodestyle warning
"YTT", # flake8-2020
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"D", # pydocstyle
"E", # pycodestyle error
"EXE", # flake8-executable
"F", # pyflakes
"FA", # flake8-future-annotations
"FBT003", # boolean-positional-value-in-call
"FLY", # flynt
"I", # isort
"ICN", # flake8-import-conventions
"ISC", # flake8-implicit-str-concat
"PD", # pandas-vet
"PERF", # perflint
"PIE", # flake8-pie
"PL", # pylint
"PLR0402",
"PLR1714",
"PLR5501",
"PT", # flake8-pytest-style
"PYI", # flakes8-pyi
"Q", # flake8-quotes
"RET", # flake8-return
"RSE", # flake8-raise
"RUF", # Ruff-specific rules
"SIM", # flake8-simplify
"SLOT", # flake8-slots
"TCH", # flake8-type-checking
"TID", # flake8-tidy-imports
"UP", # pyupgrade
"W", # pycodestyle warning
"YTT", # flake8-2020
]
lint.ignore = [
"B023", # Function definition does not bind loop variable
Expand Down
2 changes: 1 addition & 1 deletion tests/io/vasp/test_outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
import json
import os
import sys
import xml.etree.ElementTree as ElementTree
from io import StringIO
from pathlib import Path
from shutil import copyfile, copyfileobj
from xml.etree import ElementTree

import numpy as np
import pytest
Expand Down
3 changes: 1 addition & 2 deletions tests/phonon/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,8 @@

import pymatgen.phonon as ph
import pymatgen.phonon.bandstructure as bs
import pymatgen.phonon.dos as dos
import pymatgen.phonon.gruneisen as gru
import pymatgen.phonon.plotter as plotter
from pymatgen.phonon import dos, plotter


def test_convenience_imports():
Expand Down

0 comments on commit f055827

Please sign in to comment.