Skip to content

Commit 80aa781

Browse files
authored
Fix CI error "pdentries_test.csv" not found (#3168)
* snake_case * get_asum_FCM change AssertionError to RuntimeError * fix empty doc strings * snake_case * fix CI error "pdentries_test.csv" not found * better TransformedPDEntryTest.test_str * fix PeriodicSite._frac_coords type refactor PeriodicSite.__repr__ remove unused type ignore * fix TransformedPDEntryTest.test_str * better TransformedPDEntry.test_is_element * breaking: remove pltshow=True kwarg from ConnectedComponent.show_graph fix mypy * fix test broken by PeriodicSite.__repr__ dropping redundant float precision * fix mypy * fix > assert self.labeled_site.label == "Fe2" E AssertionError: assert 'site label' == 'Fe2' * mypy ignore
1 parent 1fd5cfd commit 80aa781

File tree

18 files changed

+173
-170
lines changed

18 files changed

+173
-170
lines changed

pymatgen/analysis/chemenv/connectivity/connected_components.py

Lines changed: 30 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -392,7 +392,7 @@ def compute_periodicity(self, algorithm="all_simple_paths"):
392392
self._order_periodicity_vectors()
393393

394394
def compute_periodicity_all_simple_paths_algorithm(self):
395-
"""Returns:"""
395+
"""Get the periodicity vectors of the connected component."""
396396
self_loop_nodes = list(nx.nodes_with_selfloops(self._connected_subgraph))
397397
all_nodes_independent_cell_image_vectors = []
398398
my_simple_graph = nx.Graph(self._connected_subgraph)
@@ -476,23 +476,22 @@ def compute_periodicity_all_simple_paths_algorithm(self):
476476
if len(self._periodicity_vectors) == 3:
477477
break
478478

479-
def compute_periodicity_cycle_basis(self):
480-
"""Returns:"""
479+
def compute_periodicity_cycle_basis(self) -> None:
480+
"""Compute periodicity vectors of the connected component."""
481481
my_simple_graph = nx.Graph(self._connected_subgraph)
482482
cycles = nx.cycle_basis(my_simple_graph)
483-
all_deltas = []
484-
for cyc in cycles:
485-
mycyc = list(cyc)
486-
mycyc.append(cyc[0])
483+
all_deltas: list[list] = []
484+
for cyc in map(list, cycles):
485+
cyc.append(cyc[0])
487486
this_cycle_deltas = [np.zeros(3, int)]
488-
for node1, node2 in [(node1, mycyc[inode1 + 1]) for inode1, node1 in enumerate(mycyc[:-1])]:
487+
for node1, node2 in [(node1, cyc[inode1 + 1]) for inode1, node1 in enumerate(cyc[:-1])]:
489488
this_cycle_deltas_new = []
490489
for edge_data in self._connected_subgraph[node1][node2].values():
491490
delta = get_delta(node1, node2, edge_data)
492491
for current_delta in this_cycle_deltas:
493492
this_cycle_deltas_new.append(current_delta + delta)
494493
this_cycle_deltas = this_cycle_deltas_new
495-
all_deltas.extend(this_cycle_deltas)
494+
all_deltas.extend(this_cycle_deltas) # type: ignore
496495
all_deltas = get_linearly_independent_vectors(all_deltas)
497496
if len(all_deltas) == 3:
498497
return
@@ -510,7 +509,7 @@ def compute_periodicity_cycle_basis(self):
510509
current_delta = get_delta(n1, n2, e1data)
511510
delta = get_delta(n2, n1, e2data)
512511
current_delta += delta
513-
all_deltas.append(current_delta)
512+
all_deltas.append(current_delta) # type: ignore
514513
else:
515514
raise ValueError("Should not be here ...")
516515
all_deltas = get_linearly_independent_vectors(all_deltas)
@@ -528,13 +527,17 @@ def make_supergraph(self, multiplicity):
528527
"""
529528
return make_supergraph(self._connected_subgraph, multiplicity, self._periodicity_vectors)
530529

531-
def show_graph(self, graph=None, save_file=None, drawing_type="internal", pltshow=True) -> None:
530+
def show_graph(
531+
self, graph: nx.MultiGraph | None = None, save_file: str | None = None, drawing_type: str = "internal"
532+
) -> None:
532533
"""
534+
Displays the graph using the specified drawing type.
535+
533536
Args:
534-
graph ():
535-
save_file ():
536-
drawing_type ():
537-
pltshow ():
537+
graph (Graph, optional): The graph to display. If not provided, the current graph is used.
538+
save_file (str, optional): The file path to save the graph image to.
539+
If not provided, the graph is not saved.
540+
drawing_type (str): The type of drawing to use. Can be "internal" or "external".
538541
"""
539542
import matplotlib.pyplot as plt
540543

@@ -560,51 +563,49 @@ def show_graph(self, graph=None, save_file=None, drawing_type="internal", pltsho
560563
import networkx
561564

562565
networkx.draw_random(shown_graph)
563-
if pltshow:
564-
plt.show()
565566

566567
@property
567568
def graph(self):
568569
"""Return the graph of this connected component.
569570
570571
Returns:
571572
MultiGraph: Networkx MultiGraph object with environment as nodes and links between these nodes as edges
572-
with information about the image cell difference if any.
573+
with information about the image cell difference if any.
573574
"""
574575
return self._connected_subgraph
575576

576577
@property
577578
def is_periodic(self) -> bool:
578-
"""Returns:"""
579+
"""Whether this connected component is periodic."""
579580
return not self.is_0d
580581

581582
@property
582583
def is_0d(self) -> bool:
583-
"""Returns:"""
584+
"""Whether this connected component is 0-dimensional."""
584585
if self._periodicity_vectors is None:
585586
self.compute_periodicity()
586587
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
587588
return len(self._periodicity_vectors) == 0
588589

589590
@property
590591
def is_1d(self) -> bool:
591-
"""Returns:"""
592+
"""Whether this connected component is 1-dimensional."""
592593
if self._periodicity_vectors is None:
593594
self.compute_periodicity()
594595
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
595596
return len(self._periodicity_vectors) == 1
596597

597598
@property
598599
def is_2d(self) -> bool:
599-
"""Returns:"""
600+
"""Whether this connected component is 2-dimensional."""
600601
if self._periodicity_vectors is None:
601602
self.compute_periodicity()
602603
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
603604
return len(self._periodicity_vectors) == 2
604605

605606
@property
606607
def is_3d(self) -> bool:
607-
"""Returns:"""
608+
"""Whether this connected component is 3-dimensional."""
608609
if self._periodicity_vectors is None:
609610
self.compute_periodicity()
610611
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
@@ -622,8 +623,8 @@ def _order_vectors(vectors):
622623
Example: [[1, 1, 0], [0, 1, -1], [0, 1, 1]] is ordered as [[0, 1, -1], [0, 1, 1], [1, 1, 0]]
623624
"""
624625
for ipv, pv in enumerate(vectors):
625-
nonzeros = np.nonzero(pv)[0]
626-
if pv[nonzeros[0]] < 0 < len(nonzeros):
626+
non_zeros = np.nonzero(pv)[0]
627+
if pv[non_zeros[0]] < 0 < len(non_zeros):
627628
vectors[ipv] = -pv
628629
return sorted(vectors, key=lambda x: x.tolist())
629630

@@ -633,21 +634,21 @@ def _order_periodicity_vectors(self):
633634
raise ValueError("Number of periodicity vectors is larger than 3.")
634635
self._periodicity_vectors = self._order_vectors(self._periodicity_vectors)
635636
# for ipv, pv in enumerate(self._periodicity_vectors):
636-
# nonzeros = np.nonzero(pv)[0]
637-
# if (len(nonzeros) > 0) and (pv[nonzeros[0]] < 0):
637+
# non_zeros = np.nonzero(pv)[0]
638+
# if (len(non_zeros) > 0) and (pv[non_zeros[0]] < 0):
638639
# self._periodicity_vectors[ipv] = -pv
639640
# self._periodicity_vectors = sorted(self._periodicity_vectors, key=lambda x: x.tolist())
640641

641642
@property
642643
def periodicity_vectors(self):
643-
"""Returns:"""
644+
"""Get periodicity vectors of this connected component."""
644645
if self._periodicity_vectors is None:
645646
self.compute_periodicity()
646647
return [np.array(pp) for pp in self._periodicity_vectors]
647648

648649
@property
649650
def periodicity(self):
650-
"""Returns:"""
651+
"""Get periodicity of this connected component."""
651652
if self._periodicity_vectors is None:
652653
self.compute_periodicity()
653654
return f"{len(self._periodicity_vectors):d}D"

pymatgen/analysis/chemenv/connectivity/structure_connectivity.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -266,8 +266,8 @@ def setup_environments_subgraph(self, environments_symbols):
266266
def setup_atom_environments_subgraph(self, atoms_environments):
267267
raise NotImplementedError
268268

269-
def print_links(self):
270-
"""Returns:"""
269+
def print_links(self) -> None:
270+
"""Print all links in the graph."""
271271
nodes = self.environment_subgraph().nodes()
272272
print("Links in graph :")
273273
for node in nodes:
@@ -285,7 +285,7 @@ def print_links(self):
285285
)
286286

