Skip to content

Commit 6427b55

Browse files
committed
ruff fix FURB142: set.add() in a for loop and a few ruff DOC502
1 parent d9f5705 commit 6427b55

File tree

11 files changed

+67
-65
lines changed

11 files changed

+67
-65
lines changed

pyproject.toml

+1
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,7 @@ repair-wheel-command = "delocate-wheel --require-archs {delocate_archs} -w {dest
174174
[tool.ruff]
175175
target-version = "py39"
176176
line-length = 120
177+
output-format = "concise"
177178

178179
[tool.ruff.lint]
179180
select = ["ALL"]

src/pymatgen/core/lattice.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -1803,17 +1803,17 @@ def get_points_in_spheres(
18031803

18041804
# Temporarily hold the fractional coordinates
18051805
image_offsets = lattice.get_fractional_coords(all_coords)
1806-
all_fcoords = []
1806+
all_frac_coords = []
18071807

18081808
# Only wrap periodic boundary
18091809
for kk in range(3):
18101810
if _pbc[kk]:
1811-
all_fcoords.append(np.mod(image_offsets[:, kk : kk + 1], 1))
1811+
all_frac_coords.append(np.mod(image_offsets[:, kk : kk + 1], 1))
18121812
else:
1813-
all_fcoords.append(image_offsets[:, kk : kk + 1])
1814-
all_fcoords = np.concatenate(all_fcoords, axis=1)
1815-
image_offsets = image_offsets - all_fcoords
1816-
coords_in_cell = np.dot(all_fcoords, matrix)
1813+
all_frac_coords.append(image_offsets[:, kk : kk + 1])
1814+
all_frac_coords = np.concatenate(all_frac_coords, axis=1)
1815+
image_offsets = image_offsets - all_frac_coords
1816+
coords_in_cell = np.dot(all_frac_coords, matrix)
18171817

18181818
# Filter out those beyond max range
18191819
valid_coords = []

src/pymatgen/core/structure.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -2159,8 +2159,8 @@ def get_all_neighbors_old(
21592159
lattice = self._lattice
21602160
matrix = lattice.matrix
21612161
neighbors: list[list] = [[] for _ in range(len(self))]
2162-
all_fcoords = np.mod(self.frac_coords, 1)
2163-
coords_in_cell = np.dot(all_fcoords, matrix)
2162+
all_frac_coords = np.mod(self.frac_coords, 1)
2163+
coords_in_cell = np.dot(all_frac_coords, matrix)
21642164
site_coords = self.cart_coords
21652165

21662166
indices = np.arange(len(self))
@@ -2519,14 +2519,14 @@ def site_label(site):
25192519
# Group sites by species string
25202520
sites = sorted(self._sites, key=site_label)
25212521

2522-
grouped_sites = [list(a[1]) for a in itertools.groupby(sites, key=site_label)]
2522+
grouped_sites = [list(grp) for _, grp in itertools.groupby(sites, key=site_label)]
25232523
grouped_frac_coords = [np.array([s.frac_coords for s in g]) for g in grouped_sites]
25242524

25252525
# min_vecs are approximate periodicities of the cell. The exact
25262526
# periodicities from the supercell matrices are checked against these
25272527
# first
2528-
min_fcoords = min(grouped_frac_coords, key=len)
2529-
min_vecs = min_fcoords - min_fcoords[0]
2528+
min_frac_coords = min(grouped_frac_coords, key=len)
2529+
min_vecs = min_frac_coords - min_frac_coords[0]
25302530

25312531
# Fractional tolerance in the supercell
25322532
super_ftol = np.divide(tolerance, self.lattice.abc)
@@ -2636,14 +2636,14 @@ def factors(n: int):
26362636

26372637
# Add the new sites, averaging positions
26382638
added = np.zeros(len(gsites))
2639-
new_fcoords = all_frac % 1
2639+
new_frac_coords = all_frac % 1
26402640
for grp_idx, group in enumerate(groups):
26412641
if not added[grp_idx]:
26422642
added[group] = True
26432643
inds = np.where(group)[0]
2644-
coords = new_fcoords[inds[0]]
2644+
coords = new_frac_coords[inds[0]]
26452645
for inner_idx, ind in enumerate(inds[1:]):
2646-
offset = new_fcoords[ind] - coords
2646+
offset = new_frac_coords[ind] - coords
26472647
coords += (offset - np.round(offset)) / (inner_idx + 2)
26482648
new_sp.append(gsites[inds[0]].species)
26492649
for k in gsites[inds[0]].properties:

src/pymatgen/core/surface.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -828,10 +828,10 @@ def get_slab_regions(
828828
# If slab is noncontiguous
829829
if frac_coords:
830830
# Locate the lowest site within the upper Slab
831-
last_fcoords = []
831+
last_frac_coords = []
832832
last_indices = []
833833
while frac_coords:
834-
last_fcoords = copy.copy(frac_coords)
834+
last_frac_coords = copy.copy(frac_coords)
835835
last_indices = copy.copy(indices)
836836

837837
site = slab[indices[frac_coords.index(min(frac_coords))]]
@@ -850,7 +850,7 @@ def get_slab_regions(
850850
for site in slab:
851851
if all(nn.index not in all_indices for nn in slab.get_neighbors(site, blength)):
852852
upper_fcoords.append(site.frac_coords[2])
853-
coords: list = copy.copy(frac_coords) if frac_coords else copy.copy(last_fcoords)
853+
coords: list = copy.copy(frac_coords) if frac_coords else copy.copy(last_frac_coords)
854854
min_top = slab[last_indices[coords.index(min(coords))]].frac_coords[2]
855855
return [(0, max(upper_fcoords)), (min_top, 1)]
856856

src/pymatgen/core/trajectory.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -699,10 +699,11 @@ def _check_site_props(self, site_props: SitePropsType | None) -> None:
699699
n_sites = len(self.coords[0])
700700
for dct in site_props:
701701
for key, val in dct.items():
702-
assert len(val) == n_sites, (
703-
f"Size of site property {key} {len(val)}) does not equal the "
704-
f"number of sites in the structure {n_sites}."
705-
)
702+
if len(val) != n_sites:
703+
raise ValueError(
704+
f"Size of site property {key} {len(val)}) does not equal the "
705+
f"number of sites in the structure {n_sites}."
706+
)
706707

707708
def _check_frame_props(self, frame_props: list[dict] | None) -> None:
708709
"""Check data shape of site properties."""

src/pymatgen/io/multiwfn.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -448,8 +448,7 @@ def sort_cps_by_distance(
448448
# Add all unique atoms involved in this ring
449449
atom_inds = set()
450450
for bond_name in bond_names:
451-
for atom_ind in bond_cps[bond_name]["atom_inds"]:
452-
atom_inds.add(atom_ind)
451+
atom_inds.update(bond_cps[bond_name]["atom_inds"])
453452

454453
modified_organized_cps["ring"][cp_name]["bond_names"] = bond_names
455454
modified_organized_cps["ring"][cp_name]["atom_inds"] = list(atom_inds)
@@ -477,10 +476,8 @@ def sort_cps_by_distance(
477476
bond_names_cage = set()
478477
atom_inds = set()
479478
for ring_name in ring_names:
480-
for bond_name in ring_cps[ring_name]["bond_names"]:
481-
bond_names_cage.add(bond_name) # type: ignore[attr-defined]
482-
for atom_ind in ring_cps[ring_name]["atom_inds"]:
483-
atom_inds.add(atom_ind) # type: ignore[attr-defined]
479+
bond_names_cage.update(ring_cps[ring_name]["bond_names"]) # type: ignore[attr-defined]
480+
atom_inds.update(ring_cps[ring_name]["atom_inds"]) # type: ignore[attr-defined]
484481

485482
modified_organized_cps["cage"][cp_name]["ring_names"] = ring_names
486483
modified_organized_cps["cage"][cp_name]["bond_names"] = list(bond_names_cage)

src/pymatgen/optimization/neighbors.pyx

+7-7
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ def find_points_in_spheres(
9494
double [:, ::1] frac_coords = <double[:n_center, :3]> safe_malloc(
9595
n_center * 3 * sizeof(double)
9696
)
97-
double[:, ::1] all_fcoords = <double[:n_total, :3]> safe_malloc(
97+
double[:, ::1] all_frac_coords = <double[:n_total, :3]> safe_malloc(
9898
n_total * 3 * sizeof(double)
9999
)
100100
double[:, ::1] coords_in_cell = <double[:n_total, :3]> safe_malloc(
@@ -149,10 +149,10 @@ def find_points_in_spheres(
149149
for j in range(3):
150150
if pbc[j]:
151151
# only wrap atoms when this dimension is PBC
152-
all_fcoords[i, j] = offset_correction[i, j] % 1
153-
offset_correction[i, j] = offset_correction[i, j] - all_fcoords[i, j]
152+
all_frac_coords[i, j] = offset_correction[i, j] % 1
153+
offset_correction[i, j] = offset_correction[i, j] - all_frac_coords[i, j]
154154
else:
155-
all_fcoords[i, j] = offset_correction[i, j]
155+
all_frac_coords[i, j] = offset_correction[i, j]
156156
offset_correction[i, j] = 0
157157

158158
# compute the reciprocal lattice in place
@@ -165,7 +165,7 @@ def find_points_in_spheres(
165165

166166
for i in range(3):
167167
nlattice *= (max_bounds[i] - min_bounds[i])
168-
matmul(all_fcoords, lattice, coords_in_cell)
168+
matmul(all_frac_coords, lattice, coords_in_cell)
169169

170170
# Get translated images, coordinates and indices
171171
for i in range(min_bounds[0], max_bounds[0]):
@@ -229,7 +229,7 @@ def find_points_in_spheres(
229229
# if no valid neighbors were found return empty
230230
if count == 0:
231231
free(&frac_coords[0, 0])
232-
free(&all_fcoords[0, 0])
232+
free(&all_frac_coords[0, 0])
233233
free(&coords_in_cell[0, 0])
234234
free(&offset_correction[0, 0])
235235
free(&center_indices1[0])
@@ -379,7 +379,7 @@ def find_points_in_spheres(
379379

380380
free(&offset_correction[0, 0])
381381
free(&frac_coords[0, 0])
382-
free(&all_fcoords[0, 0])
382+
free(&all_frac_coords[0, 0])
383383
free(&coords_in_cell[0, 0])
384384
free(&center_indices1[0])
385385
free(&center_indices3[0, 0])

src/pymatgen/symmetry/groups.py

+7-5
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ def from_space_group(cls, sg_symbol: str) -> PointGroup:
178178
179179
Raises:
180180
AssertionError if a valid crystal class cannot be created
181+
181182
Returns:
182183
crystal class in Hermann-Mauguin notation.
183184
"""
@@ -202,18 +203,19 @@ def from_space_group(cls, sg_symbol: str) -> PointGroup:
202203
if symbol in [spg["hermann_mauguin"], spg["universal_h_m"], spg["hermann_mauguin_u"]]:
203204
symbol = spg["short_h_m"]
204205

205-
assert symbol[0].isupper(), f"Invalid sg_symbol {sg_symbol}"
206-
assert not symbol[1:].isupper(), f"Invalid sg_symbol {sg_symbol}"
206+
if not symbol[0].isupper():
207+
raise ValueError(f"Invalid {sg_symbol=}")
208+
if symbol[1:].isupper():
209+
raise ValueError(f"Invalid {sg_symbol=}")
207210

208211
symbol = symbol[1:] # Remove centering
209212
symbol = symbol.translate(str.maketrans("abcden", "mmmmmm")) # Remove translation from glide planes
210213
symbol = re.sub(r"_.", "", symbol) # Remove translation from screw axes
211214
symbol = abbrev_map.get(symbol, symbol)
212215
symbol = non_standard_map.get(symbol, symbol)
213216

214-
assert (
215-
symbol in SYMM_DATA["point_group_encoding"]
216-
), f"Could not create a valid crystal class ({symbol}) from sg_symbol {sg_symbol}"
217+
if symbol not in SYMM_DATA["point_group_encoding"]:
218+
raise ValueError(f"Could not create a valid crystal class ({symbol}) from {sg_symbol=}")
217219
return cls(symbol)
218220

219221

src/pymatgen/util/testing/aims.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ def comp_system(
100100
user_kpt_settings (dict[str, Any] | None): settings for k-point density in FHI-aims
101101
102102
Raises:
103-
AssertionError: If the input files are not the same
103+
ValueError: If the input files are not the same
104104
"""
105105
if user_kpt_settings is None:
106106
user_kpt_settings = {}
@@ -130,7 +130,7 @@ def compare_single_files(ref_file: str | Path, test_file: str | Path) -> None:
130130
test_file (str | Path): The file to compare against the reference
131131
132132
Raises:
133-
AssertionError: If the files are not the same
133+
ValueError: If the files are not the same
134134
"""
135135
with open(test_file) as tf:
136136
test_lines = tf.readlines()[5:]
@@ -141,7 +141,8 @@ def compare_single_files(ref_file: str | Path, test_file: str | Path) -> None:
141141
for test_line, ref_line in zip(test_lines, ref_lines):
142142
if "species_dir" in ref_line:
143143
continue
144-
assert test_line.strip() == ref_line.strip()
144+
if test_line.strip() != ref_line.strip():
145+
raise ValueError(f"{test_line=} != {ref_line=}")
145146

146147

147148
Si = Structure(

src/pymatgen/vis/structure_vtk.py

+12-12
Original file line numberDiff line numberDiff line change
@@ -1033,10 +1033,10 @@ def apply_tags(self):
10331033
if cell_index == (0, 0, 0):
10341034
coords = site.coords
10351035
else:
1036-
fcoords = site.frac_coords + np.array(cell_index)
1036+
frac_coords = site.frac_coords + np.array(cell_index)
10371037
site_image = PeriodicSite(
10381038
site.species,
1039-
fcoords,
1039+
frac_coords,
10401040
self.current_structure.lattice,
10411041
to_unit_cell=False,
10421042
coords_are_cartesian=False,
@@ -1097,20 +1097,20 @@ def display_warning(self, warning):
10971097
warning (str): Warning.
10981098
"""
10991099
self.warning_txt_mapper = vtk.vtkTextMapper()
1100-
tprops = self.warning_txt_mapper.GetTextProperty()
1101-
tprops.SetFontSize(14)
1102-
tprops.SetFontFamilyToTimes()
1103-
tprops.SetColor(1, 0, 0)
1104-
tprops.BoldOn()
1105-
tprops.SetJustificationToRight()
1100+
text_props = self.warning_txt_mapper.GetTextProperty()
1101+
text_props.SetFontSize(14)
1102+
text_props.SetFontFamilyToTimes()
1103+
text_props.SetColor(1, 0, 0)
1104+
text_props.BoldOn()
1105+
text_props.SetJustificationToRight()
11061106
self.warning_txt = f"WARNING : {warning}"
11071107
self.warning_txt_actor = vtk.vtkActor2D()
11081108
self.warning_txt_actor.VisibilityOn()
11091109
self.warning_txt_actor.SetMapper(self.warning_txt_mapper)
11101110
self.ren.AddActor(self.warning_txt_actor)
11111111
self.warning_txt_mapper.SetInput(self.warning_txt)
1112-
winsize = self.ren_win.GetSize()
1113-
self.warning_txt_actor.SetPosition(winsize[0] - 10, 10)
1112+
win_size = self.ren_win.GetSize()
1113+
self.warning_txt_actor.SetPosition(win_size[0] - 10, 10)
11141114
self.warning_txt_actor.VisibilityOn()
11151115

11161116
def erase_warning(self):
@@ -1135,8 +1135,8 @@ def display_info(self, info):
11351135
self.info_txt_actor.SetMapper(self.info_txt_mapper)
11361136
self.ren.AddActor(self.info_txt_actor)
11371137
self.info_txt_mapper.SetInput(self.info_txt)
1138-
winsize = self.ren_win.GetSize()
1139-
self.info_txt_actor.SetPosition(10, winsize[1] - 10)
1138+
win_size = self.ren_win.GetSize()
1139+
self.info_txt_actor.SetPosition(10, win_size[1] - 10)
11401140
self.info_txt_actor.VisibilityOn()
11411141

11421142
def erase_info(self):

tests/core/test_lattice.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ def test_get_points_in_sphere(self):
390390
assert types == {np.ndarray}, f"Expected only np.ndarray, got {types}"
391391

392392
def test_get_all_distances(self):
393-
fcoords = np.array(
393+
frac_coords = np.array(
394394
[
395395
[0.3, 0.3, 0.5],
396396
[0.1, 0.1, 0.3],
@@ -409,10 +409,10 @@ def test_get_all_distances(self):
409409
[3.245, 4.453, 1.788, 3.852, 0.000],
410410
]
411411
)
412-
output = lattice.get_all_distances(fcoords, fcoords)
412+
output = lattice.get_all_distances(frac_coords, frac_coords)
413413
assert_allclose(output, expected, 3)
414414
# test just one input point
415-
output2 = lattice.get_all_distances(fcoords[0], fcoords)
415+
output2 = lattice.get_all_distances(frac_coords[0], frac_coords)
416416
assert_allclose(output2, [expected[0]], 2)
417417
# test distance when initial points are not in unit cell
418418
f1 = [0, 0, 17]
@@ -429,7 +429,7 @@ def test_get_all_distances(self):
429429
[3.519, 1.131, 2.251, 0.000, 4.235],
430430
]
431431
)
432-
output3 = lattice_pbc.get_all_distances(fcoords[:-1], fcoords)
432+
output3 = lattice_pbc.get_all_distances(frac_coords[:-1], frac_coords)
433433
assert_allclose(output3, expected_pbc, 3)
434434

435435
def test_monoclinic(self):
@@ -481,20 +481,20 @@ def test_lll_basis(self):
481481
l2 = Lattice([a + b, b + c, c])
482482

483483
cart_coords = np.array([[1, 1, 2], [2, 2, 1.5]])
484-
l1_fcoords = l1.get_fractional_coords(cart_coords)
485-
l2_fcoords = l2.get_fractional_coords(cart_coords)
484+
l1_frac_coords = l1.get_fractional_coords(cart_coords)
485+
l2_frac_coords = l2.get_fractional_coords(cart_coords)
486486

487487
assert_allclose(l1.matrix, l2.lll_matrix)
488488
assert_allclose(np.dot(l2.lll_mapping, l2.matrix), l1.matrix)
489489

490-
assert_allclose(np.dot(l2_fcoords, l2.matrix), np.dot(l1_fcoords, l1.matrix))
490+
assert_allclose(np.dot(l2_frac_coords, l2.matrix), np.dot(l1_frac_coords, l1.matrix))
491491

492-
lll_fcoords = l2.get_lll_frac_coords(l2_fcoords)
492+
lll_frac_coords = l2.get_lll_frac_coords(l2_frac_coords)
493493

494-
assert_allclose(lll_fcoords, l1_fcoords)
495-
assert_allclose(l1.get_cartesian_coords(lll_fcoords), np.dot(lll_fcoords, l2.lll_matrix))
494+
assert_allclose(lll_frac_coords, l1_frac_coords)
495+
assert_allclose(l1.get_cartesian_coords(lll_frac_coords), np.dot(lll_frac_coords, l2.lll_matrix))
496496

497-
assert_allclose(l2.get_frac_coords_from_lll(lll_fcoords), l2_fcoords)
497+
assert_allclose(l2.get_frac_coords_from_lll(lll_frac_coords), l2_frac_coords)
498498

499499
def test_get_miller_index_from_sites(self):
500500
# test on a cubic system

0 commit comments

Comments
 (0)