Skip to content

Commit

Permalink
rename variables for readability
Browse files Browse the repository at this point in the history
  • Loading branch information
janosh committed Mar 30, 2024
1 parent 80166ed commit 0c20f19
Show file tree
Hide file tree
Showing 12 changed files with 131 additions and 133 deletions.
2 changes: 1 addition & 1 deletion pymatgen/analysis/chempot_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ def get_centroid_2d(vertices: np.ndarray) -> np.ndarray:
polygon. Useful for calculating the location of an annotation on a chemical
potential domain within a 3D chemical potential diagram.
**NOTE**: vertices must be ordered circumferentially!
NOTE vertices must be ordered circumferentially!
Args:
vertices: array of 2-d coordinates corresponding to a polygon, ordered
Expand Down
20 changes: 10 additions & 10 deletions pymatgen/analysis/eos.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,16 +467,16 @@ def get_rms(x, y):
# loop over the data points.
while (n_data_fit >= n_data_min) and (e_min in e_v_work):
max_poly_order = n_data_fit - max_poly_order_factor
e = [ei[0] for ei in e_v_work]
v = [ei[1] for ei in e_v_work]
energies = [ei[0] for ei in e_v_work]
volumes = [ei[1] for ei in e_v_work]
# loop over polynomial order
for idx in range(min_poly_order, max_poly_order + 1):
coeffs = np.polyfit(v, e, idx)
pder = np.polyder(coeffs)
a = np.poly1d(pder)(v_before)
b = np.poly1d(pder)(v_after)
coeffs = np.polyfit(volumes, energies, idx)
polyder = np.polyder(coeffs)
a = np.poly1d(polyder)(v_before)
b = np.poly1d(polyder)(v_after)
if a * b < 0:
rms = get_rms(e, np.poly1d(coeffs)(v))
rms = get_rms(energies, np.poly1d(coeffs)(volumes))
rms_min = min(rms_min, rms * idx / n_data_fit)
all_coeffs[(idx, n_data_fit)] = [coeffs.tolist(), rms]
# store the fit coefficients small to large,
Expand All @@ -495,12 +495,12 @@ def get_rms(x, y):
weighted_avg_coeffs = np.zeros((fit_poly_order,))

# combine all the filtered polynomial candidates to get the final fit.
for k, v in all_coeffs.items():
for key, val in all_coeffs.items():
# weighted rms = rms * polynomial order / rms_min / ndata_fit
weighted_rms = v[1] * k[0] / rms_min / k[1]
weighted_rms = val[1] * key[0] / rms_min / key[1]
weight = np.exp(-(weighted_rms**2))
norm += weight
coeffs = np.array(v[0])
coeffs = np.array(val[0])
# pad the coefficient array with zeros
coeffs = np.lib.pad(coeffs, (0, max(fit_poly_order - len(coeffs), 0)), "constant")
weighted_avg_coeffs += weight * coeffs
Expand Down
12 changes: 7 additions & 5 deletions pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1737,19 +1737,21 @@ def from_local_env_strategy(cls, molecule, strategy) -> Self:
else:
structure = None

for n in range(len(molecule)):
neighbors = strategy.get_nn_info(molecule, n) if structure is None else strategy.get_nn_info(structure, n)
for idx in range(len(molecule)):
neighbors = (
strategy.get_nn_info(molecule, idx) if structure is None else strategy.get_nn_info(structure, idx)
)
for neighbor in neighbors:
# all bonds in molecules should not cross
# (artificial) periodic boundaries
if not np.array_equal(neighbor["image"], [0, 0, 0]):
continue

if n > neighbor["site_index"]:
if idx > neighbor["site_index"]:
from_index = neighbor["site_index"]
to_index = n
to_index = idx
else:
from_index = n
from_index = idx
to_index = neighbor["site_index"]

