Skip to content

Commit 2762399

Browse files
add ruff pre-commit hook
1 parent 5c3f883 commit 2762399

14 files changed

+118
-45
lines changed

.pre-commit-config.yaml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,13 @@ ci:
88
skip: [flake8, autoflake, mypy]
99

1010
repos:
11+
12+
- repo: https://github.com/astral-sh/ruff-pre-commit
13+
rev: v0.4.3
14+
hooks:
15+
- id: ruff
16+
args: [--fix, --unsafe-fixes]
17+
1118
- repo: https://github.com/psf/black
1219
rev: 24.2.0
1320
hooks:

examples/MP_compliant_job.py

Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99

1010

1111
def get_GaAs_structure(a0: float = 5.6) -> Structure:
12-
1312
lattice_vectors = a0 * np.array([[0.0 if i == j else 0.5 for j in range(3)] for i in range(3)])
1413
return Structure(
1514
lattice=Lattice(lattice_vectors),
@@ -32,9 +31,11 @@ def assign_meta(flow, metadata: dict, name: str | None = None):
3231

3332

3433
def get_MP_compliant_r2SCAN_flow(
35-
structure: Structure, user_incar_settings: dict | None = None, metadata: dict | None = None, name: str | None = None
34+
structure: Structure,
35+
user_incar_settings: dict | None = None,
36+
metadata: dict | None = None,
37+
name: str | None = None,
3638
) -> Flow:
37-
3839
from atomate2.vasp.jobs.mp import MPMetaGGAStaticMaker
3940
from atomate2.vasp.powerups import update_user_incar_settings
4041

@@ -53,7 +54,6 @@ def get_MP_compliant_r2SCAN_flow(
5354

5455

5556
def run_job_fully_locally(flow, job_store=None):
56-
5757
from jobflow import run_locally, JobStore
5858
from maggma.stores import MemoryStore
5959

@@ -66,7 +66,6 @@ def run_job_fully_locally(flow, job_store=None):
6666

6767

6868
def MP_compliant_calc():
69-
7069
structure = get_GaAs_structure()
7170
flow = get_MP_compliant_r2SCAN_flow(
7271
structure=structure,
@@ -84,7 +83,6 @@ def MP_compliant_calc():
8483

8584

8685
def MP_non_compliant_calc():
87-
8886
structure = get_GaAs_structure()
8987
flow = get_MP_compliant_r2SCAN_flow(
9088
structure=structure,
@@ -103,16 +101,17 @@ def MP_non_compliant_calc():
103101

104102

105103
def MP_flows() -> None:
106-
107104
compliant_task_doc = MP_compliant_calc()
108105
dumpfn(jsanitize(compliant_task_doc), "./MP_compatible_GaAs_r2SCAN_static.json.gz")
109106

110107
non_compliant_task_doc = MP_non_compliant_calc()
111-
dumpfn(jsanitize(non_compliant_task_doc), "./MP_incompatible_GaAs_r2SCAN_static.json.gz")
108+
dumpfn(
109+
jsanitize(non_compliant_task_doc),
110+
"./MP_incompatible_GaAs_r2SCAN_static.json.gz",
111+
)
112112

113113

114114
def generate_task_documents(cdir, task_id: str | None = None, filename: str | None = None) -> TaskDocument:
115-
116115
from atomate.vasp.drones import VaspDrone
117116
from emmet.core.mpid import MPID
118117

@@ -130,5 +129,4 @@ def generate_task_documents(cdir, task_id: str | None = None, filename: str | No
130129

131130

132131
if __name__ == "__main__":
133-
134132
MP_flows()

pymatgen/io/validation/check_common_errors.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,6 @@ def _check_parse(self) -> None:
8484
)
8585

8686
def _check_gga_and_metagga(self) -> None:
87-
8887
# Check for cases where both GGA and METAGGA are set. This should *not* be allowed, as it can erroneously change
8988
# the outputted energy significantly. See https://github.com/materialsproject/atomate2/issues/453#issuecomment-1699605867
9089
# for more details.
@@ -101,7 +100,6 @@ def _check_electronic_convergence(self) -> None:
101100
if self.incar.get("ALGO", self.defaults["ALGO"]["value"]).lower() != "chi":
102101
# Response function calculations are non-self-consistent: only one ionic step, no electronic SCF
103102
if self.parameters.get("LEPSILON", self.defaults["LEPSILON"]["value"]):
104-
105103
final_esteps = self.ionic_steps[-1]["electronic_steps"]
106104
to_check = {"e_wo_entrp", "e_fr_energy", "e_0_energy"}
107105

pymatgen/io/validation/check_for_excess_empty_space.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ def check_for_excess_empty_space(structure):
2525
lattice_vec_3_diffs = np.diff(lattice_vec_3_frac_coords)
2626
max_lattice_vec_3_empty_dist = max(lattice_vec_3_diffs) * lattice_vec_lengths[2]
2727

28-
max_empty_distance = max(max_lattice_vec_1_empty_dist, max_lattice_vec_2_empty_dist, max_lattice_vec_3_empty_dist)
28+
max_empty_distance = max(
29+
max_lattice_vec_1_empty_dist,
30+
max_lattice_vec_2_empty_dist,
31+
max_lattice_vec_3_empty_dist,
32+
)
2933

3034
# Check 2: get max voronoi polyhedra volume in structure
3135
def get_max_voronoi_polyhedra_volume(structure):

pymatgen/io/validation/check_incar.py

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,6 @@ def check(self) -> None:
109109
# Validate each parameter in the set of working parameters
110110
simple_validator = BasicValidator()
111111
for key in working_params.defaults:
112-
113112
if self.fast and len(self.reasons) > 0:
114113
# fast check: stop checking whenever a single check fails
115114
break
@@ -326,7 +325,10 @@ def update_precision_params(self) -> None:
326325
self.parameters["LREAL"] = str(self._incar.get("LREAL", self.defaults["LREAL"]["value"])).upper()
327326
# PREC.
328327
self.parameters["PREC"] = self.parameters["PREC"].upper()
329-
if self.input_set.incar.get("PREC", self.defaults["PREC"]["value"]).upper() in ["ACCURATE", "HIGH"]:
328+
if self.input_set.incar.get("PREC", self.defaults["PREC"]["value"]).upper() in [
329+
"ACCURATE",
330+
"HIGH",
331+
]:
330332
self.valid_values["PREC"] = ["ACCURATE", "ACCURA", "HIGH"]
331333
else:
332334
raise ValueError("Validation code check for PREC tag needs to be updated to account for a new input set!")
@@ -374,7 +376,10 @@ def update_misc_special_params(self) -> None:
374376
if self._incar.get("IWAVPR"):
375377
self.parameters["IWAVPR"] = self._incar["IWAVPR"] if self._incar["IWAVPR"] is not None else 0
376378
self.defaults["IWAVPR"].update(
377-
{"operation": "==", "comment": "VASP discourages users from setting the IWAVPR tag (as of July 2023)."}
379+
{
380+
"operation": "==",
381+
"comment": "VASP discourages users from setting the IWAVPR tag (as of July 2023).",
382+
}
378383
)
379384

380385
# LCORR.
@@ -451,8 +456,16 @@ def update_fft_params(self) -> None:
451456
self.valid_values["ENMAX"] = max(self.parameters["ENMAX"], self.valid_values["ENMAX"])
452457

453458
(
454-
[self.valid_values["NGX"], self.valid_values["NGY"], self.valid_values["NGZ"]],
455-
[self.valid_values["NGXF"], self.valid_values["NGYF"], self.valid_values["NGZF"]],
459+
[
460+
self.valid_values["NGX"],
461+
self.valid_values["NGY"],
462+
self.valid_values["NGZ"],
463+
],
464+
[
465+
self.valid_values["NGXF"],
466+
self.valid_values["NGYF"],
467+
self.valid_values["NGZF"],
468+
],
456469
) = self.input_set.calculate_ng(custom_encut=self.valid_values["ENMAX"])
457470

458471
for key in grid_keys:
@@ -566,7 +579,8 @@ def update_smearing_params(self, bandgap_tol=1.0e-4) -> None:
566579
for ionic_step in self._ionic_steps:
567580
if eentropy := ionic_step["electronic_steps"][-1].get("eentropy"):
568581
self.parameters["ELECTRONIC ENTROPY"] = max(
569-
self.parameters["ELECTRONIC ENTROPY"], abs(eentropy / self.structure.num_sites)
582+
self.parameters["ELECTRONIC ENTROPY"],
583+
abs(eentropy / self.structure.num_sites),
570584
)
571585

572586
convert_eV_to_meV = 1000
@@ -702,7 +716,8 @@ def update_ionic_params(self):
702716
cur_ionic_step_energies = [ionic_step["e_fr_energy"] for ionic_step in self._ionic_steps]
703717
cur_ionic_step_energy_gradient = np.diff(cur_ionic_step_energies)
704718
self.parameters["MAX ENERGY GRADIENT"] = round(
705-
max(np.abs(cur_ionic_step_energy_gradient)) / self.structure.num_sites, 3
719+
max(np.abs(cur_ionic_step_energy_gradient)) / self.structure.num_sites,
720+
3,
706721
)
707722
self.valid_values["MAX ENERGY GRADIENT"] = 1
708723
self.defaults["MAX ENERGY GRADIENT"] = {
@@ -736,7 +751,8 @@ def update_ionic_params(self):
736751

737752
elif self.valid_values["EDIFFG"] < 0.0:
738753
self.parameters["EDIFFG"] = round(
739-
max([np.linalg.norm(force_on_atom) for force_on_atom in self.task_doc["output"]["forces"]]), 3
754+
max([np.linalg.norm(force_on_atom) for force_on_atom in self.task_doc["output"]["forces"]]),
755+
3,
740756
)
741757

742758
self.valid_values["EDIFFG"] = abs(self.valid_values["EDIFFG"])
@@ -788,7 +804,17 @@ class BasicValidator:
788804
"""
789805

790806
# avoiding dunder methods because these raise too many NotImplemented's
791-
operations: set[str | None] = {"==", ">", ">=", "<", "<=", "in", "approx", "auto fail", None}
807+
operations: set[str | None] = {
808+
"==",
809+
">",
810+
">=",
811+
"<",
812+
"<=",
813+
"in",
814+
"approx",
815+
"auto fail",
816+
None,
817+
}
792818

793819
def __init__(self, global_tolerance=1.0e-4) -> None:
794820
"""Set math.isclose tolerance"""

pymatgen/io/validation/check_kpoints_kspacing.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,9 @@ def _check_kpoint_density(self) -> None:
109109
self.kpoints = self.kpoints.as_dict()
110110

111111
cur_num_kpts = max(
112-
self.kpoints.get("nkpoints", 0), np.prod(self.kpoints.get("kpoints")), len(self.kpoints.get("kpoints"))
112+
self.kpoints.get("nkpoints", 0),
113+
np.prod(self.kpoints.get("kpoints")),
114+
len(self.kpoints.get("kpoints")),
113115
)
114116
if cur_num_kpts < valid_num_kpts:
115117
self.reasons.append(

pymatgen/io/validation/check_package_versions.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" Optionally check whether package versions are up to date. """
1+
"""Optionally check whether package versions are up to date."""
22

33
from __future__ import annotations
44
from importlib.metadata import version

pymatgen/io/validation/check_potcar.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -110,9 +110,13 @@ def _check_potcar_spec(self):
110110
# format error string
111111
incorrect_potcars = [potcar.split("_")[0] for potcar in incorrect_potcars]
112112
if len(incorrect_potcars) == 2:
113-
incorrect_potcars = ", ".join(incorrect_potcars[:-1]) + f" and {incorrect_potcars[-1]}" # type: ignore
113+
incorrect_potcars = (
114+
", ".join(incorrect_potcars[:-1]) + f" and {incorrect_potcars[-1]}"
115+
) # type: ignore
114116
elif len(incorrect_potcars) >= 3:
115-
incorrect_potcars = ", ".join(incorrect_potcars[:-1]) + "," + f" and {incorrect_potcars[-1]}" # type: ignore
117+
incorrect_potcars = (
118+
", ".join(incorrect_potcars[:-1]) + "," + f" and {incorrect_potcars[-1]}"
119+
) # type: ignore
116120

117121
self.reasons.append(
118122
f"PSEUDOPOTENTIALS --> Incorrect POTCAR files were used for {incorrect_potcars}. "
@@ -157,7 +161,9 @@ def compare_potcar_stats(self, potcar_stats_1: dict, potcar_stats_2: dict) -> bo
157161
data_match = False
158162
if key_match:
159163
data_diff = [
160-
abs(potcar_stats_1["stats"].get(key, {}).get(stat) - potcar_stats_2["stats"].get(key, {}).get(stat)) # type: ignore
164+
abs(
165+
potcar_stats_1["stats"].get(key, {}).get(stat) - potcar_stats_2["stats"].get(key, {}).get(stat)
166+
) # type: ignore
161167
for stat in ["MEAN", "ABSMEAN", "VAR", "MIN", "MAX"]
162168
for key in ["header", "data"]
163169
]

pymatgen/io/validation/common.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
""" Common class constructor for validation checks. """
1+
"""Common class constructor for validation checks."""
22

33
from dataclasses import dataclass
44

@@ -47,7 +47,6 @@ def check(self) -> None:
4747

4848
checklist = {attr for attr in dir(self) if attr.startswith("_check_")}
4949
for attr in checklist:
50-
5150
if self.fast and len(self.reasons) > 0:
5251
# fast check: stop checking whenever a single check fails
5352
break

pymatgen/io/validation/compare_to_MP_ehull.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,10 @@ def compare_to_MP_ehull(mp_api_key=None, task_doc=None):
2424
entries = mpr.get_entries_in_chemsys(
2525
elements=elements,
2626
compatible_only=True,
27-
additional_criteria={"thermo_types": ["GGA_GGA+U", "R2SCAN"], "is_stable": True},
27+
additional_criteria={
28+
"thermo_types": ["GGA_GGA+U", "R2SCAN"],
29+
"is_stable": True,
30+
},
2831
)
2932

3033
entries.append(cur_structure_entry)

0 commit comments

Comments
 (0)