Skip to content

Commit

Permalink
self.assertArrayEqual->assert (#2955)
Browse files Browse the repository at this point in the history
* remove unused type ignore

.format str to f-str

* ruff auto doc str format

* drop B031 from ruff ignore

* rename single-letter and non-snake-case vars

* self.assertArrayEqual -> assert
  • Loading branch information
janosh authored Apr 26, 2023
1 parent a553f37 commit 33b3195
Show file tree
Hide file tree
Showing 25 changed files with 247 additions and 283 deletions.
2 changes: 1 addition & 1 deletion dev_scripts/chemenv/get_plane_permutations_optimized.py
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ def random_permutations_iterator(initial_permutation, n_permutations):
f"Optimized perturbations {len(perms_used)}/{len(algo.permutations)} (old : "
f"{original_nexplicit_optimized_perms[ialgo]}/{original_nexplicit_perms[ialgo]}) are :"
)
# print('Optimized permutations ({:d}/{:d}) : '.format(len(perms_used), len(algo.permutations)))
# print(f"Optimized permutations ({len(perms_used):d}/{len(algo.permutations):d}) : ")
explicit_optimized_permutations = [list(perm) for perm in perms_used]
explicit_optimized_permutations.sort()
print(explicit_optimized_permutations)
Expand Down
10 changes: 5 additions & 5 deletions dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,11 @@ def parse_ionic_radii():
with open("periodic_table.yaml") as f:
data = yaml.load(f)
with open("ionic_radii.csv") as f:
radiidata = f.read()
radiidata = radiidata.split("\r")
header = radiidata[0].split(",")
for i in range(1, len(radiidata)):
line = radiidata[i]
radii_data = f.read()
radii_data = radii_data.split("\r")
header = radii_data[0].split(",")
for idx in range(1, len(radii_data)):
line = radii_data[idx]
toks = line.strip().split(",")
suffix = ""
name = toks[1]
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,9 +348,9 @@ def ensemble_center(cls, site_list, indices, cartesian=True):
Cartesian coordinate
"""
if cartesian:
return np.average([site_list[i].coords for i in indices], axis=0)
return np.average([site_list[idx].coords for idx in indices], axis=0)

return np.average([site_list[i].frac_coords for i in indices], axis=0)
return np.average([site_list[idx].frac_coords for idx in indices], axis=0)

def add_adsorbate(self, molecule, ads_coord, repeat=None, translate=True, reorient=True):
"""Adds an adsorbate at a particular coordinate. Adsorbate represented
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -271,9 +271,9 @@ def get_valences(self, structure):

# make variables needed for recursion
if structure.is_ordered:
n_sites = np.array([len(i) for i in equi_sites])
vmin = np.array([min(i) for i in valences])
vmax = np.array([max(i) for i in valences])
n_sites = np.array(list(map(len, equi_sites)))
vmin = np.array(list(map(min, valences)))
vmax = np.array(list(map(max, valences)))

self._n = 0
self._best_score = 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from pymatgen.util.testing import PymatgenTest

try:
import bson # type: ignore # Ignore bson import for mypy
import bson
except ModuleNotFoundError:
bson = None # type: ignore

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
from pymatgen.util.testing import PymatgenTest

try:
import bson # type: ignore # Ignore bson import for mypy
import bson
except ModuleNotFoundError:
bson = None # type: ignore

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,9 @@ def test_coordination_geometry(self):
cg_oct = allcg["O:6"]
cg_oct2 = CoordinationGeometry.from_dict(cg_oct.as_dict())