mg.add_edge(
Expand Down
10 changes: 5 additions & 5 deletions pymatgen/analysis/nmr.py
Original file line number Diff line number Diff line change
Expand Up @@ -219,16 +219,16 @@ def coupling_constant(self, specie):
if len(specie.split("-")) > 1:
isotope = str(specie)
specie = Species(specie.split("-")[0])
Q = specie.get_nmr_quadrupole_moment(isotope)
quad_pol_mom = specie.get_nmr_quadrupole_moment(isotope)
else:
specie = Species(specie)
Q = specie.get_nmr_quadrupole_moment()
quad_pol_mom = specie.get_nmr_quadrupole_moment()
elif isinstance(specie, Site):
specie = specie.specie
Q = specie.get_nmr_quadrupole_moment()
quad_pol_mom = specie.get_nmr_quadrupole_moment()
elif isinstance(specie, Species):
Q = specie.get_nmr_quadrupole_moment()
quad_pol_mom = specie.get_nmr_quadrupole_moment()
else:
raise ValueError("Invalid species provided for quadrupolar coupling constant calculations")

return (e * Q * Vzz / planks_constant).to("MHz")
return (e * quad_pol_mom * Vzz / planks_constant).to("MHz")
19 changes: 9 additions & 10 deletions pymatgen/analysis/piezo_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -421,7 +421,6 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1):
3Nx3N numpy array representing the force constant matrix
"""
operations = self.FCM_operations
D = unsymmetrized_fcm
for op in operations:
same = 0
transpose = 0
Expand All @@ -430,24 +429,24 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1):
if op[0] == op[3] and op[1] == op[2]:
transpose = 1
if transpose == 0 and same == 0:
D[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] = np.zeros([3, 3])
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 = D[3 * op[2] : 3 * op[2] + 3, 3 * op[3] : 3 * op[3] + 3]
tempfcm = unsymmetrized_fcm[3 * op[2] : 3 * op[2] + 3, 3 * op[3] : 3 * op[3] + 3]
tempfcm = symop.transform_tensor(tempfcm)

D[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] += tempfcm

if len(op[4]) != 0:
D[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] = D[
unsymmetrized_fcm[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] = unsymmetrized_fcm[
3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3
] / len(op[4])
D[3 * op[1] : 3 * op[1] + 3, 3 * op[0] : 3 * op[0] + 3] = D[
unsymmetrized_fcm[3 * op[1] : 3 * op[1] + 3, 3 * op[0] : 3 * op[0] + 3] = unsymmetrized_fcm[
3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3
].T
continue

temp_tensor = Tensor(D[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3])
temp_tensor = Tensor(unsymmetrized_fcm[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3])
temp_tensor_sum = sum(temp_tensor.transform(symm_op) for symm_op in self.sharedops[op[0]][op[1]])
if len(self.sharedops[op[0]][op[1]]) != 0:
temp_tensor_sum = temp_tensor_sum / (len(self.sharedops[op[0]][op[1]]))
Expand All @@ -462,10 +461,10 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1):
else:
temp_tensor_sum = (temp_tensor_sum + temp_tensor_sum.T) / 2

D[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] = temp_tensor_sum
D[3 * op[1] : 3 * op[1] + 3, 3 * op[0] : 3 * op[0] + 3] = temp_tensor_sum.T
unsymmetrized_fcm[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] = temp_tensor_sum
unsymmetrized_fcm[3 * op[1] : 3 * op[1] + 3, 3 * op[0] : 3 * op[0] + 3] = temp_tensor_sum.T

return D
return unsymmetrized_fcm

def get_stable_FCM(self, fcm, fcmasum=10):
"""
Expand Down
32 changes: 16 additions & 16 deletions pymatgen/analysis/topological/spillage.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

class SOCSpillage:
"""
Spin-orbit spillage criteria to predict whether a material is topologically non-trival.
Spin-orbit spillage criteria to predict whether a material is topologically non-trivial.
The spillage criteria physically signifies number of band-inverted electrons.
A non-zero, high value (generally >0.5) suggests non-trivial behavior.
"""
Expand All @@ -39,24 +39,24 @@ def isclose(n1, n2, rel_tol=1e-7):
def orth(A):
"""Helper function to create orthonormal basis."""
u, s, _vh = np.linalg.svd(A, full_matrices=False)
M, N = A.shape
n_rows, n_cols = A.shape
eps = np.finfo(float).eps
tol = max(M, N) * np.amax(s) * eps
tol = max(n_rows, n_cols) * np.amax(s) * eps
num = np.sum(s > tol, dtype=int)
Q = u[:, :num]
return Q, num
orthonormal_basis = u[:, :num]
return orthonormal_basis, num