287287
def as_dict(self):
288-
"""Returns:"""
288+
"""Convert to MSONable dict."""
289289
return {
290290
"@module": type(self).__module__,
291291
"@class": type(self).__name__,

pymatgen/analysis/chemenv/coordination_environments/structure_environments.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1746,10 +1746,10 @@ def setup_statistic_lists(self):
17461746
fraction_ion_stat[elmt][oxi_state] = {env: fraction / sumspecie for env, fraction in envs.items()}
17471747
for ce_symbol, ions in ce_ion_stat.items():
17481748
fraction_ce_ion_stat[ce_symbol] = {}
1749-
sum_ce = np.sum([np.sum(list(oxistates.values())) for elmt, oxistates in ions.items()])
1750-
for elmt, oxistates in ions.items():
1749+
sum_ce = np.sum([np.sum(list(oxi_states.values())) for elmt, oxi_states in ions.items()])
1750+
for elmt, oxi_states in ions.items():
17511751
fraction_ce_ion_stat[ce_symbol][elmt] = {
1752-
oxistate: fraction / sum_ce for oxistate, fraction in oxistates.items()
1752+
oxistate: fraction / sum_ce for oxistate, fraction in oxi_states.items()
17531753
}
17541754

17551755
def get_site_info_for_specie_ce(self, specie, ce_symbol):

pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -603,11 +603,11 @@ def __init__(self, coefficients, p1=None, p2=None, p3=None):
603603
self.normal_vector = np.array([coefficients[0], coefficients[1], coefficients[2]], np.float_)
604604
normv = np.linalg.norm(self.normal_vector)
605605
self.normal_vector /= normv
606-
nonzeros = np.argwhere(self.normal_vector != 0.0).flatten()
607-
zeros = list(set(range(3)) - set(nonzeros))
608-
if len(nonzeros) == 0:
606+
non_zeros = np.argwhere(self.normal_vector != 0.0).flatten()
607+
zeros = list(set(range(3)) - set(non_zeros))
608+
if len(non_zeros) == 0:
609609
raise ValueError("Normal vector is equal to 0.0")
610-
if self.normal_vector[nonzeros[0]] < 0.0:
610+
if self.normal_vector[non_zeros[0]] < 0.0:
611611
self.normal_vector = -self.normal_vector
612612
dd = -np.float_(coefficients[3]) / normv
613613
else:
@@ -622,32 +622,32 @@ def __init__(self, coefficients, p1=None, p2=None, p3=None):
622622
self.p3 = p3
623623
# Initializes 3 points belonging to the plane (useful for some methods)
624624
if self.p1 is None:
625-
self.init_3points(nonzeros, zeros)
625+
self.init_3points(non_zeros, zeros)
626626
self.vector_to_origin = dd * self.normal_vector
627627
self.e1 = self.e2 = None
628628
self.e3 = self.normal_vector
629629

630-
def init_3points(self, nonzeros, zeros):
630+
def init_3points(self, non_zeros, zeros):
631631
"""Initialize three random points on this plane.
632632
633-
:param nonzeros: Indices of plane coefficients ([a, b, c]) that are not zero.
633+
:param non_zeros: Indices of plane coefficients ([a, b, c]) that are not zero.
634634
:param zeros: Indices of plane coefficients ([a, b, c]) that are equal to zero.
635635
:return: None
636636
"""
637-
if len(nonzeros) == 3:
637+
if len(non_zeros) == 3:
638638
self.p1 = np.array([-self.d / self.a, 0.0, 0.0], np.float_)
639639
self.p2 = np.array([0.0, -self.d / self.b, 0.0], np.float_)
640640
self.p3 = np.array([0.0, 0.0, -self.d / self.c], np.float_)
641-
elif len(nonzeros) == 2:
641+
elif len(non_zeros) == 2:
642642
self.p1 = np.zeros(3, np.float_)
643-
self.p1[nonzeros[1]] = -self.d / self.coefficients[nonzeros[1]]
643+
self.p1[non_zeros[1]] = -self.d / self.coefficients[non_zeros[1]]
644644
self.p2 = np.array(self.p1)
645645
self.p2[zeros[0]] = 1.0
646646
self.p3 = np.zeros(3, np.float_)
647-
self.p3[nonzeros[0]] = -self.d / self.coefficients[nonzeros[0]]
648-
elif len(nonzeros) == 1:
647+
self.p3[non_zeros[0]] = -self.d / self.coefficients[non_zeros[0]]
648+
elif len(non_zeros) == 1:
649649
self.p1 = np.zeros(3, np.float_)
650-
self.p1[nonzeros[0]] = -self.d / self.coefficients[nonzeros[0]]
650+
self.p1[non_zeros[0]] = -self.d / self.coefficients[non_zeros[0]]
651651
self.p2 = np.array(self.p1)
652652
self.p2[zeros[0]] = 1.0
653653
self.p3 = np.array(self.p1)
@@ -937,8 +937,8 @@ def from_3points(cls, p1, p2, p3):
937937
"""
938938
nn = np.cross(p1 - p3, p2 - p3)
939939
normal_vector = nn / norm(nn)
940-
nonzeros = np.argwhere(normal_vector != 0.0)
941-
if normal_vector[nonzeros[0, 0]] < 0.0:
940+
non_zeros = np.argwhere(normal_vector != 0.0)
941+
if normal_vector[non_zeros[0, 0]] < 0.0:
942942
normal_vector = -normal_vector
943943
dd = -np.dot(normal_vector, p1)
944944
coefficients = np.array([normal_vector[0], normal_vector[1], normal_vector[2], dd], np.float_)
@@ -980,8 +980,8 @@ def from_npoints_least_square_distance(cls, points):
980980
[UU, SS, Vt] = np.linalg.svd(AA)
981981
imin = np.argmin(SS)
982982
normal_vector = Vt[imin]
983-
nonzeros = np.argwhere(normal_vector != 0.0)
984-
if normal_vector[nonzeros[0, 0]] < 0.0:
983+
non_zeros = np.argwhere(normal_vector != 0.0)
984+
if normal_vector[non_zeros[0, 0]] < 0.0:
985985
normal_vector = -normal_vector
986986
dd = -np.dot(normal_vector, mean_point)
987987
coefficients = np.array([normal_vector[0], normal_vector[1], normal_vector[2], dd], np.float_)

pymatgen/analysis/ewald.py

Lines changed: 18 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -315,10 +315,10 @@ def _calc_recip(self):
315315
This method is heavily vectorized to utilize numpy's C backend for
316316
speed.
317317
"""
318-
numsites = self._s.num_sites
318+
n_sites = self._s.num_sites
319319
prefactor = 2 * pi / self._vol
320-
erecip = np.zeros((numsites, numsites), dtype=np.float_)
321-
forces = np.zeros((numsites, 3), dtype=np.float_)
320+
e_recip = np.zeros((n_sites, n_sites), dtype=np.float_)
321+
forces = np.zeros((n_sites, 3), dtype=np.float_)
322322
coords = self._coords
323323
rcp_latt = self._s.lattice.reciprocal_lattice
324324
recip_nn = rcp_latt.get_points_in_sphere([[0, 0, 0]], [0, 0, 0], self._gmax)
@@ -327,51 +327,51 @@ def _calc_recip(self):
327327

328328
gs = rcp_latt.get_cartesian_coords(frac_coords)
329329
g2s = np.sum(gs**2, 1)
330-
expvals = np.exp(-g2s / (4 * self._eta))
330+
exp_vals = np.exp(-g2s / (4 * self._eta))
331331
grs = np.sum(gs[:, None] * coords[None, :], 2)
332332

333-
oxistates = np.array(self._oxi_states)
333+
oxi_states = np.array(self._oxi_states)
334334

335335
# create array where q_2[i,j] is qi * qj
336-
qiqj = oxistates[None, :] * oxistates[:, None]
336+
qiqj = oxi_states[None, :] * oxi_states[:, None]
337337

338338
# calculate the structure factor
339-
sreals = np.sum(oxistates[None, :] * np.cos(grs), 1)
340-
simags = np.sum(oxistates[None, :] * np.sin(grs), 1)
339+
s_reals = np.sum(oxi_states[None, :] * np.cos(grs), 1)
340+
s_imags = np.sum(oxi_states[None, :] * np.sin(grs), 1)
341341

342-
for g, g2, gr, expval, sreal, simag in zip(gs, g2s, grs, expvals, sreals, simags):
342+
for g, g2, gr, expval, sreal, simag in zip(gs, g2s, grs, exp_vals, s_reals, s_imags):
343343
# Uses the identity sin(x)+cos(x) = 2**0.5 sin(x + pi/4)
344344
m = (gr[None, :] + pi / 4) - gr[:, None]
345345
np.sin(m, m)
346346
m *= expval / g2
347347

348-
erecip += m
348+
e_recip += m
349349

350350
if self._compute_forces:
351-
pref = 2 * expval / g2 * oxistates
351+
pref = 2 * expval / g2 * oxi_states
352352
factor = prefactor * pref * (sreal * np.sin(gr) - simag * np.cos(gr))
353353

354354
forces += factor[:, None] * g[None, :]
355355

356356
forces *= EwaldSummation.CONV_FACT
357-
erecip *= prefactor * EwaldSummation.CONV_FACT * qiqj * 2**0.5
358-
return erecip, forces
357+
e_recip *= prefactor * EwaldSummation.CONV_FACT * qiqj * 2**0.5
358+
return e_recip, forces
359359

360360
def _calc_real_and_point(self):
361361
"""Determines the self energy -(eta/pi)**(1/2) * sum_{i=1}^{N} q_i**2."""
362362
fcoords = self._s.frac_coords
363363
forcepf = 2 * self._sqrt_eta / sqrt(pi)
364364
coords = self._coords
365-
numsites = self._s.num_sites
366-
ereal = np.empty((numsites, numsites), dtype=np.float_)
365+
n_sites = self._s.num_sites
366+
ereal = np.empty((n_sites, n_sites), dtype=np.float_)
367367

368-
forces = np.zeros((numsites, 3), dtype=np.float_)
368+
forces = np.zeros((n_sites, 3), dtype=np.float_)
369369

370370
qs = np.array(self._oxi_states)
371371

372372
epoint = -(qs**2) * sqrt(self._eta / pi)
373373

374-
for i in range(numsites):
374+
for i in range(n_sites):
375375
nfcoords, rij, js, _ = self._s.lattice.get_points_in_sphere(
376376
fcoords, coords[i], self._rmax, zip_results=False
377377
)
@@ -389,7 +389,7 @@ def _calc_real_and_point(self):
389389
new_ereals = erfcval * qi * qj / rij
390390

391391
# insert new_ereals
392-
for key in range(numsites):
392+
for key in range(n_sites):
393393
ereal[key, i] = np.sum(new_ereals[js == key])
394394

395395
if self._compute_forces:

pymatgen/analysis/local_env.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,8 @@ def _handle_disorder(structure: Structure, on_disorder: on_disorder_options):
208208
raise ValueError(
209209
f"Generating StructureGraphs for disordered Structures is unsupported. Pass on_disorder='take "
210210
"majority' | 'take_max_species' | 'error'. 'take_majority_strict' considers only the majority species from "
211-
"each site in the bonding algorithm and raises ValueError in case there is no majority (e.g. as in {{Fe: "
212-
"0.4, O: 0.4, C: 0.2}}) whereas 'take_majority_drop' just ignores the site altogether when computing bonds "
211+
"each site in the bonding algorithm and raises ValueError in case there is no majority (e.g. as in {Fe: "
212+
"0.4, O: 0.4, C: 0.2}) whereas 'take_majority_drop' just ignores the site altogether when computing bonds "
213213
"as if it didn't exist. 'take_max_species' extracts the first max species on each site (Fe in prev. "
214214
"example since Fe and O have equal occupancy and Fe comes first). 'error' raises an error in case "
215215
f"of disordered structure. Offending {structure = }"

pymatgen/analysis/magnetism/tests/test_analyzer.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -212,10 +212,10 @@ def test_str(self):
212212
B : 0.0 0.0 -4.17
213213
C : -2.085 2.085 0.0
214214
Magmoms Sites
215-
+5.00 PeriodicSite: Ni (0.0000, 0.0000, 0.0000) [0.0000, 0.0000, 0.0000]
216-
PeriodicSite: O (0.0000, 0.0000, -2.0850) [0.0000, 0.5000, 0.0000]
217-
PeriodicSite: O (0.0000, 2.0850, 0.0000) [0.5000, 0.0000, 0.5000]
218-
-5.00 PeriodicSite: Ni (0.0000, 2.0850, -2.0850) [0.5000, 0.5000, 0.5000]"""
215+
+5.00 PeriodicSite: Ni (0.0, 0.0, 0.0) [0.0, 0.0, 0.0]
216+
PeriodicSite: O (0.0, 0.0, -2.085) [0.0, 0.5, 0.0]
217+
PeriodicSite: O (0.0, 2.085, 0.0) [0.5, 0.0, 0.5]
218+
-5.00 PeriodicSite: Ni (0.0, 2.085, -2.085) [0.5, 0.5, 0.5]"""
219219

220220
# just compare lines form 'Magmoms Sites',
221221
# since lattice param string can vary based on machine precision

0 commit comments

Comments
 (0)