self.assertArrayAlmostEqual(cg_oct.central_site, cg_oct2.central_site)
self.assertArrayAlmostEqual(cg_oct.points, cg_oct2.points)
assert cg_oct.central_site == pytest.approx(cg_oct2.central_site)
for p1, p2 in zip(cg_oct.points, cg_oct2.points):
assert p1 == pytest.approx(p2)
assert (
str(cg_oct) == "Coordination geometry type : Octahedron (IUPAC: OC-6 || IUCr: [6o])\n"
"\n"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,25 +255,25 @@ def test_distances(self):
67.1666666666666,
],
)
self.assertArrayEqual(indices_sorted, [1, 0, 2, 4, 3, 5])
assert indices_sorted == [1, 0, 2, 4, 3, 5]
# Plane 2y+1=0 (perpendicular to y)
plane = Plane.from_coefficients(0, 2, 0, 1)
plist = [point_1, point_5, point_6, point_7]
distances, indices_sorted = plane.distances_indices_sorted(plist)
self.assertArrayAlmostEqual(distances, [0.5, -1.0, 2.5, 10.5])
self.assertArrayEqual(indices_sorted, [0, 1, 2, 3])
assert indices_sorted == [0, 1, 2, 3]
plist = [point_1, point_5, point_6, point_7]
distances, indices_sorted = plane.distances_indices_sorted(plist)
self.assertArrayAlmostEqual(distances, [0.5, -1.0, 2.5, 10.5])
self.assertArrayEqual(indices_sorted, [0, 1, 2, 3])
assert indices_sorted == [0, 1, 2, 3]
distances, indices_sorted = plane.distances_indices_sorted(plist, sign=True)
self.assertArrayAlmostEqual(distances, [0.5, -1.0, 2.5, 10.5])
self.assertArrayEqual(indices_sorted, [(0, 1), (1, -1), (2, 1), (3, 1)])
assert indices_sorted == [(0, 1), (1, -1), (2, 1), (3, 1)]
plist = [point_5, point_1, point_6, point_7]
distances, indices_sorted, groups = plane.distances_indices_groups(plist)
self.assertArrayAlmostEqual(distances, [-1.0, 0.5, 2.5, 10.5])
self.assertArrayEqual(indices_sorted, [1, 0, 2, 3])
self.assertArrayEqual(groups, [[1, 0], [2], [3]])
assert indices_sorted == [1, 0, 2, 3]
assert groups == [[1, 0], [2], [3]]
plist = [point_1, point_2, point_3, point_4, point_5, point_6, point_7, point_8]
distances, indices_sorted = plane.distances_indices_sorted(plist)
self.assertArrayAlmostEqual(distances, [0.5, 0.5, 0.5, 0.5, -1.0, 2.5, 10.5, 0.5])
Expand All @@ -285,37 +285,31 @@ def test_distances(self):
for zz in zzs:
plist.append([random.uniform(-20.0, 20.0), random.uniform(-20.0, 20.0), zz])
distances, indices_sorted, groups = plane.distances_indices_groups(points=plist, delta=0.25)
self.assertArrayEqual(indices_sorted, [5, 0, 1, 2, 6, 7, 9, 4, 3, 8])
self.assertArrayEqual(groups, [[5, 0, 1], [2, 6, 7], [9, 4, 3], [8]])
assert indices_sorted == [5, 0, 1, 2, 6, 7, 9, 4, 3, 8]
assert groups == [[5, 0, 1], [2, 6, 7], [9, 4, 3], [8]]
self.assertArrayAlmostEqual(distances, zzs)
distances, indices_sorted, groups = plane.distances_indices_groups(points=plist, delta_factor=0.1)
self.assertArrayEqual(indices_sorted, [5, 0, 1, 2, 6, 7, 9, 4, 3, 8])
self.assertArrayEqual(groups, [[5, 0, 1, 2, 6, 7], [9, 4, 3], [8]])
assert indices_sorted == [5, 0, 1, 2, 6, 7, 9, 4, 3, 8]
assert groups == [[5, 0, 1, 2, 6, 7], [9, 4, 3], [8]]
self.assertArrayAlmostEqual(distances, zzs)
distances, indices_sorted, groups = plane.distances_indices_groups(points=plist, delta_factor=0.1, sign=True)
self.assertArrayEqual(
indices_sorted,
[
(5, 0),
(0, 1),
(1, -1),
(2, 1),
(6, -1),
(7, -1),
(9, 1),
(4, -1),
(3, -1),
(8, -1),
],
)
self.assertArrayEqual(
groups,
[
[(5, 0), (0, 1), (1, -1), (2, 1), (6, -1), (7, -1)],
[(9, 1), (4, -1), (3, -1)],
[(8, -1)],
],
)
assert indices_sorted == [
(5, 0),
(0, 1),
(1, -1),
(2, 1),
(6, -1),
(7, -1),
(9, 1),
(4, -1),
(3, -1),
(8, -1),
]
assert groups == [
[(5, 0), (0, 1), (1, -1), (2, 1), (6, -1), (7, -1)],
[(9, 1), (4, -1), (3, -1)],
[(8, -1)],
]
self.assertArrayAlmostEqual(distances, zzs)

