From 082056db1e342f86e3f3b5c0daca42864c1da18d Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 17:19:24 -0700 Subject: [PATCH 01/14] snake_case --- pymatgen/analysis/ewald.py | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/pymatgen/analysis/ewald.py b/pymatgen/analysis/ewald.py index 11f675338b7..042d2f50f23 100644 --- a/pymatgen/analysis/ewald.py +++ b/pymatgen/analysis/ewald.py @@ -315,10 +315,10 @@ def _calc_recip(self): This method is heavily vectorized to utilize numpy's C backend for speed. """ - numsites = self._s.num_sites + n_sites = self._s.num_sites prefactor = 2 * pi / self._vol - erecip = np.zeros((numsites, numsites), dtype=np.float_) - forces = np.zeros((numsites, 3), dtype=np.float_) + e_recip = np.zeros((n_sites, n_sites), dtype=np.float_) + forces = np.zeros((n_sites, 3), dtype=np.float_) coords = self._coords rcp_latt = self._s.lattice.reciprocal_lattice recip_nn = rcp_latt.get_points_in_sphere([[0, 0, 0]], [0, 0, 0], self._gmax) @@ -327,51 +327,51 @@ def _calc_recip(self): gs = rcp_latt.get_cartesian_coords(frac_coords) g2s = np.sum(gs**2, 1) - expvals = np.exp(-g2s / (4 * self._eta)) + exp_vals = np.exp(-g2s / (4 * self._eta)) grs = np.sum(gs[:, None] * coords[None, :], 2) - oxistates = np.array(self._oxi_states) + oxi_states = np.array(self._oxi_states) # create array where q_2[i,j] is qi * qj - qiqj = oxistates[None, :] * oxistates[:, None] + qiqj = oxi_states[None, :] * oxi_states[:, None] # calculate the structure factor - sreals = np.sum(oxistates[None, :] * np.cos(grs), 1) - simags = np.sum(oxistates[None, :] * np.sin(grs), 1) + 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, expval, sreal, simag in zip(gs, g2s, grs, expvals, sreals, simags): + for g, g2, gr, expval, sreal, simag in zip(gs, g2s, grs, exp_vals, s_reals, s_imags): # Uses the identity sin(x)+cos(x) = 2**0.5 sin(x + pi/4) m = (gr[None, :] + pi / 4) - gr[:, None] np.sin(m, m) m *= expval / g2 - erecip += m + e_recip += m if self._compute_forces: - pref = 2 * expval / g2 * oxistates + pref = 2 * expval / g2 * oxi_states factor = prefactor * pref * (sreal * np.sin(gr) - simag * np.cos(gr)) forces += factor[:, None] * g[None, :] forces *= EwaldSummation.CONV_FACT - erecip *= prefactor * EwaldSummation.CONV_FACT * qiqj * 2**0.5 - return erecip, forces + e_recip *= prefactor * EwaldSummation.CONV_FACT * qiqj * 2**0.5 + return e_recip, forces def _calc_real_and_point(self): """Determines the self energy -(eta/pi)**(1/2) * sum_{i=1}^{N} q_i**2.""" fcoords = self._s.frac_coords forcepf = 2 * self._sqrt_eta / sqrt(pi) coords = self._coords - numsites = self._s.num_sites - ereal = np.empty((numsites, numsites), dtype=np.float_) + n_sites = self._s.num_sites + ereal = np.empty((n_sites, n_sites), dtype=np.float_) - forces = np.zeros((numsites, 3), dtype=np.float_) + forces = np.zeros((n_sites, 3), dtype=np.float_) qs = np.array(self._oxi_states) epoint = -(qs**2) * sqrt(self._eta / pi) - for i in range(numsites): + for i in range(n_sites): nfcoords, rij, js, _ = self._s.lattice.get_points_in_sphere( fcoords, coords[i], self._rmax, zip_results=False ) @@ -389,7 +389,7 @@ def _calc_real_and_point(self): new_ereals = erfcval * qi * qj / rij # insert new_ereals - for key in range(numsites): + for key in range(n_sites): ereal[key, i] = np.sum(new_ereals[js == key]) if self._compute_forces: From 0de723b4a0609ebfc725d780c053e7d454147cc9 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 17:20:28 -0700 Subject: [PATCH 02/14] get_asum_FCM change AssertionError to RuntimeError --- pymatgen/analysis/piezo_sensitivity.py | 33 +++++++++++++------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/pymatgen/analysis/piezo_sensitivity.py b/pymatgen/analysis/piezo_sensitivity.py index bc499da04a8..895b4b21b87 100644 --- a/pymatgen/analysis/piezo_sensitivity.py +++ b/pymatgen/analysis/piezo_sensitivity.py @@ -534,21 +534,22 @@ def get_asum_FCM(self, fcm: np.ndarray, numiter: int = 15): """ # set max force in reciprocal space operations = self.FCM_operations - assert operations is not None, "No symmetry operations found" + if operations is None: + raise RuntimeError("No symmetry operations found. Run get_FCM_operations first.") - numsites = len(self.structure) + n_sites = len(self.structure) - D = np.ones([numsites * 3, numsites * 3]) + D = np.ones([n_sites * 3, n_sites * 3]) for _ in range(numiter): X = np.real(fcm) # symmetry operations pastrow = 0 total = np.zeros([3, 3]) - for col in range(numsites): + for col in range(n_sites): total = total + X[0:3, col * 3 : col * 3 + 3] - total = total / (numsites) + total = total / (n_sites) for op in operations: same = 0 transpose = 0 @@ -574,15 +575,15 @@ def get_asum_FCM(self, fcm: np.ndarray, numiter: int = 15): ].T continue # Get the difference in the sum up to this point - currrow = op[0] - if currrow != pastrow: + curr_row = op[0] + if curr_row != pastrow: total = np.zeros([3, 3]) - for col in range(numsites): - total = total + X[currrow * 3 : currrow * 3 + 3, col * 3 : col * 3 + 3] - for col in range(currrow): - total = total - D[currrow * 3 : currrow * 3 + 3, col * 3 : col * 3 + 3] - total = total / (numsites - currrow) - pastrow = currrow + for col in range(n_sites): + total = total + X[curr_row * 3 : curr_row * 3 + 3, col * 3 : col * 3 + 3] + for col in range(curr_row): + total = total - D[curr_row * 3 : curr_row * 3 + 3, col * 3 : col * 3 + 3] + total = total / (n_sites - curr_row) + pastrow = curr_row # Apply the point symmetry operations of the site temp_tensor = Tensor(total) @@ -669,8 +670,8 @@ def get_piezo(BEC, IST, FCM, rcond=0.0001): Return: 3x3x3 calculated Piezo tensor """ - numsites = len(BEC) - temp_fcm = np.reshape(np.swapaxes(FCM, 1, 2), (numsites * 3, numsites * 3)) + n_sites = len(BEC) + temp_fcm = np.reshape(np.swapaxes(FCM, 1, 2), (n_sites * 3, n_sites * 3)) eigs, vecs = np.linalg.eig(temp_fcm) K = np.linalg.pinv( @@ -678,7 +679,7 @@ def get_piezo(BEC, IST, FCM, rcond=0.0001): rcond=np.abs(eigs[np.argsort(np.abs(eigs))[2]]) / np.abs(eigs[np.argsort(np.abs(eigs))[-1]]) + rcond, ) - K = np.reshape(K, (numsites, 3, numsites, 3)).swapaxes(1, 2) + K = np.reshape(K, (n_sites, 3, n_sites, 3)).swapaxes(1, 2) return np.einsum("ikl,ijlm,jmno->kno", BEC, K, IST) * 16.0216559424 From 4f6d4ffb41dfcdf6b9f03e3573010519287db185 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 17:21:01 -0700 Subject: [PATCH 03/14] fix empty doc strings --- .../connectivity/connected_components.py | 37 +++++++++---------- pymatgen/analysis/pourbaix_diagram.py | 19 +++++----- 2 files changed, 28 insertions(+), 28 deletions(-) diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index f5903f7fc8b..d5d10545162 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -392,7 +392,7 @@ def compute_periodicity(self, algorithm="all_simple_paths"): self._order_periodicity_vectors() def compute_periodicity_all_simple_paths_algorithm(self): - """Returns:""" + """Get the periodicity vectors of the connected component.""" self_loop_nodes = list(nx.nodes_with_selfloops(self._connected_subgraph)) all_nodes_independent_cell_image_vectors = [] my_simple_graph = nx.Graph(self._connected_subgraph) @@ -476,16 +476,15 @@ def compute_periodicity_all_simple_paths_algorithm(self): if len(self._periodicity_vectors) == 3: break - def compute_periodicity_cycle_basis(self): - """Returns:""" + def compute_periodicity_cycle_basis(self) -> None: + """Compute periodicity vectors of the connected component.""" my_simple_graph = nx.Graph(self._connected_subgraph) cycles = nx.cycle_basis(my_simple_graph) all_deltas = [] - for cyc in cycles: - mycyc = list(cyc) - mycyc.append(cyc[0]) + for cyc in map(list, cycles): + cyc.append(cyc[0]) this_cycle_deltas = [np.zeros(3, int)] - for node1, node2 in [(node1, mycyc[inode1 + 1]) for inode1, node1 in enumerate(mycyc[:-1])]: + for node1, node2 in [(node1, cyc[inode1 + 1]) for inode1, node1 in enumerate(cyc[:-1])]: this_cycle_deltas_new = [] for edge_data in self._connected_subgraph[node1][node2].values(): delta = get_delta(node1, node2, edge_data) @@ -569,18 +568,18 @@ def graph(self): Returns: MultiGraph: Networkx MultiGraph object with environment as nodes and links between these nodes as edges - with information about the image cell difference if any. + with information about the image cell difference if any. """ return self._connected_subgraph @property def is_periodic(self) -> bool: - """Returns:""" + """Whether this connected component is periodic.""" return not self.is_0d @property def is_0d(self) -> bool: - """Returns:""" + """Whether this connected component is 0-dimensional.""" if self._periodicity_vectors is None: self.compute_periodicity() assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional @@ -588,7 +587,7 @@ def is_0d(self) -> bool: @property def is_1d(self) -> bool: - """Returns:""" + """Whether this connected component is 1-dimensional.""" if self._periodicity_vectors is None: self.compute_periodicity() assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional @@ -596,7 +595,7 @@ def is_1d(self) -> bool: @property def is_2d(self) -> bool: - """Returns:""" + """Whether this connected component is 2-dimensional.""" if self._periodicity_vectors is None: self.compute_periodicity() assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional @@ -604,7 +603,7 @@ def is_2d(self) -> bool: @property def is_3d(self) -> bool: - """Returns:""" + """Whether this connected component is 3-dimensional.""" if self._periodicity_vectors is None: self.compute_periodicity() assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional @@ -622,8 +621,8 @@ def _order_vectors(vectors): Example: [[1, 1, 0], [0, 1, -1], [0, 1, 1]] is ordered as [[0, 1, -1], [0, 1, 1], [1, 1, 0]] """ for ipv, pv in enumerate(vectors): - nonzeros = np.nonzero(pv)[0] - if pv[nonzeros[0]] < 0 < len(nonzeros): + non_zeros = np.nonzero(pv)[0] + if pv[non_zeros[0]] < 0 < len(non_zeros): vectors[ipv] = -pv return sorted(vectors, key=lambda x: x.tolist()) @@ -633,21 +632,21 @@ def _order_periodicity_vectors(self): raise ValueError("Number of periodicity vectors is larger than 3.") self._periodicity_vectors = self._order_vectors(self._periodicity_vectors) # for ipv, pv in enumerate(self._periodicity_vectors): - # nonzeros = np.nonzero(pv)[0] - # if (len(nonzeros) > 0) and (pv[nonzeros[0]] < 0): + # non_zeros = np.nonzero(pv)[0] + # if (len(non_zeros) > 0) and (pv[non_zeros[0]] < 0): # self._periodicity_vectors[ipv] = -pv # self._periodicity_vectors = sorted(self._periodicity_vectors, key=lambda x: x.tolist()) @property def periodicity_vectors(self): - """Returns:""" + """Get periodicity vectors of this connected component.""" if self._periodicity_vectors is None: self.compute_periodicity() return [np.array(pp) for pp in self._periodicity_vectors] @property def periodicity(self): - """Returns:""" + """Get periodicity of this connected component.""" if self._periodicity_vectors is None: self.compute_periodicity() return f"{len(self._periodicity_vectors):d}D" diff --git a/pymatgen/analysis/pourbaix_diagram.py b/pymatgen/analysis/pourbaix_diagram.py index fdaa888b740..e29a3e44961 100644 --- a/pymatgen/analysis/pourbaix_diagram.py +++ b/pymatgen/analysis/pourbaix_diagram.py @@ -96,7 +96,7 @@ def __init__(self, entry, entry_id=None, concentration=1e-6): else: self.concentration = 1.0 self.phase_type = "Solid" - self.charge = 0.0 + self.charge = 0 self.uncorrected_energy = entry.energy if entry_id is not None: self.entry_id = entry_id @@ -107,22 +107,22 @@ def __init__(self, entry, entry_id=None, concentration=1e-6): @property def npH(self): - """Returns:""" - return self.entry.composition.get("H", 0.0) - 2 * self.entry.composition.get("O", 0.0) + """Get the number of H.""" + return self.entry.composition.get("H", 0) - 2 * self.entry.composition.get("O", 0) @property def nH2O(self): - """Returns: Number of H2O.""" - return self.entry.composition.get("O", 0.0) + """Get the number of H2O.""" + return self.entry.composition.get("O", 0) @property def nPhi(self): - """Returns: Number of H2O.""" + """Get the number of electrons.""" return self.npH - self.charge @property def name(self): - """Returns: Name for entry.""" + """Get the name for entry.""" if self.phase_type == "Solid": return self.entry.composition.reduced_formula + "(s)" @@ -252,9 +252,10 @@ def to_pretty_string(self) -> str: return self.entry.name def __repr__(self): + energy, npH, nPhi, nH2O, entry_id = self.energy, self.npH, self.nPhi, self.nH2O, self.entry_id return ( - f"Pourbaix Entry : {self.entry.composition} with energy = {self.energy:.4f}, npH = {self.npH}, " - f"nPhi = {self.nPhi}, nH2O = {self.nH2O}, entry_id = {self.entry_id} " + f"{type(self).__name__}({self.entry.composition} with {energy = :.4f}, {npH = }, " + f"{nPhi = }, {nH2O = }, {entry_id = })" ) From ad720ea5c7b0c3cbbe5959f68b4724696b682e9f Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 17:22:51 -0700 Subject: [PATCH 04/14] snake_case --- .../connectivity/structure_connectivity.py | 6 ++-- .../structure_environments.py | 6 ++-- .../utils/coordination_geometry_utils.py | 34 +++++++++---------- .../analysis/tests/test_piezo_sensitivity.py | 20 +++++------ pymatgen/io/tests/test_ase.py | 2 +- pymatgen/io/tests/test_cif.py | 2 +- test_files/.pytest-split-durations | 4 +-- 7 files changed, 37 insertions(+), 37 deletions(-) diff --git a/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py b/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py index f0b3d445852..ddc6a58615a 100644 --- a/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py +++ b/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py @@ -266,8 +266,8 @@ def setup_environments_subgraph(self, environments_symbols): def setup_atom_environments_subgraph(self, atoms_environments): raise NotImplementedError - def print_links(self): - """Returns:""" + def print_links(self) -> None: + """Print all links in the graph.""" nodes = self.environment_subgraph().nodes() print("Links in graph :") for node in nodes: @@ -285,7 +285,7 @@ def print_links(self): ) def as_dict(self): - """Returns:""" + """Convert to MSONable dict.""" return { "@module": type(self).__module__, "@class": type(self).__name__, diff --git a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py index 6fbd567711f..0b68f811239 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py +++ b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py @@ -1746,10 +1746,10 @@ def setup_statistic_lists(self): fraction_ion_stat[elmt][oxi_state] = {env: fraction / sumspecie for env, fraction in envs.items()} for ce_symbol, ions in ce_ion_stat.items(): fraction_ce_ion_stat[ce_symbol] = {} - sum_ce = np.sum([np.sum(list(oxistates.values())) for elmt, oxistates in ions.items()]) - for elmt, oxistates in ions.items(): + sum_ce = np.sum([np.sum(list(oxi_states.values())) for elmt, oxi_states in ions.items()]) + for elmt, oxi_states in ions.items(): fraction_ce_ion_stat[ce_symbol][elmt] = { - oxistate: fraction / sum_ce for oxistate, fraction in oxistates.items() + oxistate: fraction / sum_ce for oxistate, fraction in oxi_states.items() } def get_site_info_for_specie_ce(self, specie, ce_symbol): diff --git a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py index 013f0d2b930..1b3378555ed 100644 --- a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py +++ b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py @@ -603,11 +603,11 @@ def __init__(self, coefficients, p1=None, p2=None, p3=None): self.normal_vector = np.array([coefficients[0], coefficients[1], coefficients[2]], np.float_) normv = np.linalg.norm(self.normal_vector) self.normal_vector /= normv - nonzeros = np.argwhere(self.normal_vector != 0.0).flatten() - zeros = list(set(range(3)) - set(nonzeros)) - if len(nonzeros) == 0: + non_zeros = np.argwhere(self.normal_vector != 0.0).flatten() + zeros = list(set(range(3)) - set(non_zeros)) + if len(non_zeros) == 0: raise ValueError("Normal vector is equal to 0.0") - if self.normal_vector[nonzeros[0]] < 0.0: + if self.normal_vector[non_zeros[0]] < 0.0: self.normal_vector = -self.normal_vector dd = -np.float_(coefficients[3]) / normv else: @@ -622,32 +622,32 @@ def __init__(self, coefficients, p1=None, p2=None, p3=None): self.p3 = p3 # Initializes 3 points belonging to the plane (useful for some methods) if self.p1 is None: - self.init_3points(nonzeros, zeros) + self.init_3points(non_zeros, zeros) self.vector_to_origin = dd * self.normal_vector self.e1 = self.e2 = None self.e3 = self.normal_vector - def init_3points(self, nonzeros, zeros): + def init_3points(self, non_zeros, zeros): """Initialize three random points on this plane. - :param nonzeros: Indices of plane coefficients ([a, b, c]) that are not zero. + :param non_zeros: Indices of plane coefficients ([a, b, c]) that are not zero. :param zeros: Indices of plane coefficients ([a, b, c]) that are equal to zero. :return: None """ - if len(nonzeros) == 3: + if len(non_zeros) == 3: self.p1 = np.array([-self.d / self.a, 0.0, 0.0], np.float_) self.p2 = np.array([0.0, -self.d / self.b, 0.0], np.float_) self.p3 = np.array([0.0, 0.0, -self.d / self.c], np.float_) - elif len(nonzeros) == 2: + elif len(non_zeros) == 2: self.p1 = np.zeros(3, np.float_) - self.p1[nonzeros[1]] = -self.d / self.coefficients[nonzeros[1]] + self.p1[non_zeros[1]] = -self.d / self.coefficients[non_zeros[1]] self.p2 = np.array(self.p1) self.p2[zeros[0]] = 1.0 self.p3 = np.zeros(3, np.float_) - self.p3[nonzeros[0]] = -self.d / self.coefficients[nonzeros[0]] - elif len(nonzeros) == 1: + self.p3[non_zeros[0]] = -self.d / self.coefficients[non_zeros[0]] + elif len(non_zeros) == 1: self.p1 = np.zeros(3, np.float_) - self.p1[nonzeros[0]] = -self.d / self.coefficients[nonzeros[0]] + self.p1[non_zeros[0]] = -self.d / self.coefficients[non_zeros[0]] self.p2 = np.array(self.p1) self.p2[zeros[0]] = 1.0 self.p3 = np.array(self.p1) @@ -937,8 +937,8 @@ def from_3points(cls, p1, p2, p3): """ nn = np.cross(p1 - p3, p2 - p3) normal_vector = nn / norm(nn) - nonzeros = np.argwhere(normal_vector != 0.0) - if normal_vector[nonzeros[0, 0]] < 0.0: + non_zeros = np.argwhere(normal_vector != 0.0) + if normal_vector[non_zeros[0, 0]] < 0.0: normal_vector = -normal_vector dd = -np.dot(normal_vector, p1) 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): [UU, SS, Vt] = np.linalg.svd(AA) imin = np.argmin(SS) normal_vector = Vt[imin] - nonzeros = np.argwhere(normal_vector != 0.0) - if normal_vector[nonzeros[0, 0]] < 0.0: + non_zeros = np.argwhere(normal_vector != 0.0) + if normal_vector[non_zeros[0, 0]] < 0.0: normal_vector = -normal_vector dd = -np.dot(normal_vector, mean_point) coefficients = np.array([normal_vector[0], normal_vector[1], normal_vector[2], dd], np.float_) diff --git a/pymatgen/analysis/tests/test_piezo_sensitivity.py b/pymatgen/analysis/tests/test_piezo_sensitivity.py index 3a20b7892c9..6eae753db1f 100644 --- a/pymatgen/analysis/tests/test_piezo_sensitivity.py +++ b/pymatgen/analysis/tests/test_piezo_sensitivity.py @@ -221,13 +221,13 @@ def test_rand_FCM(self): dyn = pnstruc.get_dynamical_matrix_at_q([0, 0, 0]) dyn = np.reshape(dyn, (10, 3, 10, 3)).swapaxes(1, 2) dyn = np.real(dyn) - numsites = len(self.piezo_struc) + n_sites = len(self.piezo_struc) masses = [] - for j in range(numsites): + for j in range(n_sites): masses.append(self.piezo_struc.sites[j].specie.atomic_mass) - dynmass = np.zeros([numsites, numsites, 3, 3]) - for m in range(numsites): - for n in range(numsites): + dynmass = np.zeros([n_sites, n_sites, 3, 3]) + for m in range(n_sites): + for n in range(n_sites): dynmass[m][n] = dyn[m][n] / np.sqrt(masses[m]) / np.sqrt(masses[n]) dynmass = np.reshape(np.swapaxes(dynmass, 1, 2), (10 * 3, 10 * 3)) @@ -295,13 +295,13 @@ def test_rand_piezo(self): dyn = pnstruc.get_dynamical_matrix_at_q([0, 0, 0]) dyn = np.reshape(dyn, (10, 3, 10, 3)).swapaxes(1, 2) dyn = np.real(dyn) - numsites = len(self.piezo_struc) + n_sites = len(self.piezo_struc) masses = [] - for j in range(numsites): + for j in range(n_sites): masses.append(self.piezo_struc.sites[j].specie.atomic_mass) - dynmass = np.zeros([numsites, numsites, 3, 3]) - for m in range(numsites): - for n in range(numsites): + dynmass = np.zeros([n_sites, n_sites, 3, 3]) + for m in range(n_sites): + for n in range(n_sites): dynmass[m][n] = dyn[m][n] / np.sqrt(masses[m]) / np.sqrt(masses[n]) dynmass = np.reshape(np.swapaxes(dynmass, 1, 2), (10 * 3, 10 * 3)) diff --git a/pymatgen/io/tests/test_ase.py b/pymatgen/io/tests/test_ase.py index d9a968f4574..800ef7c9dbd 100644 --- a/pymatgen/io/tests/test_ase.py +++ b/pymatgen/io/tests/test_ase.py @@ -90,7 +90,7 @@ def test_get_atoms_from_structure_charge(self): assert atoms.get_initial_charges().tolist(), initial_charges assert atoms.get_charges().tolist(), charges - def test_get_atoms_from_structure_oxistates(self): + def test_get_atoms_from_structure_oxi_states(self): p = Poscar.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR")) structure = p.structure oxi_states = [1.0] * len(structure) diff --git a/pymatgen/io/tests/test_cif.py b/pymatgen/io/tests/test_cif.py index 009207ed8a3..7170b4abf9a 100644 --- a/pymatgen/io/tests/test_cif.py +++ b/pymatgen/io/tests/test_cif.py @@ -675,7 +675,7 @@ def test_primes(self): for s in parser.get_structures(False): assert s.composition == 8 * Composition("C26H16BeN2O2S2") - def test_missing_atom_site_type_with_oxistates(self): + def test_missing_atom_site_type_with_oxi_states(self): parser = CifParser(f"{self.TEST_FILES_DIR}/P24Ru4H252C296S24N16.cif") c = Composition({"S0+": 24, "Ru0+": 4, "H0+": 252, "C0+": 296, "N0+": 16, "P0+": 24}) for s in parser.get_structures(False): diff --git a/test_files/.pytest-split-durations b/test_files/.pytest-split-durations index b15a8198bf2..0bb28cab348 100644 --- a/test_files/.pytest-split-durations +++ b/test_files/.pytest-split-durations @@ -1833,7 +1833,7 @@ "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_atoms_from_structure_charge": 0.08603604200470727, "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_atoms_from_structure_dyn": 0.030622125006630085, "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_atoms_from_structure_mags": 0.09381933399708942, - "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_atoms_from_structure_oxistates": 0.03135274999658577, + "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_atoms_from_structure_oxi_states": 0.03135274999658577, "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_molecule": 0.0010516249894862995, "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_structure": 0.0023741670011077076, "pymatgen/io/tests/test_ase.py::AseAtomsAdaptorTest::test_get_structure_dyn": 0.000730792002286762, @@ -1860,7 +1860,7 @@ "pymatgen/io/tests/test_cif.py::CifIOTest::test_get_lattice_from_lattice_type": 0.03534312501142267, "pymatgen/io/tests/test_cif.py::CifIOTest::test_get_symmetrized_structure": 0.022903416989720426, "pymatgen/io/tests/test_cif.py::CifIOTest::test_implicit_hydrogen": 0.017406540995580144, - "pymatgen/io/tests/test_cif.py::CifIOTest::test_missing_atom_site_type_with_oxistates": 0.08963220796431415, + "pymatgen/io/tests/test_cif.py::CifIOTest::test_missing_atom_site_type_with_oxi_states": 0.08963220796431415, "pymatgen/io/tests/test_cif.py::CifIOTest::test_no_coords_or_species": 0.00048429201706312597, "pymatgen/io/tests/test_cif.py::CifIOTest::test_no_symmops": 0.015507333009736612, "pymatgen/io/tests/test_cif.py::CifIOTest::test_one_line_symm": 0.0024171670083887875, From bb4f8b7354ea32c349d6a85a79fee70f2736878b Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 17:23:11 -0700 Subject: [PATCH 05/14] fix CI error "pdentries_test.csv" not found --- pymatgen/analysis/tests/test_chempot_diagram.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pymatgen/analysis/tests/test_chempot_diagram.py b/pymatgen/analysis/tests/test_chempot_diagram.py index aa72920e783..3269e970625 100644 --- a/pymatgen/analysis/tests/test_chempot_diagram.py +++ b/pymatgen/analysis/tests/test_chempot_diagram.py @@ -22,7 +22,7 @@ class ChemicalPotentialDiagramTest(PymatgenTest): def setUp(self): - self.entries = EntrySet.from_csv(str(module_dir / "pdentries_test.csv")) + self.entries = EntrySet.from_csv(str(module_dir / "pd_entries_test.csv")) self.cpd_ternary = ChemicalPotentialDiagram(entries=self.entries, default_min_limit=-25, formal_chempots=False) self.cpd_ternary_formal = ChemicalPotentialDiagram( entries=self.entries, default_min_limit=-25, formal_chempots=True From 4b60d4163cfed6a3ed29a38fd07e7a8492da8489 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 17:23:28 -0700 Subject: [PATCH 06/14] better TransformedPDEntryTest.test_str --- pymatgen/analysis/tests/test_phase_diagram.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pymatgen/analysis/tests/test_phase_diagram.py b/pymatgen/analysis/tests/test_phase_diagram.py index decfbbe2636..b2589849017 100644 --- a/pymatgen/analysis/tests/test_phase_diagram.py +++ b/pymatgen/analysis/tests/test_phase_diagram.py @@ -138,7 +138,10 @@ def test_to_from_dict(self): assert entry.energy_per_atom == approx(53.0 / (23 / 15)) def test_str(self): - assert str(self.transformed_entry) is not None + assert ( + str(self.transformed_entry) == "TransformedPDEntry Xf0+0.46666667 Xg0+1.0 Xh0+0.06666667 " + "with original composition Li1 Fe1 O2, energy = 53.0000" + ) def test_normalize(self): norm_entry = self.transformed_entry.normalize(mode="atom") From fe9d8e176453a232d0aef842625fa66849fda3c0 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 18:31:42 -0700 Subject: [PATCH 07/14] fix PeriodicSite._frac_coords type refactor PeriodicSite.__repr__ remove unused type ignore --- pymatgen/analysis/tests/test_phase_diagram.py | 16 +++---- pymatgen/core/sites.py | 48 +++++++++---------- pymatgen/core/tests/test_sites.py | 6 ++- 3 files changed, 35 insertions(+), 35 deletions(-) diff --git a/pymatgen/analysis/tests/test_phase_diagram.py b/pymatgen/analysis/tests/test_phase_diagram.py index b2589849017..fd99df9fe64 100644 --- a/pymatgen/analysis/tests/test_phase_diagram.py +++ b/pymatgen/analysis/tests/test_phase_diagram.py @@ -53,8 +53,8 @@ def test_get_energy_per_atom(self): assert self.gpentry.energy_per_atom == 50.0 / 2, "Wrong energy per atom!" def test_get_name(self): - assert self.entry.name == "mp-757614", "Wrong name!" - assert self.gpentry.name == "mp-757614", "Wrong name!" + assert self.entry.name == "mp-757614" + assert self.gpentry.name == "mp-757614" def test_get_composition(self): comp = self.entry.composition @@ -73,10 +73,10 @@ def test_to_from_dict(self): gpd = self.gpentry.as_dict() entry = PDEntry.from_dict(d) - assert entry.name == "mp-757614", "Wrong name!" + assert entry.name == "mp-757614" assert entry.energy_per_atom == 53.0 / 4 gpentry = GrandPotPDEntry.from_dict(gpd) - assert gpentry.name == "mp-757614", "Wrong name!" + assert gpentry.name == "mp-757614" assert gpentry.energy_per_atom == 50.0 / 2 d_anon = d.copy() @@ -121,7 +121,7 @@ def test_get_energy_per_atom(self): assert self.transformed_entry.energy_per_atom == approx(53.0 / (23 / 15)) def test_get_name(self): - assert self.transformed_entry.name == "LiFeO2", "Wrong name!" + assert self.transformed_entry.name == "LiFeO2" def test_get_composition(self): comp = self.transformed_entry.composition @@ -132,9 +132,9 @@ def test_is_element(self): assert not self.transformed_entry.is_element def test_to_from_dict(self): - d = self.transformed_entry.as_dict() - entry = TransformedPDEntry.from_dict(d) - assert entry.name == "LiFeO2", "Wrong name!" + dct = self.transformed_entry.as_dict() + entry = TransformedPDEntry.from_dict(dct) + assert entry.name == "LiFeO2" assert entry.energy_per_atom == approx(53.0 / (23 / 15)) def test_str(self): diff --git a/pymatgen/core/sites.py b/pymatgen/core/sites.py index 32bc15dbaa7..4a8c05622e5 100644 --- a/pymatgen/core/sites.py +++ b/pymatgen/core/sites.py @@ -337,7 +337,7 @@ def __init__( raise ValueError("Species occupancies sum to more than 1!") self._lattice: Lattice = lattice - self._frac_coords: ArrayLike = frac_coords + self._frac_coords: np.ndarray = np.asarray(frac_coords) self._species: Composition = species # type: ignore self._coords: np.ndarray | None = None self.properties: dict = properties or {} @@ -361,8 +361,8 @@ def lattice(self, lattice: Lattice): self._lattice = lattice self._coords = self._lattice.get_cartesian_coords(self._frac_coords) - @property # type: ignore - def coords(self) -> np.ndarray: # type: ignore + @property + def coords(self) -> np.ndarray: """Cartesian coordinates.""" if self._coords is None: self._coords = self._lattice.get_cartesian_coords(self._frac_coords) @@ -377,7 +377,7 @@ def coords(self, coords): @property def frac_coords(self) -> np.ndarray: """Fractional coordinates.""" - return self._frac_coords # type: ignore + return self._frac_coords @frac_coords.setter def frac_coords(self, frac_coords): @@ -388,31 +388,31 @@ def frac_coords(self, frac_coords): @property def a(self) -> float: """Fractional a coordinate.""" - return self._frac_coords[0] # type: ignore + return self._frac_coords[0] @a.setter def a(self, a: float): - self._frac_coords[0] = a # type: ignore + self._frac_coords[0] = a self._coords = self._lattice.get_cartesian_coords(self._frac_coords) @property def b(self) -> float: """Fractional b coordinate.""" - return self._frac_coords[1] # type: ignore + return self._frac_coords[1] @b.setter def b(self, b: float): - self._frac_coords[1] = b # type: ignore + self._frac_coords[1] = b self._coords = self._lattice.get_cartesian_coords(self._frac_coords) @property def c(self) -> float: """Fractional c coordinate.""" - return self._frac_coords[2] # type: ignore + return self._frac_coords[2] @c.setter def c(self, c: float): - self._frac_coords[2] = c # type: ignore + self._frac_coords[2] = c self._coords = self._lattice.get_cartesian_coords(self._frac_coords) @property @@ -554,20 +554,18 @@ def __repr__(self): if self.label: name = f"{self.label} ({name})" - return ( - f"PeriodicSite: {name} " - f"({self.coords[0]:.4f}, {self.coords[1]:.4f}, {self.coords[2]:.4f}) " - f"[{self._frac_coords[0]:.4f}, {self._frac_coords[1]:.4f}, {self._frac_coords[2]:.4f}]" - ) + x, y, z = self.coords + x_frac, y_frac, z_frac = self.frac_coords + cls_name = type(self).__name__ + return f"{cls_name}: {name} ({x:.4}, {y:.4}, {z:.4}) [{x_frac:.4}, {y_frac:.4}, {z_frac:.4}]" def as_dict(self, verbosity: int = 0) -> dict: """ JSON-serializable dict representation of PeriodicSite. Args: - verbosity (int): Verbosity level. Default of 0 only includes the - matrix representation. Set to 1 for more details such as - Cartesian coordinates, etc. + verbosity (int): Verbosity level. Default of 0 only includes the matrix + representation. Set to 1 for more details such as Cartesian coordinates, etc. """ species_list = [] for spec, occu in self._species.items(): @@ -595,12 +593,12 @@ def as_dict(self, verbosity: int = 0) -> dict: return dct @classmethod - def from_dict(cls, d, lattice=None) -> PeriodicSite: + def from_dict(cls, dct, lattice=None) -> PeriodicSite: """ Create PeriodicSite from dict representation. Args: - d (dict): dict representation of PeriodicSite + dct (dict): dict representation of PeriodicSite lattice: Optional lattice to override lattice specified in d. Useful for ensuring all sites in a structure share the same lattice. @@ -609,7 +607,7 @@ def from_dict(cls, d, lattice=None) -> PeriodicSite: PeriodicSite """ species = {} - for sp_occu in d["species"]: + for sp_occu in dct["species"]: if "oxidation_state" in sp_occu and Element.is_valid_symbol(sp_occu["element"]): sp = Species.from_dict(sp_occu) elif "oxidation_state" in sp_occu: @@ -617,10 +615,10 @@ def from_dict(cls, d, lattice=None) -> PeriodicSite: else: sp = Element(sp_occu["element"]) # type: ignore species[sp] = sp_occu["occu"] - props = d.get("properties") + props = dct.get("properties") if props is not None: for key in props: props[key] = json.loads(json.dumps(props[key], cls=MontyEncoder), cls=MontyDecoder) - label = d.get("label") - lattice = lattice or Lattice.from_dict(d["lattice"]) - return cls(species, d["abc"], lattice, properties=props, label=label) + label = dct.get("label") + lattice = lattice or Lattice.from_dict(dct["lattice"]) + return cls(species, dct["abc"], lattice, properties=props, label=label) diff --git a/pymatgen/core/tests/test_sites.py b/pymatgen/core/tests/test_sites.py index cd5ba60e26b..93689a01620 100644 --- a/pymatgen/core/tests/test_sites.py +++ b/pymatgen/core/tests/test_sites.py @@ -93,7 +93,7 @@ def setUp(self): self.lattice, properties={"magmom": 5.1, "charge": 4.2}, ) - self.labeled_site = PeriodicSite("Fe", [0.25, 0.35, 0.45], self.lattice, label="Fe2") + self.labeled_site = PeriodicSite("Fe", [0.25, 0.35, 0.45], self.lattice, label="site label") self.dummy_site = PeriodicSite("X", [0, 0, 0], self.lattice) def test_properties(self): @@ -220,7 +220,9 @@ def test_setters(self): def test_repr(self): assert repr(self.propertied_site) == "PeriodicSite: Fe2+ (2.5000, 3.5000, 4.5000) [0.2500, 0.3500, 0.4500]" - assert repr(self.labeled_site) == "PeriodicSite: Fe2 (Fe) (2.5000, 3.5000, 4.5000) [0.2500, 0.3500, 0.4500]" + assert ( + repr(self.labeled_site) == "PeriodicSite: site label (Fe) (2.5000, 3.5000, 4.5000) [0.2500, 0.3500, 0.4500]" + ) def get_distance_and_image_old(site1, site2, jimage=None): From 64ac96af4d99e8549ac0c03c740f0b23e45fdbc9 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 18:35:56 -0700 Subject: [PATCH 08/14] fix TransformedPDEntryTest.test_str --- pymatgen/analysis/phase_diagram.py | 5 ++--- pymatgen/analysis/tests/test_phase_diagram.py | 12 +++++------- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index 60c56214a1f..0133685c6af 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -270,13 +270,12 @@ def as_dict(self): Returns: MSONable dictionary representation of TransformedPDEntry. """ - d = { + return { "@module": type(self).__module__, "@class": type(self).__name__, "sp_mapping": self.sp_mapping, + **self.original_entry.as_dict(), } - d.update(self.original_entry.as_dict()) - return d @classmethod def from_dict(cls, d): diff --git a/pymatgen/analysis/tests/test_phase_diagram.py b/pymatgen/analysis/tests/test_phase_diagram.py index fd99df9fe64..ee4c8456ddd 100644 --- a/pymatgen/analysis/tests/test_phase_diagram.py +++ b/pymatgen/analysis/tests/test_phase_diagram.py @@ -138,10 +138,8 @@ def test_to_from_dict(self): assert entry.energy_per_atom == approx(53.0 / (23 / 15)) def test_str(self): - assert ( - str(self.transformed_entry) == "TransformedPDEntry Xf0+0.46666667 Xg0+1.0 Xh0+0.06666667 " - "with original composition Li1 Fe1 O2, energy = 53.0000" - ) + assert str(self.transformed_entry).startswith("TransformedPDEntry Xf0+0.46666667 Xg") + assert str(self.transformed_entry).endswith("with original composition Li1 Fe1 O2, energy = 53.0000") def test_normalize(self): norm_entry = self.transformed_entry.normalize(mode="atom") @@ -178,14 +176,14 @@ def test_repr(self): def test_dim1(self): # Ensure that dim 1 PDs can be generated. - for el in ["Li", "Fe", "O2"]: + for el in ("Li", "Fe", "O2"): entries = [entry for entry in self.entries if entry.composition.reduced_formula == el] pd = PhaseDiagram(entries) assert len(pd.stable_entries) == 1 for entry in entries: - ehull = pd.get_e_above_hull(entry) - assert ehull >= 0 + e_hull = pd.get_e_above_hull(entry) + assert e_hull >= 0 plotter = PDPlotter(pd) lines, *_ = plotter.pd_plot_data From f61268f09c9163f24e6be03d5d6e3f4073fe2033 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 18:41:39 -0700 Subject: [PATCH 09/14] better TransformedPDEntry.test_is_element --- pymatgen/analysis/phase_diagram.py | 3 +-- pymatgen/analysis/tests/test_phase_diagram.py | 21 +++++++++++-------- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index 0133685c6af..91da2c56851 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -220,8 +220,7 @@ def __init__(self, entry, sp_mapping, name=None): """ Args: entry (PDEntry): Original entry to be transformed. - sp_mapping ({Composition: DummySpecies}): dictionary - mapping Terminal Compositions to Dummy Species. + sp_mapping ({Composition: DummySpecies}): dictionary mapping Terminal Compositions to Dummy Species. """ super().__init__( entry.composition, diff --git a/pymatgen/analysis/tests/test_phase_diagram.py b/pymatgen/analysis/tests/test_phase_diagram.py index ee4c8456ddd..bd883118f9b 100644 --- a/pymatgen/analysis/tests/test_phase_diagram.py +++ b/pymatgen/analysis/tests/test_phase_diagram.py @@ -59,10 +59,10 @@ def test_get_name(self): def test_get_composition(self): comp = self.entry.composition expected_comp = Composition("LiFeO2") - assert comp == expected_comp, "Wrong composition!" + assert comp == expected_comp comp = self.gpentry.composition expected_comp = Composition("LiFe") - assert comp == expected_comp, "Wrong composition!" + assert comp == expected_comp def test_is_element(self): assert not self.entry.is_element @@ -108,8 +108,8 @@ def setUp(self): terminal_compositions = [Composition(c) for c in terminal_compositions] sp_mapping = {} - for i, comp in enumerate(terminal_compositions): - sp_mapping[comp] = DummySpecies("X" + chr(102 + i)) + for idx, comp in enumerate(terminal_compositions): + sp_mapping[comp] = DummySpecies("X" + chr(102 + idx)) self.transformed_entry = TransformedPDEntry(entry, sp_mapping) @@ -126,16 +126,19 @@ def test_get_name(self): def test_get_composition(self): comp = self.transformed_entry.composition expected_comp = Composition({DummySpecies("Xf"): 14 / 30, DummySpecies("Xg"): 1.0, DummySpecies("Xh"): 2 / 30}) - assert comp == expected_comp, "Wrong composition!" + assert comp == expected_comp def test_is_element(self): - assert not self.transformed_entry.is_element + assert self.transformed_entry.is_element is False + assert self.transformed_entry.original_entry.is_element is False + iron = Composition("Fe") + assert TransformedPDEntry(PDEntry(iron, 0), {iron: iron}).is_element is True def test_to_from_dict(self): dct = self.transformed_entry.as_dict() entry = TransformedPDEntry.from_dict(dct) - assert entry.name == "LiFeO2" - assert entry.energy_per_atom == approx(53.0 / (23 / 15)) + assert entry.name == "LiFeO2" == self.transformed_entry.name + assert entry.energy_per_atom == approx(53.0 / (23 / 15)) == self.transformed_entry.energy_per_atom def test_str(self): assert str(self.transformed_entry).startswith("TransformedPDEntry Xf0+0.46666667 Xg") @@ -146,7 +149,7 @@ def test_normalize(self): expected_comp = Composition( {DummySpecies("Xf"): 7 / 23, DummySpecies("Xg"): 15 / 23, DummySpecies("Xh"): 1 / 23} ) - assert norm_entry.composition == expected_comp, "Wrong composition!" + assert norm_entry.composition == expected_comp class PhaseDiagramTest(PymatgenTest): From 7f1bfb74d290b59d579c07a4990074a16ba23245 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 18:56:24 -0700 Subject: [PATCH 10/14] breaking: remove pltshow=True kwarg from ConnectedComponent.show_graph fix mypy --- .../chemenv/connectivity/connected_components.py | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index d5d10545162..27416584991 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -527,13 +527,17 @@ def make_supergraph(self, multiplicity): """ return make_supergraph(self._connected_subgraph, multiplicity, self._periodicity_vectors) - def show_graph(self, graph=None, save_file=None, drawing_type="internal", pltshow=True) -> None: + def show_graph( + self, graph: nx.MultiGraph | None = None, save_file: str | None = None, drawing_type: str = "internal" + ) -> None: """ + Displays the graph using the specified drawing type. + Args: - graph (): - save_file (): - drawing_type (): - pltshow (): + graph (Graph, optional): The graph to display. If not provided, the current graph is used. + save_file (str, optional): The file path to save the graph image to. + If not provided, the graph is not saved. + drawing_type (str): The type of drawing to use. Can be "internal" or "external". """ import matplotlib.pyplot as plt @@ -559,8 +563,6 @@ def show_graph(self, graph=None, save_file=None, drawing_type="internal", pltsho import networkx networkx.draw_random(shown_graph) - if pltshow: - plt.show() @property def graph(self): From d1e2e05055b7366c989cdcde92e7f8c0ec7c1b2c Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 19:02:10 -0700 Subject: [PATCH 11/14] fix test broken by PeriodicSite.__repr__ dropping redundant float precision --- pymatgen/analysis/local_env.py | 4 ++-- pymatgen/analysis/magnetism/tests/test_analyzer.py | 8 ++++---- pymatgen/core/sites.py | 2 +- pymatgen/core/tests/test_sites.py | 6 ++---- 4 files changed, 9 insertions(+), 11 deletions(-) diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index ca32b1a25d3..f13defb0543 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -208,8 +208,8 @@ def _handle_disorder(structure: Structure, on_disorder: on_disorder_options): raise ValueError( f"Generating StructureGraphs for disordered Structures is unsupported. Pass on_disorder='take " "majority' | 'take_max_species' | 'error'. 'take_majority_strict' considers only the majority species from " - "each site in the bonding algorithm and raises ValueError in case there is no majority (e.g. as in {{Fe: " - "0.4, O: 0.4, C: 0.2}}) whereas 'take_majority_drop' just ignores the site altogether when computing bonds " + "each site in the bonding algorithm and raises ValueError in case there is no majority (e.g. as in {Fe: " + "0.4, O: 0.4, C: 0.2}) whereas 'take_majority_drop' just ignores the site altogether when computing bonds " "as if it didn't exist. 'take_max_species' extracts the first max species on each site (Fe in prev. " "example since Fe and O have equal occupancy and Fe comes first). 'error' raises an error in case " f"of disordered structure. Offending {structure = }" diff --git a/pymatgen/analysis/magnetism/tests/test_analyzer.py b/pymatgen/analysis/magnetism/tests/test_analyzer.py index cde7cf00901..8f92161290e 100644 --- a/pymatgen/analysis/magnetism/tests/test_analyzer.py +++ b/pymatgen/analysis/magnetism/tests/test_analyzer.py @@ -212,10 +212,10 @@ def test_str(self): B : 0.0 0.0 -4.17 C : -2.085 2.085 0.0 Magmoms Sites -+5.00 PeriodicSite: Ni (0.0000, 0.0000, 0.0000) [0.0000, 0.0000, 0.0000] - PeriodicSite: O (0.0000, 0.0000, -2.0850) [0.0000, 0.5000, 0.0000] - PeriodicSite: O (0.0000, 2.0850, 0.0000) [0.5000, 0.0000, 0.5000] --5.00 PeriodicSite: Ni (0.0000, 2.0850, -2.0850) [0.5000, 0.5000, 0.5000]""" ++5.00 PeriodicSite: Ni (0.0, 0.0, 0.0) [0.0, 0.0, 0.0] + PeriodicSite: O (0.0, 0.0, -2.085) [0.0, 0.5, 0.0] + PeriodicSite: O (0.0, 2.085, 0.0) [0.5, 0.0, 0.5] +-5.00 PeriodicSite: Ni (0.0, 2.085, -2.085) [0.5, 0.5, 0.5]""" # just compare lines form 'Magmoms Sites', # since lattice param string can vary based on machine precision diff --git a/pymatgen/core/sites.py b/pymatgen/core/sites.py index 4a8c05622e5..9777e5ee325 100644 --- a/pymatgen/core/sites.py +++ b/pymatgen/core/sites.py @@ -555,7 +555,7 @@ def __repr__(self): name = f"{self.label} ({name})" x, y, z = self.coords - x_frac, y_frac, z_frac = self.frac_coords + x_frac, y_frac, z_frac = map(float, self.frac_coords) cls_name = type(self).__name__ return f"{cls_name}: {name} ({x:.4}, {y:.4}, {z:.4}) [{x_frac:.4}, {y_frac:.4}, {z_frac:.4}]" diff --git a/pymatgen/core/tests/test_sites.py b/pymatgen/core/tests/test_sites.py index 93689a01620..82944acada0 100644 --- a/pymatgen/core/tests/test_sites.py +++ b/pymatgen/core/tests/test_sites.py @@ -219,10 +219,8 @@ def test_setters(self): self.assert_all_close(site.frac_coords, [0.015, 0.0325, 0.05]) def test_repr(self): - assert repr(self.propertied_site) == "PeriodicSite: Fe2+ (2.5000, 3.5000, 4.5000) [0.2500, 0.3500, 0.4500]" - assert ( - repr(self.labeled_site) == "PeriodicSite: site label (Fe) (2.5000, 3.5000, 4.5000) [0.2500, 0.3500, 0.4500]" - ) + assert repr(self.propertied_site) == "PeriodicSite: Fe2+ (2.5, 3.5, 4.5) [0.25, 0.35, 0.45]" + assert repr(self.labeled_site) == "PeriodicSite: site label (Fe) (2.5, 3.5, 4.5) [0.25, 0.35, 0.45]" def get_distance_and_image_old(site1, site2, jimage=None): From c7a6b72a187265e991b76a8e4161a7a0db1f96fb Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 19:09:56 -0700 Subject: [PATCH 12/14] fix mypy --- pymatgen/analysis/chemenv/connectivity/connected_components.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index 27416584991..7b1ad755f7d 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -480,7 +480,7 @@ def compute_periodicity_cycle_basis(self) -> None: """Compute periodicity vectors of the connected component.""" my_simple_graph = nx.Graph(self._connected_subgraph) cycles = nx.cycle_basis(my_simple_graph) - all_deltas = [] + all_deltas: list[list] = [] for cyc in map(list, cycles): cyc.append(cyc[0]) this_cycle_deltas = [np.zeros(3, int)] From 5e7fa8ff8b452ef3925b4648c1df2d0f69e32620 Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 19:26:02 -0700 Subject: [PATCH 13/14] fix > assert self.labeled_site.label == "Fe2" E AssertionError: assert 'site label' == 'Fe2' --- pymatgen/core/tests/test_sites.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pymatgen/core/tests/test_sites.py b/pymatgen/core/tests/test_sites.py index 82944acada0..5fe23dd870f 100644 --- a/pymatgen/core/tests/test_sites.py +++ b/pymatgen/core/tests/test_sites.py @@ -109,7 +109,7 @@ def test_properties(self): assert not self.site2.is_ordered assert self.propertied_site.properties["magmom"] == 5.1 assert self.propertied_site.properties["charge"] == 4.2 - assert self.labeled_site.label == "Fe2" + assert self.labeled_site.label == "site label" def test_distance(self): other_site = PeriodicSite("Fe", np.array([0, 0, 0]), self.lattice) From bed8b51990786e2a6e909fd86835f889ccb900ea Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Wed, 19 Jul 2023 20:50:03 -0700 Subject: [PATCH 14/14] mypy ignore --- .../analysis/chemenv/connectivity/connected_components.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index 7b1ad755f7d..3375142ab9a 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -491,7 +491,7 @@ def compute_periodicity_cycle_basis(self) -> None: for current_delta in this_cycle_deltas: this_cycle_deltas_new.append(current_delta + delta) this_cycle_deltas = this_cycle_deltas_new - all_deltas.extend(this_cycle_deltas) + all_deltas.extend(this_cycle_deltas) # type: ignore all_deltas = get_linearly_independent_vectors(all_deltas) if len(all_deltas) == 3: return @@ -509,7 +509,7 @@ def compute_periodicity_cycle_basis(self) -> None: current_delta = get_delta(n1, n2, e1data) delta = get_delta(n2, n1, e2data) current_delta += delta - all_deltas.append(current_delta) + all_deltas.append(current_delta) # type: ignore else: raise ValueError("Should not be here ...") all_deltas = get_linearly_independent_vectors(all_deltas)