def overlap_so_spinpol(self):
"""Main function to calculate SOC spillage."""
noso = Wavecar(self.wf_noso)
no_so = Wavecar(self.wf_noso)
so = Wavecar(self.wf_so)

b_cell = np.linalg.inv(noso.a).T
tmp = np.linalg.norm(np.dot(np.diff(noso.kpoints, axis=0), b_cell), axis=1)
b_cell = np.linalg.inv(no_so.a).T
tmp = np.linalg.norm(np.dot(np.diff(no_so.kpoints, axis=0), b_cell), axis=1)
noso_k = np.concatenate(([0], np.cumsum(tmp)))
noso_bands = np.array(noso.band_energy)[:, :, :, 0]
noso_kvecs = np.array(noso.kpoints)
noso_occs = np.array(noso.band_energy)[:, :, :, 2]
noso_bands = np.array(no_so.band_energy)[:, :, :, 0]
noso_kvecs = np.array(no_so.kpoints)
noso_occs = np.array(no_so.band_energy)[:, :, :, 2]
n_kpts_noso = len(noso_k)

b_cell = np.linalg.inv(so.a).T
Expand Down Expand Up @@ -141,11 +141,11 @@ def overlap_so_spinpol(self):
kpoints.append(kso)
Mmn = 0.0
vnoso = np.array(
noso.coeffs[0][nk1 - 1][0]
no_so.coeffs[0][nk1 - 1][0]
) # noso.readBandCoeff(ispin=1, ikpt=nk1, iband=1, norm=False)
n_noso1 = vnoso.shape[0]
vnoso = np.array(
noso.coeffs[1][nk1 - 1][0]
no_so.coeffs[1][nk1 - 1][0]
) # noso.readBandCoeff(ispin=2, ikpt=nk1, iband=1, norm=False)
# n_noso2 = vnoso.shape[0]
vso = so.coeffs[nk1 - 1][0].flatten() # so.readBandCoeff(ispin=1, ikpt=nk2, iband=1, norm=False)
Expand All @@ -155,13 +155,13 @@ def overlap_so_spinpol(self):
Vnoso = np.zeros((vs, nelec_tot), dtype=complex)
Vso = np.zeros((vs, nelec_tot), dtype=complex)