def test_projections(self):
Expand Down
12 changes: 6 additions & 6 deletions pymatgen/analysis/chemenv/utils/tests/test_graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ def test_multigraph_cycle(self):
# Testing all cases for a length-4 cycle
nodes_ref = tuple(FakeNodeWithEqLtMethods(inode) for inode in range(4))
edges_ref = (3, 6, 9, 12)
for inodes, iedges in [
for i_nodes, i_edges in [
((0, 1, 2, 3), (3, 6, 9, 12)),
((1, 2, 3, 0), (6, 9, 12, 3)),
((2, 3, 0, 1), (9, 12, 3, 6)),
Expand All @@ -649,12 +649,12 @@ def test_multigraph_cycle(self):
((0, 3, 2, 1), (12, 9, 6, 3)),
]:
mgc = MultiGraphCycle(
[FakeNodeWithEqLtMethods(inode) for inode in inodes],
edge_indices=list(iedges),
[FakeNodeWithEqLtMethods(inode) for inode in i_nodes],
edge_indices=list(i_edges),
)
strnodes = ", ".join(str(i) for i in inodes)
assert mgc.nodes == nodes_ref, f"Nodes not equal for inodes = ({', '.join([str(i) for i in inodes])})"
assert mgc.edge_indices == edges_ref, f"Edges not equal for inodes = ({strnodes})"
str_nodes = ", ".join(str(i) for i in i_nodes)
assert mgc.nodes == nodes_ref, f"Nodes not equal for inodes = ({', '.join([str(i) for i in i_nodes])})"
assert mgc.edge_indices == edges_ref, f"Edges not equal for inodes = ({str_nodes})"


class EnvironmentNodesGraphUtilsTest(PymatgenTest):
Expand Down
11 changes: 5 additions & 6 deletions pymatgen/analysis/chempot_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -676,16 +676,15 @@ def get_centroid_2d(vertices: np.ndarray) -> np.ndarray:
Returns:
Array giving 2-d centroid coordinates
"""
n = len(vertices)
cx = 0
cy = 0
a = 0

for i in range(0, n - 1):
xi = vertices[i, 0]
yi = vertices[i, 1]
xi_p = vertices[i + 1, 0]
yi_p = vertices[i + 1, 1]
for idx in range(0, len(vertices) - 1):
xi = vertices[idx, 0]
yi = vertices[idx, 1]
xi_p = vertices[idx + 1, 0]
yi_p = vertices[idx + 1, 1]
common_term = xi * yi_p - xi_p * yi

cx += (xi + xi_p) * common_term
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/cost.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,8 @@ def get_lowest_decomposition(self, composition):
"""
entries_list = []
elements = [e.symbol for e in composition.elements]
for i in range(len(elements)):
for combi in itertools.combinations(elements, i + 1):
for idx in range(len(elements)):
for combi in itertools.combinations(elements, idx + 1):
chemsys = [Element(e) for e in combi]
x = self.costdb.get_entries(chemsys)
entries_list.extend(x)
Expand Down
16 changes: 8 additions & 8 deletions pymatgen/analysis/diffraction/tests/test_tem.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@

class TEMCalculatorTest(PymatgenTest):
def test_wavelength_rel(self):
# Tests that the relativistic wavelength formula (for 200kv electron beam) is correct
# Test that the relativistic wavelength formula (for 200kv electron beam) is correct
c = TEMCalculator()
assert c.wavelength_rel() == pytest.approx(0.025079, rel=1e-4)

def test_generate_points(self):
# Tests that 3d points are properly generated
# Test that 3d points are properly generated
c = TEMCalculator()
actual = c.generate_points(-1, 1)
expected = np.array(
Expand Down Expand Up @@ -65,10 +65,10 @@ def test_generate_points(self):
[1, 1, 1],
]
)
self.assertArrayEqual(expected, actual)
assert expected == pytest.approx(actual)

def test_zone_axis_filter(self):
# Tests that the appropriate Laue-Zoned points are returned
# Test that the appropriate Laue-Zoned points are returned
c = TEMCalculator()
empty_points = np.asarray([])
assert c.zone_axis_filter(empty_points) == []
Expand All @@ -78,7 +78,7 @@ def test_zone_axis_filter(self):
assert c.zone_axis_filter(laue_1, 1) == [(0, 0, 1)]

def test_get_interplanar_spacings(self):
# Tests that the appropriate interplacing spacing is returned
# Test that the appropriate interplacing spacing is returned
c = TEMCalculator()
point = [(3, 9, 0)]
latt = Lattice.cubic(4.209)
Expand All @@ -100,7 +100,7 @@ def test_get_interplanar_spacings(self):
assert spacings_mono[p] == pytest.approx(0.84450786041677972)

def test_bragg_angles(self):
# Tests that the appropriate bragg angle is returned. Testing formula with values of x-ray diffraction in
# Test that the appropriate bragg angle is returned. Testing formula with values of x-ray diffraction in
# materials project.
c = TEMCalculator()
latt = Lattice.cubic(4.209)
Expand All @@ -111,7 +111,7 @@ def test_bragg_angles(self):
assert bragg_angles_val == pytest.approx(0.26179, rel=1e-4)

