Skip to content

Commit

Permalink
Drop black for ruff format (#3420)
Browse files Browse the repository at this point in the history
* pre-commit autoupdate and ruff auto fix

* manual fixes

* remove Python 2 __div__ magic methods

unrecognized in Python 3 which uses __truediv__ and __floordiv__ instead

* io/vasp/test_outputs.py manually format long list[float]

* drop black in favor of ruff format

* ruff format
  • Loading branch information
janosh authored Oct 24, 2023
1 parent c90a7c8 commit 3ec73a7
Show file tree
Hide file tree
Showing 39 changed files with 141 additions and 302 deletions.
8 changes: 2 additions & 6 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,13 @@ jobs:

- name: Install dependencies
run: |
pip install --upgrade ruff black mypy
pip install --upgrade ruff mypy
- name: ruff
run: |
ruff --version
ruff .
- name: black
run: |
black --version
black --check --diff --color ${{ github.event.repository.name }}
ruff format --check .
- name: mypy
run: |
Expand Down
10 changes: 3 additions & 7 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ ci:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.0
rev: v0.1.2
hooks:
- id: ruff
args: [--fix]
- id: ruff-format

- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
Expand All @@ -20,13 +21,8 @@ repos:
- id: end-of-file-fixer
- id: trailing-whitespace

- repo: https://github.com/psf/black
rev: 23.9.1
hooks:
- id: black

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.6.0
rev: v1.6.1
hooks:
- id: mypy

Expand Down
3 changes: 2 additions & 1 deletion pymatgen/analysis/diffraction/tem.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,8 @@ def x_ray_factors(
coeffs = np.array(ATOMIC_SCATTERING_PARAMS[atom.symbol])
for plane in bragg_angles:
scattering_factor_curr = atom.Z - 41.78214 * s2[plane] * np.sum(
coeffs[:, 0] * np.exp(-coeffs[:, 1] * s2[plane]), axis=None # type: ignore
coeffs[:, 0] * np.exp(-coeffs[:, 1] * s2[plane]),
axis=None, # type: ignore
)
scattering_factors_for_atom[plane] = scattering_factor_curr
x_ray_factors[atom.symbol] = scattering_factors_for_atom
Expand Down
3 changes: 2 additions & 1 deletion pymatgen/analysis/diffraction/xrd.py
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,8 @@ def get_pattern(self, structure: Structure, scaled=True, two_theta_range=(0, 90)
# fs = el.Z - 41.78214 * s2 * sum(
# [d[0] * exp(-d[1] * s2) for d in coeff])
fs = zs - 41.78214 * s2 * np.sum(
coeffs[:, :, 0] * np.exp(-coeffs[:, :, 1] * s2), axis=1 # type: ignore
coeffs[:, :, 0] * np.exp(-coeffs[:, :, 1] * s2),
axis=1, # type: ignore
)

dw_correction = np.exp(-dwfactors * s2)
Expand Down
12 changes: 3 additions & 9 deletions pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -597,9 +597,7 @@ def remove_nodes(self, indices):
self.structure.remove_sites(indices)
self.graph.remove_nodes_from(indices)

mapping = {}
for correct, current in enumerate(sorted(self.graph.nodes)):
mapping[current] = correct
mapping = {val: idx for idx, val in enumerate(sorted(self.graph.nodes))}

nx.relabel_nodes(self.graph, mapping, copy=False)
self.set_node_attributes()
Expand Down Expand Up @@ -1922,9 +1920,7 @@ def remove_nodes(self, indices):
self.molecule.remove_sites(indices)
self.graph.remove_nodes_from(indices)

mapping = {}
for correct, current in enumerate(sorted(self.graph.nodes)):
mapping[current] = correct
mapping = {val: idx for idx, val in enumerate(sorted(self.graph.nodes))}

nx.relabel_nodes(self.graph, mapping, copy=False)
self.set_node_attributes()
Expand Down Expand Up @@ -1961,9 +1957,7 @@ def get_disconnected_fragments(self, return_index_map: bool = False):
new_to_old_index += list(nodes)
# Molecule indices are essentially list-based, so node indices
# must be remapped, incrementing from 0
mapping = {}
for idx, node in enumerate(nodes):
mapping[node] = idx
mapping = {val: idx for idx, val in enumerate(nodes)}

# just give charge to whatever subgraph has node with index 0
# TODO: actually figure out how to distribute charge
Expand Down
42 changes: 24 additions & 18 deletions pymatgen/analysis/interfaces/coherent_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,15 +90,17 @@ def _find_matches(self) -> None:
for match in self.zsl_matches:
xform = get_2d_transform(film_vectors, match.film_vectors)
strain, rot = polar(xform)
assert_allclose(
strain, np.round(strain), atol=1e-12
), "Film lattice vectors changed during ZSL match, check your ZSL Generator parameters"
(
assert_allclose(strain, np.round(strain), atol=1e-12),
"Film lattice vectors changed during ZSL match, check your ZSL Generator parameters",
)

xform = get_2d_transform(substrate_vectors, match.substrate_vectors)
strain, rot = polar(xform)
assert_allclose(
strain, strain.astype(int), atol=1e-12
), "Substrate lattice vectors changed during ZSL match, check your ZSL Generator parameters"
(
assert_allclose(strain, strain.astype(int), atol=1e-12),
"Substrate lattice vectors changed during ZSL match, check your ZSL Generator parameters",
)

def _find_terminations(self):
"""Finds all terminations."""
Expand Down Expand Up @@ -198,25 +200,29 @@ def get_interfaces(
).astype(int)
film_sl_slab = film_slab.copy()
film_sl_slab.make_supercell(super_film_transform)
assert_allclose(
film_sl_slab.lattice.matrix[2], film_slab.lattice.matrix[2], atol=1e-08
), "2D transformation affected C-axis for Film transformation"
assert_allclose(
film_sl_slab.lattice.matrix[:2], match.film_sl_vectors, atol=1e-08
), "Transformation didn't make proper supercell for film"
(
assert_allclose(film_sl_slab.lattice.matrix[2], film_slab.lattice.matrix[2], atol=1e-08),
"2D transformation affected C-axis for Film transformation",
)
(
assert_allclose(film_sl_slab.lattice.matrix[:2], match.film_sl_vectors, atol=1e-08),
"Transformation didn't make proper supercell for film",
)

# Build substrate superlattice
super_sub_transform = np.round(
from_2d_to_3d(get_2d_transform(sub_slab.lattice.matrix[:2], match.substrate_sl_vectors))
).astype(int)
sub_sl_slab = sub_slab.copy()
sub_sl_slab.make_supercell(super_sub_transform)
assert_allclose(
sub_sl_slab.lattice.matrix[2], sub_slab.lattice.matrix[2], atol=1e-08
), "2D transformation affected C-axis for Film transformation"
assert_allclose(
sub_sl_slab.lattice.matrix[:2], match.substrate_sl_vectors, atol=1e-08
), "Transformation didn't make proper supercell for substrate"
(
assert_allclose(sub_sl_slab.lattice.matrix[2], sub_slab.lattice.matrix[2], atol=1e-08),
"2D transformation affected C-axis for Film transformation",
)
(
assert_allclose(sub_sl_slab.lattice.matrix[:2], match.substrate_sl_vectors, atol=1e-08),
"Transformation didn't make proper supercell for substrate",
)

# Add extra info
match_dict = match.as_dict()
Expand Down
5 changes: 3 additions & 2 deletions pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -505,7 +505,7 @@ def pd_coords(self, comp: Composition) -> np.ndarray:
The coordinates for a given composition in the PhaseDiagram's basis
"""
if set(comp.elements) - set(self.elements):
raise ValueError(f"{comp} has elements not in the phase diagram {', '.join(map(str,self.elements))}")
raise ValueError(f"{comp} has elements not in the phase diagram {', '.join(map(str, self.elements))}")
return np.array([comp.get_atomic_fraction(el) for el in self.elements[1:]])

@property
Expand Down Expand Up @@ -894,7 +894,8 @@ def get_decomp_and_phase_separation_energy(
same_comp_mem_ids = [
id(c)
for c in compare_entries
if ( # NOTE use this construction to avoid calls to fractional_composition
# NOTE use this construction to avoid calls to fractional_composition
if (
len(entry_frac) == len(c.composition)
and all(
abs(v - c.composition.get_atomic_fraction(el)) <= Composition.amount_tolerance
Expand Down
4 changes: 1 addition & 3 deletions pymatgen/analysis/xas/spectrum.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,9 +162,7 @@ def stitch(self, other: XAS, num_samples: int = 500, mode: Literal["XAFS", "L23"
f_final = interp1d(np.asarray(wavenumber), np.asarray(mu), bounds_error=False, fill_value=0)
wavenumber_final = np.linspace(min(wavenumber), max(wavenumber), num=num_samples)
mu_final = f_final(wavenumber_final)
energy_final = [
3.8537 * i**2 + xanes.e0 if i > 0 else -3.8537 * i**2 + xanes.e0 for i in wavenumber_final
]
energy_final = [3.8537 * i**2 + xanes.e0 if i > 0 else -3.8537 * i**2 + xanes.e0 for i in wavenumber_final]

return XAS(
energy_final,
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/apps/battery/battery_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ def get_sub_electrodes(self, adjacent_only=True):
"""
NotImplementedError(
"The get_sub_electrodes function must be implemented for each concrete electrode "
f"class {type(self).__name__,}"
f"class {type(self).__name__}"
)

def get_average_voltage(self, min_voltage=None, max_voltage=None):
Expand Down
5 changes: 1 addition & 4 deletions pymatgen/apps/battery/conversion_battery.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,7 @@ def from_composition_and_pd(cls, comp, pd, working_ion_symbol="Li", allow_unstab
if len(profile) < 2:
return None
working_ion = working_ion_entry.elements[0].symbol
normalization_els = {}
for el, amt in comp.items():
if el != Element(working_ion):
normalization_els[el] = amt
normalization_els = {el: amt for el, amt in comp.items() if el != Element(working_ion)}
framework = comp.as_dict()
if working_ion in framework:
framework.pop(working_ion)
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/command_line/enumlib_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def get_sg_info(ss):
target_sg_num = get_sg_info(list(symmetrized_structure))
curr_sites = list(itertools.chain.from_iterable(disordered_sites))
sg_num = get_sg_info(curr_sites)
ordered_sites = sorted(ordered_sites, key=lambda sites: len(sites))
ordered_sites = sorted(ordered_sites, key=len)
logger.debug(f"Disordered sites has sg # {sg_num}")
self.ordered_sites = []

Expand Down
4 changes: 2 additions & 2 deletions pymatgen/command_line/vampire_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -274,9 +274,9 @@ def _create_input(self):
]

# Set temperature range and step size of simulation
start_t = self.user_input_settings["start_t"] if "start_t" in self.user_input_settings else 0
start_t = self.user_input_settings.get("start_t", 0)

end_t = self.user_input_settings["end_t"] if "end_t" in self.user_input_settings else 1500
end_t = self.user_input_settings.get("end_t", 1500)

temp_increment = self.user_input_settings.get("temp_increment", 25)

Expand Down
4 changes: 2 additions & 2 deletions pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def formula(self) -> str:
"""
sym_amt = self.get_el_amt_dict()
syms = sorted(sym_amt, key=lambda sym: get_el_sp(sym).X)
formula = [f"{s}{formula_double_format(sym_amt[s],ignore_ones= False)}" for s in syms]
formula = [f"{s}{formula_double_format(sym_amt[s], ignore_ones= False)}" for s in syms]
return " ".join(formula)

@property
Expand All @@ -302,7 +302,7 @@ def iupac_formula(self) -> str:
"""
sym_amt = self.get_el_amt_dict()
syms = sorted(sym_amt, key=lambda s: get_el_sp(s).iupac_ordering)
formula = [f"{s}{formula_double_format(sym_amt[s],ignore_ones= False)}" for s in syms]
formula = [f"{s}{formula_double_format(sym_amt[s], ignore_ones= False)}" for s in syms]
return " ".join(formula)

@property
Expand Down
4 changes: 1 addition & 3 deletions pymatgen/core/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -938,9 +938,7 @@ def __eq__(self, other: object) -> bool:
return NotImplemented

return (
self.symbol == other.symbol
and self.oxi_state == other.oxi_state
and (self.spin == other.spin) # type: ignore
self.symbol == other.symbol and self.oxi_state == other.oxi_state and (self.spin == other.spin) # type: ignore
)

def __hash__(self) -> int:
Expand Down
17 changes: 11 additions & 6 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2345,11 +2345,14 @@ def factors(n: int):
for a in factors(det):
for e in factors(det // a):
g = det // a // e
yield det, np.array(
[
[[a, b, c], [0, e, f], [0, 0, g]]
for b, c, f in itertools.product(range(a), range(a), range(e))
]
yield (
det,
np.array(
[
[[a, b, c], [0, e, f], [0, 0, g]]
for b, c, f in itertools.product(range(a), range(a), range(e))
]
),
)

# we can't let sites match to their neighbors in the supercell
Expand Down Expand Up @@ -3388,7 +3391,9 @@ def get_boxed_structure(
centered_coords = self.cart_coords - self.center_of_mass + offset

for i, j, k in itertools.product(
list(range(images[0])), list(range(images[1])), list(range(images[2])) # type: ignore
list(range(images[0])),
list(range(images[1])),
list(range(images[2])), # type: ignore
):
box_center = [(i + 0.5) * a, (j + 0.5) * b, (k + 0.5) * c]
if random_rotation:
Expand Down
14 changes: 1 addition & 13 deletions pymatgen/core/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,17 +193,14 @@ def __mul__(self, other):
new_units[k] += v
return Unit(new_units)

def __div__(self, other):
def __truediv__(self, other):
new_units = collections.defaultdict(int)
for k, v in self.items():
new_units[k] += v
for k, v in other.items():
new_units[k] -= v
return Unit(new_units)

def __truediv__(self, other):
return self.__div__(other)

def __pow__(self, i):
return Unit({k: v * i for k, v in self.items()})

Expand Down Expand Up @@ -571,15 +568,6 @@ def __rmul__(self, other):
)
return self.__class__(np.array(self) * np.array(other), unit=self.unit * other.unit)

def __div__(self, other):
if not hasattr(other, "unit_type"):
return self.__class__(
np.array(self) / np.array(other),
unit_type=self._unit_type,
unit=self._unit,
)
return self.__class__(np.array(self) / np.array(other), unit=self.unit / other.unit)

def __truediv__(self, other):
if not hasattr(other, "unit_type"):
return self.__class__(np.array(self) / np.array(other), unit_type=self._unit_type, unit=self._unit)
Expand Down
8 changes: 7 additions & 1 deletion pymatgen/electronic_structure/boltztrap2.py
Original file line number Diff line number Diff line change
Expand Up @@ -801,7 +801,13 @@ def compute_properties_doping(self, doping, temp_r=None):
for idx_t, temp in enumerate(temp_r):
for idx_d, dop_car in enumerate(doping_carriers):
mu_doping[dop_type][idx_t, idx_d] = BL.solve_for_mu(
self.epsilon, self.dos, self.nelect + dop_car, temp, self.dosweight, True, False # noqa: FBT003
self.epsilon,
self.dos,
self.nelect + dop_car,
temp,
self.dosweight,
True, # noqa: FBT003
False, # noqa: FBT003
)

N, L0, L1, L2, Lm11 = BL.fermiintegrals(
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/electronic_structure/cohp.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ def has_antibnd_states_below_efermi(self, spin=None, limit=0.01):
def from_dict(cls, dct):
"""Returns a COHP object from a dict representation of the COHP."""
icohp = {Spin(int(key)): np.array(val) for key, val in dct["ICOHP"].items()} if "ICOHP" in dct else None
are_cobis = False if "are_cobis" not in dct else dct["are_cobis"]
are_cobis = dct.get("are_cobis", False)
return Cohp(
dct["efermi"],
dct["energies"],
Expand Down Expand Up @@ -622,7 +622,7 @@ def from_dict(cls, d):
icohp = None
avg_cohp = Cohp(efermi, energies, cohp, icohp=icohp)

are_cobis = False if "are_cobis" not in d else d["are_cobis"]
are_cobis = d.get("are_cobis", False)

return CompleteCohp(
structure,
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/entries/mixing_scheme.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,7 +547,7 @@ def _get_sg(struct) -> int:
l_pre_group = list(pre_group)
if comp.reduced_formula in ["O2", "H2", "Cl2", "F2", "N2", "I", "Br", "H2O"] and self.fuzzy_matching:
# group by number of sites
for idx, site_group in groupby(sorted(l_pre_group, key=lambda s: len(s)), key=lambda s: len(s)):
for idx, site_group in groupby(sorted(l_pre_group, key=len), key=len):
l_sitegroup = list(site_group)
row_list.append(
self._populate_df_row(l_sitegroup, comp, sg, idx, pd_type_1, pd_type_2, all_entries)
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/io/abinit/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,9 +164,9 @@ def format_list2d(values, float_decimal=0):

# Determine the format
width = max(len(str(s)) for s in flattened_list)
if type_all == int:
if type_all is int:
fmt_spec = f">{width}d"
elif type_all == str:
elif type_all is str:
fmt_spec = f">{width}"
else:
# Number of decimal
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/io/lammps/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ def get_str(self, distance: int = 6, velocity: int = 8, charge: int = 4, hybrid:
all_stats = list(counts.values()) + list(types.values())
right_indent = len(str(max(all_stats)))
count_lines = [f"{v:>{right_indent}} {k}" for k, v in counts.items()]
type_lines = [f"{v:>{right_indent}} {k+ ' types'}" for k, v in types.items()]
type_lines = [f"{v:>{right_indent}} {k + ' types'}" for k, v in types.items()]
stats = "\n".join([*count_lines, "", *type_lines])

def map_coords(q) -> str:
Expand Down
Loading

0 comments on commit 3ec73a7

Please sign in to comment.