Skip to content

Commit

Permalink
Run pyupgrade and flake8-simplify through ruff (#2851)
Browse files Browse the repository at this point in the history
* sort [tool.ruff] select array

* add rule class "SIM" to ruff select

* ruff check . --fix

* ignore flake8-simplify rules in pre-commit.ci

* fix Undefined name `densities` in pymatgen/electronic_structure/dos.py:871:76: F821

and pymatgen/electronic_structure/dos.py:1062:76: F821 Undefined name `densities`
pymatgen/electronic_structure/dos.py:1118:76: F821 Undefined name `densities`

* fix some mypy errors

* ignore remaining 5 mypy errors
  • Loading branch information
janosh authored Feb 20, 2023
1 parent ee52d53 commit 3bb196c
Show file tree
Hide file tree
Showing 127 changed files with 820 additions and 1,576 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ jobs:
- name: ruff
run: |
ruff --version
ruff check . --ignore D
ruff check . --ignore 'D,SIM'
- name: black
run: |
Expand Down
19 changes: 1 addition & 18 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,7 @@ repos:
rev: v0.0.247
hooks:
- id: ruff
args: [--fix, --ignore, D]

- repo: https://github.com/PyCQA/autoflake
rev: v2.0.1
hooks:
- id: autoflake

- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args: [--py38-plus]
args: [--fix, --ignore, 'D,SIM']

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
Expand All @@ -30,12 +19,6 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace

- repo: https://github.com/PyCQA/isort
rev: 5.12.0
hooks:
- id: isort
args: [--profile, black]

- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
Expand Down
5 changes: 1 addition & 4 deletions dev_scripts/chemenv/test_algos_all_geoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,7 @@
symbol_name_mapping = allcg.get_symbol_name_mapping(coordination=coordination)

if perms_def == "standard":
if coordination > 6:
test = "500"
else:
test = "all"
test = "500" if coordination > 6 else "all"
elif perms_def == "ndefined":
test = nperms # type: ignore[assignment]
else:
Expand Down
10 changes: 2 additions & 8 deletions dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,10 +182,7 @@ def parse_shannon_radii():
if cn not in radii[el][charge]:
radii[el][charge][cn] = {}

if sheet[f"D{i}"].value is not None:
spin = sheet[f"D{i}"].value
else:
spin = ""
spin = sheet[f"D{i}"].value if sheet[f"D{i}"].value is not None else ""

radii[el][charge][cn][spin] = {
"crystal_radius": float(sheet[f"E{i}"].value),
Expand Down Expand Up @@ -300,10 +297,7 @@ def add_ionization_energies():
if row:
Z = int(row[0])
val = re.sub(r"\s", "", row[8].strip("()[]"))
if val == "":
val = None
else:
val = float(val)
val = None if val == "" else float(val)
data[Z].append(val)
print(data)
print(data[51])
Expand Down
5 changes: 2 additions & 3 deletions pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,9 +161,8 @@ def test(self, structure):
nn = structure.get_neighbors(site, max_r)
for sp in sp_to_test:
for nn_site, dist, *_ in nn:
if sp in nn_site.species:
if dist < self.specie_and_min_dist[sp]:
return False
if sp in nn_site.species and dist < self.specie_and_min_dist[sp]:
return False
return True

def as_dict(self):
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/alchemy/materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ def was_modified(self) -> bool:
is in the case of performing a substitution transformation on the
structure when the specie to replace isn't in the structure.
"""
return not self.final_structure == self.structures[-2]
return self.final_structure != self.structures[-2]

@property
def structures(self) -> list[Structure]:
Expand Down
18 changes: 9 additions & 9 deletions pymatgen/alchemy/tests/test_materials.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ def setUp(self):
def test_append_transformation(self):
t = SubstitutionTransformation({"Fe": "Mn"})
self.trans.append_transformation(t)
assert "NaMnPO4" == self.trans.final_structure.composition.reduced_formula
assert self.trans.final_structure.composition.reduced_formula == "NaMnPO4"
assert len(self.trans.structures) == 3
coords = []
coords.append([0, 0, 0])
Expand All @@ -59,19 +59,19 @@ def test_append_filter(self):
def test_get_vasp_input(self):
SETTINGS["PMG_VASP_PSP_DIR"] = PymatgenTest.TEST_FILES_DIR
potcar = self.trans.get_vasp_input(MPRelaxSet)["POTCAR"]
assert "Na_pv\nFe_pv\nP\nO" == "\n".join(p.symbol for p in potcar)
assert "\n".join(p.symbol for p in potcar) == "Na_pv\nFe_pv\nP\nO"
assert len(self.trans.structures) == 2

def test_final_structure(self):
assert "NaFePO4" == self.trans.final_structure.composition.reduced_formula
assert self.trans.final_structure.composition.reduced_formula == "NaFePO4"

def test_from_dict(self):
d = json.load(open(os.path.join(PymatgenTest.TEST_FILES_DIR, "transformations.json")))
d["other_parameters"] = {"tags": ["test"]}
ts = TransformedStructure.from_dict(d)
ts.other_parameters["author"] = "Will"
ts.append_transformation(SubstitutionTransformation({"Fe": "Mn"}))
assert "MnPO4" == ts.final_structure.composition.reduced_formula
assert ts.final_structure.composition.reduced_formula == "MnPO4"
assert ts.other_parameters == {"author": "Will", "tags": ["test"]}

def test_undo_and_redo_last_change(self):
Expand All @@ -80,17 +80,17 @@ def test_undo_and_redo_last_change(self):
SubstitutionTransformation({"Fe": "Mn"}),
]
ts = TransformedStructure(self.structure, trans)
assert "NaMnPO4" == ts.final_structure.composition.reduced_formula
assert ts.final_structure.composition.reduced_formula == "NaMnPO4"
ts.undo_last_change()
assert "NaFePO4" == ts.final_structure.composition.reduced_formula
assert ts.final_structure.composition.reduced_formula == "NaFePO4"
ts.undo_last_change()
assert "LiFePO4" == ts.final_structure.composition.reduced_formula
assert ts.final_structure.composition.reduced_formula == "LiFePO4"
with pytest.raises(IndexError):
ts.undo_last_change()
ts.redo_next_change()
assert "NaFePO4" == ts.final_structure.composition.reduced_formula
assert ts.final_structure.composition.reduced_formula == "NaFePO4"
ts.redo_next_change()
assert "NaMnPO4" == ts.final_structure.composition.reduced_formula
assert ts.final_structure.composition.reduced_formula == "NaMnPO4"
with pytest.raises(IndexError):
ts.redo_next_change()
# Make sure that this works with filters.
Expand Down
34 changes: 16 additions & 18 deletions pymatgen/analysis/bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,10 +207,9 @@ def fragment_and_process(self, bonds):
if frag_pair[1].isomorphic_to(frags[1]):
frags_done = True
break
elif frag_pair[1].isomorphic_to(frags[0]):
if frag_pair[0].isomorphic_to(frags[1]):
frags_done = True
break
elif frag_pair[1].isomorphic_to(frags[0]) and frag_pair[0].isomorphic_to(frags[1]):
frags_done = True
break
if not frags_done:
# If we haven't, we save this pair and search for the relevant fragment entries:
self.done_frag_pairs += [frags]
Expand Down Expand Up @@ -343,20 +342,19 @@ def filter_fragment_entries(self, fragment_entries):
found_similar_entry = False
# Check for uniqueness
for ii, filtered_entry in enumerate(self.filtered_entries):
if filtered_entry["formula_pretty"] == entry["formula_pretty"]:
if (
filtered_entry["initial_molgraph"].isomorphic_to(entry["initial_molgraph"])
and filtered_entry["final_molgraph"].isomorphic_to(entry["final_molgraph"])
and filtered_entry["initial_molecule"]["charge"] == entry["initial_molecule"]["charge"]
):
found_similar_entry = True
# If two entries are found that pass the above similarity check, take the one with the lower
# energy:
if entry["final_energy"] < filtered_entry["final_energy"]:
self.filtered_entries[ii] = entry
# Note that this will essentially choose between singlet and triplet entries assuming both have
# the same structural details
break
if filtered_entry["formula_pretty"] == entry["formula_pretty"] and (
filtered_entry["initial_molgraph"].isomorphic_to(entry["initial_molgraph"])
and filtered_entry["final_molgraph"].isomorphic_to(entry["final_molgraph"])
and filtered_entry["initial_molecule"]["charge"] == entry["initial_molecule"]["charge"]
):
found_similar_entry = True
# If two entries are found that pass the above similarity check, take the one with the lower
# energy:
if entry["final_energy"] < filtered_entry["final_energy"]:
self.filtered_entries[ii] = entry
# Note that this will essentially choose between singlet and triplet entries assuming both have
# the same structural details
break
if not found_similar_entry:
self.filtered_entries += [entry]

Expand Down
10 changes: 2 additions & 8 deletions pymatgen/analysis/chemenv/connectivity/connected_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,10 +240,7 @@ def __init__(
for edge in links:
env_node1 = edge[0]
env_node2 = edge[1]
if len(edge) == 2:
key = None
else:
key = edge[2]
key = None if len(edge) == 2 else edge[2]
if (not self._connected_subgraph.has_node(env_node1)) or (
not self._connected_subgraph.has_node(env_node2)
):
Expand Down Expand Up @@ -550,10 +547,7 @@ def show_graph(self, graph=None, save_file=None, drawing_type="internal", pltsho
"""
import matplotlib.pyplot as plt

if graph is None:
shown_graph = self._connected_subgraph
else:
shown_graph = graph
shown_graph = self._connected_subgraph if graph is None else graph

plt.figure()
# pos = nx.spring_layout(shown_graph)
Expand Down
11 changes: 3 additions & 8 deletions pymatgen/analysis/chemenv/connectivity/connectivity_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,7 @@

import numpy as np

from pymatgen.analysis.chemenv.connectivity.structure_connectivity import (
StructureConnectivity,
)
from pymatgen.analysis.chemenv.connectivity.structure_connectivity import StructureConnectivity

__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
Expand Down Expand Up @@ -73,9 +71,6 @@ def setup_parameters(self, multiple_environments_choice):
"""
Setup of the parameters for the connectivity finder.
"""
if multiple_environments_choice is not None:
if multiple_environments_choice not in ["TAKE_HIGHEST_FRACTION"]:
raise ValueError(
f"Option {multiple_environments_choice!r} for multiple_environments_choice is not allowed"
)
if multiple_environments_choice is not None and multiple_environments_choice not in ["TAKE_HIGHEST_FRACTION"]:
raise ValueError(f"Option {multiple_environments_choice!r} for multiple_environments_choice is not allowed")
self.multiple_environments_choice = multiple_environments_choice
11 changes: 5 additions & 6 deletions pymatgen/analysis/chemenv/connectivity/structure_connectivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,12 +123,11 @@ def add_bonds(self, isite, site_neighbors_set):
else:
if isite == nb_index_unitcell:
for isite1, ineighb1, data1 in existing_edges:
if isite1 == ineighb1:
if np.allclose(data1["delta"], nb_image_cell) or np.allclose(
data1["delta"], -nb_image_cell
):
exists = True
break
if isite1 == ineighb1 and (
np.allclose(data1["delta"], nb_image_cell) or np.allclose(data1["delta"], -nb_image_cell)
):
exists = True
break
else:
for _, ineighb1, data1 in existing_edges:
if nb_index_unitcell == ineighb1:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2725,10 +2725,7 @@ def get_site_coordination_environments_fractions(
dict_fractions["Fraction"] = nb_set_fraction * fraction
ce_dict_fractions.append(dict_fractions)
ce_maps.append(cn_map)
if ordered:
indices = np.argsort(ce_fractions)[::-1]
else:
indices = list(range(len(ce_fractions)))
indices = np.argsort(ce_fractions)[::-1] if ordered else list(range(len(ce_fractions)))

fractions_info_list = [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -858,10 +858,7 @@ def faces(self, sites, permutation=None):
Returns the list of faces of this coordination geometry. Each face is given as a
list of its vertices coordinates.
"""
if permutation is None:
coords = [site.coords for site in sites]
else:
coords = [sites[ii].coords for ii in permutation]
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 f] for f in self._faces]

def edges(self, sites, permutation=None, input="sites"):
Expand Down Expand Up @@ -896,10 +893,7 @@ def get_pmeshes(self, sites, permutation=None):
"""
pmeshes = []
# _vertices = [site.coords for site in sites]
if permutation is None:
_vertices = [site.coords for site in sites]
else:
_vertices = [sites[ii].coords for ii in permutation]
_vertices = [site.coords for site in sites] if permutation is None else [sites[ii].coords for ii in permutation]
_face_centers = []
number_of_faces = 0
for face in self._faces:
Expand Down Expand Up @@ -1234,36 +1228,30 @@ def is_a_valid_coordination_geometry(
if mp_symbol is not None:
try:
cg = self.get_geometry_from_mp_symbol(mp_symbol)
if IUPAC_symbol is not None:
if IUPAC_symbol != cg.IUPAC_symbol:
return False
if IUCr_symbol is not None:
if IUCr_symbol != cg.IUCr_symbol:
return False
if cn is not None:
if int(cn) != int(cg.coordination_number):
return False
if IUPAC_symbol is not None and IUPAC_symbol != cg.IUPAC_symbol:
return False
if IUCr_symbol is not None and IUCr_symbol != cg.IUCr_symbol:
return False
if cn is not None and int(cn) != int(cg.coordination_number):
return False
return True
except LookupError:
return False
elif IUPAC_symbol is not None:
try:
cg = self.get_geometry_from_IUPAC_symbol(IUPAC_symbol)
if IUCr_symbol is not None:
if IUCr_symbol != cg.IUCr_symbol:
return False
if cn is not None:
if cn != cg.coordination_number:
return False
if IUCr_symbol is not None and IUCr_symbol != cg.IUCr_symbol:
return False
if cn is not None and cn != cg.coordination_number:
return False
return True
except LookupError:
return False
elif IUCr_symbol is not None:
try:
cg = self.get_geometry_from_IUCr_symbol(IUCr_symbol)
if cn is not None:
if cn != cg.coordination_number:
return False
if cn is not None and cn != cg.coordination_number:
return False
return True
except LookupError:
return True
Expand Down Expand Up @@ -1319,10 +1307,7 @@ def pretty_print(self, type="implemented_geometries", maxcn=8, additional_info=N
for cg in self.get_implemented_geometries(coordination=cn):
if additional_info is not None:
if "nb_hints" in additional_info:
if cg.neighbors_sets_hints is not None:
addinfo = " *"
else:
addinfo = ""
addinfo = " *" if cg.neighbors_sets_hints is not None else ""
else:
addinfo = ""
else:
Expand Down
Loading

0 comments on commit 3bb196c

Please sign in to comment.