def test_get_s2(self):
# Tests that the appropriate s2 factor is returned.
# Test that the appropriate s2 factor is returned.
c = TEMCalculator()
latt = Lattice.cubic(4.209)
cubic = Structure(latt, ["Cs", "Cl"], [[0, 0, 0], [0.5, 0.5, 0.5]])
Expand Down Expand Up @@ -231,7 +231,7 @@ def test_get_positions(self):
points = c.generate_points(-2, 2)
structure = self.get_structure("Si")
positions = c.get_positions(structure, points)
self.assertArrayEqual([0, 0], positions[(0, 0, 0)])
assert [0, 0] == positions[(0, 0, 0)].tolist()
# Test silicon diffraction data spot rough positions:
# see https://www.doitpoms.ac.uk/tlplib/diffraction-patterns/printall.php
self.assertArrayAlmostEqual([1, 0], positions[(-1, 0, 0)], 0)
Expand Down
16 changes: 8 additions & 8 deletions pymatgen/analysis/dimensionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,21 +418,21 @@ def find_connected_atoms(struct, tolerance=0.45, ldict=None):
fc_diff = fc_copy - neighbors
species = list(map(str, struct.species))
# in case of charged species
for i, item in enumerate(species):
for ii, item in enumerate(species):
if item not in ldict:
species[i] = str(Species.from_string(item).element)
species[ii] = str(Species.from_string(item).element)
latmat = struct.lattice.matrix
connected_matrix = np.zeros((n_atoms, n_atoms))

for i in range(n_atoms):
for j in range(i + 1, n_atoms):
max_bond_length = ldict[species[i]] + ldict[species[j]] + tolerance
frac_diff = fc_diff[j] - fc_copy[i]
for ii in range(n_atoms):
for jj in range(ii + 1, n_atoms):
max_bond_length = ldict[species[ii]] + ldict[species[jj]] + tolerance
frac_diff = fc_diff[jj] - fc_copy[ii]
distance_ij = np.dot(latmat.T, frac_diff)
# print(np.linalg.norm(distance_ij,axis=0))
if sum(np.linalg.norm(distance_ij, axis=0) < max_bond_length) > 0:
connected_matrix[i, j] = 1
connected_matrix[j, i] = 1
connected_matrix[ii, jj] = 1
connected_matrix[jj, ii] = 1
return connected_matrix


Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/elasticity/strain.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,11 +256,11 @@ def convert_strain_to_deformation(strain, shape: Literal["upper", "lower", "symm
'symmetric' produces a symmetric defo
"""
strain = SquareTensor(strain)
ftdotf = 2 * strain + np.eye(3)
ft_dot_f = 2 * strain + np.eye(3)
if shape == "upper":
result = scipy.linalg.cholesky(ftdotf)
result = scipy.linalg.cholesky(ft_dot_f)
elif shape == "symmetric":
result = scipy.linalg.sqrtm(ftdotf)
result = scipy.linalg.sqrtm(ft_dot_f)
else:
raise ValueError('shape must be "upper" or "symmetric"')
return Deformation(result)
16 changes: 8 additions & 8 deletions pymatgen/analysis/ewald.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,9 +132,9 @@ def compute_partial_energy(self, removed_indices):
out.
"""
total_energy_matrix = self.total_energy_matrix.copy()
for i in removed_indices:
total_energy_matrix[i, :] = 0
total_energy_matrix[:, i] = 0
for idx in removed_indices:
total_energy_matrix[idx, :] = 0
total_energy_matrix[:, idx] = 0
return sum(sum(total_energy_matrix))

def compute_sub_structure(self, sub_structure, tol: float = 1e-3):
Expand Down Expand Up @@ -547,11 +547,11 @@ def __init__(self, matrix, m_list, num_to_return=1, algo=ALGO_FAST):
# Setup and checking of inputs
self._matrix = copy(matrix)
# Make the matrix diagonally symmetric (so matrix[i,:] == matrix[:,j])
for i in range(len(self._matrix)):
for j in range(i, len(self._matrix)):
value = (self._matrix[i, j] + self._matrix[j, i]) / 2
self._matrix[i, j] = value
self._matrix[j, i] = value
for ii in range(len(self._matrix)):
for jj in range(ii, len(self._matrix)):
value = (self._matrix[ii, jj] + self._matrix[jj, ii]) / 2
self._matrix[ii, jj] = value
self._matrix[jj, ii] = value

# sort the m_list based on number of permutations
self._m_list = sorted(m_list, key=lambda x: comb(len(x[2]), x[1]), reverse=True)
Expand Down
Loading

0 comments on commit 33b3195

Please sign in to comment.