Skip to content

Commit

Permalink
_ prefix unused variables
Browse files Browse the repository at this point in the history
bump ruff from 0.1.7 to 0.1.8
  • Loading branch information
janosh committed Dec 13, 2023
1 parent 3933e7d commit d860b0a
Show file tree
Hide file tree
Showing 37 changed files with 87 additions and 90 deletions.
4 changes: 2 additions & 2 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.1.7
rev: v0.1.8
hooks:
- id: ruff
args: [--fix]
Expand Down Expand Up @@ -47,7 +47,7 @@ repos:
- id: blacken-docs

- repo: https://github.com/igorshubovych/markdownlint-cli
rev: v0.37.0
rev: v0.38.0
hooks:
- id: markdownlint
# MD013: line too long
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ def get_mi_vec(slab):
def get_rot(slab):
"""Gets the transformation to rotate the z axis into the miller index."""
new_z = get_mi_vec(slab)
a, b, c = slab.lattice.matrix
a, _b, _c = slab.lattice.matrix
new_x = a / np.linalg.norm(a)
new_y = np.cross(new_z, new_x)
x, y, z = np.eye(3)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def draw_network(env_graph, pos, ax, sg=None, periodicity_vectors=None):
c = Circle(pos[n], radius=0.02, alpha=0.5)
ax.add_patch(c)
env_graph.node[n]["patch"] = c
x, y = pos[n]
_x, _y = pos[n]
ax.annotate(str(n), pos[n], ha="center", va="center", xycoords="data")
seen = {}
e = None
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,7 @@ def get_site_neighbors(self, site, isite=None, dequivsite=None, dthissite=None,
if isite is None:
isite, dequivsite, dthissite, mysym = self.equivalent_site_index_and_transform(site)

ce, cn_map = self.get_site_coordination_environment(
_ce, cn_map = self.get_site_coordination_environment(
site=site,
isite=isite,
dequivsite=dequivsite,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ def find_rotation(points_distorted, points_perfect):
The rotation matrix.
"""
H = np.matmul(points_distorted.T, points_perfect)
U, S, Vt = svd(H)
U, _S, Vt = svd(H)
return np.matmul(Vt.T, U.T)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,7 @@ def neighbors_surfaces_bounded(self, isite, surface_calculation_options=None):
ap2 = angle_bounds[iap]
if ap2 < minang or ap1 > maxang:
continue
intersection, interror = rectangle_surface_intersection(
intersection, _interror = rectangle_surface_intersection(
rectangle=((d1, d2), (ap1, ap2)),
f_lower=f_lower,
f_upper=f_upper,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1037,7 +1037,7 @@ def from_npoints_least_square_distance(cls, points):
for ii, pp in enumerate(points):
for jj in range(3):
AA[ii, jj] = pp[jj] - mean_point[jj]
[UU, SS, Vt] = np.linalg.svd(AA)
_UU, SS, Vt = np.linalg.svd(AA)
imin = np.argmin(SS)
normal_vector = Vt[imin]
non_zeros = np.argwhere(normal_vector != 0.0)
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/chemenv/utils/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ def order(self, raise_on_fail=True):
self.ordered = False
return

min_index, min_node = min(enumerate(self.nodes), key=operator.itemgetter(1))
min_index, _min_node = min(enumerate(self.nodes), key=operator.itemgetter(1))
reverse = self.nodes[(min_index - 1) % len(self.nodes)] < self.nodes[(min_index + 1) % len(self.nodes)]
if reverse:
self.nodes = self.nodes[min_index::-1] + self.nodes[:min_index:-1]
Expand Down Expand Up @@ -413,7 +413,7 @@ def order(self, raise_on_fail=True):
self.ordered = False
return

min_index, min_node = min(enumerate(self.nodes), key=operator.itemgetter(1))
min_index, _min_node = min(enumerate(self.nodes), key=operator.itemgetter(1))

# Special case when number of nodes is 2 because the two
# edge_indices refer to the same pair of nodes
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/chempot_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -466,7 +466,7 @@ def _get_3d_domain_simplexes_and_ann_loc(
into 2-dimensional space so that ConvexHull can be used to identify the
bounding polygon.
"""
points_2d, v, w = simple_pca(points_3d, k=2)
points_2d, _v, w = simple_pca(points_3d, k=2)
domain = ConvexHull(points_2d)
centroid_2d = get_centroid_2d(points_2d[domain.vertices])
ann_loc = centroid_2d @ w.T + np.mean(points_3d.T, axis=1)
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/analysis/dimensionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,11 +338,11 @@ def get_dimensionality_cheon(
structure = structure_raw
structure_save = copy.copy(structure_raw)
connected_list1 = find_connected_atoms(structure, tolerance=tolerance, ldict=ldict)
max1, min1, clusters1 = find_clusters(structure, connected_list1)
max1, min1, _clusters1 = find_clusters(structure, connected_list1)
if larger_cell:
structure.make_supercell([[3, 0, 0], [0, 3, 0], [0, 0, 3]])
connected_list3 = find_connected_atoms(structure, tolerance=tolerance, ldict=ldict)
max3, min3, clusters3 = find_clusters(structure, connected_list3)
max3, min3, _clusters3 = find_clusters(structure, connected_list3)
if min3 == min1:
dim = "0D" if max3 == max1 else "intercalated molecule"
else:
Expand All @@ -354,7 +354,7 @@ def get_dimensionality_cheon(
else:
structure.make_supercell([[2, 0, 0], [0, 2, 0], [0, 0, 2]])
connected_list2 = find_connected_atoms(structure, tolerance=tolerance, ldict=ldict)
max2, min2, clusters2 = find_clusters(structure, connected_list2)
max2, min2, _clusters2 = find_clusters(structure, connected_list2)
if min2 == 1:
dim = "intercalated ion"
elif min2 == min1:
Expand All @@ -367,7 +367,7 @@ def get_dimensionality_cheon(
structure = copy.copy(structure_save)
structure.make_supercell([[3, 0, 0], [0, 3, 0], [0, 0, 3]])
connected_list3 = find_connected_atoms(structure, tolerance=tolerance, ldict=ldict)
max3, min3, clusters3 = find_clusters(structure, connected_list3)
max3, min3, _clusters3 = find_clusters(structure, connected_list3)
if min3 == min2:
dim = "0D" if max3 == max2 else "intercalated molecule"
else:
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/elasticity/elastic.py
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ def get_tgt(self, temperature: float | None = None, structure: Structure = None,
num, denom, c = np.zeros((3, 3)), 0, 1
for p, w in zip(points, weights):
gk = ElasticTensor(self[0]).green_kristoffel(p)
rho_wsquareds, us = np.linalg.eigh(gk)
_rho_wsquareds, us = np.linalg.eigh(gk)
us = [u / np.linalg.norm(u) for u in np.transpose(us)]
for u in us:
# TODO: this should be benchmarked
Expand Down Expand Up @@ -876,7 +876,7 @@ def diff_fit(strains, stresses, eq_stress=None, order=2, tol: float = 1e-10):
coef = get_diff_coeff(hvec, i)
dei_dsi[i - 1, :, n] = np.dot(coef, data["stresses"])

m, absent = generate_pseudo(list(strain_state_dict), order)
m, _absent = generate_pseudo(list(strain_state_dict), order)
for i in range(1, order):
cvec, carr = get_symbol_list(i + 1)
svec = np.ravel(dei_dsi[i - 1].T)
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/interfaces/coherent_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,14 @@ def _find_matches(self) -> None:

for match in self.zsl_matches:
xform = get_2d_transform(film_vectors, match.film_vectors)
strain, rot = polar(xform)
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",
)

xform = get_2d_transform(substrate_vectors, match.substrate_vectors)
strain, rot = polar(xform)
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",
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/magnetism/analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -1090,7 +1090,7 @@ def magnetic_deformation(structure_A: Structure, structure_B: Structure) -> Magn
lattice_a_inv = np.linalg.inv(lattice_a)
p = np.dot(lattice_a_inv, lattice_b)
eta = 0.5 * (np.dot(p.T, p) - np.identity(3))
w, v = np.linalg.eig(eta)
w, _v = np.linalg.eig(eta)
deformation = 100 * (1 / 3) * np.sqrt(w[0] ** 2 + w[1] ** 2 + w[2] ** 2)

return MagneticDeformation(deformation=deformation, type=type_str)
33 changes: 15 additions & 18 deletions pymatgen/analysis/magnetism/heisenberg.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,14 +469,12 @@ def estimate_exchange(self, fm_struct=None, afm_struct=None, fm_e=None, afm_e=No

m_avg = np.mean([np.sqrt(m**2) for m in magmoms])

# If m_avg for FM config is < 1 we won't get sensibile results.
# If m_avg for FM config is < 1 we won't get sensible results.
if m_avg < 1:
iamthedanger = """
Local magnetic moments are small (< 1 muB / atom). The
exchange parameters may be wrong, but <J> and the mean
field critical temperature estimate may be OK.
"""
logging.warning(iamthedanger)
logging.warning(
"Local magnetic moments are small (< 1 muB / atom). The exchange parameters may "
"be wrong, but <J> and the mean field critical temperature estimate may be OK."
)

delta_e = afm_e - fm_e # J > 0 -> FM
j_avg = delta_e / (m_avg**2) # eV / magnetic ion
Expand All @@ -487,7 +485,7 @@ def estimate_exchange(self, fm_struct=None, afm_struct=None, fm_e=None, afm_e=No
def get_mft_temperature(self, j_avg):
"""
Crude mean field estimate of critical temperature based on <J> for
one sublattice, or solving the coupled equations for a multisublattice
one sublattice, or solving the coupled equations for a multi-sublattice
material.
Args:
Expand All @@ -496,15 +494,15 @@ def get_mft_temperature(self, j_avg):
Returns:
mft_t (float): Critical temperature (K)
"""
num_sublattices = len(self.unique_site_ids)
num_sub_lattices = len(self.unique_site_ids)
k_boltzmann = 0.0861733 # meV/K

# Only 1 magnetic sublattice
if num_sublattices == 1:
if num_sub_lattices == 1:
mft_t = 2 * abs(j_avg) / 3 / k_boltzmann

else: # multiple magnetic sublattices
omega = np.zeros((num_sublattices, num_sublattices))
omega = np.zeros((num_sub_lattices, num_sub_lattices))
ex_params = self.ex_params
ex_params = {k: v for (k, v) in ex_params.items() if k != "E0"} # ignore E0
for k in ex_params:
Expand All @@ -516,15 +514,14 @@ def get_mft_temperature(self, j_avg):
omega[j, i] += ex_params[k]

omega = omega * 2 / 3 / k_boltzmann
eigenvals, eigenvecs = np.linalg.eig(omega)
mft_t = max(eigenvals)
eigen_vals, _eigen_vecs = np.linalg.eig(omega)
mft_t = max(eigen_vals)

if mft_t > 1500: # Not sensible!
stayoutofmyterritory = """
This mean field estimate is too high! Probably
the true low energy orderings were not given as inputs.
"""
logging.warning(stayoutofmyterritory)
logging.warning(
"This mean field estimate is too high! Probably "
"the true low energy orderings were not given as inputs."
)

return mft_t

Expand Down
8 changes: 4 additions & 4 deletions pymatgen/analysis/molecule_matcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -825,7 +825,7 @@ def kabsch(P: np.ndarray, Q: np.ndarray):

# Computation of the optimal rotation matrix
# using singular value decomposition (SVD).
V, S, WT = np.linalg.svd(C)
V, _S, WT = np.linalg.svd(C)

# Getting the sign of the det(V*Wt) to decide whether
d = np.linalg.det(np.dot(V, WT))
Expand Down Expand Up @@ -1064,7 +1064,7 @@ def permutations(p_atoms, p_centroid, p_weights, q_atoms, q_centroid, q_weights)
# Perform Hungarian analysis on distance matrix between atoms of 1st
# structure and trial structure
distances = cdist(A, B, "euclidean")
a_inds, b_inds = linear_sum_assignment(distances)
_a_inds, b_inds = linear_sum_assignment(distances)

perm_inds[q_atom_inds] = p_atom_inds[b_inds]

Expand All @@ -1089,7 +1089,7 @@ def permutations(p_atoms, p_centroid, p_weights, q_atoms, q_centroid, q_weights)
# Perform Hungarian analysis on distance matrix between atoms of 1st
# structure and trial structure
distances = cdist(A, B, "euclidean")
a_inds, b_inds = linear_sum_assignment(distances)
_a_inds, b_inds = linear_sum_assignment(distances)

perm_inds[q_atom_inds] = p_atom_inds[b_inds]

Expand Down Expand Up @@ -1119,7 +1119,7 @@ def get_principal_axis(coords, weights):

inertia_tensor = np.array([[Ixx, Ixy, Ixz], [Ixy, Iyy, Iyz], [Ixz, Iyz, Izz]])

eigvals, eigvecs = np.linalg.eigh(inertia_tensor)
_eigvals, eigvecs = np.linalg.eigh(inertia_tensor)

return eigvecs[:, 0]

Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/piezo_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ def get_BEC_operations(self, eigtol=1e-5, opstol=1e-3):
relations = []
for site, val in enumerate(bec):
unique = 1
eig1, vecs1 = np.linalg.eig(val)
eig1, _vecs1 = np.linalg.eig(val)
index = np.argsort(eig1)
new_eig = np.real([eig1[index[0]], eig1[index[1]], eig1[index[2]]])
for index, p in enumerate(passed):
Expand Down Expand Up @@ -670,7 +670,7 @@ def get_piezo(BEC, IST, FCM, rcond=0.0001):
n_sites = len(BEC)
temp_fcm = np.reshape(np.swapaxes(FCM, 1, 2), (n_sites * 3, n_sites * 3))

eigs, vecs = np.linalg.eig(temp_fcm)
eigs, _vecs = np.linalg.eig(temp_fcm)
K = np.linalg.pinv(
-temp_fcm,
rcond=np.abs(eigs[np.argsort(np.abs(eigs))[2]]) / np.abs(eigs[np.argsort(np.abs(eigs))[-1]]) + rcond,
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/structure_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def plot_vor_analysis(voronoi_ensemble: list[tuple[str, float]]) -> plt.Axes:
arr /= np.sum(arr)
pos = np.arange(len(arr)) + 0.5 # the bar centers on the y axis

fig, ax = plt.subplots()
_fig, ax = plt.subplots()
ax.barh(pos, arr, align="center", alpha=0.5)
ax.set_yticks(pos)
ax.set_yticklabels(labels)
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/topological/spillage.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def isclose(n1, n2, rel_tol=1e-7):
@staticmethod
def orth(A):
"""Helper function to create orthonormal basis."""
u, s, vh = np.linalg.svd(A, full_matrices=False)
u, s, _vh = np.linalg.svd(A, full_matrices=False)
M, N = A.shape
eps = np.finfo(float).eps
tol = max(M, N) * np.amax(s) * eps
Expand Down Expand Up @@ -168,9 +168,9 @@ def overlap_so_spinpol(self):
t = so.coeffs[nk2 - 1][n1 - 1].flatten()
Vso[0 : vs // 2, n1 - 1] = t[0 : vs // 2]
Vso[vs // 2 : vs, n1 - 1] = t[n_so // 2 : n_so // 2 + vs // 2]
Qnoso, num_noso = self.orth(Vnoso) # make orthonormal basis?
Qnoso, _num_noso = self.orth(Vnoso) # make orthonormal basis?

Qso, num_so = self.orth(Vso)
Qso, _num_so = self.orth(Vso)

gamma_k.append(nelec_tot)
a = []
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/wulff.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,7 +500,7 @@ def get_plotly(
(plotly.graph_objects.Figure)
"""
units = "Jm⁻²" if units_in_JPERM2 else "eVÅ⁻²"
color_list, color_proxy, color_proxy_on_wulff, miller_on_wulff, e_surf_on_wulff = self._get_colors(
color_list, _color_proxy, _color_proxy_on_wulff, _miller_on_wulff, e_surf_on_wulff = self._get_colors(
color_set, alpha, off_color, custom_colors=custom_colors or {}
)

Expand Down
4 changes: 2 additions & 2 deletions pymatgen/apps/borg/hive.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def get_valid_paths(self, path):
Returns:
List of valid dir/file paths for assimilation
"""
(parent, subdirs, files) = path
parent, subdirs, _files = path
if "relax1" in subdirs and "relax2" in subdirs:
return [parent]
if (
Expand Down Expand Up @@ -381,7 +381,7 @@ def get_valid_paths(self, path):
Returns:
List of valid dir/file paths for assimilation
"""
parent, subdirs, files = path
parent, _subdirs, files = path
return [os.path.join(parent, f) for f in files if os.path.splitext(f)[1] in self._file_extensions]

def __str__(self):
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 @@ -317,7 +317,7 @@ def _get_structures(self, num_structs):
stdin=subprocess.PIPE,
close_fds=True,
) as rs:
stdout, stderr = rs.communicate()
_stdout, stderr = rs.communicate()
if stderr:
logger.warning(stderr.decode())

Expand Down
8 changes: 4 additions & 4 deletions pymatgen/command_line/gulp_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,20 +349,20 @@ def library_line(file_name):
Returns:
GULP input string specifying library option
"""
gulplib_set = "GULP_LIB" in os.environ
gulp_lib_set = "GULP_LIB" in os.environ

def readable(f):
return os.path.isfile(f) and os.access(f, os.R_OK)

gin = ""
dirpath, fname = os.path.split(file_name)
dirpath, _fname = os.path.split(file_name)
if dirpath and readable(file_name): # Full path specified
gin = "library " + file_name
else:
fpath = os.path.join(os.getcwd(), file_name) # Check current dir
if readable(fpath):
gin = "library " + fpath
elif gulplib_set: # Check the GULP_LIB path
elif gulp_lib_set: # Check the GULP_LIB path
fpath = os.path.join(os.environ["GULP_LIB"], file_name)
if readable(fpath):
gin = "library " + file_name
Expand Down Expand Up @@ -637,7 +637,7 @@ def __init__(self, cmd="gulp"):
def is_exe(f) -> bool:
return os.path.isfile(f) and os.access(f, os.X_OK)

fpath, fname = os.path.split(cmd)
fpath, _fname = os.path.split(cmd)
if fpath:
if is_exe(cmd):
self._gulp_cmd = cmd
Expand Down
Loading

0 comments on commit d860b0a

Please sign in to comment.