if np.array(noso.coeffs[1][nk1 - 1]).shape[1] == vs // 2:
if np.array(no_so.coeffs[1][nk1 - 1]).shape[1] == vs // 2:
# if nk1==10 and nk2==10:
# prepare matrices
for n1 in range(1, nelec_up + 1):
Vnoso[0 : vs // 2, n1 - 1] = np.array(noso.coeffs[0][nk1 - 1][n1 - 1])[0 : vs // 2]
Vnoso[0 : vs // 2, n1 - 1] = np.array(no_so.coeffs[0][nk1 - 1][n1 - 1])[0 : vs // 2]
for n1 in range(1, nelec_dn + 1):
Vnoso[vs // 2 : vs, n1 - 1 + nelec_up] = np.array(noso.coeffs[1][nk1 - 1][n1 - 1])[
Vnoso[vs // 2 : vs, n1 - 1 + nelec_up] = np.array(no_so.coeffs[1][nk1 - 1][n1 - 1])[
0 : vs // 2
]
for n1 in range(1, nelec_tot + 1):
Expand Down
28 changes: 13 additions & 15 deletions pymatgen/cli/pmg.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,28 +51,26 @@ def format_lists(v):
return " ".join(f"{len(tuple(group))}*{i:.2f}" for (i, group) in itertools.groupby(v))
return v

d = incar1.diff(incar2)
diff = incar1.diff(incar2)
output = [
["SAME PARAMS", "", ""],
["---------------", "", ""],
["", "", ""],
["DIFFERENT PARAMS", "", ""],
["----------------", "", ""],
]
output.extend(
[(k, format_lists(d["Same"][k]), format_lists(d["Same"][k])) for k in sorted(d["Same"]) if k != "SYSTEM"]
)
output.extend(
[
(
k,
format_lists(d["Different"][k]["INCAR1"]),
format_lists(d["Different"][k]["INCAR2"]),
)
for k in sorted(d["Different"])
if k != "SYSTEM"
]
)
output += [
(k, format_lists(diff["Same"][k]), format_lists(diff["Same"][k])) for k in sorted(diff["Same"]) if k != "SYSTEM"
]
output += [
(
k,
format_lists(diff["Different"][k]["INCAR1"]),
format_lists(diff["Different"][k]["INCAR2"]),
)
for k in sorted(diff["Different"])
if k != "SYSTEM"
]
print(tabulate(output, headers=["", filepath1, filepath2]))
return 0

Expand Down
6 changes: 3 additions & 3 deletions pymatgen/electronic_structure/boltztrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -1481,9 +1481,9 @@ def is_isotropic(x, isotropy_tolerance) -> bool:
d = self.get_zt(output="eigs", doping_levels=True)

else:
raise ValueError(f"Target property: {target_prop} not recognized!")
raise ValueError(f"Unrecognized {target_prop=}")

absval = True # take the absolute value of properties
abs_val = True # take the absolute value of properties

x_val = x_temp = x_doping = x_isotropic = None
output = {}
Expand All @@ -1500,7 +1500,7 @@ def is_isotropic(x, isotropy_tolerance) -> bool:
doping_lvl = self.doping[pn][didx]
if min_doping <= doping_lvl <= max_doping:
isotropic = is_isotropic(evs, isotropy_tolerance)
if absval:
if abs_val:
evs = [abs(x) for x in evs]
val = float(sum(evs)) / len(evs) if use_average else max(evs)
if x_val is None or (val > x_val and maximize) or (val < x_val and not maximize):
Expand Down
22 changes: 11 additions & 11 deletions pymatgen/io/cif.py
Original file line number Diff line number Diff line change
Expand Up @@ -180,34 +180,34 @@ def from_str(cls, string: str) -> Self:
Returns:
CifBlock
"""
q = cls._process_string(string)
header = q.popleft()[0][5:]
deq = cls._process_string(string)
header = deq.popleft()[0][5:]
data: dict = {}
loops = []
while q:
s = q.popleft()
while deq:
s = deq.popleft()
# cif keys aren't in quotes, so show up in s[0]
if s[0] == "_eof":
break
if s[0].startswith("_"):
try:
data[s[0]] = "".join(q.popleft())
data[s[0]] = "".join(deq.popleft())
except IndexError:
data[s[0]] = ""
elif s[0].startswith("loop_"):
columns = []
items = []
while q:
s = q[0]
while deq:
s = deq[0]
if s[0].startswith("loop_") or not s[0].startswith("_"):
break
columns.append("".join(q.popleft()))
columns.append("".join(deq.popleft()))
data[columns[-1]] = []
while q:
s = q[0]
while deq:
s = deq[0]
if s[0].startswith(("loop_", "_")):
break
items.append("".join(q.popleft()))
items.append("".join(deq.popleft()))
n = len(items) // len(columns)
assert len(items) % n == 0
loops.append(columns)
Expand Down
7 changes: 3 additions & 4 deletions pymatgen/io/lammps/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -772,19 +772,18 @@ def from_ff_and_topologies(
v_collector: list | None = [] if topologies[0].velocities else None
topo_collector: dict[str, list] = {"Bonds": [], "Angles": [], "Dihedrals": [], "Impropers": []}
topo_labels: dict[str, list] = {"Bonds": [], "Angles": [], "Dihedrals": [], "Impropers": []}
for i, topo in enumerate(topologies):
for idx, topo in enumerate(topologies):
if topo.topologies:
shift = len(labels)
for k, v in topo.topologies.items():
topo_collector[k].append(np.array(v) + shift + 1)
topo_labels[k].extend([tuple(topo.type_by_sites[j] for j in t) for t in v])
if isinstance(v_collector, list):
v_collector.append(topo.velocities)
mol_ids.extend([i + 1] * len(topo.sites))
mol_ids.extend([idx + 1] * len(topo.sites))
labels.extend(topo.type_by_sites)
coords.append(topo.sites.cart_coords)
q = [0.0] * len(topo.sites) if not topo.charges else topo.charges
charges.extend(q)
charges.extend(topo.charges if topo.charges else [0.0] * len(topo.sites))

atoms = pd.DataFrame(np.concatenate(coords), columns=["x", "y", "z"])
atoms["molecule-ID"] = mol_ids
Expand Down
Loading

0 comments on commit 0c20f19

Please sign in to comment.