Skip to content

Commit

Permalink
Fix typo in Cp2kOutput.parse_hirshfeld `add_site_property("hirshf[i…
Browse files Browse the repository at this point in the history
…->'']eld")` (#4055)

* fix typo in Cp2kOutput.parse_hirshfeld add_site_property("hirshf[i->'']eld")

* fix Polarization doc str format

* fix pwmat type hints: np.array->np.ndarray

* rename single-letter index vars

* fix doc str return type np.(''->nd)array

* define successive immutable same-value vars on one line

found with regex \w+ = (\w+)\n\s+\w+ = \1
more left
  • Loading branch information
janosh authored Sep 8, 2024
1 parent f6b4073 commit dc6a292
Show file tree
Hide file tree
Showing 54 changed files with 195 additions and 284 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -668,8 +668,7 @@ def pauling_stability_ratio(self):
if self.ce_symbol in ["S:1", "L:2"]:
self._pauling_stability_ratio = 0.0
else:
min_dist_anions = 1_000_000
min_dist_cation_anion = 1_000_000
min_dist_anions = min_dist_cation_anion = 1_000_000
for ipt1 in range(len(self.points)):
pt1 = np.array(self.points[ipt1])
min_dist_cation_anion = min(min_dist_cation_anion, np.linalg.norm(pt1 - self.central_site))
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/chemenv/utils/defs_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,7 @@ class AdditionalConditions:
ONLY_ANION_CATION_BONDS_AND_NO_ELEMENT_TO_SAME_ELEMENT_BONDS = 3
ONLY_ELEMENT_TO_OXYGEN_BONDS = 4
# Short versions
NONE = NO_ADDITIONAL_CONDITION
NO_AC = NO_ADDITIONAL_CONDITION
NONE = NO_AC = NO_ADDITIONAL_CONDITION
ONLY_ACB = ONLY_ANION_CATION_BONDS
NO_E2SEB = NO_ELEMENT_TO_SAME_ELEMENT_BONDS
ONLY_ACB_AND_NO_E2SEB = ONLY_ANION_CATION_BONDS_AND_NO_ELEMENT_TO_SAME_ELEMENT_BONDS
Expand Down
11 changes: 5 additions & 6 deletions src/pymatgen/analysis/chemenv/utils/scripts_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -358,8 +358,7 @@ def compute_environments(chemenv_configuration):
deltas = [np.zeros(3, float)]
if first_time and StructureVis is not None:
vis = StructureVis(show_polyhedron=False, show_unit_cell=True)
vis.show_help = False
first_time = False
vis.show_help = first_time = False
else:
vis = None # TODO: following code logic seems buggy

Expand All @@ -375,17 +374,17 @@ def compute_environments(chemenv_configuration):
ce = strategy.get_site_coordination_environment(site)
if ce is not None and ce[0] != UNCLEAR_ENVIRONMENT_SYMBOL:
for delta in deltas:
psite = PeriodicSite(
p_site = PeriodicSite(
site.species,
site.frac_coords + delta,
site.lattice,
properties=site.properties,
)
vis.add_site(psite)
neighbors = strategy.get_site_neighbors(psite)
vis.add_site(p_site)
neighbors = strategy.get_site_neighbors(p_site)
draw_cg(
vis,
psite,
p_site,
neighbors,
cg=lgf.allcg.get_geometry_from_mp_symbol(ce[0]),
perm=ce[1]["permutation"],
Expand Down
6 changes: 2 additions & 4 deletions src/pymatgen/analysis/chempot_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -670,11 +670,9 @@ def get_centroid_2d(vertices: np.ndarray) -> np.ndarray:
circumferentially
Returns:
np.array: Giving 2-d centroid coordinates.
np.ndarray: Giving 2-d centroid coordinates.
"""
cx = 0
cy = 0
a = 0
cx = cy = a = 0

for idx in range(len(vertices) - 1):
xi = vertices[idx, 0]
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/diffraction/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,8 @@ 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=True)):
self.get_plot(structure, fontsize=fontsize, ax=ax, with_labels=i == n_rows - 1, **kwargs)
for idx, (ax, structure) in enumerate(zip(axes.ravel(), structures, strict=True)):
self.get_plot(structure, fontsize=fontsize, ax=ax, with_labels=idx == n_rows - 1, **kwargs)
spg_symbol, spg_number = structure.get_space_group_info()
ax.set_title(f"{structure.formula} {spg_symbol} ({spg_number}) ")

Expand All @@ -207,7 +207,7 @@ def get_unique_families(hkls):
{hkl: multiplicity}: A dict with unique hkl and multiplicity.
"""

# TODO: Definitely can be sped up.
# TODO can definitely be sped up
def is_perm(hkl1, hkl2) -> bool:
h1 = np.abs(hkl1)
h2 = np.abs(hkl2)
Expand Down
21 changes: 11 additions & 10 deletions src/pymatgen/analysis/ferroelectricity/polarization.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ def __init__(
self, p_elecs, p_ions, structures: Sequence[Structure], p_elecs_in_cartesian=True, p_ions_in_cartesian=False
):
"""
p_elecs: np.array of electronic contribution to the polarization with shape [N, 3]
p_ions: np.array of ionic contribution to the polarization with shape [N, 3]
p_elecs (np.ndarray): electronic contribution to the polarization with shape [N, 3]
p_ions (np.ndarray): ionic contribution to the polarization with shape [N, 3]
p_elecs_in_cartesian: whether p_elecs is along Cartesian directions (rather than lattice directions).
Default is True because that is the convention for VASP.
p_ions_in_cartesian: whether p_ions is along Cartesian directions (rather than lattice directions).
Expand All @@ -158,13 +158,14 @@ def __init__(
if len(p_elecs) != len(p_ions) or len(p_elecs) != len(structures):
raise ValueError("The number of electronic polarization and ionic polarization values must be equal.")
if p_elecs_in_cartesian:
p_elecs = np.array(
[struct.lattice.get_vector_along_lattice_directions(p_elecs[i]) for i, struct in enumerate(structures)]
)
p_elecs = [
struct.lattice.get_vector_along_lattice_directions(p_elecs[idx])
for idx, struct in enumerate(structures)
]
if p_ions_in_cartesian:
p_ions = np.array(
[struct.lattice.get_vector_along_lattice_directions(p_ions[i]) for i, struct in enumerate(structures)]
)
p_ions = [
struct.lattice.get_vector_along_lattice_directions(p_ions[idx]) for idx, struct in enumerate(structures)
]
self.p_elecs = np.array(p_elecs)
self.p_ions = np.array(p_ions)
self.structures = structures
Expand Down Expand Up @@ -392,9 +393,9 @@ def max_spline_jumps(self, convert_to_muC_per_cm2=True, all_in_polar=True):
)
sps = self.same_branch_splines(convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar)
max_jumps = [None, None, None]
for i, sp in enumerate(sps):
for idx, sp in enumerate(sps):
if sp is not None:
max_jumps[i] = max(tot[:, i].ravel() - sp(range(len(tot[:, i].ravel()))))
max_jumps[idx] = max(tot[:, idx].ravel() - sp(range(len(tot[:, idx].ravel()))))
return max_jumps

def smoothness(self, convert_to_muC_per_cm2=True, all_in_polar=True):
Expand Down
3 changes: 1 addition & 2 deletions src/pymatgen/analysis/hhi.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ def get_hhi(self, comp_or_form):
if not isinstance(comp_or_form, Composition):
comp_or_form = Composition(comp_or_form)

hhi_p = 0
hhi_r = 0
hhi_p = hhi_r = 0

for e in comp_or_form.elements:
percent = comp_or_form.get_wt_fraction(e)
Expand Down
21 changes: 10 additions & 11 deletions src/pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -1770,27 +1770,27 @@ def get_nn_info(self, structure: Structure, n: int):
except Exception:
eln = site.species_string

reldists_neighs = []
rel_dists_neighs = []
for nn in neighs_dists:
neigh = nn
dist = nn.nn_distance
try:
el2 = neigh.specie.element
except Exception:
el2 = neigh.species_string
reldists_neighs.append([dist / get_okeeffe_distance_prediction(eln, el2), neigh])
rel_dists_neighs.append([dist / get_okeeffe_distance_prediction(eln, el2), neigh])

siw = []
min_reldist = min(reldist for reldist, neigh in reldists_neighs)
for reldist, s in reldists_neighs:
if reldist < (1 + self.tol) * min_reldist:
w = min_reldist / reldist
min_rel_dist = min(reldist for reldist, neigh in rel_dists_neighs)
for rel_dist, site in rel_dists_neighs:
if rel_dist < (1 + self.tol) * min_rel_dist:
w = min_rel_dist / rel_dist
siw.append(
{
"site": s,
"image": self._get_image(structure, s),
"site": site,
"image": self._get_image(structure, site),
"weight": w,
"site_index": self._get_original_site(structure, s),
"site_index": self._get_original_site(structure, site),
}
)

Expand Down Expand Up @@ -2967,8 +2967,7 @@ def get_order_parameters(
twothird = 2 / 3.0
for j in range(n_neighbors): # Neighbor j is put to the North pole.
zaxis = rij_norm[j]
kc = 0
idx = 0
kc = idx = 0
for k in range(n_neighbors): # From neighbor k, we construct
if j != k: # the prime meridian.
for idx in range(len(self._types)):
Expand Down
8 changes: 2 additions & 6 deletions src/pymatgen/analysis/magnetism/heisenberg.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,10 +394,7 @@ def get_low_energy_orderings(self):
fm_struct, afm_struct = None, None
mag_min = np.inf
mag_max = 0.001
fm_e = 0
afm_e = 0
fm_e_min = 0
afm_e_min = 0
fm_e = afm_e = fm_e_min = afm_e_min = 0

# epas = [e / len(s) for (e, s) in zip(self.energies, self.ordered_structures)]

Expand Down Expand Up @@ -589,8 +586,7 @@ def _get_j_exc(self, i, j, dist):
float: Exchange parameter J_exc in meV
"""
# Get unique site identifiers
i_index = 0
j_index = 0
i_index = j_index = 0
for k, v in self.unique_site_ids.items():
if i in k:
i_index = v
Expand Down
13 changes: 6 additions & 7 deletions src/pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -1673,7 +1673,7 @@ def as_dict(self) -> dict[str, Any]:
to a dictionary.
NOTE unlike PhaseDiagram the computation involved in constructing the
PatchedPhaseDiagram is not saved on serialisation. This is done because
PatchedPhaseDiagram is not saved on serialization. This is done because
hierarchically calling the `PhaseDiagram.as_dict()` method would break the
link in memory between entries in overlapping patches leading to a
ballooning of the amount of memory used.
Expand All @@ -1694,10 +1694,10 @@ def as_dict(self) -> dict[str, Any]:

@classmethod
def from_dict(cls, dct: dict) -> Self:
"""Reconstruct PatchedPhaseDiagram from dictionary serialisation.
"""Reconstruct PatchedPhaseDiagram from dictionary serialization.
NOTE unlike PhaseDiagram the computation involved in constructing the
PatchedPhaseDiagram is not saved on serialisation. This is done because
PatchedPhaseDiagram is not saved on serialization. This is done because
hierarchically calling the `PhaseDiagram.as_dict()` method would break the
link in memory between entries in overlapping patches leading to a
ballooning of the amount of memory used.
Expand Down Expand Up @@ -1725,8 +1725,8 @@ def remove_redundant_spaces(spaces, keep_all_spaces=False):
sorted_spaces = sorted(spaces, key=len, reverse=True)

result = []
for i, space_i in enumerate(sorted_spaces):
if not any(space_i.issubset(larger_space) for larger_space in sorted_spaces[:i]):
for idx, space_i in enumerate(sorted_spaces):
if not any(space_i.issubset(larger_space) for larger_space in sorted_spaces[:idx]):
result.append(space_i)

return result
Expand Down Expand Up @@ -2408,8 +2408,7 @@ class (pymatgen.analysis.chempot_diagram).

for entry, lines in chempot_ranges.items():
comp = entry.composition
center_x = 0
center_y = 0
center_x = center_y = 0
coords = []
contain_zero = any(comp.get_atomic_fraction(el) == 0 for el in elements)
is_boundary = (not contain_zero) and sum(comp.get_atomic_fraction(el) for el in elements) == 1
Expand Down
18 changes: 7 additions & 11 deletions src/pymatgen/analysis/piezo_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -360,8 +360,7 @@ def get_unstable_FCM(self, max_force=1):
n_sites = len(struct)
D = (1 / max_force) * 2 * (np.ones([n_sites * 3, n_sites * 3]))
for op in operations:
same = 0
transpose = 0
same = transpose = 0
if op[0] == op[1] and op[0] == op[2] and op[0] == op[3]:
same = 1
if op[0] == op[3] and op[1] == op[2]:
Expand Down Expand Up @@ -413,8 +412,7 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1):
"""
operations = self.FCM_operations
for op in operations:
same = 0
transpose = 0
same = transpose = 0
if op[0] == op[1] and op[0] == operations[2] and op[0] == op[3]:
same = 1
if op[0] == op[3] and op[1] == op[2]:
Expand All @@ -423,10 +421,10 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1):
unsymmetrized_fcm[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] = np.zeros([3, 3])

for symop in op[4]:
tempfcm = unsymmetrized_fcm[3 * op[2] : 3 * op[2] + 3, 3 * op[3] : 3 * op[3] + 3]
tempfcm = symop.transform_tensor(tempfcm)
temp_fcm = unsymmetrized_fcm[3 * op[2] : 3 * op[2] + 3, 3 * op[3] : 3 * op[3] + 3]
temp_fcm = symop.transform_tensor(temp_fcm)

unsymmetrized_fcm[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] += tempfcm
unsymmetrized_fcm[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] += temp_fcm

if len(op[4]) != 0:
unsymmetrized_fcm[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] /= len(op[4])
Expand Down Expand Up @@ -468,8 +466,7 @@ def get_stable_FCM(self, fcm, fcmasum=10):
Returns:
3Nx3N numpy array representing the force constant matrix
"""
check = 0
count = 0
check = count = 0
while check == 0:
# if re-symmetrizing brings back unstable modes 20 times, the method breaks
if count > 20:
Expand Down Expand Up @@ -535,8 +532,7 @@ def get_asum_FCM(self, fcm: np.ndarray, numiter: int = 15):

total /= n_sites
for op in operations:
same = 0
transpose = 0
same = transpose = 0
if op[0] == op[1] and op[0] == op[2] and op[0] == op[3]:
same = 1
if op[0] == op[3] and op[1] == op[2]:
Expand Down
4 changes: 1 addition & 3 deletions src/pymatgen/analysis/quasirrho.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,9 +226,7 @@ def _get_quasirrho_thermo(
er = 3 * ideal_gas_const * self.temp / 2

# Vibrational component of Entropy and Energy
ev = 0
sv_quasiRRHO = 0
sv = 0
ev = sv_quasiRRHO = sv = 0

for vt in vib_temps:
ev += vt * (1 / 2 + 1 / (np.exp(vt / self.temp) - 1))
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/solar/slme.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def to_matrix(xx, yy, zz, xy, yz, xz):
xz (float): xz component of the matrix.
Returns:
np.array: The matrix, as a 3x3 numpy array.
np.ndarray: The matrix, as a 3x3 numpy array.
"""
return np.array([[xx, xy, xz], [xy, yy, yz], [xz, yz, zz]])

Expand All @@ -79,7 +79,7 @@ def parse_dielectric_data(data):
a list of ``[xx, yy, zz, xy , xz, yz ]`` dielectric tensor elements.
Returns:
np.array: a Nx3 numpy array. Each row contains the eigenvalues
np.ndarray: a Nx3 numpy array. Each row contains the eigenvalues
for the corresponding row in `data`.
"""
return np.array([np.linalg.eig(to_matrix(*eps))[0] for eps in data])
Expand All @@ -98,7 +98,7 @@ def absorption_coefficient(dielectric):
- element 2: imaginary dielectric tensors, in ``[xx, yy, zz, xy, xz, yz]`` format.
Returns:
np.array: absorption coefficient using eV as frequency units (cm^-1).
np.ndarray: absorption coefficient using eV as frequency units (cm^-1).
"""
energies_in_eV = np.array(dielectric[0])
real_dielectric = parse_dielectric_data(dielectric[1])
Expand Down
4 changes: 1 addition & 3 deletions src/pymatgen/analysis/structure_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,9 +457,7 @@ def parse_oxide(self) -> tuple[str, int]:
return "hydroxide", int(len(np.where(dist_matrix < relative_cutoff * 0.93)[0]) / 2)
dist_matrix = lattice.get_all_distances(o_sites_frac_coords, o_sites_frac_coords)
np.fill_diagonal(dist_matrix, 1000)
is_superoxide = False
is_peroxide = False
is_ozonide = False
is_superoxide = is_peroxide = is_ozonide = False
bond_atoms = []
if np.any(dist_matrix < relative_cutoff * 1.35):
bond_atoms = np.where(dist_matrix < relative_cutoff * 1.35)[0]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,7 @@ def predict(self, structure: Structure, ref_structure):
):
raise ValueError("Not all the ionic radii are available!")

numerator = 0
denominator = 0
numerator = denominator = 0
# Here, the 1/3 factor on the composition accounts for atomic
# packing. We want the number per unit length.
for k, v in comp.items():
Expand All @@ -102,8 +101,7 @@ def predict(self, structure: Structure, ref_structure):
ref_comp = ref_structure.composition
# Here, the 1/3 factor on the composition accounts for atomic
# packing. We want the number per unit length.
numerator = 0
denominator = 0
numerator = denominator = 0
for k, v in comp.items():
numerator += k.atomic_radius * v ** (1 / 3)
for k, v in ref_comp.items():
Expand Down
Loading

0 comments on commit dc6a292

Please sign in to comment.