Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use strict=True with zip to ensure length equality #4011

Merged
merged 7 commits into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ def gen_iupac_ordering():

order = sum((list(product(x, y)) for x, y in order), []) # noqa: RUF017
iupac_ordering_dict = dict(
zip([Element.from_row_and_group(row, group) for group, row in order], range(len(order)), strict=False)
zip([Element.from_row_and_group(row, group) for group, row in order], range(len(order)), strict=True)
)

# first clean periodic table of any IUPAC ordering
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/adsorption.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def find_surface_sites_by_height(self, slab: Slab, height=0.9, xy_tol=0.05):
surf_sites = [slab.sites[n] for n in np.where(mask)[0]]
if xy_tol:
# sort surface sites by height
surf_sites = [s for (h, s) in zip(m_projs[mask], surf_sites, strict=False)]
surf_sites = [s for (h, s) in zip(m_projs[mask], surf_sites, strict=True)]
surf_sites.reverse()
unique_sites: list = []
unique_perp_fracs: list = []
Expand Down Expand Up @@ -268,7 +268,7 @@ def find_adsorption_sites(
for v in dt.simplices:
if -1 not in v:
dots = []
for i_corner, i_opp in zip(range(3), ((1, 2), (0, 2), (0, 1)), strict=False):
for i_corner, i_opp in zip(range(3), ((1, 2), (0, 2), (0, 1)), strict=True):
corner, opp = v[i_corner], [v[o] for o in i_opp]
vecs = [mesh[d].coords - mesh[corner].coords for d in opp]
vecs = [vec / np.linalg.norm(vec) for vec in vecs]
Expand Down Expand Up @@ -701,7 +701,7 @@ def plot_slab(
ads_sites = asf.find_adsorption_sites()["all"]
symm_op = get_rot(orig_slab)
ads_sites = [symm_op.operate(ads_site)[:2].tolist() for ads_site in ads_sites]
ax.plot(*zip(*ads_sites, strict=False), color="k", marker="x", markersize=10, mew=1, linestyle="", zorder=10000)
ax.plot(*zip(*ads_sites, strict=True), color="k", marker="x", markersize=10, mew=1, linestyle="", zorder=10000)
# Draw unit cell
if draw_unit_cell:
vertices = np.insert(vertices, 1, lattice_sum, axis=0).tolist()
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,7 @@ def _recurse(assigned=None):
if self._best_vset:
if structure.is_ordered:
assigned = {}
for val, sites in zip(self._best_vset, equi_sites, strict=False):
for val, sites in zip(self._best_vset, equi_sites, strict=True):
for site in sites:
assigned[site] = val

Expand All @@ -414,7 +414,7 @@ def _recurse(assigned=None):
new_best_vset.append([])
for ival, val in enumerate(self._best_vset):
new_best_vset[attrib[ival]].append(val)
for val, sites in zip(new_best_vset, equi_sites, strict=False):
for val, sites in zip(new_best_vset, equi_sites, strict=True):
for site in sites:
assigned[site] = val

Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/chempot_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ def _get_domains(self) -> dict[str, np.ndarray]:

domains: dict[str, list] = {entry.reduced_formula: [] for entry in entries}

for intersection, facet in zip(hs_int.intersections, hs_int.dual_facets, strict=False):
for intersection, facet in zip(hs_int.intersections, hs_int.dual_facets, strict=True):
for v in facet:
if v < len(entries):
this_entry = entries[v]
Expand Down Expand Up @@ -578,7 +578,7 @@ def get_chempot_axis_title(element) -> str:
return f"<br> μ<sub>{element}</sub> - μ<sub>{element}</sub><sup>o</sup> (eV)"

axes_layout = {}
for ax, el in zip(axes, elements, strict=False):
for ax, el in zip(axes, elements, strict=True):
layout = plotly_layouts[layout_name].copy()
layout["title"] = get_chempot_axis_title(el)
axes_layout[ax] = layout
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/diffraction/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def get_plot(
xrd = self.get_pattern(structure, two_theta_range=two_theta_range)
imax = max(xrd.y)

for two_theta, i, hkls in zip(xrd.x, xrd.y, xrd.hkls, strict=False):
for two_theta, i, hkls in zip(xrd.x, xrd.y, xrd.hkls, strict=True):
if two_theta_range[0] <= two_theta <= two_theta_range[1]:
hkl_tuples = [hkl["hkl"] for hkl in hkls]
label = ", ".join(map(str, hkl_tuples)) # 'full' label
Expand Down Expand Up @@ -188,7 +188,7 @@ def plot_structures(self, structures, fontsize=6, **kwargs):
n_rows = len(structures)
fig, axes = plt.subplots(nrows=n_rows, ncols=1, sharex=True, squeeze=False)

for i, (ax, structure) in enumerate(zip(axes.ravel(), structures, strict=False)):
for i, (ax, structure) in enumerate(zip(axes.ravel(), structures, strict=True)):
self.get_plot(structure, fontsize=fontsize, ax=ax, with_labels=i == n_rows - 1, **kwargs)
spg_symbol, spg_number = structure.get_space_group_info()
ax.set_title(f"{structure.formula} {spg_symbol} ({spg_number}) ")
Expand Down
8 changes: 4 additions & 4 deletions src/pymatgen/analysis/diffraction/tem.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ def get_interplanar_spacings(
if (0, 0, 0) in points_filtered:
points_filtered.remove((0, 0, 0))
interplanar_spacings_val = np.array([structure.lattice.d_hkl(x) for x in points_filtered])
return dict(zip(points_filtered, interplanar_spacings_val, strict=False))
return dict(zip(points_filtered, interplanar_spacings_val, strict=True))

def bragg_angles(self, interplanar_spacings: dict[Tuple3Ints, float]) -> dict[Tuple3Ints, float]:
"""Get the Bragg angles for every hkl point passed in (where n = 1).
Expand All @@ -153,7 +153,7 @@ def bragg_angles(self, interplanar_spacings: dict[Tuple3Ints, float]) -> dict[Tu
plane = list(interplanar_spacings)
interplanar_spacings_val = np.array(list(interplanar_spacings.values()))
bragg_angles_val = np.arcsin(self.wavelength_rel() / (2 * interplanar_spacings_val))
return dict(zip(plane, bragg_angles_val, strict=False))
return dict(zip(plane, bragg_angles_val, strict=True))

def get_s2(self, bragg_angles: dict[Tuple3Ints, float]) -> dict[Tuple3Ints, float]:
"""
Expand All @@ -169,7 +169,7 @@ def get_s2(self, bragg_angles: dict[Tuple3Ints, float]) -> dict[Tuple3Ints, floa
plane = list(bragg_angles)
bragg_angles_val = np.array(list(bragg_angles.values()))
s2_val = (np.sin(bragg_angles_val) / self.wavelength_rel()) ** 2
return dict(zip(plane, s2_val, strict=False))
return dict(zip(plane, s2_val, strict=True))

def x_ray_factors(
self, structure: Structure, bragg_angles: dict[Tuple3Ints, float]
Expand Down Expand Up @@ -269,7 +269,7 @@ def cell_intensity(self, structure: Structure, bragg_angles: dict[Tuple3Ints, fl
csf = self.cell_scattering_factors(structure, bragg_angles)
csf_val = np.array(list(csf.values()))
cell_intensity_val = (csf_val * csf_val.conjugate()).real
return dict(zip(bragg_angles, cell_intensity_val, strict=False))
return dict(zip(bragg_angles, cell_intensity_val, strict=True))

def get_pattern(
self,
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/elasticity/elastic.py
Original file line number Diff line number Diff line change
Expand Up @@ -619,7 +619,7 @@ def get_tgt(self, temperature: float | None = None, structure: Structure = None,
points = quad["points"]
weights = quad["weights"]
num, denom, c = np.zeros((3, 3)), 0, 1
for p, w in zip(points, weights, strict=False):
for p, w in zip(points, weights, strict=True):
gk = ElasticTensor(self[0]).green_kristoffel(p)
_rho_wsquareds, us = np.linalg.eigh(gk)
us = [u / np.linalg.norm(u) for u in np.transpose(us)]
Expand Down Expand Up @@ -882,7 +882,7 @@ def diff_fit(strains, stresses, eq_stress=None, order=2, tol: float = 1e-10):
for _ord in range(1, order):
cvec, carr = get_symbol_list(_ord + 1)
svec = np.ravel(dei_dsi[_ord - 1].T)
cmap = dict(zip(cvec, np.dot(m[_ord - 1], svec), strict=False))
cmap = dict(zip(cvec, np.dot(m[_ord - 1], svec), strict=True))
c_list.append(v_subs(carr, cmap))
return [Tensor.from_voigt(c) for c in c_list]

Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/elasticity/strain.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def get_perturbed_indices(self, tol: float = 1e-8):
"""Get indices of perturbed elements of the deformation gradient,
i. e. those that differ from the identity.
"""
return list(zip(*np.where(abs(self - np.eye(3)) > tol), strict=False))
return list(zip(*np.where(abs(self - np.eye(3)) > tol), strict=True))

@property
def green_lagrange_strain(self):
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/eos.py
Original file line number Diff line number Diff line change
Expand Up @@ -431,7 +431,7 @@ def get_rms(x, y):
return np.sqrt(np.sum((np.array(x) - np.array(y)) ** 2) / len(x))

# list of (energy, volume) tuples
e_v = list(zip(self.energies, self.volumes, strict=False))
e_v = list(zip(self.energies, self.volumes, strict=True))
n_data = len(e_v)
# minimum number of data points used for fitting
n_data_min = max(n_data - 2 * min_ndata_factor, min_poly_order + 1)
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/ewald.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ def _calc_recip(self):
s_reals = np.sum(oxi_states[None, :] * np.cos(grs), 1)
s_imags = np.sum(oxi_states[None, :] * np.sin(grs), 1)

for g, g2, gr, exp_val, s_real, s_imag in zip(gs, g2s, grs, exp_vals, s_reals, s_imags, strict=False):
for g, g2, gr, exp_val, s_real, s_imag in zip(gs, g2s, grs, exp_vals, s_reals, s_imags, strict=True):
# Uses the identity sin(x)+cos(x) = 2**0.5 sin(x + pi/4)
m = np.sin((gr[None, :] + math.pi / 4) - gr[:, None])
m *= exp_val / g2
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/ferroelectricity/polarization.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,7 @@ def get_same_branch_polarization_data(self, convert_to_muC_per_cm2=True, all_in_
sites.append(new_site[0])

adjust_pol = []
for site, struct in zip(sites, d_structs, strict=False):
for site, struct in zip(sites, d_structs, strict=True):
adjust_pol.append(np.multiply(site.frac_coords, np.array(struct.lattice.lengths)).ravel())
return np.array(adjust_pol)

Expand Down
12 changes: 6 additions & 6 deletions src/pymatgen/analysis/interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ def get_kinks(self) -> list[tuple[int, float, float, Reaction, float]]:

index_kink = range(1, len(critical_comp) + 1)

return list(zip(index_kink, x_kink, energy_kink, react_kink, energy_per_rxt_formula, strict=False))
return list(zip(index_kink, x_kink, energy_kink, react_kink, energy_per_rxt_formula, strict=True))

def plot(self, backend: Literal["plotly", "matplotlib"] = "plotly") -> Figure | plt.Figure:
"""
Expand Down Expand Up @@ -326,7 +326,7 @@ def _get_elem_amt_in_rxn(self, rxn: Reaction) -> float:

def _get_plotly_figure(self) -> Figure:
"""Get a Plotly figure of reaction kinks diagram."""
kinks = map(list, zip(*self.get_kinks(), strict=False))
kinks = map(list, zip(*self.get_kinks(), strict=True))
_, x, energy, reactions, _ = kinks

lines = Scatter(
Expand All @@ -348,7 +348,7 @@ def _get_plotly_figure(self) -> Figure:

labels = [
f"{htmlify(str(r))} <br>\u0394E<sub>rxn</sub> = {round(e, 3)} eV/atom"
for r, e in zip(reactions, energy, strict=False)
for r, e in zip(reactions, energy, strict=True)
]

markers = Scatter(
Expand Down Expand Up @@ -392,13 +392,13 @@ def _get_matplotlib_figure(self) -> plt.Figure:
ax = pretty_plot(8, 5)
plt.xlim([-0.05, 1.05]) # plot boundary is 5% wider on each side

kinks = list(zip(*self.get_kinks(), strict=False))
kinks = list(zip(*self.get_kinks(), strict=True))
_, x, energy, reactions, _ = kinks

plt.plot(x, energy, "o-", markersize=8, c="navy", zorder=1)
plt.scatter(self.minimum[0], self.minimum[1], marker="*", c="red", s=400, zorder=2)

for x_coord, y_coord, rxn in zip(x, energy, reactions, strict=False):
for x_coord, y_coord, rxn in zip(x, energy, reactions, strict=True):
products = ", ".join(
[latexify(p.reduced_formula) for p in rxn.products if not np.isclose(rxn.get_coeff(p), 0)]
)
Expand Down Expand Up @@ -438,7 +438,7 @@ def _get_xaxis_title(self, latex: bool = True) -> str:
def _get_plotly_annotations(x: list[float], y: list[float], reactions: list[Reaction]):
"""Get dictionary of annotations for the Plotly figure layout."""
annotations = []
for x_coord, y_coord, rxn in zip(x, y, reactions, strict=False):
for x_coord, y_coord, rxn in zip(x, y, reactions, strict=True):
products = ", ".join(
[htmlify(p.reduced_formula) for p in rxn.products if not np.isclose(rxn.get_coeff(p), 0)]
)
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/interfaces/coherent_interfaces.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ def _find_terminations(self):
self._terminations = {
(film_label, sub_label): (film_shift, sub_shift)
for (film_label, film_shift), (sub_label, sub_shift) in product(
zip(film_terminations, film_shifts, strict=False), zip(sub_terminations, sub_shifts, strict=False)
zip(film_terminations, film_shifts, strict=True), zip(sub_terminations, sub_shifts, strict=True)
)
}
self.terminations = list(self._terminations)
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/interfaces/zsl.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ def get_equiv_transformations(self, transformation_sets, film_vectors, substrate
for (f_trans, s_trans), (f, s) in zip(
product(film_transformations, substrate_transformations),
product(films, substrates),
strict=False,
strict=True,
):
if is_same_vectors(
f,
Expand Down
34 changes: 15 additions & 19 deletions src/pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,13 +83,13 @@ def __init__(self, structure: Structure) -> None:
def radii(self):
"""List of ionic radii of elements in the order of sites."""
elems = [site.species_string for site in self._structure]
return dict(zip(elems, self._ionic_radii, strict=False))
return dict(zip(elems, self._ionic_radii, strict=True))

@property
def valences(self):
"""List of oxidation states of elements in the order of sites."""
el = [site.species_string for site in self._structure]
return dict(zip(el, self._valences, strict=False))
return dict(zip(el, self._valences, strict=True))

@property
def structure(self):
Expand Down Expand Up @@ -522,7 +522,7 @@ def _get_nn_shell_info(
# And, different first steps might results in the same neighbor
# Now, we condense those neighbors into a single entry per neighbor
all_sites = {}
for first_site, term_sites in zip(allowed_steps, terminal_neighbors, strict=False):
for first_site, term_sites in zip(allowed_steps, terminal_neighbors, strict=True):
for term_site in term_sites:
key = (term_site["site_index"], tuple(term_site["image"]))

Expand Down Expand Up @@ -2398,12 +2398,8 @@ def compute_trigonometric_terms(self, thetas, phis):
self._cos_n_p[1] = [math.cos(float(p)) for p in phis]

for idx in range(2, self._max_trig_order + 1):
self._pow_sin_t[idx] = [
e[0] * e[1] for e in zip(self._pow_sin_t[idx - 1], self._pow_sin_t[1], strict=False)
]
self._pow_cos_t[idx] = [
e[0] * e[1] for e in zip(self._pow_cos_t[idx - 1], self._pow_cos_t[1], strict=False)
]
self._pow_sin_t[idx] = [e[0] * e[1] for e in zip(self._pow_sin_t[idx - 1], self._pow_sin_t[1], strict=True)]
self._pow_cos_t[idx] = [e[0] * e[1] for e in zip(self._pow_cos_t[idx - 1], self._pow_cos_t[1], strict=True)]
self._sin_n_p[idx] = [math.sin(float(idx) * float(p)) for p in phis]
self._cos_n_p[idx] = [math.cos(float(idx) * float(p)) for p in phis]

Expand Down Expand Up @@ -2433,7 +2429,7 @@ def get_q2(self, thetas=None, phis=None):

pre_y_2_2 = [0.25 * sqrt_15_2pi * val for val in self._pow_sin_t[2]]
pre_y_2_1 = [
0.5 * sqrt_15_2pi * val[0] * val[1] for val in zip(self._pow_sin_t[1], self._pow_cos_t[1], strict=False)
0.5 * sqrt_15_2pi * val[0] * val[1] for val in zip(self._pow_sin_t[1], self._pow_cos_t[1], strict=True)
]

acc = 0.0
Expand Down Expand Up @@ -2506,15 +2502,15 @@ def get_q4(self, thetas=None, phis=None):

pre_y_4_4 = [i16_3 * sqrt_35_2pi * val for val in self._pow_sin_t[4]]
pre_y_4_3 = [
i8_3 * sqrt_35_pi * val[0] * val[1] for val in zip(self._pow_sin_t[3], self._pow_cos_t[1], strict=False)
i8_3 * sqrt_35_pi * val[0] * val[1] for val in zip(self._pow_sin_t[3], self._pow_cos_t[1], strict=True)
]
pre_y_4_2 = [
i8_3 * sqrt_5_2pi * val[0] * (7 * val[1] - 1.0)
for val in zip(self._pow_sin_t[2], self._pow_cos_t[2], strict=False)
for val in zip(self._pow_sin_t[2], self._pow_cos_t[2], strict=True)
]
pre_y_4_1 = [
i8_3 * sqrt_5_pi * val[0] * (7 * val[1] - 3 * val[2])
for val in zip(self._pow_sin_t[1], self._pow_cos_t[3], self._pow_cos_t[1], strict=False)
for val in zip(self._pow_sin_t[1], self._pow_cos_t[3], self._pow_cos_t[1], strict=True)
]

acc = 0.0
Expand Down Expand Up @@ -2618,19 +2614,19 @@ def get_q6(self, thetas=None, phis=None):

pre_y_6_6 = [i64 * sqrt_3003_pi * val for val in self._pow_sin_t[6]]
pre_y_6_5 = [
i32_3 * sqrt_1001_pi * val[0] * val[1] for val in zip(self._pow_sin_t[5], self._pow_cos_t[1], strict=False)
i32_3 * sqrt_1001_pi * val[0] * val[1] for val in zip(self._pow_sin_t[5], self._pow_cos_t[1], strict=True)
]
pre_y_6_4 = [
i32_3 * sqrt_91_2pi * val[0] * (11 * val[1] - 1.0)
for val in zip(self._pow_sin_t[4], self._pow_cos_t[2], strict=False)
for val in zip(self._pow_sin_t[4], self._pow_cos_t[2], strict=True)
]
pre_y_6_3 = [
i32 * sqrt_1365_pi * val[0] * (11 * val[1] - 3 * val[2])
for val in zip(self._pow_sin_t[3], self._pow_cos_t[3], self._pow_cos_t[1], strict=False)
for val in zip(self._pow_sin_t[3], self._pow_cos_t[3], self._pow_cos_t[1], strict=True)
]
pre_y_6_2 = [
i64 * sqrt_1365_pi * val[0] * (33 * val[1] - 18 * val[2] + 1.0)
for val in zip(self._pow_sin_t[2], self._pow_cos_t[4], self._pow_cos_t[2], strict=False)
for val in zip(self._pow_sin_t[2], self._pow_cos_t[4], self._pow_cos_t[2], strict=True)
]
pre_y_6_1 = [
i16 * sqrt_273_2pi * val[0] * (33 * val[1] - 30 * val[2] + 5 * val[3])
Expand All @@ -2639,7 +2635,7 @@ def get_q6(self, thetas=None, phis=None):
self._pow_cos_t[5],
self._pow_cos_t[3],
self._pow_cos_t[1],
strict=False,
strict=True,
)
]

Expand Down Expand Up @@ -3694,7 +3690,7 @@ def get_nn_info(self, structure: Structure, n: int):
mefir = _get_mean_fictive_ionic_radius(firs, minimum_fir=mefir)

siw = []
for nn, fir in zip(neighbors, firs, strict=False):
for nn, fir in zip(neighbors, firs, strict=True):
if nn.nn_distance < self.cutoff:
w = math.exp(1 - (fir / mefir) ** 6)
if w > self.tol:
Expand Down
Loading
Loading