diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index beaf271d3b7..1aa0926e4aa 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -6,7 +6,7 @@ ci: repos: - repo: https://github.com/PyCQA/autoflake - rev: v2.0.0 + rev: v2.0.1 hooks: - id: autoflake @@ -25,13 +25,13 @@ repos: - id: trailing-whitespace - repo: https://github.com/PyCQA/isort - rev: 5.11.4 + rev: 5.12.0 hooks: - id: isort args: [--profile, black] - repo: https://github.com/psf/black - rev: 22.12.0 + rev: 23.1.0 hooks: - id: black @@ -65,13 +65,13 @@ repos: args: [--ignore-words-list, 'titel,titels,reson,rute,pres,kno,coo'] - repo: https://github.com/PyCQA/pydocstyle - rev: 6.1.1 + rev: 6.3.0 hooks: - id: pydocstyle exclude: tests - repo: https://github.com/MarcoGorelli/cython-lint - rev: v0.10.1 + rev: v0.11.1 hooks: - id: cython-lint args: [--no-pycodestyle] diff --git a/dev_scripts/chemenv/equivalent_indices.py b/dev_scripts/chemenv/equivalent_indices.py index 5f5b830f4ab..3e43e114e87 100644 --- a/dev_scripts/chemenv/equivalent_indices.py +++ b/dev_scripts/chemenv/equivalent_indices.py @@ -17,7 +17,6 @@ __date__ = "Feb 20, 2016" if __name__ == "__main__": - cg_symbol = "O:6" equiv_list = [] diff --git a/dev_scripts/chemenv/explicit_permutations.py b/dev_scripts/chemenv/explicit_permutations.py index eae9eea806e..71ad211fa22 100644 --- a/dev_scripts/chemenv/explicit_permutations.py +++ b/dev_scripts/chemenv/explicit_permutations.py @@ -36,7 +36,6 @@ class Algo: if __name__ == "__main__": - # Choose the geometry allcg = AllCoordinationGeometries() while True: diff --git a/dev_scripts/chemenv/explicit_permutations_plane_algorithm.py b/dev_scripts/chemenv/explicit_permutations_plane_algorithm.py index 5cac089aecd..0b1a9467cb1 100644 --- a/dev_scripts/chemenv/explicit_permutations_plane_algorithm.py +++ b/dev_scripts/chemenv/explicit_permutations_plane_algorithm.py @@ -23,7 +23,6 @@ from pymatgen.analysis.chemenv.utils.coordination_geometry_utils import Plane, collinear if __name__ == "__main__": - # Choose the geometry allcg = AllCoordinationGeometries() while True: diff --git a/dev_scripts/chemenv/get_plane_permutations_optimized.py b/dev_scripts/chemenv/get_plane_permutations_optimized.py index 15064fae49d..028c807d5ae 100644 --- a/dev_scripts/chemenv/get_plane_permutations_optimized.py +++ b/dev_scripts/chemenv/get_plane_permutations_optimized.py @@ -343,7 +343,6 @@ def random_permutations_iterator(initial_permutation, n_permutations): t0 = time.process_time() timeleft = "Unknown" for indices_perm in perms_iterator: - prt1( string=f"Perm # {iperm:d}/{npermutations:d} : " f"{'-'.join(map(str, indices_perm))} " diff --git a/dev_scripts/chemenv/plane_multiplicity.py b/dev_scripts/chemenv/plane_multiplicity.py index 76a59cdd676..80557c23fea 100644 --- a/dev_scripts/chemenv/plane_multiplicity.py +++ b/dev_scripts/chemenv/plane_multiplicity.py @@ -19,7 +19,6 @@ __date__ = "Feb 20, 2016" if __name__ == "__main__": - allcg = AllCoordinationGeometries() cg_symbol = "I:12" diff --git a/dev_scripts/chemenv/test_algos.py b/dev_scripts/chemenv/test_algos.py index 297be2611a9..00441178cbd 100644 --- a/dev_scripts/chemenv/test_algos.py +++ b/dev_scripts/chemenv/test_algos.py @@ -30,7 +30,6 @@ __date__ = "Feb 20, 2016" if __name__ == "__main__": - allcg = AllCoordinationGeometries() while True: @@ -68,7 +67,6 @@ iperm = 1 t1 = time.clock() for indices_perm in perms_iterator: - lgf.setup_test_perfect_environment(cg_symbol, indices=indices_perm) lgf.perfect_geometry = AbstractGeometry.from_cg(cg=cg) diff --git a/dev_scripts/chemenv/test_algos_all_geoms.py b/dev_scripts/chemenv/test_algos_all_geoms.py index 99b0a8de375..d9e7a852a99 100644 --- a/dev_scripts/chemenv/test_algos_all_geoms.py +++ b/dev_scripts/chemenv/test_algos_all_geoms.py @@ -27,7 +27,6 @@ __date__ = "Feb 20, 2016" if __name__ == "__main__": - allcg = AllCoordinationGeometries() test = input('Standard ("s", all permutations for cn <= 6, 500 random permutations for cn > 6) or on demand') @@ -96,7 +95,6 @@ # Loop on the permutations iperm = 1 for indices_perm in perms_iterator: - lgf.setup_test_perfect_environment( cg_symbol, indices=indices_perm, diff --git a/pymatgen/analysis/adsorption.py b/pymatgen/analysis/adsorption.py index b3f47e0bd93..ed1669864fd 100644 --- a/pymatgen/analysis/adsorption.py +++ b/pymatgen/analysis/adsorption.py @@ -496,7 +496,6 @@ def adsorb_both_surfaces( new_ad_slabss = [] for ad_slabs in ad_slabss: - # Find the adsorbate sites and indices in each slab _, adsorbates, indices = False, [], [] for i, site in enumerate(ad_slabs.sites): diff --git a/pymatgen/analysis/bond_valence.py b/pymatgen/analysis/bond_valence.py index ddde99f1457..95b8cf930ae 100644 --- a/pymatgen/analysis/bond_valence.py +++ b/pymatgen/analysis/bond_valence.py @@ -286,7 +286,7 @@ def get_valences(self, structure): all_prob.append(prob) full_all_prob.extend(prob.values()) vals = [] - for (elsp, _) in get_z_ordered_elmap(test_site.species): + for elsp, _ in get_z_ordered_elmap(test_site.species): val = list(prob[elsp.symbol]) # Sort valences in order of decreasing probability. val = sorted(val, key=lambda v: -prob[elsp.symbol][v]) diff --git a/pymatgen/analysis/chemenv/connectivity/connected_components.py b/pymatgen/analysis/chemenv/connectivity/connected_components.py index ea88d14581e..0e6e158b26e 100644 --- a/pymatgen/analysis/chemenv/connectivity/connected_components.py +++ b/pymatgen/analysis/chemenv/connectivity/connected_components.py @@ -41,7 +41,7 @@ def draw_network(env_graph, pos, ax, sg=None, periodicity_vectors=None): ax.annotate(str(n), pos[n], ha="center", va="center", xycoords="data") seen = {} e = None - for (u, v, d) in env_graph.edges(data=True): + for u, v, d in env_graph.edges(data=True): n1 = env_graph.node[u]["patch"] n2 = env_graph.node[v]["patch"] rad = 0.1 @@ -147,7 +147,7 @@ def make_supergraph(graph, multiplicity, periodicity_vectors): edges = graph.edges(data=True, keys=True) connecting_edges = [] other_edges = [] - for (n1, n2, key, data) in edges: + for n1, n2, key, data in edges: print(n1, n2, key, data) if np.all(np.array(data["delta"]) == np.array(periodicity_vectors[0])): connecting_edges.append((n1, n2, key, data)) @@ -457,7 +457,7 @@ def compute_periodicity_all_simple_paths_algorithm(self): # TODO: there are some paths that appears twice for cycles, and there are some paths that should # probably not be considered this_path_deltas = [np.zeros(3, int)] - for (node1, node2) in [(node1, path[inode1 + 1]) for inode1, node1 in enumerate(path[:-1])]: + for node1, node2 in [(node1, path[inode1 + 1]) for inode1, node1 in enumerate(path[:-1])]: this_path_deltas_new = [] for edge_data in self._connected_subgraph[node1][node2].values(): delta = get_delta(node1, node2, edge_data) @@ -496,7 +496,7 @@ def compute_periodicity_cycle_basis(self): mycyc = list(cyc) mycyc.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, mycyc[inode1 + 1]) for inode1, node1 in enumerate(mycyc[:-1])]: this_cycle_deltas_new = [] for edge_data in self._connected_subgraph[node1][node2].values(): delta = get_delta(node1, node2, edge_data) diff --git a/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py b/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py index ff3d0614d26..dcaf4b1758a 100644 --- a/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py +++ b/pymatgen/analysis/chemenv/connectivity/structure_connectivity.py @@ -122,7 +122,7 @@ def add_bonds(self, isite, site_neighbors_set): break else: if isite == nb_index_unitcell: - for (isite1, ineighb1, data1) in existing_edges: + for isite1, ineighb1, data1 in existing_edges: if isite1 == ineighb1: if np.allclose(data1["delta"], nb_image_cell) or np.allclose( data1["delta"], -nb_image_cell @@ -316,7 +316,7 @@ def print_links(self): print("Links in graph :") for node in nodes: print(node.isite, " is connected with : ") - for (n1, n2, data) in self.environment_subgraph().edges(node, data=True): + for n1, n2, data in self.environment_subgraph().edges(node, data=True): if n1.isite == data["start"]: print( f" - {n2.isite} by {len(data['ligands'])} ligands ({data['delta'][0]} " diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py index 947620b834c..1340e884e98 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometry_finder.py @@ -1427,7 +1427,6 @@ def coordination_geometry_symmetry_measures_standard( local2perfect_maps = [] perfect2local_maps = [] for iperm, perm in enumerate(algo.permutations): - local2perfect_map = {} perfect2local_map = {} permutations.append(perm) diff --git a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py index 056343b291e..b1f9cd27530 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py +++ b/pymatgen/analysis/chemenv/coordination_environments/structure_environments.py @@ -1266,7 +1266,6 @@ def differences_wrt(self, other): return differences def __eq__(self, other: object) -> bool: - if not isinstance(other, StructureEnvironments): return NotImplemented diff --git a/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py b/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py index 9c369b58970..cc5fac45b49 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py +++ b/pymatgen/analysis/chemenv/coordination_environments/tests/test_weights.py @@ -545,7 +545,6 @@ def test_delta_csms_weight(self): assert abs(delta_w - 1.0) < 1e-8 def test_dist_angle_area_weight(self): - surface_definition = { "type": "standard_elliptic", "distance_bounds": {"lower": 1.2, "upper": 1.8}, @@ -589,7 +588,6 @@ def test_dist_angle_area_weight(self): assert da_area_weight.rectangle_crosses_area(d1=d1, d2=d2, a1=a1, a2=a2) def test_dist_nb_set_weight(self): - dnbset_weight = DistanceNbSetWeight() dnbset_weight2 = DistanceNbSetWeight( weight_function={ diff --git a/pymatgen/analysis/chemenv/coordination_environments/voronoi.py b/pymatgen/analysis/chemenv/coordination_environments/voronoi.py index 4a7bb0e63a9..e39a0cf408c 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/voronoi.py +++ b/pymatgen/analysis/chemenv/coordination_environments/voronoi.py @@ -583,7 +583,7 @@ def maps_and_surfaces( for cn, value in self._unique_coordinated_neighbors_parameters_indices[isite].items(): # pylint: disable=E1101 for imap, list_parameters_indices in enumerate(value): thissurf = 0.0 - for (idp, iap, iacb) in list_parameters_indices: + for idp, iap, iacb in list_parameters_indices: if iacb in additional_conditions: thissurf += surfaces[idp, iap] maps_and_surfaces.append( @@ -617,7 +617,7 @@ def maps_and_surfaces_bounded(self, isite, surface_calculation_options=None, add for cn, value in self._unique_coordinated_neighbors_parameters_indices[isite].items(): # pylint: disable=E1101 for imap, list_parameters_indices in enumerate(value): thissurf = 0.0 - for (idp, iap, iacb) in list_parameters_indices: + for idp, iap, iacb in list_parameters_indices: if iacb in additional_conditions: thissurf += surfaces[idp, iap] maps_and_surfaces.append( diff --git a/pymatgen/analysis/chemenv/utils/graph_utils.py b/pymatgen/analysis/chemenv/utils/graph_utils.py index fa4d5328421..3789fbf50b5 100644 --- a/pymatgen/analysis/chemenv/utils/graph_utils.py +++ b/pymatgen/analysis/chemenv/utils/graph_utils.py @@ -56,7 +56,7 @@ def get_all_simple_paths_edges(graph, source, target, cutoff=None, data=True): continue node_paths.append(path) current_edge_paths = [[]] - for (node1, node2) in [(node1, path[inode1 + 1]) for inode1, node1 in enumerate(path[:-1])]: + for node1, node2 in [(node1, path[inode1 + 1]) for inode1, node1 in enumerate(path[:-1])]: new_edge_paths = [] for key, edge_data in graph[node1][node2].items(): for tmp_edge_path in current_edge_paths: diff --git a/pymatgen/analysis/diffraction/core.py b/pymatgen/analysis/diffraction/core.py index fc7a437785d..661d16d18cb 100644 --- a/pymatgen/analysis/diffraction/core.py +++ b/pymatgen/analysis/diffraction/core.py @@ -224,6 +224,7 @@ def get_unique_families(hkls): Returns: {hkl: multiplicity}: A dict with unique hkl and multiplicity. """ + # TODO: Definitely can be sped up. def is_perm(hkl1, hkl2) -> bool: h1 = np.abs(hkl1) diff --git a/pymatgen/analysis/diffraction/neutron.py b/pymatgen/analysis/diffraction/neutron.py index c4505f1a2b2..10e3d47a1a0 100644 --- a/pymatgen/analysis/diffraction/neutron.py +++ b/pymatgen/analysis/diffraction/neutron.py @@ -140,7 +140,6 @@ def get_pattern(self, structure: Structure, scaled=True, two_theta_range=(0, 90) # Force miller indices to be integers. hkl = [int(round(i)) for i in hkl] if g_hkl != 0: - d_hkl = 1 / g_hkl # Bragg condition diff --git a/pymatgen/analysis/diffraction/xrd.py b/pymatgen/analysis/diffraction/xrd.py index b0af7408a75..686a4e5baf3 100644 --- a/pymatgen/analysis/diffraction/xrd.py +++ b/pymatgen/analysis/diffraction/xrd.py @@ -214,7 +214,6 @@ def get_pattern(self, structure: Structure, scaled=True, two_theta_range=(0, 90) # Force miller indices to be integers. hkl = [int(round(i)) for i in hkl] if g_hkl != 0: - # Bragg condition theta = asin(wavelength * g_hkl / 2) diff --git a/pymatgen/analysis/dimensionality.py b/pymatgen/analysis/dimensionality.py index 4567b169a32..ad5231addf5 100644 --- a/pymatgen/analysis/dimensionality.py +++ b/pymatgen/analysis/dimensionality.py @@ -229,7 +229,6 @@ def rank_increase(seen, candidate): seen_comp_vertices[comp_i].add(image_i) for comp_j, image_j in connected_sites[comp_i]: - image_j = tuple(np.add(image_j, image_i)) if (comp_j, image_j) in seen_vertices: @@ -280,7 +279,6 @@ def zero_d_graph_to_molecule_graph(bonded_structure, graph): sites.append(site_i) for site_j in bonded_structure.get_connected_sites(comp_i, jimage=image_i): - if (site_j.index, site_j.jimage) not in seen_indices and ( site_j.index, site_j.jimage, diff --git a/pymatgen/analysis/elasticity/elastic.py b/pymatgen/analysis/elasticity/elastic.py index 4ddc1ff4fdb..375aa9cf758 100644 --- a/pymatgen/analysis/elasticity/elastic.py +++ b/pymatgen/analysis/elasticity/elastic.py @@ -97,14 +97,18 @@ def energy_density(self, strain, convert_GPa_to_eV=True): @classmethod def from_diff_fit(cls, strains, stresses, eq_stress=None, order=2, tol: float = 1e-10): """ + Takes a list of strains and stresses, and returns a list of coefficients for a + polynomial fit of the given order. + Args: - strains (): - stresses (): - eq_stress (): - order (): - tol (): + strains: a list of strain values + stresses: the stress values + eq_stress: The stress at which the material is assumed to be elastic. + order: The order of the polynomial to fit. Defaults to 2 + tol (float): tolerance for the fit. Returns: + NthOrderElasticTensor: the fitted elastic tensor """ return cls(diff_fit(strains, stresses, eq_stress, order, tol)[order - 2]) @@ -160,7 +164,7 @@ def __new__(cls, input_array, tol: float = 1e-4): @property def compliance_tensor(self): """ - returns the Voigt-notation compliance tensor, + Returns the Voigt-notation compliance tensor, which is the matrix inverse of the Voigt-notation elastic tensor """ @@ -170,14 +174,14 @@ def compliance_tensor(self): @property def k_voigt(self): """ - returns the K_v bulk modulus + Returns the K_v bulk modulus """ return self.voigt[:3, :3].mean() @property def g_voigt(self): """ - returns the G_v shear modulus + Returns the G_v shear modulus """ return ( 2.0 * self.voigt[:3, :3].trace() - np.triu(self.voigt[:3, :3]).sum() + 3 * self.voigt[3:, 3:].trace() @@ -186,14 +190,14 @@ def g_voigt(self): @property def k_reuss(self): """ - returns the K_r bulk modulus + Returns the K_r bulk modulus """ return 1.0 / self.compliance_tensor.voigt[:3, :3].sum() @property def g_reuss(self): """ - returns the G_r shear modulus + Returns the G_r shear modulus """ return 15.0 / ( 8.0 * self.compliance_tensor.voigt[:3, :3].trace() @@ -204,14 +208,14 @@ def g_reuss(self): @property def k_vrh(self): """ - returns the K_vrh (Voigt-Reuss-Hill) average bulk modulus + Returns the K_vrh (Voigt-Reuss-Hill) average bulk modulus """ return 0.5 * (self.k_voigt + self.k_reuss) @property def g_vrh(self): """ - returns the G_vrh (Voigt-Reuss-Hill) average shear modulus + Returns the G_vrh (Voigt-Reuss-Hill) average shear modulus """ return 0.5 * (self.g_voigt + self.g_reuss) @@ -397,14 +401,14 @@ def debye_temperature(self, structure): @property def universal_anisotropy(self): """ - returns the universal anisotropy value + Returns the universal anisotropy value """ return 5.0 * self.g_voigt / self.g_reuss + self.k_voigt / self.k_reuss - 6.0 @property def homogeneous_poisson(self): """ - returns the homogeneous poisson ratio + Returns the homogeneous poisson ratio """ return (1.0 - 2.0 / 3.0 * self.g_vrh / self.k_vrh) / (2.0 + 2.0 / 3.0 * self.g_vrh / self.k_vrh) @@ -417,7 +421,7 @@ def green_kristoffel(self, u): @property def property_dict(self): """ - returns a dictionary of properties derived from the elastic tensor + Returns a dictionary of properties derived from the elastic tensor """ props = [ "k_voigt", @@ -436,7 +440,7 @@ def get_structure_property_dict( self, structure: Structure, include_base_props: bool = True, ignore_errors: bool = False ) -> dict[str, float | Structure | None]: """ - returns a dictionary of properties derived from the elastic tensor + Returns a dictionary of properties derived from the elastic tensor and an associated structure Args: diff --git a/pymatgen/analysis/elasticity/stress.py b/pymatgen/analysis/elasticity/stress.py index 3be158950fd..d8e0fa6e7b0 100644 --- a/pymatgen/analysis/elasticity/stress.py +++ b/pymatgen/analysis/elasticity/stress.py @@ -48,7 +48,7 @@ def __new__(cls, stress_matrix): @property def dev_principal_invariants(self): """ - returns the principal invariants of the deviatoric stress tensor, + Returns the principal invariants of the deviatoric stress tensor, which is calculated by finding the coefficients of the characteristic polynomial of the stress tensor minus the identity times the mean stress @@ -58,7 +58,7 @@ def dev_principal_invariants(self): @property def von_mises(self): """ - returns the von mises stress + Returns the von mises stress """ if not self.is_symmetric(): raise ValueError( @@ -69,14 +69,14 @@ def von_mises(self): @property def mean_stress(self): """ - returns the mean stress + Returns the mean stress """ return 1.0 / 3.0 * self.trace() @property def deviator_stress(self): """ - returns the deviatoric component of the stress + Returns the deviatoric component of the stress """ if not self.is_symmetric: raise ValueError("The stress tensor is not symmetric, so deviator stress will not be either") @@ -84,7 +84,7 @@ def deviator_stress(self): def piola_kirchoff_1(self, def_grad): """ - calculates the first Piola-Kirchoff stress + Calculates the first Piola-Kirchoff stress Args: def_grad (3x3 array-like): deformation gradient tensor @@ -99,7 +99,7 @@ def piola_kirchoff_1(self, def_grad): def piola_kirchoff_2(self, def_grad): """ - calculates the second Piola-Kirchoff stress + Calculates the second Piola-Kirchoff stress Args: def_grad (3x3 array-like): rate of deformation tensor diff --git a/pymatgen/analysis/elasticity/tests/test_elastic.py b/pymatgen/analysis/elasticity/tests/test_elastic.py index 5a9902d3f97..7fb6fb82f69 100644 --- a/pymatgen/analysis/elasticity/tests/test_elastic.py +++ b/pymatgen/analysis/elasticity/tests/test_elastic.py @@ -204,7 +204,6 @@ def test_from_independent_strains(self): self.assertArrayAlmostEqual(et.voigt, self.toec_dict["C2_raw"], decimal=-1) def test_energy_density(self): - film_elac = ElasticTensor.from_voigt( [ [324.32, 187.3, 170.92, 0.0, 0.0, 0.0], diff --git a/pymatgen/analysis/eos.py b/pymatgen/analysis/eos.py index 0685331dbda..b180b2f0278 100644 --- a/pymatgen/analysis/eos.py +++ b/pymatgen/analysis/eos.py @@ -29,7 +29,7 @@ class EOSBase(metaclass=ABCMeta): """ - Abstract class that must be subcalssed by all equation of state + Abstract class that must be subclassed by all equation of state implementations. """ diff --git a/pymatgen/analysis/ewald.py b/pymatgen/analysis/ewald.py index 94f52571d41..1db3550c91c 100644 --- a/pymatgen/analysis/ewald.py +++ b/pymatgen/analysis/ewald.py @@ -351,7 +351,6 @@ def _calc_recip(self): simags = np.sum(oxistates[None, :] * np.sin(grs), 1) for g, g2, gr, expval, sreal, simag in zip(gs, g2s, grs, expvals, sreals, simags): - # 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) diff --git a/pymatgen/analysis/fragmenter.py b/pymatgen/analysis/fragmenter.py index 71b921f45d4..131543779e8 100644 --- a/pymatgen/analysis/fragmenter.py +++ b/pymatgen/analysis/fragmenter.py @@ -97,7 +97,6 @@ def __init__( self.unique_frag_dict = {} # all fragments from both the given molecule and prev_unique_frag_dict if depth == 0: # Non-iterative, find all possible fragments: - # Find all unique fragments besides those involving ring opening self.all_unique_frag_dict = self.mol_graph.build_unique_fragments() diff --git a/pymatgen/analysis/gb/grain.py b/pymatgen/analysis/gb/grain.py index 70dd7e9349a..dac510c8099 100644 --- a/pymatgen/analysis/gb/grain.py +++ b/pymatgen/analysis/gb/grain.py @@ -1859,7 +1859,6 @@ def enum_sigma_ort(cutoff, r_axis, c2_b2_a2_ratio): else: m_max = int(np.sqrt((cutoff * 4 * mu * mv * lam * mv - n**2 * d) / mu / lam)) for m in range(0, m_max + 1): - if gcd(m, n) == 1 or m == 0: # construct the rotation matrix, refer to the reference R_list = [ diff --git a/pymatgen/analysis/graphs.py b/pymatgen/analysis/graphs.py index 6316d3118e6..658883c296b 100644 --- a/pymatgen/analysis/graphs.py +++ b/pymatgen/analysis/graphs.py @@ -220,7 +220,6 @@ def with_edges(structure, edges): sg = StructureGraph.with_empty_graph(structure, name="bonds", edge_weight_name="weight", edge_weight_units="") for edge, props in edges.items(): - try: from_index = edge[0] to_index = edge[1] @@ -726,7 +725,7 @@ def map_indices(grp): func_grp.remove_species("X") if graph_dict is not None: - for (u, v) in graph_dict: + for u, v in graph_dict: edge_props = graph_dict[(u, v)] if "to_jimage" in edge_props: to_jimage = edge_props["to_jimage"] @@ -783,7 +782,6 @@ def get_connected_sites(self, n, jimage=(0, 0, 0)): in_edges = [(u, v, d, "in") for u, v, d in self.graph.in_edges(n, data=True)] for u, v, d, dir in out_edges + in_edges: - to_jimage = d["to_jimage"] if dir == "in": @@ -920,7 +918,6 @@ def draw_graph_to_file( # add display options for edges for u, v, k, d in g.edges(keys=True, data=True): - # retrieve from/to images, set as origin if not defined to_image = d["to_jimage"] @@ -987,7 +984,6 @@ def draw_graph_to_file( write_dot(g, basename + ".dot") with open(filename, "w") as f: - args = [algo, "-T", extension, basename + ".dot"] with subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) as rs: rs.communicate() @@ -1053,7 +1049,6 @@ def types_of_coordination_environments(self, anonymous=False): """ motifs = set() for idx, site in enumerate(self.structure): - centre_sp = site.species_string connected_sites = self.get_connected_sites(idx) @@ -1154,7 +1149,6 @@ def __mul__(self, scaling_matrix): new_graphs = [] for v in c_lat: - # create a map of nodes from original graph to its image mapping = {n: n + len(new_sites) for n in range(len(self.structure))} @@ -1198,12 +1192,10 @@ def __mul__(self, scaling_matrix): tol = 0.05 for u, v, k, d in new_g.edges(keys=True, data=True): - to_jimage = d["to_jimage"] # for node v # reduce unnecessary checking if to_jimage != (0, 0, 0): - # get index in original site n_u = u % len(self.structure) n_v = v % len(self.structure) @@ -1237,7 +1229,6 @@ def __mul__(self, scaling_matrix): # and if so, delete old edge that went through # periodic boundary if v_present is not None: - new_u = u new_v = v_present new_d = d.copy() @@ -1250,7 +1241,6 @@ def __mul__(self, scaling_matrix): # make sure we don't try to add duplicate edges # will remove two edges for everyone one we add if {new_u, new_v} not in edges_inside_supercell: - # normalize direction if new_v < new_u: new_u, new_v = new_v, new_u @@ -1259,7 +1249,6 @@ def __mul__(self, scaling_matrix): edges_to_add.append((new_u, new_v, new_d)) else: - # want to find new_v such that we have # full periodic boundary conditions # so that nodes on one side of supercell @@ -1278,7 +1267,6 @@ def __mul__(self, scaling_matrix): v_present = v_present[1] if v_present[0] <= tol else None if v_present is not None: - new_u = u new_v = v_present new_d = d.copy() @@ -1302,7 +1290,7 @@ def __mul__(self, scaling_matrix): # add/delete marked edges for edge in edges_to_remove: new_g.remove_edge(*edge) - for (u, v, d) in edges_to_add: + for u, v, d in edges_to_add: new_g.add_edge(u, v, **d) # return new instance of StructureGraph with supercell @@ -1322,7 +1310,6 @@ def __rmul__(self, other): @classmethod def _edges_to_string(cls, g): - header = "from to to_image " header_line = "---- ---- ------------" edge_weight_name = g.graph["edge_weight_name"] @@ -1402,7 +1389,7 @@ def sort(self, key=None, reverse=False): # add/delete marked edges for edge in edges_to_remove: self.graph.remove_edge(*edge) - for (u, v, d) in edges_to_add: + for u, v, d in edges_to_add: self.graph.add_edge(u, v, **d) def __copy__(self): @@ -1463,7 +1450,6 @@ def diff(self, other, strict=True): return ValueError("Meaningless to compare StructureGraphs if corresponding Structures are different.") if strict: - # sort for consistent node indices # PeriodicSite should have a proper __hash__() value, # using its frac_coords as a convenient key @@ -1476,7 +1462,6 @@ def diff(self, other, strict=True): edges_other = {(u, v, d["to_jimage"]) for u, v, d in other_sorted.graph.edges(keys=False, data=True)} else: - edges = { (str(self.structure[u].specie), str(self.structure[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) @@ -1554,7 +1539,6 @@ def edge_match(e1, e2): # prune duplicate subgraphs unique_subgraphs = [] for subgraph in molecule_subgraphs: - already_present = [ nx.is_isomorphic(subgraph, g, node_match=node_match, edge_match=edge_match) for g in unique_subgraphs ] @@ -1693,7 +1677,6 @@ def with_edges(molecule, edges): mg = MoleculeGraph.with_empty_graph(molecule, name="bonds", edge_weight_name="weight", edge_weight_units="") for edge, props in edges.items(): - try: from_index = edge[0] to_index = edge[1] @@ -1754,13 +1737,11 @@ def with_local_env_strategy(molecule, strategy): structure = None for n in range(len(molecule)): - if structure is None: neighbors = strategy.get_nn_info(molecule, n) else: neighbors = strategy.get_nn_info(structure, n) for neighbor in neighbors: - # all bonds in molecules should not cross # (artificial) periodic boundaries if not np.array_equal(neighbor["image"], [0, 0, 0]): @@ -2049,7 +2030,6 @@ def get_disconnected_fragments(self): subgraphs = [original.graph.subgraph(c) for c in nx.weakly_connected_components(original.graph)] for subg in subgraphs: - nodes = sorted(list(subg.nodes)) # Molecule indices are essentially list-based, so node indices @@ -2137,7 +2117,7 @@ def split_molecule_subgraphs(self, bonds, allow_reverse=False, alterations=None) # alter any bonds before partition, to avoid remapping if alterations is not None: - for (u, v) in alterations: + for u, v in alterations: if "weight" in alterations[(u, v)]: weight = alterations[(u, v)]["weight"] del alterations[(u, v)]["weight"] @@ -2283,12 +2263,11 @@ def map_indices(grp): # Work is simplified if a graph is already in place if isinstance(func_grp, MoleculeGraph): - self.molecule.substitute(index, func_grp.molecule, bond_order=bond_order) mapping = map_indices(func_grp.molecule) - for (u, v) in list(func_grp.graph.edges()): + for u, v in list(func_grp.graph.edges()): edge_props = func_grp.graph.get_edge_data(u, v)[0] weight = None if "weight" in edge_props: @@ -2313,7 +2292,7 @@ def map_indices(grp): func_grp.remove_species("X") if graph_dict is not None: - for (u, v) in graph_dict: + for u, v in graph_dict: edge_props = graph_dict[(u, v)] if "weight" in edge_props: weight = edge_props["weight"] @@ -2331,7 +2310,7 @@ def map_indices(grp): strat = strategy(**strategy_params) graph = self.with_local_env_strategy(func_grp, strat) - for (u, v) in list(graph.graph.edges()): + for u, v in list(graph.graph.edges()): edge_props = graph.graph.get_edge_data(u, v)[0] weight = None if "weight" in edge_props: @@ -2504,7 +2483,6 @@ def get_connected_sites(self, n): in_edges = list(self.graph.in_edges(n, data=True)) for u, v, d in out_edges + in_edges: - weight = d.get("weight", None) if v == n: @@ -2633,7 +2611,6 @@ def draw_graph_to_file( # add display options for edges for u, v, k, d in g.edges(keys=True, data=True): - # retrieve from/to images, set as origin if not defined if "to_image" in d: to_image = d["to_jimage"] @@ -2703,7 +2680,6 @@ def draw_graph_to_file( write_dot(g, basename + ".dot") with open(filename, "w") as f: - args = [algo, "-T", extension, basename + ".dot"] with subprocess.Popen(args, stdout=f, stdin=subprocess.PIPE, close_fds=True) as rs: rs.communicate() @@ -2740,7 +2716,6 @@ def from_dict(cls, d): @classmethod def _edges_to_string(cls, g): - header = "from to to_image " header_line = "---- ---- ------------" edge_weight_name = g.graph["edge_weight_name"] @@ -2820,7 +2795,7 @@ def sort(self, key: Callable[[Molecule], float] | None = None, reverse: bool = F # add/delete marked edges for edge in edges_to_remove: self.graph.remove_edge(*edge) - for (u, v, data) in edges_to_add: + for u, v, data in edges_to_add: self.graph.add_edge(u, v, **data) def __copy__(self): @@ -2916,7 +2891,6 @@ def diff(self, other, strict=True): } else: - edges = { (str(self.molecule[u].specie), str(self.molecule[v].specie)) for u, v, d in self.graph.edges(keys=False, data=True) diff --git a/pymatgen/analysis/interfaces/substrate_analyzer.py b/pymatgen/analysis/interfaces/substrate_analyzer.py index e1aed896655..6571b7fb6f6 100644 --- a/pymatgen/analysis/interfaces/substrate_analyzer.py +++ b/pymatgen/analysis/interfaces/substrate_analyzer.py @@ -187,7 +187,6 @@ def calculate( substrate_miller, ] in surface_vector_sets: for match in self(film_vectors, substrate_vectors, lowest): - sub_match = SubstrateMatch.from_zsl( match=match, film=film, diff --git a/pymatgen/analysis/interfaces/tests/test_coherent_interface.py b/pymatgen/analysis/interfaces/tests/test_coherent_interface.py index ad1a6d5cf56..72b94877a51 100644 --- a/pymatgen/analysis/interfaces/tests/test_coherent_interface.py +++ b/pymatgen/analysis/interfaces/tests/test_coherent_interface.py @@ -19,14 +19,12 @@ class InterfaceBuilderTest(PymatgenTest): @classmethod def setUpClass(cls): - si_struct = cls.get_structure("Si") sio2_struct = cls.get_structure("SiO2") cls.si_conventional = SpacegroupAnalyzer(si_struct).get_conventional_standard_structure() cls.sio2_conventional = SpacegroupAnalyzer(sio2_struct).get_conventional_standard_structure() def test_utils(self): - self.assertArrayAlmostEqual(from_2d_to_3d([[1, 2], [3, 4]]), [[1, 2, 0], [3, 4, 0], [0, 0, 1]]) self.assertArrayAlmostEqual(get_2d_transform([[1, 0], [0, 1]], [[1, 2], [3, 4]]), [[1, 2], [3, 4]]) self.assertArrayAlmostEqual( diff --git a/pymatgen/analysis/interfaces/tests/test_zsl.py b/pymatgen/analysis/interfaces/tests/test_zsl.py index de5e3d9ba02..920721f11b2 100644 --- a/pymatgen/analysis/interfaces/tests/test_zsl.py +++ b/pymatgen/analysis/interfaces/tests/test_zsl.py @@ -36,7 +36,6 @@ def setUp(self): ).get_conventional_standard_structure() def test_zsl(self): - z = ZSLGenerator() assert fast_norm([3, 2, 1]) == pytest.approx(3.74165738) @@ -50,7 +49,6 @@ def test_zsl(self): assert len(matches) == 8 def test_bidirectional(self): - z = ZSLGenerator(max_area_ratio_tol=0.05, max_angle_tol=0.05, max_length_tol=0.05) matches = list(z(self.film.lattice.matrix[:2], self.substrate.lattice.matrix[:2])) diff --git a/pymatgen/analysis/interfaces/zsl.py b/pymatgen/analysis/interfaces/zsl.py index d528d2ae4d9..fd6b77137a7 100644 --- a/pymatgen/analysis/interfaces/zsl.py +++ b/pymatgen/analysis/interfaces/zsl.py @@ -186,7 +186,7 @@ def get_equiv_transformations(self, transformation_sets, film_vectors, substrate substrate_vectors(array): substrate vectors to generate super lattices """ - for (film_transformations, substrate_transformations) in transformation_sets: + for film_transformations, substrate_transformations in transformation_sets: # Apply transformations and reduce using Zur reduce methodology films = [reduce_vectors(*np.dot(f, film_vectors)) for f in film_transformations] diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index e915044632e..33a426796af 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -2975,7 +2975,6 @@ def get_order_parameters( thetas = [] phis = [] for vec in rijnorm: - # z is North pole --> theta between vec and (0, 0, 1)^T. # Because vec is normalized, dot product is simply vec[2]. thetas.append(acos(max(-1.0, min(vec[2], 1.0)))) diff --git a/pymatgen/analysis/magnetism/analyzer.py b/pymatgen/analysis/magnetism/analyzer.py index 3b566955939..002691e7fa9 100644 --- a/pymatgen/analysis/magnetism/analyzer.py +++ b/pymatgen/analysis/magnetism/analyzer.py @@ -245,7 +245,6 @@ def __init__( raise ValueError("Unsupported mode.") for idx, site in enumerate(structure): - if site.species_string in self.default_magmoms: # look for species first, e.g. Fe2+ default_magmom = self.default_magmoms[site.species_string] @@ -308,14 +307,11 @@ def _round_magmoms(magmoms: VectorLike, round_magmoms_mode: int | float) -> np.n intelligently by grouping magmoms. """ if isinstance(round_magmoms_mode, int): - # simple rounding to number of decimal places magmoms = np.around(magmoms, decimals=round_magmoms_mode) elif isinstance(round_magmoms_mode, float): - try: - # get range of possible magmoms, pad by 50% just to be safe range_m = max([max(magmoms), abs(min(magmoms))]) * 1.5 @@ -333,7 +329,6 @@ def _round_magmoms(magmoms: VectorLike, round_magmoms_mode: int | float) -> np.n magmoms = [extrema[(np.abs(extrema - m)).argmin()] for m in magmoms] except Exception as e: - # TODO: typically a singular matrix warning, investigate this warnings.warn("Failed to round magmoms intelligently, falling back to simple rounding.") warnings.warn(str(e)) @@ -871,7 +866,6 @@ def _generate_transformations(self, structure: Structure) -> dict[str, MagOrderi # ...to which we can add simple AFM cases first... if "antiferromagnetic" in self.strategies: - constraint = MagOrderParameterConstraint( 0.5, # TODO: update MagOrderParameterConstraint in @@ -890,7 +884,6 @@ def _generate_transformations(self, structure: Structure) -> dict[str, MagOrderi # ...and then we also try ferrimagnetic orderings by motif if a # single magnetic species is present... if "ferrimagnetic_by_motif" in self.strategies and len(wyckoff_symbols) > 1: - # these orderings are AFM on one local environment, and FM on the rest for symbol in wyckoff_symbols: constraints = [ @@ -906,7 +899,6 @@ def _generate_transformations(self, structure: Structure) -> dict[str, MagOrderi # and also try ferrimagnetic when there are multiple magnetic species if "ferrimagnetic_by_species" in self.strategies: - sp_list = [str(site.specie) for site in structure] num_sp = {sp: sp_list.count(str(sp)) for sp in types_mag_species} total_mag_sites = sum(num_sp.values()) @@ -931,7 +923,6 @@ def _generate_transformations(self, structure: Structure) -> dict[str, MagOrderi # environment, and non-magnetic on the rest -- this is less common # but unless explicitly attempted, these states are unlikely to be found if "antiferromagnetic_by_motif" in self.strategies: - for symbol in wyckoff_symbols: constraints = [ MagOrderParameterConstraint(0.5, site_constraint_name="wyckoff", site_constraints=symbol) @@ -1023,7 +1014,6 @@ def _add_structures(ordered_structures, ordered_structures_origins, structures_t # also remove low symmetry structures if self.truncate_by_symmetry: - # by default, keep structures with 5 most symmetric space groups if not isinstance(self.truncate_by_symmetry, int): self.truncate_by_symmetry = 5 diff --git a/pymatgen/analysis/magnetism/heisenberg.py b/pymatgen/analysis/magnetism/heisenberg.py index 6250f08a3ad..8baf904e6bb 100644 --- a/pymatgen/analysis/magnetism/heisenberg.py +++ b/pymatgen/analysis/magnetism/heisenberg.py @@ -417,7 +417,6 @@ def get_low_energy_orderings(self): # epas = [e / len(s) for (e, s) in zip(self.energies, self.ordered_structures)] for s, e in zip(self.ordered_structures, self.energies): - ordering = CollinearMagneticStructureAnalyzer(s, threshold=0.0, make_primitive=False).ordering magmoms = s.site_properties["magmom"] diff --git a/pymatgen/analysis/magnetism/jahnteller.py b/pymatgen/analysis/magnetism/jahnteller.py index 0aa73656b08..489be2ff5dc 100644 --- a/pymatgen/analysis/magnetism/jahnteller.py +++ b/pymatgen/analysis/magnetism/jahnteller.py @@ -128,13 +128,11 @@ def get_analysis_and_structure( non_jt_sites = [] for indices in symmetrized_structure.equivalent_indices: - idx = indices[0] site = symmetrized_structure[idx] # only interested in sites with oxidation states if isinstance(site.specie, Species) and site.specie.element.is_transition_metal: - # get motif around site order_params = op.get_order_parameters(symmetrized_structure, idx) @@ -149,12 +147,10 @@ def get_analysis_and_structure( motif_order_parameter = None if motif in ["oct", "tet"]: - motif = cast(Literal["oct", "tet"], motif) # mypy needs help # guess spin of metal ion if guesstimate_spin and "magmom" in site.properties: - # estimate if high spin or low spin magmom = site.properties["magmom"] spin_state = self._estimate_spin_state(site.specie, motif, magmom) @@ -164,7 +160,6 @@ def get_analysis_and_structure( magnitude = self.get_magnitude_of_effect_from_species(site.specie, spin_state, motif) if magnitude != "none": - ligands = get_neighbors_of_site_with_index(structure, idx, approach="min_dist", delta=0.15) ligand_bond_lengths = [ligand.distance(structure[idx]) for ligand in ligands] ligands_species = list({str(ligand.specie) for ligand in ligands}) @@ -384,7 +379,6 @@ def get_magnitude_of_effect_from_species(self, species: str | Species, spin_stat # has to be Species; we need to know the oxidation state if isinstance(sp, Species) and sp.element.is_transition_metal: - d_electrons = self._get_number_of_d_electrons(sp) if motif in self.spin_configs: diff --git a/pymatgen/analysis/molecule_matcher.py b/pymatgen/analysis/molecule_matcher.py index 231fb27afb0..53eb00edde2 100644 --- a/pymatgen/analysis/molecule_matcher.py +++ b/pymatgen/analysis/molecule_matcher.py @@ -93,7 +93,6 @@ def from_dict(cls, d): AbstractMolAtomMapper """ for trans_modules in ["molecule_matcher"]: - level = 0 # Python 3.x mod = __import__( "pymatgen.analysis." + trans_modules, @@ -911,7 +910,6 @@ def match(self, p: Molecule, ignore_warning=False): # Generate all permutation grouped/sorted by the elements for p_inds_test in self.permutations(p_atoms): - p_centroid_test = p_centroid[p_inds_test] U_test = self.kabsch(p_centroid_test, q_centroid) @@ -1009,7 +1007,6 @@ def match(self, p: Molecule): # Generate all permutation grouped/sorted by the elements for p_inds_test in self.permutations(p_atoms, p_centroid, p_weights, q_atoms, q_centroid, q_weights): - p_centroid_test = p_centroid[p_inds_test] U_test = self.kabsch(p_centroid_test, q_centroid) @@ -1129,7 +1126,6 @@ def get_principal_axis(coords, weights): Ixx = Iyy = Izz = Ixy = Ixz = Iyz = 0.0 for (x, y, z), wt in zip(coords, weights): - Ixx += wt * (y * y + z * z) Iyy += wt * (x * x + z * z) Izz += wt * (x * x + y * y) @@ -1293,9 +1289,7 @@ def permutations(self, p: Molecule): matches = [] for indices in partial_matches: - for jdx in range(self.N): - # skipping if the this index is already matched if jdx in indices: continue diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index d7682ca91c8..08a24609bc8 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -1588,7 +1588,7 @@ def __init__( # TODO comprhys: refactor to have self._compute method to allow serialisation self.spaces = sorted(spaces, key=len, reverse=False) # Calculate pds for smaller dimension spaces first - self.pds = dict(self._get_pd_patch_for_space(s) for s in tqdm(self.spaces, disable=(not verbose))) + self.pds = dict(self._get_pd_patch_for_space(s) for s in tqdm(self.spaces, disable=not verbose)) self.all_entries = all_entries self.el_refs = el_refs self.elements = elements @@ -1870,7 +1870,6 @@ def fmt(fl): continue try: - mat = [] for e in face_entries: mat.append([e.composition.get_atomic_fraction(el) for el in elements]) @@ -1881,7 +1880,6 @@ def fmt(fl): x = coeffs[-1] # pylint: disable=R1716 if all(c >= -tol for c in coeffs) and (abs(sum(coeffs[:-1]) - 1) < tol) and (tol < x < 1 - tol): - c1 = x / r1.num_atoms c2 = (1 - x) / r2.num_atoms factor = 1 / (c1 + c2) @@ -2727,8 +2725,8 @@ def get_contour_pd_plot(self): f = interpolate.LinearNDInterpolator(data[:, 0:2], data[:, 2]) znew = np.zeros((len(ynew), len(xnew))) - for (i, xval) in enumerate(xnew): - for (j, yval) in enumerate(ynew): + for i, xval in enumerate(xnew): + for j, yval in enumerate(ynew): znew[j, i] = f(xval, yval) # pylint: disable=E1101 diff --git a/pymatgen/analysis/piezo_sensitivity.py b/pymatgen/analysis/piezo_sensitivity.py index 8a91d31e790..9d7254c0125 100644 --- a/pymatgen/analysis/piezo_sensitivity.py +++ b/pymatgen/analysis/piezo_sensitivity.py @@ -139,7 +139,6 @@ def get_rand_BEC(self, max_charge=1): else: tempfcm = np.zeros([3, 3]) for op in ops[2]: - tempfcm += op.transform_tensor(BEC[self.BEC_operations[atom][1]]) BEC[ops[0]] = tempfcm if len(ops[2]) != 0: @@ -150,7 +149,6 @@ def get_rand_BEC(self, max_charge=1): add = np.zeros([l, 3, 3]) for atom, ops in enumerate(self.BEC_operations): - if ops[0] == ops[1]: temp_tensor = Tensor(disp_charge) temp_tensor = sum(temp_tensor.transform(symm_op) for symm_op in self.pointops[atom]) / len( @@ -160,7 +158,6 @@ def get_rand_BEC(self, max_charge=1): else: temp_tensor = np.zeros([3, 3]) for op in ops[2]: - temp_tensor += op.transform_tensor(add[self.BEC_operations[atom][1]]) add[ops[0]] = temp_tensor @@ -393,7 +390,6 @@ def get_unstable_FCM(self, max_force=1): D[3 * op[1] : 3 * op[1] + 3, 3 * op[0] : 3 * op[0] + 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 = symop.transform_tensor(tempfcm) D[3 * op[0] : 3 * op[0] + 3, 3 * op[1] : 3 * op[1] + 3] += tempfcm @@ -414,7 +410,6 @@ def get_unstable_FCM(self, max_force=1): temp_tensor_sum = temp_tensor_sum / (len(self.sharedops[op[0]][op[1]])) if op[0] != op[1]: for pair in range(len(op[4])): - temp_tensor2 = temp_tensor_sum.T temp_tensor2 = op[4][pair].transform_tensor(temp_tensor2) temp_tensor_sum = (temp_tensor_sum + temp_tensor2) / 2 @@ -451,7 +446,6 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1): D[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 = symop.transform_tensor(tempfcm) @@ -473,9 +467,7 @@ def get_symmetrized_FCM(self, unsymmetrized_fcm, max_force=1): # Apply the proper transformation if there is an equivalent already if op[0] != op[1]: - for pair in range(len(op[4])): - temp_tensor2 = temp_tensor_sum.T temp_tensor2 = op[4][pair].transform_tensor(temp_tensor2) temp_tensor_sum = (temp_tensor_sum + temp_tensor2) / 2 @@ -578,7 +570,6 @@ def get_asum_FCM(self, fcm: np.ndarray, numiter: int = 15): D[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 = symop.transform_tensor(tempfcm) @@ -612,9 +603,7 @@ def get_asum_FCM(self, fcm: np.ndarray, numiter: int = 15): # Apply the proper transformation if there is an equivalent already if op[0] != op[1]: - for pair in range(len(op[4])): - temp_tensor2 = temp_tensor_sum.T temp_tensor2 = op[4][pair].transform_tensor(temp_tensor2) temp_tensor_sum = (temp_tensor_sum + temp_tensor2) / 2 diff --git a/pymatgen/analysis/pourbaix_diagram.py b/pymatgen/analysis/pourbaix_diagram.py index f740948939c..b87ee705e12 100644 --- a/pymatgen/analysis/pourbaix_diagram.py +++ b/pymatgen/analysis/pourbaix_diagram.py @@ -133,8 +133,6 @@ def name(self): @property def energy(self): """ - returns energy - Returns (float): total energy of the Pourbaix entry (at pH, V = 0 vs. SHE) """ @@ -449,6 +447,7 @@ def ion_or_solid_comp_object(formula): # heatmap plotter, because the reference states for decomposition # don't include oxygen/hydrogen in the OER/HER regions + # TODO: create a from_phase_diagram class method for non-formation energy # invocation # TODO: invocation from a MultiEntry entry list could be a bit more robust diff --git a/pymatgen/analysis/structure_analyzer.py b/pymatgen/analysis/structure_analyzer.py index 170eb8b5f6d..8c12e3939f8 100644 --- a/pymatgen/analysis/structure_analyzer.py +++ b/pymatgen/analysis/structure_analyzer.py @@ -549,7 +549,6 @@ def sulfide_type(structure): s_sites = [site for site in structure if site.specie == s] def process_site(site): - # in an exceptionally rare number of structures, the search # radius needs to be increased to find a neighbor atom search_radius = 4 diff --git a/pymatgen/analysis/structure_prediction/dopant_predictor.py b/pymatgen/analysis/structure_prediction/dopant_predictor.py index 76f0fe678b3..4b7e36bdfe0 100644 --- a/pymatgen/analysis/structure_prediction/dopant_predictor.py +++ b/pymatgen/analysis/structure_prediction/dopant_predictor.py @@ -201,7 +201,7 @@ def _int_to_roman(number): roman_conv = [(10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")] result = [] - for (arabic, roman) in roman_conv: + for arabic, roman in roman_conv: (factor, number) = divmod(number, arabic) result.append(roman * factor) if number == 0: diff --git a/pymatgen/analysis/structure_prediction/substitutor.py b/pymatgen/analysis/structure_prediction/substitutor.py index 4888d584e11..6d4a19155ec 100644 --- a/pymatgen/analysis/structure_prediction/substitutor.py +++ b/pymatgen/analysis/structure_prediction/substitutor.py @@ -62,7 +62,7 @@ def __init__(self, threshold=1e-3, symprec: float = 0.1, **kwargs): def get_allowed_species(self): """ - returns the species in the domain of the probability function + Returns the species in the domain of the probability function any other specie will not work """ return self._sp.species @@ -75,7 +75,7 @@ def pred_from_structures( remove_existing=False, ): """ - performs a structure prediction targeting compounds containing all of + Performs a structure prediction targeting compounds containing all of the target_species, based on a list of structure (those structures can for instance come from a database like the ICSD). It will return all the structures formed by ionic substitutions with a probability @@ -126,7 +126,6 @@ def pred_from_structures( and len(list(set(els) & set(self.get_allowed_species()))) == len(els) and self._sp.cond_prob_list(permut, els) > self._threshold ): - clean_subst = {els[i]: permut[i] for i in range(0, len(els)) if els[i] != permut[i]} if len(clean_subst) == 0: @@ -164,14 +163,14 @@ def pred_from_structures( @staticmethod def _is_charge_balanced(struct): """ - checks if the structure object is charge balanced + Checks if the structure object is charge balanced """ return sum(s.specie.oxi_state for s in struct.sites) == 0.0 @staticmethod def _is_from_chemical_system(chemical_system, struct): """ - checks if the structure object is from the given chemical system + Checks if the structure object is from the given chemical system """ return {sp.symbol for sp in struct.composition} == set(chemical_system) diff --git a/pymatgen/analysis/surface_analysis.py b/pymatgen/analysis/surface_analysis.py index f9e227a9c1d..86941e33ea1 100644 --- a/pymatgen/analysis/surface_analysis.py +++ b/pymatgen/analysis/surface_analysis.py @@ -683,7 +683,6 @@ def get_surface_equilibrium(self, slab_entries, delu_dict=None): if type(se).__name__ == "float": all_eqns.append(se - Symbol("gamma")) else: - se = sub_chempots(se, delu_dict) if delu_dict else se all_eqns.append(se - Symbol("gamma")) all_parameters.extend([p for p in list(se.free_symbols) if p not in all_parameters]) @@ -1002,11 +1001,9 @@ def chempot_vs_gamma( already_labelled = [] label = "" for clean_entry in self.all_slab_entries[hkl]: - urange = stable_u_range_dict[clean_entry] if not show_unstable else chempot_range # Don't plot if the slab is unstable, plot if it is. if urange != []: - label = clean_entry.label if label in already_labelled: label = None @@ -1259,12 +1256,10 @@ def surface_chempot_range_map( # Plot the edges of the phases for entry, v in vertices_dict.items(): - xvals, yvals = [], [] # Plot each edge of a phase within the borders for ii, pt1 in enumerate(v): - # Determine if the surface energy at this lower range # of dmu2 is negative. If so, shade this region. if len(pt1[delu2][1]) == 3: diff --git a/pymatgen/analysis/tests/test_adsorption.py b/pymatgen/analysis/tests/test_adsorption.py index 2d250fbe9d7..dd5a50798f6 100644 --- a/pymatgen/analysis/tests/test_adsorption.py +++ b/pymatgen/analysis/tests/test_adsorption.py @@ -122,7 +122,6 @@ def test_generate_adsorption_structures(self): self.assertArrayAlmostEqual(c_site.coords, ads_site_coords + np.array([1.0, -0.5, 3])) def test_adsorb_both_surfaces(self): - # Test out for monatomic adsorption o = Molecule("O", [[0, 0, 0]]) ad_slabs = self.asf_100.adsorb_both_surfaces(o) @@ -148,7 +147,6 @@ def test_adsorb_both_surfaces(self): assert sg.is_laue() def test_generate_substitution_structures(self): - # Test this for a low miller index halite structure slabs = generate_all_slabs(self.MgO, 1, 10, 10, center_slab=True, max_normal_search=1) for slab in slabs: diff --git a/pymatgen/analysis/tests/test_eos.py b/pymatgen/analysis/tests/test_eos.py index 42af2415860..b125f8a43ca 100644 --- a/pymatgen/analysis/tests/test_eos.py +++ b/pymatgen/analysis/tests/test_eos.py @@ -80,7 +80,6 @@ def setUp(self): self.num_eos_fit = num_eos.fit(self.volumes, self.energies) def test_run_all_models(self): - # these have been checked for plausibility, # but are not benchmarked against independently known values test_output = { @@ -137,7 +136,6 @@ def test_run_all_models(self): self.assertArrayAlmostEqual(_.results[param], test_output[eos_name][param], decimal=1) def test_fitting(self): - # courtesy of @katherinelatimer2013 # known correct values for Vinet diff --git a/pymatgen/analysis/tests/test_graphs.py b/pymatgen/analysis/tests/test_graphs.py index 492461dc82c..c74acefa768 100644 --- a/pymatgen/analysis/tests/test_graphs.py +++ b/pymatgen/analysis/tests/test_graphs.py @@ -57,7 +57,6 @@ class StructureGraphTest(PymatgenTest): def setUp(self): - self.maxDiff = None # trivial example, simple square lattice for testing @@ -123,7 +122,6 @@ def test_inappropriate_construction(self): StructureGraph.with_local_env_strategy(self.NiO, CovalentBondNN()) def test_properties(self): - assert self.mos2_sg.name == "bonds" assert self.mos2_sg.edge_weight_name == "bond_length" assert self.mos2_sg.edge_weight_unit == "Å" @@ -189,7 +187,6 @@ def test_edge_editing(self): assert len(square.graph.get_edge_data(0, 0)) == 1 def test_insert_remove(self): - struct_copy = copy.deepcopy(self.square_sg.structure) square_copy = copy.deepcopy(self.square_sg) @@ -249,14 +246,12 @@ def test_substitute(self): assert edge["weight"] == 0.5 def test_auto_image_detection(self): - sg = StructureGraph.with_empty_graph(self.structure) sg.add_edge(0, 0) assert len(list(sg.graph.edges(data=True))) == 3 def test_str(self): - square_sg_str_ref = """Structure Graph Structure: Full Formula (H1) @@ -306,7 +301,6 @@ def test_str(self): self.assertStrContentEqual(str(self.mos2_sg), mos2_sg_str_ref) def test_mul(self): - square_sg_mul = self.square_sg * (2, 1, 1) square_sg_mul_ref_str = """Structure Graph @@ -365,7 +359,6 @@ def test_mul(self): @unittest.skipIf(pygraphviz is None or not (which("neato") and which("fdp")), "graphviz executables not present") def test_draw(self): - # draw MoS2 graph self.mos2_sg.draw_graph_to_file("MoS2_single.pdf", image_labels=True, hide_image_edges=False) mos2_sg = self.mos2_sg * (9, 9, 1) @@ -450,7 +443,6 @@ def test_from_edges(self): assert sg == self.square_sg def test_extract_molecules(self): - structure_file = os.path.join( PymatgenTest.TEST_FILES_DIR, "H6PbCI3N_mp-977013_symmetrized.cif", @@ -469,14 +461,12 @@ def test_extract_molecules(self): assert len(molecules) == 0 def test_types_and_weights_of_connections(self): - types = self.mos2_sg.types_and_weights_of_connections assert len(types["Mo-S"]) == 6 assert types["Mo-S"][0] == approx(2.416931678417331) def test_weight_statistics(self): - weight_statistics = self.mos2_sg.weight_statistics assert len(weight_statistics["all_weights"]) == 6 @@ -484,7 +474,6 @@ def test_weight_statistics(self): assert weight_statistics["variance"] == approx(0, abs=1e-10) def test_types_of_coordination_environments(self): - types = self.mos2_sg.types_of_coordination_environments() assert types == ["Mo-S(6)", "S-Mo(3)"] @@ -492,7 +481,6 @@ def test_types_of_coordination_environments(self): assert types_anonymous == ["A-B(3)", "A-B(6)"] def test_no_duplicate_hops(self): - test_structure = Structure( lattice=[[2.990355, -5.149042, 0.0], [2.990355, 5.149042, 0.0], [0.0, 0.0, 24.51998]], species=["Ba"], @@ -506,7 +494,6 @@ def test_no_duplicate_hops(self): assert sg.graph.number_of_edges() == 3 def test_sort(self): - sg = copy.deepcopy(self.bc_square_sg_r) # insert an unsorted edge, don't use sg.add_edge as it auto-sorts sg.graph.add_edge(3, 1, to_jimage=(0, 0, 0)) @@ -519,7 +506,6 @@ def test_sort(self): class MoleculeGraphTest(unittest.TestCase): def setUp(self): - cyclohexene = Molecule.from_file( os.path.join( PymatgenTest.TEST_FILES_DIR, @@ -951,7 +937,6 @@ def test_as_from_dict(self): assert str(d) == str(d2) def test_sort(self): - sg = copy.deepcopy(self.ethylene) # insert an unsorted edge, don't use sg.add_edge as it auto-sorts diff --git a/pymatgen/analysis/tests/test_local_env.py b/pymatgen/analysis/tests/test_local_env.py index 77df09cc341..9448db0eff3 100644 --- a/pymatgen/analysis/tests/test_local_env.py +++ b/pymatgen/analysis/tests/test_local_env.py @@ -605,7 +605,6 @@ def setUp(self): ) def set_nn_info(self): - # check conformance # implicitly assumes that all NearNeighbors subclasses # will correctly identify bonds in diamond, if it diff --git a/pymatgen/analysis/tests/test_molecule_matcher.py b/pymatgen/analysis/tests/test_molecule_matcher.py index 4cede872aff..8df33466611 100644 --- a/pymatgen/analysis/tests/test_molecule_matcher.py +++ b/pymatgen/analysis/tests/test_molecule_matcher.py @@ -271,7 +271,6 @@ def test_cdi_23(self): class KabschMatcherTest(unittest.TestCase): def test_get_rmsd(self): - mol1 = Molecule.from_file(os.path.join(test_dir, "t3.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "t4.xyz")) @@ -289,7 +288,6 @@ def test_to_and_from_dict(self): assert d_source == mm_target.as_dict() def test_rotated_molecule(self): - coords = [ [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], @@ -309,18 +307,15 @@ def test_rotated_molecule(self): assert rmsd == approx(0, abs=6) def test_mismatched_atom_composition(self): - mol1 = Molecule.from_file(os.path.join(test_dir, "benzene1.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "t2.xyz")) mm = KabschMatcher(mol1) with pytest.raises(ValueError): - _, rmsd = mm.fit(mol2) def test_missmatched_atom_order(self): - mol1 = Molecule.from_file(os.path.join(test_dir, "benzene1.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "benzene2.xyz")) @@ -374,7 +369,6 @@ def test_to_and_from_dict(self): assert d_source == mm_target.as_dict() def test_rotated_molecule(self): - coords = [ [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], @@ -394,7 +388,6 @@ def test_rotated_molecule(self): assert rmsd == approx(0, abs=6) def test_mismatched_atom_composition(self): - mol1 = Molecule.from_file(os.path.join(test_dir, "benzene1.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "t2.xyz")) mm = HungarianOrderMatcher(mol1) @@ -403,7 +396,6 @@ def test_mismatched_atom_composition(self): _, rmsd = mm.fit(mol2) def test_fit(self): - mol1 = Molecule.from_file(os.path.join(test_dir, "benzene1.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "benzene2.xyz")) @@ -482,7 +474,6 @@ def test_to_and_from_dict(self): assert d_source == mm_target.as_dict() def test_rotated_molecule(self): - coords = [ [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], @@ -502,7 +493,6 @@ def test_rotated_molecule(self): assert rmsd == approx(0, abs=6) def test_mismatched_atom_composition(self): - mol1 = Molecule.from_file(os.path.join(test_dir, "benzene1.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "t2.xyz")) mm = GeneticOrderMatcher(mol1, threshold=0.3) @@ -511,7 +501,6 @@ def test_mismatched_atom_composition(self): _, rmsd = mm.fit(mol2)[0] def test_fit(self): - mol1 = Molecule.from_file(os.path.join(test_dir, "benzene1.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "benzene2.xyz")) @@ -702,7 +691,6 @@ def test_random_match(self): class KabschMatcherSi2OTest(unittest.TestCase): @classmethod def setUpClass(cls): - cls.mol1 = Molecule.from_file(os.path.join(test_dir, "Si2O_cluster.xyz")) cls.mm = KabschMatcher(cls.mol1) @@ -764,7 +752,6 @@ def test_random_match(self): class HungarianOrderMatcherSi2OTest(unittest.TestCase): @classmethod def setUpClass(cls): - cls.mol1 = Molecule.from_file(os.path.join(test_dir, "Si2O_cluster.xyz")) cls.mm = HungarianOrderMatcher(cls.mol1) diff --git a/pymatgen/analysis/tests/test_molecule_structure_comparator.py b/pymatgen/analysis/tests/test_molecule_structure_comparator.py index 0ffde8cee5e..76e97b52171 100644 --- a/pymatgen/analysis/tests/test_molecule_structure_comparator.py +++ b/pymatgen/analysis/tests/test_molecule_structure_comparator.py @@ -24,17 +24,17 @@ def test_are_equal(self): mol1 = Molecule.from_file(os.path.join(test_dir, "t1.xyz")) mol2 = Molecule.from_file(os.path.join(test_dir, "t2.xyz")) mol3 = Molecule.from_file(os.path.join(test_dir, "t3.xyz")) - self.assertFalse(msc1.are_equal(mol1, mol2)) - self.assertTrue(msc1.are_equal(mol2, mol3)) + assert not msc1.are_equal(mol1, mol2) + assert msc1.are_equal(mol2, mol3) thio1 = Molecule.from_file(os.path.join(test_dir, "thiophene1.xyz")) thio2 = Molecule.from_file(os.path.join(test_dir, "thiophene2.xyz")) # noinspection PyProtectedMember msc2 = MoleculeStructureComparator(priority_bonds=msc1._get_bonds(thio1)) - self.assertTrue(msc2.are_equal(thio1, thio2)) + assert msc2.are_equal(thio1, thio2) hal1 = Molecule.from_file(os.path.join(test_dir, "molecule_with_halogen_bonds_1.xyz")) hal2 = Molecule.from_file(os.path.join(test_dir, "molecule_with_halogen_bonds_2.xyz")) msc3 = MoleculeStructureComparator(priority_bonds=msc1._get_bonds(hal1)) - self.assertTrue(msc3.are_equal(hal1, hal2)) + assert msc3.are_equal(hal1, hal2) def test_get_bonds(self): mol1 = Molecule.from_file(os.path.join(test_dir, "t1.xyz")) @@ -70,76 +70,70 @@ def test_get_bonds(self): (23, 24), (23, 25), ] - self.assertEqual(bonds, bonds_ref) + assert bonds == bonds_ref mol2 = Molecule.from_file(os.path.join(test_dir, "MgBH42.xyz")) bonds = msc._get_bonds(mol2) - self.assertEqual(bonds, [(1, 3), (2, 3), (3, 4), (3, 5), (6, 8), (7, 8), (8, 9), (8, 10)]) + assert bonds == [(1, 3), (2, 3), (3, 4), (3, 5), (6, 8), (7, 8), (8, 9), (8, 10)] msc = MoleculeStructureComparator(ignore_ionic_bond=False) bonds = msc._get_bonds(mol2) - self.assertEqual( - bonds, - [ - (0, 1), - (0, 2), - (0, 3), - (0, 5), - (0, 6), - (0, 7), - (0, 8), - (0, 9), - (1, 3), - (2, 3), - (3, 4), - (3, 5), - (6, 8), - (7, 8), - (8, 9), - (8, 10), - ], - ) + assert bonds == [ + (0, 1), + (0, 2), + (0, 3), + (0, 5), + (0, 6), + (0, 7), + (0, 8), + (0, 9), + (1, 3), + (2, 3), + (3, 4), + (3, 5), + (6, 8), + (7, 8), + (8, 9), + (8, 10), + ] mol1 = Molecule.from_file(os.path.join(test_dir, "molecule_with_halogen_bonds_1.xyz")) msc = MoleculeStructureComparator() # noinspection PyProtectedMember bonds = msc._get_bonds(mol1) - self.assertEqual( - bonds, - [ - (0, 12), - (0, 13), - (0, 14), - (0, 15), - (1, 12), - (1, 16), - (1, 17), - (1, 18), - (2, 4), - (2, 11), - (2, 19), - (3, 5), - (3, 10), - (3, 20), - (4, 6), - (4, 10), - (5, 11), - (5, 12), - (6, 7), - (6, 8), - (6, 9), - ], - ) + assert bonds == [ + (0, 12), + (0, 13), + (0, 14), + (0, 15), + (1, 12), + (1, 16), + (1, 17), + (1, 18), + (2, 4), + (2, 11), + (2, 19), + (3, 5), + (3, 10), + (3, 20), + (4, 6), + (4, 10), + (5, 11), + (5, 12), + (6, 7), + (6, 8), + (6, 9), + ] def test_to_and_from_dict(self): msc1 = MoleculeStructureComparator() d1 = msc1.as_dict() d2 = MoleculeStructureComparator.from_dict(d1).as_dict() - self.assertEqual(d1, d2) + assert d1 == d2 thio1 = Molecule.from_file(os.path.join(test_dir, "thiophene1.xyz")) # noinspection PyProtectedMember msc2 = MoleculeStructureComparator(bond_length_cap=0.2, priority_bonds=msc1._get_bonds(thio1), priority_cap=0.5) d1 = msc2.as_dict() d2 = MoleculeStructureComparator.from_dict(d1).as_dict() - self.assertEqual(d1, d2) + assert d1 == d2 # def test_structural_change_in_geom_opt(self): # qcout_path = os.path.join(test_dir, "mol_1_3_bond.qcout") @@ -186,7 +180,7 @@ def test_get_13_bonds(self): (6, 8), (6, 10), ) - self.assertEqual(bonds_13, tuple(ans)) + assert bonds_13 == tuple(ans) if __name__ == "__main__": diff --git a/pymatgen/analysis/tests/test_nmr.py b/pymatgen/analysis/tests/test_nmr.py index 9bfacd5ed0f..dd808554d31 100644 --- a/pymatgen/analysis/tests/test_nmr.py +++ b/pymatgen/analysis/tests/test_nmr.py @@ -67,7 +67,6 @@ def test_principal_axis_system(self): ) def test_Attributes(self): - efg = ElectricFieldGradient([[11.11, 1.371, 2.652], [1.371, 3.635, -3.572], [2.652, -3.572, -14.746]]) assert efg.V_yy == approx(11.516, abs=1e-3) assert efg.V_xx == approx(4.204, abs=1e-3) diff --git a/pymatgen/analysis/tests/test_phase_diagram.py b/pymatgen/analysis/tests/test_phase_diagram.py index d95c6c04506..4f0c49e37bd 100644 --- a/pymatgen/analysis/tests/test_phase_diagram.py +++ b/pymatgen/analysis/tests/test_phase_diagram.py @@ -272,12 +272,10 @@ def test_get_e_above_hull(self): assert e_ah >= 0 def test_get_decomp_and_e_above_hull_on_error(self): - for method, expected in ( (self.pd.get_e_above_hull, None), (self.pd.get_decomp_and_e_above_hull, (None, None)), ): - # test raises ValueError on entry with element not in the phase diagram U_entry = PDEntry("U", 0) with pytest.raises(ValueError, match="Unable to get decomposition for PDEntry : U1 with energy"): diff --git a/pymatgen/analysis/tests/test_structure_analyzer.py b/pymatgen/analysis/tests/test_structure_analyzer.py index f24ce445968..6ff0645a546 100644 --- a/pymatgen/analysis/tests/test_structure_analyzer.py +++ b/pymatgen/analysis/tests/test_structure_analyzer.py @@ -106,7 +106,6 @@ def test_solid_angle(self): assert solid_angle(center, coords) == approx(1.83570965938, abs=1e-7), "Wrong result returned by solid_angle" def test_contains_peroxide(self): - for f in ["LiFePO4", "NaFePO4", "Li3V2(PO4)3", "Li2O"]: assert not contains_peroxide(self.get_structure(f)) diff --git a/pymatgen/analysis/tests/test_structure_matcher.py b/pymatgen/analysis/tests/test_structure_matcher.py index 41bcabc8c37..ce50a0e96a5 100644 --- a/pymatgen/analysis/tests/test_structure_matcher.py +++ b/pymatgen/analysis/tests/test_structure_matcher.py @@ -759,7 +759,6 @@ def test_disordered_to_disordered(self): assert not sm_atoms.fit(s1, s2) def test_occupancy_comparator(self): - lp = Lattice.orthorhombic(10, 20, 30) pcoords = [[0, 0, 0], [0.5, 0.5, 0.5]] s1 = Structure(lp, [{"Na": 0.6, "K": 0.4}, "Cl"], pcoords) diff --git a/pymatgen/analysis/tests/test_surface_analysis.py b/pymatgen/analysis/tests/test_surface_analysis.py index 8f504ce5a7a..0a1dc5717a2 100644 --- a/pymatgen/analysis/tests/test_surface_analysis.py +++ b/pymatgen/analysis/tests/test_surface_analysis.py @@ -32,7 +32,6 @@ def get_path(path_str): class SlabEntryTest(PymatgenTest): def setUp(self): - with warnings.catch_warnings(): warnings.simplefilter("ignore") @@ -84,7 +83,6 @@ def test_properties(self): ) def test_create_slab_label(self): - for el, val in self.metals_O_entry_dict.items(): for hkl in val: # Test WulffShape for adsorbed surfaces @@ -133,7 +131,6 @@ def test_cleaned_up_slab(self): class SurfaceEnergyPlotterTest(PymatgenTest): def setUp(self): - entry_dict = get_entry_dict(os.path.join(get_path(""), "Cu_entries.txt")) self.Cu_entry_dict = entry_dict with open(os.path.join(get_path(""), "ucell_entries.txt")) as ucell_entries: @@ -156,7 +153,6 @@ def setUp(self): } def test_get_stable_entry_at_u(self): - for plotter in self.Oads_analyzer_dict.values(): for hkl in plotter.all_slab_entries: # Test that the surface energy is clean for specific range of chempot @@ -178,7 +174,6 @@ def test_get_stable_entry_at_u(self): assert gamma3 != gamma4 def test_wulff_from_chempot(self): - # Test if it generates a Wulff shape, test if # all the facets for Cu wulff shape are inside. Cu_wulff = self.Cu_analyzer.wulff_from_chempot() @@ -215,7 +210,6 @@ def test_wulff_from_chempot(self): assert wulff_neg55.weighted_surface_energy != wulff_neg525.weighted_surface_energy def test_color_palette_dict(self): - for el, val in self.metals_O_entry_dict.items(): analyzer = self.Oads_analyzer_dict[el] color_dict = analyzer.color_palette_dict() @@ -259,7 +253,6 @@ def test_stable_u_range_dict(self): assert len(all_u) > 1 def test_entry_dict_from_list(self): - # Plug in a list of entries to see if it works all_Pt_slab_entries = [] Pt_entries = self.Pt_analyzer.all_slab_entries diff --git a/pymatgen/analysis/tests/test_wulff.py b/pymatgen/analysis/tests/test_wulff.py index 52db3747ed1..af353ee9bc0 100644 --- a/pymatgen/analysis/tests/test_wulff.py +++ b/pymatgen/analysis/tests/test_wulff.py @@ -23,7 +23,6 @@ class WulffShapeTest(PymatgenTest): def setUp(self): - module_dir = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(module_dir, "surface_samples.json")) as data_file: surface_properties = json.load(data_file) @@ -110,7 +109,6 @@ def symm_check(self, ucell, wulff_vertices): return True def consistency_tests(self): - # For a set of given values, these tests will # ensure that the general result given by the # algorithm does not change as the code is edited @@ -138,7 +136,6 @@ def consistency_tests(self): assert self.wulff_Nb.miller_energy_dict[(3, 1, 0)] == self.wulff_Nb.weighted_surface_energy def symmetry_test(self): - # Maintains that all wulff shapes have the same point # groups as the conventional unit cell they were # derived from. This test should pass for all subsequent @@ -152,7 +149,6 @@ def symmetry_test(self): assert check_symmetry_Ti def test_get_azimuth_elev(self): - # Test out the viewing of the Wulff shape from Miller indices. azim, elev = self.wulff_Ir._get_azimuth_elev((0, 0, 1)) assert azim == 0 @@ -161,7 +157,6 @@ def test_get_azimuth_elev(self): assert azim == approx(45) def test_properties(self): - # Simple test to check if the values of some # properties are consistent with what we already have @@ -177,7 +172,6 @@ def test_properties(self): assert round(wulff.anisotropy, 3) == round(properties["surface_anisotropy"], 3) def test_corner_and_edges(self): - # Test if it is returning the correct number of corner and edges self.assertArrayEqual(self.cube.tot_corner_sites, 8) self.assertArrayEqual(self.cube.tot_edges, 12) diff --git a/pymatgen/analysis/topological/spillage.py b/pymatgen/analysis/topological/spillage.py index 29d548e7175..268cfd6d6c4 100644 --- a/pymatgen/analysis/topological/spillage.py +++ b/pymatgen/analysis/topological/spillage.py @@ -138,7 +138,6 @@ def overlap_so_spinpol(self): if ( self.isclose(kso[0], knoso[0]) and self.isclose(kso[1], knoso[1]) and self.isclose(kso[2], knoso[2]) ): # do kpoints match? - # changes section 2 nelec_up = n_arr[nk1 - 1, 0] nelec_dn = n_arr[nk1 - 1, 1] diff --git a/pymatgen/apps/battery/tests/test_conversion_battery.py b/pymatgen/apps/battery/tests/test_conversion_battery.py index 6e77c67bfc0..d436f715fbf 100644 --- a/pymatgen/apps/battery/tests/test_conversion_battery.py +++ b/pymatgen/apps/battery/tests/test_conversion_battery.py @@ -21,11 +21,9 @@ class ConversionElectrodeTest(unittest.TestCase): def setUp(self): - self.formulas = ["LiCoO2", "FeF3", "MnO2"] self.conversion_eletrodes = {} for f in self.formulas: - with open(os.path.join(PymatgenTest.TEST_FILES_DIR, f + "_batt.json")) as fid: entries = json.load(fid, cls=MontyDecoder) if f in ["LiCoO2", "FeF3"]: diff --git a/pymatgen/apps/borg/queen.py b/pymatgen/apps/borg/queen.py index 1ebf81d4afa..ee9413995e6 100644 --- a/pymatgen/apps/borg/queen.py +++ b/pymatgen/apps/borg/queen.py @@ -58,7 +58,7 @@ def parallel_assimilate(self, rootpath): """ logger.info("Scanning for valid paths...") valid_paths = [] - for (parent, subdirs, files) in os.walk(rootpath): + for parent, subdirs, files in os.walk(rootpath): valid_paths.extend(self._drone.get_valid_paths((parent, subdirs, files))) manager = Manager() data = manager.list() @@ -79,7 +79,7 @@ def serial_assimilate(self, rootpath): Assimilate the entire subdirectory structure in rootpath serially. """ valid_paths = [] - for (parent, subdirs, files) in os.walk(rootpath): + for parent, subdirs, files in os.walk(rootpath): valid_paths.extend(self._drone.get_valid_paths((parent, subdirs, files))) data = [] count = 0 diff --git a/pymatgen/cli/pmg_analyze.py b/pymatgen/cli/pmg_analyze.py index 61cb92f19fc..22069aa1e87 100644 --- a/pymatgen/cli/pmg_analyze.py +++ b/pymatgen/cli/pmg_analyze.py @@ -112,7 +112,7 @@ def get_magnetizations(dir: str, ion_list: list[int]): """ data = [] max_row = 0 - for (parent, _subdirs, files) in os.walk(dir): + for parent, _subdirs, files in os.walk(dir): for f in files: if re.match(r"OUTCAR*", f): try: diff --git a/pymatgen/command_line/bader_caller.py b/pymatgen/command_line/bader_caller.py index f7584235eac..deb25b43232 100644 --- a/pymatgen/command_line/bader_caller.py +++ b/pymatgen/command_line/bader_caller.py @@ -532,7 +532,6 @@ def bader_analysis_from_objects(chgcar, potcar=None, aeccar0=None, aeccar2=None) """ with ScratchDir(".") as temp_dir: - if aeccar0 and aeccar2: # construct reference file chgref = aeccar0.linear_add(aeccar2) diff --git a/pymatgen/command_line/critic2_caller.py b/pymatgen/command_line/critic2_caller.py index d0bcedf8126..e7de50358b1 100644 --- a/pymatgen/command_line/critic2_caller.py +++ b/pymatgen/command_line/critic2_caller.py @@ -220,7 +220,6 @@ def from_chgcar( input_script = "\n".join(input_script) with ScratchDir(".") as temp_dir: - os.chdir(temp_dir) structure.to(filename="POSCAR") @@ -275,7 +274,6 @@ def from_path(cls, path, suffix="", zpsp=None): chgcar_ref = None if not zpsp: - potcar_path = get_filepath( "POTCAR", "Could not find POTCAR, will not be able to calculate charge transfer.", @@ -559,7 +557,6 @@ def structure_graph(self, include_critical_points=("bond", "ring", "cage")): unique_idx = self.nodes[idx]["unique_idx"] # only add edges representing bonds, not rings if self.critical_points[unique_idx].type == CriticalPointType.bond: - from_idx = edge["from_idx"] to_idx = edge["to_idx"] @@ -708,7 +705,6 @@ def _remap_indices(self): @staticmethod def _annotate_structure_with_yt(yt, structure: Structure, zpsp): - volume_idx = None charge_idx = None @@ -761,7 +757,6 @@ def get_volume_and_charge(nonequiv_idx): return structure def _parse_stdout(self, stdout): - warnings.warn( "Parsing critic2 standard output is deprecated and will not be maintained, " "please use the native JSON output in future." @@ -852,7 +847,6 @@ def _parse_stdout(self, stdout): for i, line in enumerate(stdout): if start_i <= i <= end_i: - l = line.replace("(", "").replace(")", "").split() idx = int(l[0]) - 1 diff --git a/pymatgen/command_line/enumlib_caller.py b/pymatgen/command_line/enumlib_caller.py index a3adbb87de4..182680b1571 100644 --- a/pymatgen/command_line/enumlib_caller.py +++ b/pymatgen/command_line/enumlib_caller.py @@ -289,10 +289,8 @@ def get_sg_info(ss): f.write("\n".join(output)) def _run_multienum(self): - with subprocess.Popen([enum_cmd], stdout=subprocess.PIPE, stdin=subprocess.PIPE, close_fds=True) as p: if self.timeout: - timed_out = False timer = Timer(self.timeout * 60, lambda p: p.kill(), [p]) @@ -308,7 +306,6 @@ def _run_multienum(self): raise TimeoutError("Enumeration took too long.") else: - output = p.communicate()[0].decode("utf-8") count = 0 @@ -343,7 +340,7 @@ def _get_structures(self, num_structs): # to ensure consistency, we keep track of what site properties # are missing and set them to None # TODO: improve this by mapping ordered structure to original - # disorded structure, and retrieving correct site properties + # disordered structure, and retrieving correct site properties disordered_site_properties = {} if len(self.ordered_sites) > 0: @@ -366,6 +363,9 @@ def _get_structures(self, num_structs): site_properties=site_properties, ) inv_org_latt = np.linalg.inv(original_latt.matrix) + else: + ordered_structure = None # to fix pylint E0601 + inv_org_latt = None for file in glob.glob("vasp.*"): with open(file) as f: diff --git a/pymatgen/command_line/gulp_caller.py b/pymatgen/command_line/gulp_caller.py index 18812c5bd32..68c578f61f3 100644 --- a/pymatgen/command_line/gulp_caller.py +++ b/pymatgen/command_line/gulp_caller.py @@ -692,7 +692,6 @@ def run(self, gin): stdin=subprocess.PIPE, stderr=subprocess.PIPE, ) as p: - out, err = p.communicate(bytearray(gin, "utf-8")) out = out.decode("utf-8") err = err.decode("utf-8") diff --git a/pymatgen/command_line/mcsqs_caller.py b/pymatgen/command_line/mcsqs_caller.py index 72f65d7f054..4583039b4a6 100644 --- a/pymatgen/command_line/mcsqs_caller.py +++ b/pymatgen/command_line/mcsqs_caller.py @@ -89,13 +89,11 @@ def run_mcsqs( os.chdir(directory) if isinstance(scaling, (int, float)): - if scaling % 1: raise ValueError(f"Scaling should be an integer, not {scaling}") mcsqs_find_sqs_cmd = ["mcsqs", f"-n {scaling * num_atoms}"] else: - # Set supercell to identity (will make supercell with pymatgen) with open("sqscell.out", "w") as f: f.write("1\n1 0 0\n0 1 0\n0 0 1\n") @@ -156,7 +154,6 @@ def run_mcsqs( # Find the best sqs structures if instances and instances > 1: - if not os.path.exists("bestcorr1.out"): raise RuntimeError( "mcsqs did not generate output files, " diff --git a/pymatgen/command_line/tests/test_critic2_caller.py b/pymatgen/command_line/tests/test_critic2_caller.py index 4ca527aa5df..c05958c2b30 100644 --- a/pymatgen/command_line/tests/test_critic2_caller.py +++ b/pymatgen/command_line/tests/test_critic2_caller.py @@ -93,7 +93,6 @@ def setUp(self): self.c2o_new_format = Critic2Analysis(structure, reference_stdout_new_format) def test_properties_to_from_dict(self): - assert len(self.c2o.critical_points) == 6 assert len(self.c2o.nodes) == 14 assert len(self.c2o.edges) == 10 @@ -137,7 +136,6 @@ def test_properties_to_from_dict(self): self.c2o.from_dict(d) def test_graph_output(self): - sg = self.c2o.structure_graph() assert str(sg.structure[3].specie) == "Xbcp" assert set(list(sg.graph.edges(data=True))[0][2]) == { @@ -151,5 +149,4 @@ def test_graph_output(self): if __name__ == "__main__": - unittest.main() diff --git a/pymatgen/command_line/tests/test_mcsqs_caller.py b/pymatgen/command_line/tests/test_mcsqs_caller.py index f870f21d791..b29952005c1 100644 --- a/pymatgen/command_line/tests/test_mcsqs_caller.py +++ b/pymatgen/command_line/tests/test_mcsqs_caller.py @@ -73,7 +73,6 @@ def test_mcsqs_caller_parallel(self): assert True in matches def test_mcsqs_perfect_match_error(self): - scale = 32 / self.perfect_match_zzn_rs.num_sites sqs = run_mcsqs( self.perfect_match_zzn_rs, @@ -86,7 +85,6 @@ def test_mcsqs_perfect_match_error(self): assert sqs.objective_function == "Perfect_match" def test_mcsqs_perfect_match_error_parallel(self): - scale = 32 / self.perfect_match_zzn_rs.num_sites sqs = run_mcsqs( self.perfect_match_zzn_rs, diff --git a/pymatgen/command_line/tests/test_vampire_caller.py b/pymatgen/command_line/tests/test_vampire_caller.py index abccb258d2a..b38ea5eb031 100644 --- a/pymatgen/command_line/tests/test_vampire_caller.py +++ b/pymatgen/command_line/tests/test_vampire_caller.py @@ -22,7 +22,6 @@ class VampireCallerTest(unittest.TestCase): @classmethod def setUpClass(cls): - print("Testing with: ", which("vampire-serial")) cls.Mn3Al = pd.read_json(os.path.join(test_dir, "Mn3Al.json")) diff --git a/pymatgen/command_line/vampire_caller.py b/pymatgen/command_line/vampire_caller.py index 5b4c27b39f3..f485f49969d 100644 --- a/pymatgen/command_line/vampire_caller.py +++ b/pymatgen/command_line/vampire_caller.py @@ -157,7 +157,6 @@ def __init__( self.output = VampireOutput(parsed_out, nmats, critical_temp) def _create_mat(self): - structure = self.structure mat_name = self.mat_name magmoms = structure.site_properties["magmom"] @@ -186,7 +185,6 @@ def _create_mat(self): if spin_down and not spin_up: mat_id_dict[site] = nmats if spin_up and spin_down: - # Check if spin up or down shows up first m0 = magmoms[key[0]] if m > 0 and m0 > 0: @@ -237,7 +235,6 @@ def _create_mat(self): f.write(mat_file) def _create_input(self): - structure = self.structure mcbs = self.mc_box_size equil_timesteps = self.equil_timesteps @@ -318,7 +315,6 @@ def _create_input(self): f.write(input_script) def _create_ucf(self): - structure = self.structure mat_name = self.mat_name diff --git a/pymatgen/core/composition.py b/pymatgen/core/composition.py index 0fc9020dea5..8324e1483fc 100644 --- a/pymatgen/core/composition.py +++ b/pymatgen/core/composition.py @@ -785,7 +785,6 @@ def replace(self, elem_map: dict[str, str | dict[str, int | float]]) -> Composit new_comp = {elem: amount for elem, amount in self.as_dict().items() if elem not in elem_map} for old_elem, new_elem in elem_map.items(): - amount = self[old_elem] # build a dictionary of substitutions to be made @@ -960,7 +959,6 @@ def _get_oxid_state_guesses(self, all_oxi_states, max_sites, oxi_states_override # get all possible combinations of oxidation states # and sum each combination for oxid_combo in combinations_with_replacement(oxids, int(el_amt[el])): - # List this sum as a possible option oxid_sum = sum(oxid_combo) if oxid_sum not in el_sums[idx]: diff --git a/pymatgen/core/periodic_table.py b/pymatgen/core/periodic_table.py index b9e2a2e984b..61d063f5395 100644 --- a/pymatgen/core/periodic_table.py +++ b/pymatgen/core/periodic_table.py @@ -516,7 +516,6 @@ def term_symbols(self) -> list[list[str]]: for ML in range(-L, L - 1, -1): for MS in np.arange(S, -S + 1, 1): if (ML, MS) in comb_counter: - comb_counter[(ML, MS)] -= 1 if comb_counter[(ML, MS)] == 0: del comb_counter[(ML, MS)] @@ -1185,7 +1184,6 @@ def from_string(species_string: str) -> Species: m = re.search(r"([A-Z][a-z]*)([0-9.]*)([+\-]*)(.*)", species_string) if m: - # parse symbol sym = m.group(1) diff --git a/pymatgen/core/structure.py b/pymatgen/core/structure.py index ecd18c396ce..8d867f4f264 100644 --- a/pymatgen/core/structure.py +++ b/pymatgen/core/structure.py @@ -1091,7 +1091,6 @@ def matches(self, other: IStructure | Structure, anonymous: bool = False, **kwar return m.fit_anonymous(self, other) def __eq__(self, other: object) -> bool: - # check for valid operand following class Student example from official functools docs # https://docs.python.org/3/library/functools.html#functools.total_ordering if not isinstance(other, IStructure): @@ -1797,7 +1796,7 @@ def get_all_neighbors_old(self, r, include_index=False, include_image=False, inc all_dists = all_distances(coords, site_coords) all_within_r = np.bitwise_and(all_dists <= r, all_dists > 1e-8) - for (j, d, within_r) in zip(indices, all_dists, all_within_r): + for j, d, within_r in zip(indices, all_dists, all_within_r): if include_site: nnsite = PeriodicSite( self[j].species, diff --git a/pymatgen/core/surface.py b/pymatgen/core/surface.py index a5fe9697374..1c8f83c5502 100644 --- a/pymatgen/core/surface.py +++ b/pymatgen/core/surface.py @@ -870,7 +870,6 @@ def __init__( if max_normal_search is None: slab_scale_factor.append(eye[c_index]) else: - index_range = sorted( reversed(range(-max_normal_search, max_normal_search + 1)), key=lambda x: abs(x), @@ -1194,7 +1193,6 @@ def repair_broken_bonds(self, slab, bonds): for site in self.oriented_unit_cell: poly_coord = 0 if site.species_string == el: - for nn in self.oriented_unit_cell.get_neighbors(site, blength): if nn[0].species_string == pair[i - 1]: poly_coord += 1 diff --git a/pymatgen/core/tests/test_composition.py b/pymatgen/core/tests/test_composition.py index ce950936835..efe1a95f45b 100644 --- a/pymatgen/core/tests/test_composition.py +++ b/pymatgen/core/tests/test_composition.py @@ -579,7 +579,6 @@ def test_Metallofullerene(self): assert cmp == cmp2 def test_contains_element_type(self): - formula = "EuTiO3" cmp = Composition(formula) assert cmp.contains_element_type("lanthanoid") @@ -592,7 +591,6 @@ def test_chemical_system(self): assert Composition({"Na+": 1, "Cl-": 1}).chemical_system == "Cl-Na" def test_is_valid(self): - formula = "NaCl" cmp = Composition(formula) assert cmp.valid diff --git a/pymatgen/core/tests/test_interface.py b/pymatgen/core/tests/test_interface.py index fe11ab97ffd..5d463572512 100644 --- a/pymatgen/core/tests/test_interface.py +++ b/pymatgen/core/tests/test_interface.py @@ -65,7 +65,6 @@ def test_gap_setter(self): assert np.allclose(interface.gap, gap) def test_in_plane_offset_setter(self): - interface = self.interface init_coords = np.array(self.interface.frac_coords) interface.in_plane_offset = np.array([0.2, 0.2]) diff --git a/pymatgen/core/tests/test_lattice.py b/pymatgen/core/tests/test_lattice.py index 87bc7222ccb..b6ca8b08ed4 100644 --- a/pymatgen/core/tests/test_lattice.py +++ b/pymatgen/core/tests/test_lattice.py @@ -318,7 +318,7 @@ def test_find_all_mappings(self): latt2 = Lattice(np.dot(rot, np.dot(scale, m).T).T) - for (aligned_out, rot_out, scale_out) in latt.find_all_mappings(latt2): + for aligned_out, rot_out, scale_out in latt.find_all_mappings(latt2): self.assertArrayAlmostEqual(np.inner(latt2.matrix, rot_out), aligned_out.matrix, 5) self.assertArrayAlmostEqual(np.dot(scale_out, latt.matrix), aligned_out.matrix) self.assertArrayAlmostEqual(aligned_out.parameters, latt2.parameters) @@ -375,7 +375,7 @@ def test_dot_and_norm(self): # print(family_name) self.assertArrayAlmostEqual(lattice.norm(lattice.matrix, frac_coords=False), lattice.abc, 5) self.assertArrayAlmostEqual(lattice.norm(frac_basis), lattice.abc, 5) - for (i, vec) in enumerate(frac_basis): + for i, vec in enumerate(frac_basis): length = lattice.norm(vec) self.assertArrayAlmostEqual(length[0], lattice.abc[i], 5) # We always get a ndarray. diff --git a/pymatgen/core/tests/test_operations.py b/pymatgen/core/tests/test_operations.py index 2e4292eaaa4..32e0b28030a 100644 --- a/pymatgen/core/tests/test_operations.py +++ b/pymatgen/core/tests/test_operations.py @@ -235,7 +235,6 @@ def test_xyz(self): class MagSymmOpTestCase(PymatgenTest): def test_xyzt_string(self): - xyzt_strings = ["x, y, z, +1", "x, y, z, -1", "-y+1/2, x+1/2, x+1/2, +1"] for xyzt_string in xyzt_strings: @@ -272,7 +271,6 @@ def test_to_from_dict(self): assert magop2.as_xyzt_string() == "3x-2y-z+1/2, -x+12/13, z+1/2, -1" def test_operate_magmom(self): - # all test magmoms are the same magmoms = [ Magmom([1, 2, 3]), # as Magmom diff --git a/pymatgen/core/tests/test_structure.py b/pymatgen/core/tests/test_structure.py index c84e7c5141c..b659a8f29c7 100644 --- a/pymatgen/core/tests/test_structure.py +++ b/pymatgen/core/tests/test_structure.py @@ -221,7 +221,6 @@ def test_as_dict(self): assert "xyz" not in d["sites"][0] def test_from_dict(self): - d = self.propertied_structure.as_dict() s = IStructure.from_dict(d) assert s[0].magmom == 5 @@ -915,7 +914,6 @@ def test_add_oxidation_states_by_guess(self): assert i.specie in [Species("Li", 1), Species("O", -2)] def test_add_remove_spin_states(self): - latt = Lattice.cubic(4.17) species = ["Ni", "O"] coords = [[0, 0, 0], [0.5, 0.5, 0.5]] @@ -1124,7 +1122,6 @@ def test_from_spacegroup(self): assert len(s) == 8 def test_from_magnetic_spacegroup(self): - # AFM MnF s1 = Structure.from_magnetic_spacegroup( "P4_2'/mnm'", diff --git a/pymatgen/core/tests/test_surface.py b/pymatgen/core/tests/test_surface.py index 4bab95f6d1c..28da7704495 100644 --- a/pymatgen/core/tests/test_surface.py +++ b/pymatgen/core/tests/test_surface.py @@ -193,7 +193,6 @@ def test_surface_sites_and_symmetry(self): self.assertArrayAlmostEqual(r1, r2) def test_symmetrization(self): - # Restricted to primitive_elemental materials due to the risk of # broken stoichiometry. For compound materials, use is_polar() @@ -232,7 +231,6 @@ def test_symmetrization(self): all_slabs = [all_Ti_slabs, all_Ag_fcc_slabs] for slabs in all_slabs: - asymmetric_count = 0 symmetric_count = 0 @@ -254,7 +252,6 @@ def test_symmetrization(self): assert len(all_non_laue_slabs) > 0 def test_get_symmetric_sites(self): - # Check to see if we get an equivalent site on one # surface if we add a new site to the other surface @@ -287,7 +284,6 @@ def test_get_symmetric_sites(self): assert sg.is_laue() def test_oriented_unit_cell(self): - # Check to see if we get the fully reduced oriented unit # cell. This will also ensure that the constrain_latt # parameter for get_primitive_structure is working properly @@ -304,7 +300,6 @@ def surface_area(s): assert len(slab) >= len(ouc) def test_get_slab_regions(self): - # If a slab layer in the slab cell is not completely inside # the cell (noncontiguous), check that get_slab_regions will # be able to identify where the slab layers are located @@ -358,7 +353,6 @@ def test_as_dict(self): class SlabGeneratorTest(PymatgenTest): def setUp(self): - lattice = Lattice.cubic(3.010) frac_coords = [ [0.00000, 0.00000, 0.00000], @@ -608,7 +602,6 @@ def test_nonstoichiometric_symmetrized_slab(self): assert len(s) > len(self.Dy) def test_move_to_other_side(self): - # Tests to see if sites are added to opposite side s = self.get_structure("LiFePO4") slabgen = SlabGenerator(s, (0, 0, 1), 10, 10, center_slab=True) @@ -649,7 +642,6 @@ def test_bonds_broken(self): class ReconstructionGeneratorTests(PymatgenTest): def setUp(self): - l = Lattice.cubic(3.51) species = ["Ni"] coords = [[0, 0, 0]] @@ -670,7 +662,6 @@ def setUp(self): self.rec_archive = json.load(data_file) def test_build_slab(self): - # First lets test a reconstruction where we only remove atoms recon = ReconstructionGenerator(self.Ni, 10, 10, "fcc_110_missing_row_1x2") slab = recon.get_unreconstructed_slabs()[0] @@ -710,7 +701,6 @@ def test_build_slab(self): # different reconstructions with a non-primitive_elemental system def test_get_d(self): - # Ensure that regardless of the size of the vacuum or slab # layer, the spacing between atomic layers should be the same @@ -723,7 +713,6 @@ def test_get_d(self): @unittest.skip("This test relies on neighbor orders and is hard coded. Disable temporarily") def test_previous_reconstructions(self): - # Test to see if we generated all reconstruction types correctly and nothing changes m = StructureMatcher() @@ -778,7 +767,6 @@ def setUp(self): ) def test_get_symmetrically_distinct_miller_indices(self): - # Tests to see if the function obtains the known number of unique slabs indices = get_symmetrically_distinct_miller_indices(self.cscl, 1) @@ -807,7 +795,6 @@ def test_get_symmetrically_distinct_miller_indices(self): assert all([len(hkl) == 4 for hkl in indices]) def test_get_symmetrically_equivalent_miller_indices(self): - # Tests to see if the function obtains all equivalent hkl for cubic (100) indices001 = [ (1, 0, 0), @@ -828,7 +815,6 @@ def test_get_symmetrically_equivalent_miller_indices(self): assert all([len(hkl) == 4 for hkl in hcp_indices_100]) def test_generate_all_slabs(self): - slabs = generate_all_slabs(self.cscl, 1, 10, 10) # Only three possible slabs, one each in (100), (110) and (111). assert len(slabs) == 3 diff --git a/pymatgen/core/trajectory.py b/pymatgen/core/trajectory.py index fe4f990edd9..04dbe8561ea 100644 --- a/pymatgen/core/trajectory.py +++ b/pymatgen/core/trajectory.py @@ -183,7 +183,6 @@ def to_displacements(self): This is the opposite operation of `to_positions()`. """ if not self.coords_are_displacement: - displacements = np.subtract( self.frac_coords, np.roll(self.frac_coords, 1, axis=0), @@ -283,7 +282,6 @@ def __getitem__(self, frames: int | slice | list[int]) -> Structure | Trajectory # For integer input, return the structure at that frame if isinstance(frames, int): - if frames >= len(self): raise IndexError(f"Frame index {frames} out of range.") @@ -299,7 +297,6 @@ def __getitem__(self, frames: int | slice | list[int]) -> Structure | Trajectory # For slice input, return a trajectory if isinstance(frames, (slice, list, np.ndarray)): - if isinstance(frames, slice): start, stop, step = frames.indices(len(self)) selected = list(range(start, stop, step)) @@ -384,7 +381,7 @@ def write_Xdatcar( lines.append(f"Direct configuration= {si + 1}") - for (frac_coord, specie) in zip(frac_coords, self.species): + for frac_coord, specie in zip(frac_coords, self.species): coords = frac_coord line = f'{" ".join(format_str.format(c) for c in coords)} {specie}' lines.append(line) diff --git a/pymatgen/electronic_structure/bandstructure.py b/pymatgen/electronic_structure/bandstructure.py index 62acd441e95..1be1e7131cd 100644 --- a/pymatgen/electronic_structure/bandstructure.py +++ b/pymatgen/electronic_structure/bandstructure.py @@ -932,7 +932,6 @@ def apply_scissor(self, new_band_gap): if k >= max_index: old_dict["bands"][spin][k][v] = old_dict["bands"][spin][k][v] + shift else: - shift = new_band_gap - self.get_band_gap()["energy"] old_dict = self.as_dict() for spin in old_dict["bands"]: diff --git a/pymatgen/electronic_structure/cohp.py b/pymatgen/electronic_structure/cohp.py index eb68ac9d465..7b65d921885 100644 --- a/pymatgen/electronic_structure/cohp.py +++ b/pymatgen/electronic_structure/cohp.py @@ -883,7 +883,6 @@ def __init__(self, label, atom1, atom2, length, translation, num, icohp, are_coo self._is_spin_polarized = False def __str__(self): - if not self._are_coops and not self._are_cobis: if self._is_spin_polarized: return ( @@ -1338,7 +1337,6 @@ def get_integrated_cohp_in_energy_range( summedicohp = icohps if energy_range is None: - energies_corrected = cohp.energies - cohp.efermi spl_spinup = InterpolatedUnivariateSpline(energies_corrected, summedicohp[Spin.up], ext=0) diff --git a/pymatgen/electronic_structure/core.py b/pymatgen/electronic_structure/core.py index 2768dee16a9..344522cc7e7 100644 --- a/pymatgen/electronic_structure/core.py +++ b/pymatgen/electronic_structure/core.py @@ -174,7 +174,6 @@ def from_global_moment_and_saxis(cls, global_moment, saxis): @classmethod def _get_transformation_matrix(cls, saxis): - saxis = saxis / np.linalg.norm(saxis) alpha = np.arctan2(saxis[1], saxis[0]) @@ -195,7 +194,6 @@ def _get_transformation_matrix(cls, saxis): @classmethod def _get_transformation_matrix_inv(cls, saxis): - saxis = saxis / np.linalg.norm(saxis) alpha = np.arctan2(saxis[1], saxis[0]) diff --git a/pymatgen/electronic_structure/dos.py b/pymatgen/electronic_structure/dos.py index d633905af7f..4be5d7d1a33 100644 --- a/pymatgen/electronic_structure/dos.py +++ b/pymatgen/electronic_structure/dos.py @@ -1454,7 +1454,6 @@ def get_site_t2g_eg_resolved_dos(self, site: PeriodicSite) -> dict[str, Dos]: eg_dos = [] for s, atom_dos in self.pdos.items(): if s == site: - for orb, pdos in atom_dos.items(): if _get_orb_lobster(orb) in (Orbital.dxy, Orbital.dxz, Orbital.dyz): t2g_dos.append(pdos) diff --git a/pymatgen/electronic_structure/plotter.py b/pymatgen/electronic_structure/plotter.py index abe214693f3..eca8bc0557e 100644 --- a/pymatgen/electronic_structure/plotter.py +++ b/pymatgen/electronic_structure/plotter.py @@ -617,7 +617,6 @@ def get_plot( colors = list(plt.rcParams["axes.prop_cycle"].by_key().values())[0] for ibs, bs in enumerate(self._bs): - # set first bs in the list as ref for rescaling the distances of the other bands bs_ref = self._bs[0] if len(self._bs) > 1 and ibs > 0 else None @@ -1639,7 +1638,6 @@ class to get the final_structure and as a for elt in dictpa_d: for numa in dictpa_d[elt]: for o in dictio_d[elt]: - count += 1 if num_column is None: if number_figs == 1: @@ -4362,7 +4360,6 @@ def plot_points(points, lattice=None, coords_are_cartesian=False, fold=False, ax raise ValueError("coords_are_cartesian False or fold True require the lattice") for p in points: - if fold: p = fold_point(p, lattice, coords_are_cartesian=coords_are_cartesian) diff --git a/pymatgen/electronic_structure/tests/test_bandstructure.py b/pymatgen/electronic_structure/tests/test_bandstructure.py index d2e9e658064..18a968589b2 100644 --- a/pymatgen/electronic_structure/tests/test_bandstructure.py +++ b/pymatgen/electronic_structure/tests/test_bandstructure.py @@ -54,7 +54,6 @@ def test_as_dict(self): assert self.kpoint.as_dict()["ccoords"] == [1.0, 4.0, -5.0] def test_from_dict(self): - d = self.kpoint.as_dict() kpoint = Kpoint.from_dict(d) diff --git a/pymatgen/electronic_structure/tests/test_core.py b/pymatgen/electronic_structure/tests/test_core.py index edb9a2f481f..69e328f8290 100644 --- a/pymatgen/electronic_structure/tests/test_core.py +++ b/pymatgen/electronic_structure/tests/test_core.py @@ -59,7 +59,6 @@ def test_init(self): assert np.allclose(magmom5.global_moment, [1, 2, 3]) def test_get_moments(self): - # simple cases magmom_along_x = Magmom([1, 0, 0]) assert np.allclose(magmom_along_x.get_moment(saxis=[1, 0, 0]), [0, 0, 1]) diff --git a/pymatgen/electronic_structure/tests/test_dos.py b/pymatgen/electronic_structure/tests/test_dos.py index c36f5a99695..ae14975495b 100644 --- a/pymatgen/electronic_structure/tests/test_dos.py +++ b/pymatgen/electronic_structure/tests/test_dos.py @@ -289,14 +289,12 @@ def test_dos_fp_exceptions(self): dos_fp2 = self.dos.get_dos_fp(type="tdos", min_e=-10, max_e=0, n_bins=56, normalize=True) # test exceptions with pytest.raises(ValueError) as exc_info: - self.dos.get_dos_fp_similarity(dos_fp, dos_fp2, col=1, tanimoto=True, normalize=True) assert ( str(exc_info.value) == "Cannot compute similarity index. Please set either " "normalize=True or tanimoto=True or both to False." ) with pytest.raises(ValueError) as exc_info: - self.dos.get_dos_fp(type="k", min_e=-10, max_e=0, n_bins=56, normalize=True) assert ( str(exc_info.value) == "Please recheck type requested, either the orbital " @@ -337,7 +335,6 @@ def test_spin_polarization(self): class LobsterCompleteDosTest(unittest.TestCase): def setUp(self): - with open(os.path.join(PymatgenTest.TEST_FILES_DIR, "LobsterCompleteDos_spin.json")) as f: data_spin = json.load(f) self.LobsterCompleteDOS_spin = LobsterCompleteDos.from_dict(data_spin) diff --git a/pymatgen/entries/correction_calculator.py b/pymatgen/entries/correction_calculator.py index 6b6604deff5..0460c4058d9 100644 --- a/pymatgen/entries/correction_calculator.py +++ b/pymatgen/entries/correction_calculator.py @@ -126,7 +126,6 @@ def compute_corrections(self, exp_entries: list, calc_entries: dict) -> dict: entry.correction = 0 for cmpd_info in self.exp_compounds: - # to get consistent element ordering in formula name = Composition(cmpd_info["formula"]).reduced_formula diff --git a/pymatgen/entries/mixing_scheme.py b/pymatgen/entries/mixing_scheme.py index b2c9faaea88..cf45ac8fd4f 100644 --- a/pymatgen/entries/mixing_scheme.py +++ b/pymatgen/entries/mixing_scheme.py @@ -586,7 +586,6 @@ def _filter_and_sort_entries(self, entries, verbose=True): filtered_entries = [] for entry in entries: - if not entry.parameters.get("run_type"): warnings.warn( f"Entry {entry.entry_id} is missing parameters.run_type! This field" diff --git a/pymatgen/entries/tests/test_compatibility.py b/pymatgen/entries/tests/test_compatibility.py index 2e527d72445..d17a17e0774 100644 --- a/pymatgen/entries/tests/test_compatibility.py +++ b/pymatgen/entries/tests/test_compatibility.py @@ -2014,7 +2014,6 @@ class TestMaterialsProjectAqueousCompatibility: """ def test_h_h2o_energy_with_args_single(self): - compat = MaterialsProjectAqueousCompatibility( o2_energy=-4.9276, h2o_energy=-5, @@ -2047,7 +2046,6 @@ def test_h_h2o_energy_with_args_single(self): assert h2o_form_e == pytest.approx(MU_H2O) def test_h_h2o_energy_with_args_multi(self): - compat = MaterialsProjectAqueousCompatibility( o2_energy=-4.9276, h2o_energy=-5, @@ -2073,7 +2071,6 @@ def test_h_h2o_energy_with_args_multi(self): assert h2o_form_e == pytest.approx(MU_H2O) def test_h_h2o_energy_no_args(self): - with pytest.warns(UserWarning, match="You did not provide the required O2 and H2O energies."): compat = MaterialsProjectAqueousCompatibility(solid_compat=None) @@ -2165,7 +2162,6 @@ def setUp(self): self.aqcorr = AqueousCorrection(fp) def test_aqueous_compat(self): - el_li = Element("Li") el_o = Element("O") el_h = Element("H") diff --git a/pymatgen/entries/tests/test_correction_calculator.py b/pymatgen/entries/tests/test_correction_calculator.py index 272fbe39a62..c48420137e2 100644 --- a/pymatgen/entries/tests/test_correction_calculator.py +++ b/pymatgen/entries/tests/test_correction_calculator.py @@ -11,7 +11,6 @@ class CorrectionCalculatorTest(unittest.TestCase): def setUp(self): - self.exclude_polyanions = [ "SO4", "CO3", diff --git a/pymatgen/ext/optimade.py b/pymatgen/ext/optimade.py index d08b603f83e..8c071497418 100644 --- a/pymatgen/ext/optimade.py +++ b/pymatgen/ext/optimade.py @@ -120,12 +120,10 @@ def __init__(self, aliases_or_resource_urls: str | list[str] | None = None, time ) for alias_or_resource_url in aliases_or_resource_urls: - if alias_or_resource_url in self.aliases: self.resources[alias_or_resource_url] = self.aliases[alias_or_resource_url] elif self._validate_provider(alias_or_resource_url): - # TODO: unclear what the key should be here, the "prefix" is for the root provider, # may need to walk back to the index for the given provider to find the correct identifier @@ -306,11 +304,9 @@ def get_snls_with_filter( response_fields = self._handle_response_fields(additional_response_fields) for identifier, resource in self.resources.items(): - url = join(resource, f"v1/structures?filter={optimade_filter}&{response_fields=}") try: - json = self._get_json(url) structures = self._get_snls_from_resource(json, url, identifier) @@ -329,11 +325,9 @@ def get_snls_with_filter( pbar.update(len(additional_structures)) if structures: - all_snls[identifier] = structures except Exception as exc: - # TODO: manually inspect failures to either (a) correct a bug or (b) raise more appropriate error _logger.error( @@ -344,7 +338,6 @@ def get_snls_with_filter( @staticmethod def _get_snls_from_resource(json, url, identifier) -> dict[str, StructureNL]: - snls = {} exceptions = set() @@ -363,7 +356,6 @@ def _get_comp(sp_dict): } for data in json["data"]: - # TODO: check the spec! and remove this try/except (are all providers following spec?) # e.g. can check data["type"] == "structures" @@ -394,7 +386,6 @@ def _get_comp(sp_dict): # TODO: bare exception, remove... except Exception: - try: # e.g. MP (all ordered, no vacancies) structure = Structure( diff --git a/pymatgen/ext/tests/test_matproj.py b/pymatgen/ext/tests/test_matproj.py index 95c74eb4ee6..8fefced0842 100644 --- a/pymatgen/ext/tests/test_matproj.py +++ b/pymatgen/ext/tests/test_matproj.py @@ -491,7 +491,6 @@ def test_include_user_agent(self): assert "user-agent" not in self.rester.session.headers, "user-agent header unwanted" def test_database_version(self): - with _MPResterLegacy(notify_db_version=True) as mpr: db_version = mpr.get_database_version() @@ -504,7 +503,6 @@ def test_database_version(self): assert isinstance(d["MAPI_DB_VERSION"]["LOG"][db_version], int) def test_pourbaix_heavy(self): - entries = self.rester.get_pourbaix_entries(["Li", "Mg", "Sn", "Pd"]) _ = PourbaixDiagram(entries, nproc=4, filter_solids=False) entries = self.rester.get_pourbaix_entries(["Ba", "Ca", "V", "Cu", "F"]) @@ -515,7 +513,6 @@ def test_pourbaix_heavy(self): _ = PourbaixDiagram(entries, nproc=4, filter_solids=False) def test_pourbaix_mpr_pipeline(self): - data = self.rester.get_pourbaix_entries(["Zn"]) pbx = PourbaixDiagram(data, filter_solids=True, conc_dict={"Zn": 1e-8}) pbx.find_stable_entry(10, 0) diff --git a/pymatgen/ext/tests/test_optimade.py b/pymatgen/ext/tests/test_optimade.py index 7b0f9fd3d21..58df7fe5abd 100644 --- a/pymatgen/ext/tests/test_optimade.py +++ b/pymatgen/ext/tests/test_optimade.py @@ -23,19 +23,15 @@ ) class OptimadeTest(PymatgenTest): def test_get_structures_mp(self): - with OptimadeRester("mp") as optimade: - structs = optimade.get_structures(elements=["Ga", "N"], nelements=2) with OptimadeRester("mp") as optimade: - _filter = 'elements HAS ALL "Ga", "N" AND nelements=2' raw_filter_structs = optimade.get_structures_with_filter(_filter) # skip if query fails to return any results (e.g. server down or inaccessible) if ("mp" in structs) and ("mp" in raw_filter_structs): - test_struct = next(iter(structs["mp"].values())) assert [str(el) for el in test_struct.types_of_species] == ["Ga", "N"] @@ -45,7 +41,6 @@ def test_get_structures_mp(self): def test_get_snls_mp(self): with OptimadeRester("mp") as optimade: - structs = optimade.get_snls(elements=["Ga", "N"], nelements=2) with OptimadeRester("mp") as optimade: diff --git a/pymatgen/io/abinit/abiobjects.py b/pymatgen/io/abinit/abiobjects.py index 033230d15c5..e6aa4f52cc2 100644 --- a/pymatgen/io/abinit/abiobjects.py +++ b/pymatgen/io/abinit/abiobjects.py @@ -485,7 +485,7 @@ def as_smearing(cls, obj): @property def mode(self): """String with smearing technique.""" - for (mode_str, occopt) in self._mode2occopt.items(): + for mode_str, occopt in self._mode2occopt.items(): if occopt == self.occopt: return mode_str raise AttributeError(f"Unknown occopt {self.occopt}") diff --git a/pymatgen/io/abinit/abitimer.py b/pymatgen/io/abinit/abitimer.py index d761a3e0d67..4b0d9e755cb 100644 --- a/pymatgen/io/abinit/abitimer.py +++ b/pymatgen/io/abinit/abitimer.py @@ -523,7 +523,6 @@ def __init__(self, filenames, ref_idx, *args, **kwargs): self._ref_idx = ref_idx def _order_by_peff(self, key, criterion, reverse=True): - self.estimator = { "min": min, "max": max, @@ -531,7 +530,7 @@ def _order_by_peff(self, key, criterion, reverse=True): }[criterion] data = [] - for (sect_name, peff) in self.items(): + for sect_name, peff in self.items(): # Ignore values where we had a division by zero. if all(v != -1 for v in peff[key]): values = peff[key][:] diff --git a/pymatgen/io/abinit/pseudos.py b/pymatgen/io/abinit/pseudos.py index b1d473042f4..e787207ec00 100644 --- a/pymatgen/io/abinit/pseudos.py +++ b/pymatgen/io/abinit/pseudos.py @@ -640,7 +640,7 @@ def _dict_from_lines(lines, key_nums, sep=None): kwargs = Namespace() - for (i, nk) in enumerate(key_nums): + for i, nk in enumerate(key_nums): if nk == 0: continue line = lines[i] @@ -1133,7 +1133,6 @@ def read_ppdesc(self, filename): lines = _read_nlines(filename, 80) for lineno, line in enumerate(lines): - if lineno == 2: try: tokens = line.split() @@ -1417,7 +1416,7 @@ def ae_partial_waves(self): def pseudo_partial_waves(self): """Dictionary with the pseudo partial waves indexed by state.""" pseudo_partial_waves = {} - for (mesh, values, attrib) in self._parse_all_radfuncs("pseudo_partial_wave"): + for mesh, values, attrib in self._parse_all_radfuncs("pseudo_partial_wave"): state = attrib["state"] # val_state = self.valence_states[state] pseudo_partial_waves[state] = RadialFunction(mesh, values) @@ -1428,7 +1427,7 @@ def pseudo_partial_waves(self): def projector_functions(self): """Dictionary with the PAW projectors indexed by state.""" projector_functions = {} - for (mesh, values, attrib) in self._parse_all_radfuncs("projector_function"): + for mesh, values, attrib in self._parse_all_radfuncs("projector_function"): state = attrib["state"] # val_state = self.valence_states[state] projector_functions[state] = RadialFunction(mesh, values) diff --git a/pymatgen/io/abinit/variable.py b/pymatgen/io/abinit/variable.py index 6cd934bccb8..3a072fed8e8 100644 --- a/pymatgen/io/abinit/variable.py +++ b/pymatgen/io/abinit/variable.py @@ -110,7 +110,6 @@ def __str__(self): # values in lists if isinstance(value, (list, tuple)): - # Reshape a list of lists into a single list if all(isinstance(v, (list, tuple)) for v in value): line += self.format_list2d(value, floatdecimal) @@ -182,7 +181,6 @@ def format_list2d(values, floatdecimal=0): elif type_all == str: formatspec = f">{width}" else: - # Number of decimal maxdec = max(len(str(f - int(f))) - 2 for f in lvals) ndec = min(max(maxdec, floatdecimal), 10) diff --git a/pymatgen/io/atat.py b/pymatgen/io/atat.py index 1b88204841b..ca7f128cef5 100644 --- a/pymatgen/io/atat.py +++ b/pymatgen/io/atat.py @@ -112,7 +112,6 @@ def structure_from_string(data): all_coords = [] all_species = [] for l in data[first_species_line:]: - coords = np.array([l[0], l[1], l[2]], dtype=float) scaled_coords = np.matmul(coords, np.linalg.inv(lattice_vecs)) all_coords.append(scaled_coords) @@ -124,7 +123,6 @@ def structure_from_string(data): species = {} for species_occ in species_strs: - # gets a species, occupancy pair species_occ = species_occ.split("=") diff --git a/pymatgen/io/cif.py b/pymatgen/io/cif.py index d010df581f2..212aeb0ab1a 100644 --- a/pymatgen/io/cif.py +++ b/pymatgen/io/cif.py @@ -261,7 +261,6 @@ def from_string(cls, string): """ d = {} for x in re.split(r"^\s*data_", "x\n" + string, flags=re.MULTILINE | re.DOTALL)[1:]: - # Skip over Cif block that contains powder diffraction data. # Some elements in this block were missing from CIF files in # Springer materials/Pauling file DBs. @@ -405,7 +404,6 @@ def _sanitize_data(self, data): # Check to see if "_atom_site_type_symbol" exists, as some test CIFs do # not contain this key. if "_atom_site_type_symbol" in data.data: - # Keep a track of which data row needs to be removed. # Example of a row: Nb,Zr '0.8Nb + 0.2Zr' .2a .m-3m 0 0 0 1 14 # 'rhombic dodecahedron, Nb14' @@ -425,7 +423,6 @@ def _sanitize_data(self, data): new_fract_z = [] for idx, el_row in enumerate(data["_atom_site_label"]): - # CIF files from the Springer Materials/Pauling File have # switched the label and symbol. Thus, in the # above shown example row, '0.8Nb + 0.2Zr' is the symbol. @@ -433,7 +430,6 @@ def _sanitize_data(self, data): # check if the length (or number of elements) in the label and # symbol are equal. if len(data["_atom_site_type_symbol"][idx].split(" + ")) > len(el_row.split(" + ")): - # Dictionary to hold extracted elements and occupancies els_occu = {} @@ -493,7 +489,6 @@ def _sanitize_data(self, data): specification being finalized (on advice of Branton Campbell). """ if self.feature_flags["magcif"]: - # CIF-1 style has all underscores, interim standard # had period before magn instead of before the final # component (e.g. xyz) @@ -614,7 +609,6 @@ def get_lattice( and necessary parameters are parsed """ try: - return self.get_lattice_no_exception( data=data, angle_strings=angle_strings, lattice_type=lattice_type, length_strings=length_strings ) @@ -628,7 +622,6 @@ def get_lattice( if data.data.get(lattice_lable): lattice_type = data.data.get(lattice_lable).lower() try: - required_args = getargspec(getattr(Lattice, lattice_type)).args lengths = (l for l in length_strings if l in required_args) @@ -770,14 +763,12 @@ def get_magsymops(self, data): # check to see if magCIF file explicitly contains magnetic symmetry operations if data.data.get("_space_group_symop_magn_operation.xyz"): - xyzt = data.data.get("_space_group_symop_magn_operation.xyz") if isinstance(xyzt, str): xyzt = [xyzt] magsymmops = [MagSymmOp.from_xyzt_string(s) for s in xyzt] if data.data.get("_space_group_symop_magn_centering.xyz"): - xyzt = data.data.get("_space_group_symop_magn_centering.xyz") if isinstance(xyzt, str): xyzt = [xyzt] @@ -801,7 +792,6 @@ def get_magsymops(self, data): # else check to see if it specifies a magnetic space group elif data.data.get("_space_group_magn.name_BNS") or data.data.get("_space_group_magn.number_BNS"): - if data.data.get("_space_group_magn.name_BNS"): # get BNS label for MagneticSpaceGroup() id = data.data.get("_space_group_magn.name_BNS") @@ -812,7 +802,6 @@ def get_magsymops(self, data): if data.data.get("_space_group_magn.transform_BNS_Pp_abc"): if data.data.get("_space_group_magn.transform_BNS_Pp_abc") != "a,b,c;0,0,0": - jf = data.data.get("_space_group_magn.transform_BNS_Pp_abc") msg = MagneticSpaceGroup(id, jf) @@ -957,7 +946,6 @@ def get_matching_coord(coord): return False for i in range(len(data["_atom_site_label"])): - try: # If site type symbol exists, use it. Otherwise, we use the # label. @@ -1101,7 +1089,6 @@ def get_matching_coord(coord): struct = Structure(lattice, allspecies, allcoords, site_properties=site_properties) if symmetrized: - # Wyckoff labels not currently parsed, note that not all CIFs will contain Wyckoff labels # TODO: extract Wyckoff labels (or other CIF attributes) and include as site_properties wyckoffs = ["Not Parsed"] * len(struct) @@ -1205,7 +1192,6 @@ def get_bibtex_string(self): # TODO: CIF specification supports multiple citations. for idx, data in enumerate(self._cif.data.values()): - # convert to lower-case keys, some cif files inconsistent data = {k.lower(): v for k, v in data.data.items()} diff --git a/pymatgen/io/cp2k/inputs.py b/pymatgen/io/cp2k/inputs.py index 0af4bdde819..523e9844c74 100644 --- a/pymatgen/io/cp2k/inputs.py +++ b/pymatgen/io/cp2k/inputs.py @@ -2556,7 +2556,6 @@ def from_string(cls, string: str) -> GaussianTypeOrbitalBasisSet: line_index = 2 for set_index in range(nset): - setinfo = lines[line_index].split() _n, _lmin, _lmax, _nexp = map(int, setinfo[0:4]) n.append(_n) diff --git a/pymatgen/io/cp2k/outputs.py b/pymatgen/io/cp2k/outputs.py index 8800e3e64ac..830405e8fd2 100644 --- a/pymatgen/io/cp2k/outputs.py +++ b/pymatgen/io/cp2k/outputs.py @@ -1568,7 +1568,6 @@ def parse_raman(self): @staticmethod def _gauss_smear(densities, energies, npts, width): - if not width: return densities diff --git a/pymatgen/io/cp2k/tests/test_sets.py b/pymatgen/io/cp2k/tests/test_sets.py index 38871c9b0ab..17083cd5642 100644 --- a/pymatgen/io/cp2k/tests/test_sets.py +++ b/pymatgen/io/cp2k/tests/test_sets.py @@ -40,7 +40,6 @@ def setUp(self) -> None: return super().setUp() def test_dft_set(self): - # Basis sets / potentials searching basis_and_potential = {"basis_type": "SZV", "potential_type": "Pseudopotential", "functional": None} ss = DftSet(Si_structure, basis_and_potential=basis_and_potential, xc_functionals="PBE") diff --git a/pymatgen/io/feff/sets.py b/pymatgen/io/feff/sets.py index dd82b6d85a1..2aebfdb67ea 100644 --- a/pymatgen/io/feff/sets.py +++ b/pymatgen/io/feff/sets.py @@ -333,7 +333,6 @@ def from_directory(input_dir): ) for site_index, site in enumerate(sub_d["header"].struct): - if site.specie == input_atoms[0].specie: site_atoms = Atoms(sub_d["header"].struct, absorbing_atom=site_index, radius=radius) site_distance = np.array(site_atoms.get_lines())[:, 5].astype(np.float64) diff --git a/pymatgen/io/feff/tests/test_sets.py b/pymatgen/io/feff/tests/test_sets.py index 02dd6bbadb0..42d6b2c197f 100644 --- a/pymatgen/io/feff/tests/test_sets.py +++ b/pymatgen/io/feff/tests/test_sets.py @@ -21,7 +21,6 @@ class FeffInputSetTest(unittest.TestCase): @classmethod def setUpClass(cls): - cls.header_string = """* This FEFF.inp file generated by pymatgen TITLE comment: From cif file TITLE Source: CoO19128.cif diff --git a/pymatgen/io/fiesta.py b/pymatgen/io/fiesta.py index 51e93e1b8e9..bb54dcf941f 100644 --- a/pymatgen/io/fiesta.py +++ b/pymatgen/io/fiesta.py @@ -222,7 +222,6 @@ def __init__(self, filename): @staticmethod def _parse_file(input): - lmax_nnlo_patt = re.compile(r"\s* (\d+) \s+ (\d+) \s+ \# .* ", re.VERBOSE) nl_orbital_patt = re.compile(r"\s* (\d+) \s+ (\d+) \s+ (\d+) \s+ \# .* ", re.VERBOSE) @@ -234,9 +233,10 @@ def _parse_file(input): parse_preamble = False parse_lmax_nnlo = False parse_nl_orbital = False + nnlo = None # fix pylint E0601: Using variable 'nnlo' before assignment + lmax = None for line in input.split("\n"): - if parse_nl_orbital: m = nl_orbital_patt.search(line) n = coef_alpha_patt.search(line) @@ -480,7 +480,6 @@ def molecule(self): return self._mol def __str__(self): - symbols = [] for syb in self._mol.symbol_set: symbols.append(syb) @@ -761,7 +760,6 @@ def __init__(self, filename): @staticmethod def _parse_job(output): - GW_BANDS_results_patt = re.compile( r"^ 13: raise ValueError("Environment cannot be determined. Number of neighbors is larger than 13.") # to avoid problems if _neigh_coords is empty @@ -302,9 +301,7 @@ def get_light_structure_environment(self, only_cation_environments=False, only_i new_list_neighisite = [] for ival, val in enumerate(self.valences): - if val >= 0.0: - new_list_ce_symbols.append(list_ce_symbols[ival]) new_list_csm.append(list_csm[ival]) new_list_permut.append(list_permut[ival]) @@ -334,9 +331,7 @@ def get_light_structure_environment(self, only_cation_environments=False, only_i new_list_neighisite = [] for isite, _site in enumerate(self.structure): - if isite in only_indices: - new_list_ce_symbols.append(list_ce_symbols[isite]) new_list_csm.append(list_csm[isite]) new_list_permut.append(list_permut[isite]) @@ -647,7 +642,6 @@ def get_info_icohps_between_neighbors(self, isites=None, onlycation_isites=True) done = False for icohp in icohps.values(): - atomnr1 = self._get_atomnumber(icohp._atom1) atomnr2 = self._get_atomnumber(icohp._atom2) label = icohp._label @@ -655,9 +649,7 @@ def get_info_icohps_between_neighbors(self, isites=None, onlycation_isites=True) if (index_n_site == atomnr1 and index_n_site2 == atomnr2) or ( index_n_site == atomnr2 and index_n_site2 == atomnr1 ): - if atomnr1 != atomnr2: - if np.all(np.asarray(translation) == np.asarray(icohp._translation)): summed_icohps += icohp.summed_icohp list_icohps.append(icohp.summed_icohp) @@ -724,7 +716,6 @@ def _evaluate_ce( """ # get extremum if lowerlimit is None and upperlimit is None: - lowerlimit, upperlimit = self._get_limit_from_extremum( self.Icohpcollection, percentage=perc_strength_ICOHP, @@ -757,7 +748,6 @@ def _evaluate_ce( # make a structure graph # make sure everything is relative to the given Structure and not just the atoms in the unit cell if self.add_additional_data_sg: - self.sg_list = [ [ { @@ -851,7 +841,6 @@ def _find_environments(self, additional_condition, lowerlimit, upperlimit, only_ list_lengths = [] list_keys = [] for isite in range(len(self.structure)): - icohps = self._get_icohps( icohpcollection=self.Icohpcollection, isite=isite, @@ -1031,7 +1020,6 @@ def _find_relevant_atoms_additional_condition(self, isite, icohps, additional_co elif additional_condition == 4: # ONLY_ELEMENT_TO_OXYGEN_BONDS = 4 if icohp._atom1.rstrip("0123456789") == "O" or icohp._atom2.rstrip("0123456789") == "O": - if atomnr1 == isite: neighbors_from_ICOHPs.append(atomnr2) lengths_from_ICOHPs.append(icohp._length) @@ -1285,7 +1273,6 @@ def from_Lobster( neighbors_sets = [] counter = 0 for isite, _site in enumerate(structure): - # all_nbs_sites_here=[] all_nbs_sites_indices_here = [] # Coordination environment diff --git a/pymatgen/io/lobster/outputs.py b/pymatgen/io/lobster/outputs.py index 0b3f4f42d18..438d01d1a60 100644 --- a/pymatgen/io/lobster/outputs.py +++ b/pymatgen/io/lobster/outputs.py @@ -941,7 +941,6 @@ def _get_elements_basistype_basisfunctions(data): basistype = [] basisfunctions = [] for row in data: - if begin and not end: splitrow = row.split() if splitrow[0] not in [ @@ -954,7 +953,6 @@ def _get_elements_basistype_basisfunctions(data): "spillings", "writing", ]: - elements.append(splitrow[0]) basistype.append(splitrow[1].replace("(", "").replace(")", "")) # last sign is a '' @@ -1232,7 +1230,6 @@ def __init__(self, filenames=".", vasprun="vasprun.xml", Kpointsfile="KPOINTS"): if linenumber == self.nbands: iband = 0 if line.split()[0] != "#": - if linenumber < self.nbands: if ifilename == 0: eigenvals[Spin.up][iband][ikpoint] = float(line.split()[1]) + self.efermi @@ -1256,7 +1253,6 @@ def __init__(self, filenames=".", vasprun="vasprun.xml", Kpointsfile="KPOINTS"): label_dict = {} for ilabel, label in enumerate(kpoints_object.labels[-self.number_kpts :], start=0): - if label is not None: label_dict[label] = kpoints_array[ilabel] diff --git a/pymatgen/io/lobster/tests/test_lobster.py b/pymatgen/io/lobster/tests/test_lobster.py index c42121d534e..804665be10d 100644 --- a/pymatgen/io/lobster/tests/test_lobster.py +++ b/pymatgen/io/lobster/tests/test_lobster.py @@ -1927,7 +1927,6 @@ def test_write_INCAR(self): } def test_write_KPOINTS(self): - # line mode outfile_path = tempfile.mkstemp()[1] outfile_path2 = tempfile.mkstemp(prefix="POSCAR")[1] diff --git a/pymatgen/io/qchem/outputs.py b/pymatgen/io/qchem/outputs.py index 8a8fd0dbc19..730f46ab1fd 100644 --- a/pymatgen/io/qchem/outputs.py +++ b/pymatgen/io/qchem/outputs.py @@ -787,10 +787,10 @@ def _read_SCF(self): r"[\d\-\.]+\s+[\d\-\.]+e[\d\-\.\+]+\s+Optimal value differs by [\d\-\.]+e[\d\-\.\+]+ from prediction)*" r"(?:\s*gdm_qls\: Orbitals will not converge further\.)*" r"(?:(\n\s*[a-z\dA-Z_\s/]+\.C|\n\s*GDM)::WARNING energy changes are now smaller than effective " - r"accuracy\.\s*(\n\s*[a-z\dA-Z_\s/]+\.C|\n\s*GDM)::\s+calculation will continue, but THRESH s" - r"hould be increased\s*" - r"(\n\s*[a-z\dA-Z_\s/]+\.C|\n\s*GDM)::\s+or SCF_CONVERGENCE decrea" - r"sed\.\s*(\n\s*[a-z\dA-Z_\s/]+\.C|\n\s*GDM)::\s+effective_thresh = [\d\-\.]+e[\d\-]+)*" + r"accuracy\.\s*(\n\s*[a-z\dA-Z_\s/]+\.C|\n\s*GDM)::\s+calculation will continue, but THRESH " + r"should be increased\s*" + r"(\n\s*[a-z\dA-Z_\s/]+\.C|\n\s*GDM)::\s+or SCF_CONVERGENCE decreased" + r"\.\s*(\n\s*[a-z\dA-Z_\s/]+\.C|\n\s*GDM)::\s+effective_thresh = [\d\-\.]+e[\d\-]+)*" ) else: if "SCF_failed_to_converge" in self.data.get("errors"): @@ -1002,7 +1002,7 @@ def _detect_general_warnings(self): self.data["warnings"]["inconsistent_size"] = True # Check for AO linear depend - if read_pattern(self.text, {"key": r"Linear dependence detected in AO basis"}, terminate_on_match=True,).get( + if read_pattern(self.text, {"key": r"Linear dependence detected in AO basis"}, terminate_on_match=True).get( "key" ) == [[]]: self.data["warnings"]["linear_dependence"] = True @@ -1040,13 +1040,13 @@ def _detect_general_warnings(self): self.data["warnings"]["bad_lambda_take_NR_step"] = True # Check for a switch into Cartesian coordinates - if read_pattern(self.text, {"key": r"SWITCHING TO CARTESIAN OPTIMIZATION"}, terminate_on_match=True,).get( + if read_pattern(self.text, {"key": r"SWITCHING TO CARTESIAN OPTIMIZATION"}, terminate_on_match=True).get( "key" ) == [[]]: self.data["warnings"]["switch_to_cartesian"] = True # Check for problem with eigenvalue magnitude - if read_pattern(self.text, {"key": r"\*\*WARNING\*\* Magnitude of eigenvalue"}, terminate_on_match=True,).get( + if read_pattern(self.text, {"key": r"\*\*WARNING\*\* Magnitude of eigenvalue"}, terminate_on_match=True).get( "key" ) == [[]]: self.data["warnings"]["eigenvalue_magnitude"] = True @@ -1264,9 +1264,7 @@ def _read_optimization_data(self): self._read_gradients() if temp_energy_trajectory is None: self.data["energy_trajectory"] = [] - if read_pattern(self.text, {"key": r"Error in back_transform"}, terminate_on_match=True,).get( - "key" - ) == [[]]: + if read_pattern(self.text, {"key": r"Error in back_transform"}, terminate_on_match=True).get("key") == [[]]: self.data["errors"] += ["back_transform_error"] else: real_energy_trajectory = np.zeros(len(temp_energy_trajectory)) @@ -1311,13 +1309,13 @@ def _read_optimization_data(self): terminate_on_match=True, ).get("key") == [[]]: self.data["errors"] += ["unable_to_determine_lamda"] - elif read_pattern(self.text, {"key": r"Error in back_transform"}, terminate_on_match=True,).get( + elif read_pattern(self.text, {"key": r"Error in back_transform"}, terminate_on_match=True).get( "key" ) == [[]]: self.data["errors"] += ["back_transform_error"] - elif read_pattern(self.text, {"key": r"pinv\(\)\: svd failed"}, terminate_on_match=True,).get( - "key" - ) == [[]]: + elif read_pattern(self.text, {"key": r"pinv\(\)\: svd failed"}, terminate_on_match=True).get("key") == [ + [] + ]: self.data["errors"] += ["svd_failed"] def _read_frequency_data(self): @@ -1830,17 +1828,15 @@ def _check_completion_errors(self): terminate_on_match=True, ).get("key") == [[]]: self.data["errors"] += ["driver_error"] - elif read_pattern(self.text, {"key": r"Basis not supported for the above atom"}, terminate_on_match=True,).get( + elif read_pattern(self.text, {"key": r"Basis not supported for the above atom"}, terminate_on_match=True).get( "key" ) == [[]]: self.data["errors"] += ["basis_not_supported"] - elif read_pattern(self.text, {"key": r"Unable to find relaxed density"}, terminate_on_match=True,).get( + elif read_pattern(self.text, {"key": r"Unable to find relaxed density"}, terminate_on_match=True).get( "key" ) == [[]]: self.data["errors"] += ["failed_cpscf"] - elif read_pattern(self.text, {"key": r"Out of Iterations- IterZ"}, terminate_on_match=True,).get( - "key" - ) == [[]]: + elif read_pattern(self.text, {"key": r"Out of Iterations- IterZ"}, terminate_on_match=True).get("key") == [[]]: self.data["errors"] += ["failed_cpscf"] elif read_pattern( self.text, @@ -1860,21 +1856,19 @@ def _check_completion_errors(self): terminate_on_match=True, ).get("key") == [[]]: self.data["errors"] += ["gdm_neg_precon_error"] - elif read_pattern(self.text, {"key": r"too many atoms in ESPChgFit"}, terminate_on_match=True,).get( - "key" - ) == [[]]: + elif read_pattern(self.text, {"key": r"too many atoms in ESPChgFit"}, terminate_on_match=True).get("key") == [ + [] + ]: self.data["errors"] += ["esp_chg_fit_error"] - elif read_pattern(self.text, {"key": r"Please use larger MEM_STATIC"}, terminate_on_match=True,).get( - "key" - ) == [[]]: + elif read_pattern(self.text, {"key": r"Please use larger MEM_STATIC"}, terminate_on_match=True).get("key") == [ + [] + ]: self.data["errors"] += ["mem_static_too_small"] - elif read_pattern(self.text, {"key": r"Please increase MEM_STATIC"}, terminate_on_match=True,).get( - "key" - ) == [[]]: + elif read_pattern(self.text, {"key": r"Please increase MEM_STATIC"}, terminate_on_match=True).get("key") == [ + [] + ]: self.data["errors"] += ["mem_static_too_small"] - elif read_pattern(self.text, {"key": r"Please increase MEM_TOTAL"}, terminate_on_match=True,).get( - "key" - ) == [[]]: + elif read_pattern(self.text, {"key": r"Please increase MEM_TOTAL"}, terminate_on_match=True).get("key") == [[]]: self.data["errors"] += ["mem_total_too_small"] elif self.text[-34:-2] == "Computing fast CPCM-SWIG hessian": self.data["errors"] += ["probably_out_of_memory"] @@ -2057,7 +2051,6 @@ def parse_natural_populations(lines: list[str]) -> list[pd.DataFrame]: pop_dfs = [] while no_failures: - # Natural populations try: lines = jump_to_header(lines, "Summary of Natural Population Analysis:") @@ -2073,7 +2066,6 @@ def parse_natural_populations(lines: list[str]) -> list[pd.DataFrame]: lines = lines[2:] data = [] for line in lines: - # Termination condition if "=" in line: break @@ -2130,14 +2122,12 @@ def parse_hyperbonds(lines: list[str]) -> list[pd.DataFrame]: no_failures = False if no_failures: - # Jump to values lines = lines[2:] # Extract hyperbond data hyperbond_data = [] for line in lines: - # Termination condition if "NATURAL BOND ORBITALS" in line: break @@ -2207,7 +2197,6 @@ def parse_hybridization_character(lines: list[str]) -> list[pd.DataFrame]: lp_and_bd_and_tc_dfs = [] while no_failures: - # NBO Analysis try: lines = jump_to_header(lines, "(Occupancy) Bond orbital/ Coefficients/ Hybrids") @@ -2218,7 +2207,6 @@ def parse_hybridization_character(lines: list[str]) -> list[pd.DataFrame]: no_failures = False if no_failures: - # Jump to values lines = lines[2:] @@ -2442,7 +2430,6 @@ def parse_perturbation_energy(lines: list[str]) -> list[pd.DataFrame]: e2_dfs = [] while no_failures: - # 2nd order perturbation theory analysis try: lines = jump_to_header( @@ -2453,7 +2440,6 @@ def parse_perturbation_energy(lines: list[str]) -> list[pd.DataFrame]: no_failures = False if no_failures: - # Jump to values i = -1 while True: @@ -2466,7 +2452,6 @@ def parse_perturbation_energy(lines: list[str]) -> list[pd.DataFrame]: # Extract 2nd order data e2_data = [] for line in lines: - # Termination condition if "NATURAL BOND ORBITALS" in line: break @@ -2519,7 +2504,7 @@ def parse_perturbation_energy(lines: list[str]) -> list[pd.DataFrame]: # This is a bit hacky, but making new more accurate entry # keys for 3C info forces there to be a NAN for those values # for all other entries, which I believe would nontrivially - # increase the size of the data being stored, which is aleady + # increase the size of the data being stored, which is already # very large. So, here we have saved info that should be labeled # "donor 3C 1", "donor 3C 2", and "donor 3C 3" in the # "donor atom 1 symbol", "donor atom 1 number", and @@ -2547,7 +2532,7 @@ def parse_perturbation_energy(lines: list[str]) -> list[pd.DataFrame]: # This is a bit hacky, but making new more accurate entry # keys for 3C info forces there to be a NAN for those values # for all other entries, which I believe would nontrivially - # increase the size of the data being stored, which is aleady + # increase the size of the data being stored, which is already # very large. So, here we have saved info that should be labeled # "acceptor 3C 1", "acceptor 3C 2", and "acceptor 3C 3" in the # "acceptor atom 1 symbol", "acceptor atom 1 number", and diff --git a/pymatgen/io/qchem/tests/test_inputs.py b/pymatgen/io/qchem/tests/test_inputs.py index 8c9bff0573e..cd02eba6d5e 100644 --- a/pymatgen/io/qchem/tests/test_inputs.py +++ b/pymatgen/io/qchem/tests/test_inputs.py @@ -26,7 +26,6 @@ class TestQCInput(PymatgenTest): - # ef setUpClass(cls): # add things that show up over and over again diff --git a/pymatgen/io/qchem/tests/test_outputs.py b/pymatgen/io/qchem/tests/test_outputs.py index d222eabbc45..e2a30d76013 100644 --- a/pymatgen/io/qchem/tests/test_outputs.py +++ b/pymatgen/io/qchem/tests/test_outputs.py @@ -285,7 +285,6 @@ def test_all(self): @unittest.skipIf((openbabel is None), "OpenBabel not installed.") def test_structural_change(self): - t1 = Molecule.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "molecules", "structural_change", "t1.xyz")) t2 = Molecule.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "molecules", "structural_change", "t2.xyz")) t3 = Molecule.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "molecules", "structural_change", "t3.xyz")) diff --git a/pymatgen/io/qchem/tests/test_utils.py b/pymatgen/io/qchem/tests/test_utils.py index f5056844a08..0b029f0b8c9 100644 --- a/pymatgen/io/qchem/tests/test_utils.py +++ b/pymatgen/io/qchem/tests/test_utils.py @@ -43,7 +43,6 @@ def test_lower_and_check_unique(self): lower_and_check_unique(d4) def test_process_parsed_HESS(self): - data_132 = [] with zopen(os.path.join(test_dir, "parse_hess", "132.0"), mode="rb") as file: binary = file.read() diff --git a/pymatgen/io/tests/test_ase.py b/pymatgen/io/tests/test_ase.py index 429b3fd1785..b6a4811de6e 100644 --- a/pymatgen/io/tests/test_ase.py +++ b/pymatgen/io/tests/test_ase.py @@ -143,7 +143,6 @@ def test_get_atoms_from_molecule_mags(self): @unittest.skipIf(not aio.ase_loaded, "ASE not loaded.") def test_get_atoms_from_molecule_dyn(self): - molecule = Molecule.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "acetylene.xyz")) molecule.add_site_property("selective_dynamics", [[False] * 3] * len(molecule)) atoms = aio.AseAtomsAdaptor.get_atoms(molecule) diff --git a/pymatgen/io/tests/test_atat.py b/pymatgen/io/tests/test_atat.py index 5b6126088e7..44d48e3d4bc 100644 --- a/pymatgen/io/tests/test_atat.py +++ b/pymatgen/io/tests/test_atat.py @@ -90,7 +90,6 @@ def test_mcsqs_export(self): assert Mcsqs(s).to_string() == ref_string def test_mcsqs_cif_nacl(self): - # cif file from str2cif (utility distributed with atat) struc_from_cif = Structure.from_file(os.path.join(test_dir, "bestsqs_nacl.cif")) diff --git a/pymatgen/io/tests/test_cssr.py b/pymatgen/io/tests/test_cssr.py index 598a2265f60..614da3489ca 100644 --- a/pymatgen/io/tests/test_cssr.py +++ b/pymatgen/io/tests/test_cssr.py @@ -26,7 +26,6 @@ class CssrTest(unittest.TestCase): def setUp(self): - filepath = os.path.join(PymatgenTest.TEST_FILES_DIR, "POSCAR") p = Poscar.from_file(filepath) self.cssr = Cssr(p.structure) diff --git a/pymatgen/io/tests/test_gaussian.py b/pymatgen/io/tests/test_gaussian.py index b312aab724c..bed93656d68 100644 --- a/pymatgen/io/tests/test_gaussian.py +++ b/pymatgen/io/tests/test_gaussian.py @@ -19,7 +19,6 @@ class GaussianInputTest(unittest.TestCase): def setUp(self): - coords = [ [0.000000, 0.000000, 0.000000], [0.000000, 0.000000, 1.089000], diff --git a/pymatgen/io/tests/test_packmol.py b/pymatgen/io/tests/test_packmol.py index 9c4d2d0a4c5..3e071f21b99 100644 --- a/pymatgen/io/tests/test_packmol.py +++ b/pymatgen/io/tests/test_packmol.py @@ -116,7 +116,9 @@ def test_control_params(self, water, ethanol): is raised when 'ERROR' appears in stdout (even if return code is 0) """ with tempfile.TemporaryDirectory() as scratch_dir: - pw = PackmolBoxGen(control_params={"maxit": 0, "nloop": 0},).get_input_set( + pw = PackmolBoxGen( + control_params={"maxit": 0, "nloop": 0}, + ).get_input_set( molecules=[ {"name": "water", "number": 1000, "coords": water}, {"name": "ethanol", "number": 2000, "coords": ethanol}, @@ -206,7 +208,11 @@ def test_random_seed(self, water, ethanol): # deterministic output with tempfile.TemporaryDirectory() as scratch_dir: - pw = PackmolBoxGen(seed=1, inputfile="input.in", outputfile="output.xyz",).get_input_set( + pw = PackmolBoxGen( + seed=1, + inputfile="input.in", + outputfile="output.xyz", + ).get_input_set( # scratch_dir, molecules=[ {"name": "water", "number": 10, "coords": water}, @@ -222,7 +228,11 @@ def test_random_seed(self, water, ethanol): # randomly generated structures with tempfile.TemporaryDirectory() as scratch_dir: - pw = PackmolBoxGen(seed=-1, inputfile="input.in", outputfile="output.xyz",).get_input_set( + pw = PackmolBoxGen( + seed=-1, + inputfile="input.in", + outputfile="output.xyz", + ).get_input_set( molecules=[ {"name": "water", "number": 10, "coords": water}, {"name": "ethanol", "number": 20, "coords": ethanol}, diff --git a/pymatgen/io/tests/test_prismatic.py b/pymatgen/io/tests/test_prismatic.py index 07ad2f468ab..a56f7928f00 100644 --- a/pymatgen/io/tests/test_prismatic.py +++ b/pymatgen/io/tests/test_prismatic.py @@ -14,7 +14,6 @@ class PrismaticTest(unittest.TestCase): def test_to_string(self): - structure = Structure.from_file(os.path.join(PymatgenTest.TEST_FILES_DIR, "CuCl.cif")) prismatic = Prismatic(structure) prismatic_str = prismatic.to_string() diff --git a/pymatgen/io/tests/test_template_input.py b/pymatgen/io/tests/test_template_input.py index 8f9420b869a..04e5170230d 100644 --- a/pymatgen/io/tests/test_template_input.py +++ b/pymatgen/io/tests/test_template_input.py @@ -16,7 +16,6 @@ class TestTemplateInputGen: def test_write_inputs(self): - with tempfile.TemporaryDirectory() as scratch_dir: tis = TemplateInputGen().get_input_set( template=os.path.join(test_dir, "template_input_file.txt"), diff --git a/pymatgen/io/vasp/inputs.py b/pymatgen/io/vasp/inputs.py index 88b2dea180d..983e81ad577 100644 --- a/pymatgen/io/vasp/inputs.py +++ b/pymatgen/io/vasp/inputs.py @@ -489,7 +489,7 @@ def get_string(self, direct: bool = True, vasp4_compatible: bool = False, signif lines.append("direct" if direct else "cartesian") selective_dynamics = self.selective_dynamics - for (i, site) in enumerate(self.structure): + for i, site in enumerate(self.structure): coords = site.frac_coords if direct else site.coords line = " ".join(format_str.format(c) for c in coords) if selective_dynamics is not None: @@ -645,7 +645,6 @@ def __init__(self, params: dict[str, Any] | None = None): """ super().__init__() if params: - # if Incar contains vector-like magmoms given as a list # of floats, convert to a list of lists if (params.get("MAGMOM") and isinstance(params["MAGMOM"][0], (int, float))) and ( diff --git a/pymatgen/io/vasp/outputs.py b/pymatgen/io/vasp/outputs.py index 2ddd27fb40d..756056cf4c6 100644 --- a/pymatgen/io/vasp/outputs.py +++ b/pymatgen/io/vasp/outputs.py @@ -1038,7 +1038,7 @@ def eigenvalue_band_properties(self): vbm = -float("inf") cbm = float("inf") for k, val in enumerate(d): - for (eigenval, occu) in val: + for eigenval, occu in val: if occu > self.occu_tol and eigenval > vbm: vbm = eigenval vbm_kpoint = k @@ -1385,9 +1385,7 @@ def _parse_optical_transition(elem): for va in elem.findall("varray"): if va.attrib.get("name") == "opticaltransitions": # opticaltransitions array contains oscillator strength and probability of transition - oscillator_strength = np.array(_parse_varray(va))[ - 0:, - ] + oscillator_strength = np.array(_parse_varray(va))[0:] probability_transition = np.array(_parse_varray(va))[0:, 1] return oscillator_strength, probability_transition @@ -2026,7 +2024,7 @@ def __init__(self, filename): ) ] self.data["nplwvs_at_kpoints"] = [None for n in nplwvs_at_kpoints] - for (n, nplwv) in enumerate(nplwvs_at_kpoints): + for n, nplwv in enumerate(nplwvs_at_kpoints): try: self.data["nplwvs_at_kpoints"][n] = int(nplwv) except ValueError: @@ -3554,7 +3552,6 @@ def parse_file(filename): all_dataset_aug[key] = [] all_dataset_aug[key].append(original_line) if len(all_dataset) == 4: - data = { "total": all_dataset[0], "diff_x": all_dataset[1], @@ -3641,7 +3638,7 @@ def write_spin(data_type): lines = [] count = 0 f.write(f" {a[0]} {a[1]} {a[2]}\n") - for (k, j, i) in itertools.product(list(range(a[2])), list(range(a[1])), list(range(a[0]))): + for k, j, i in itertools.product(list(range(a[2])), list(range(a[1])), list(range(a[0]))): lines.append(_print_fortran_float(self.data[data_type][i, j, k])) count += 1 if count % 5 == 0: @@ -4632,7 +4629,7 @@ def __init__(self, filename="WAVECAR", verbose=False, precision="normal", vasp_t raise ValueError(f"invalid rtag of {rtag}") # padding to end of fortran REC=1 - np.fromfile(f, dtype=np.float64, count=(recl8 - 3)) + np.fromfile(f, dtype=np.float64, count=recl8 - 3) # extract kpoint, bands, energy, and lattice information self.nk, self.nb = np.fromfile(f, dtype=np.float64, count=2).astype(int) @@ -4736,7 +4733,7 @@ def __init__(self, filename="WAVECAR", verbose=False, precision="normal", vasp_t self.Gpoints[ink], extra_gpoints, extra_coeff_inds, - ) = self._generate_G_points(kpoint, gamma=(self.vasp_type.lower()[0] == "g")) + ) = self._generate_G_points(kpoint, gamma=self.vasp_type.lower()[0] == "g") if len(self.Gpoints[ink]) != nplane and 2 * len(self.Gpoints[ink]) != nplane: raise ValueError( @@ -5194,7 +5191,7 @@ def eigenvalue_band_properties(self): vbm = -float("inf") cbm = float("inf") for k, val in enumerate(d): - for (eigenval, occu) in val: + for eigenval, occu in val: if occu > self.occu_tol and eigenval > vbm: vbm = eigenval vbm_kpoint = k diff --git a/pymatgen/io/vasp/sets.py b/pymatgen/io/vasp/sets.py index 6f80e0779f1..f4abd3f2377 100644 --- a/pymatgen/io/vasp/sets.py +++ b/pymatgen/io/vasp/sets.py @@ -1930,7 +1930,6 @@ def incar(self): } ) elif self.mode.lower() == "efg": - isotopes = {ist.split("-")[0]: ist for ist in self.isotopes} quad_efg = [ diff --git a/pymatgen/io/vasp/tests/test_outputs.py b/pymatgen/io/vasp/tests/test_outputs.py index bbe5f4fc196..494d19b0fc3 100644 --- a/pymatgen/io/vasp/tests/test_outputs.py +++ b/pymatgen/io/vasp/tests/test_outputs.py @@ -117,7 +117,6 @@ def test_bad_vasprun(self): assert issubclass(w[-1].category, UserWarning) def test_runtype(self): - v = Vasprun(self.TEST_FILES_DIR / "vasprun.GW0.xml") assert v.run_type in "HF" @@ -160,7 +159,6 @@ def test_vdw(self): assert v.final_energy == approx(-9.78310677) def test_energies(self): - # VASP 5.4.1 v = Vasprun(self.TEST_FILES_DIR / "vasprun.xml.etest1.gz") assert v.final_energy == approx(-11.18981538) @@ -178,7 +176,6 @@ def test_energies(self): assert o.final_energy == approx(-15.89364691) def test_nonlmn(self): - filepath = self.TEST_FILES_DIR / "vasprun.xml.nonlm" vasprun = Vasprun(filepath, parse_potcar_file=False) orbs = list(vasprun.complete_dos.pdos[vasprun.final_structure[0]]) @@ -1240,7 +1237,6 @@ def test_drift(self): assert np.sum(outcar.drift) == approx(0.448010) def test_electrostatic_potential(self): - outcar = Outcar(self.TEST_FILES_DIR / "OUTCAR") assert outcar.ngf == [54, 30, 54] assert np.allclose(outcar.sampling_radii, [0.9748, 0.9791, 0.7215]) @@ -1417,7 +1413,6 @@ def test_vasp620_format(self): assert outcar.run_stats["cores"] == 64 def test_energies(self): - # VASP 5.2.1 o = Outcar(self.TEST_FILES_DIR / "OUTCAR.etest1.gz") assert o.final_energy == approx(-11.18981538) diff --git a/pymatgen/io/vasp/tests/test_sets.py b/pymatgen/io/vasp/tests/test_sets.py index cae17520bca..9bf7d580b23 100644 --- a/pymatgen/io/vasp/tests/test_sets.py +++ b/pymatgen/io/vasp/tests/test_sets.py @@ -209,7 +209,6 @@ def test_nelect(self): assert MPRelaxSet(s).nelect == approx(22) def test_get_incar(self): - incar = self.mpset.incar assert incar["LDAUU"] == [5.3, 0, 0] diff --git a/pymatgen/phonon/bandstructure.py b/pymatgen/phonon/bandstructure.py index 7ce6b75b13e..d6809d4804f 100644 --- a/pymatgen/phonon/bandstructure.py +++ b/pymatgen/phonon/bandstructure.py @@ -226,7 +226,6 @@ def asr_breaking(self, tol_eigendisplacements=1e-5): """ for i in range(self.nb_qpoints): if np.allclose(self.qpoints[i].frac_coords, (0, 0, 0)): - if self.has_eigendisplacements: acoustic_modes_index = [] for j in range(self.nb_bands): diff --git a/pymatgen/phonon/gruneisen.py b/pymatgen/phonon/gruneisen.py index a999d45b3de..ffbb46ce7be 100644 --- a/pymatgen/phonon/gruneisen.py +++ b/pymatgen/phonon/gruneisen.py @@ -165,6 +165,7 @@ def tdos(self): """ The total DOS (re)constructed from the gruneisen.yaml file """ + # Here, we will reuse phonopy classes class TempMesh: """ diff --git a/pymatgen/phonon/plotter.py b/pymatgen/phonon/plotter.py index b652a51b6bb..4a3d2b567ef 100644 --- a/pymatgen/phonon/plotter.py +++ b/pymatgen/phonon/plotter.py @@ -317,7 +317,6 @@ def bs_plot_data(self): ticks = self.get_ticks() for b in self._bs.branches: - frequency.append([]) distance.append([self._bs.distance[j] for j in range(b["start_index"], b["end_index"] + 1)]) @@ -976,7 +975,6 @@ def bs_plot_data(self): ticks = self.get_ticks() for b in self._bs.branches: - frequency.append([]) gruneisen.append([]) distance.append([self._bs.distance[j] for j in range(b["start_index"], b["end_index"] + 1)]) diff --git a/pymatgen/phonon/tests/test_thermal_displacements.py b/pymatgen/phonon/tests/test_thermal_displacements.py index 8dde2e0d7d1..5c2c6aae755 100644 --- a/pymatgen/phonon/tests/test_thermal_displacements.py +++ b/pymatgen/phonon/tests/test_thermal_displacements.py @@ -318,7 +318,6 @@ def test_visualization_directionality_criterion(self): assert printed def test_from_cif_P1(self): - with tempfile.TemporaryDirectory() as tmpdirname: self.thermal.write_cif(os.path.join(tmpdirname, "U.cif")) new_thermals = ThermalDisplacementMatrices.from_cif_P1(os.path.join(tmpdirname, "U.cif")) diff --git a/pymatgen/phonon/thermal_displacements.py b/pymatgen/phonon/thermal_displacements.py index 486e17d50b9..04dc43d593f 100644 --- a/pymatgen/phonon/thermal_displacements.py +++ b/pymatgen/phonon/thermal_displacements.py @@ -521,7 +521,6 @@ def from_cif_P1(filename: str): allcoords = [] allspecies = [] for i in range(len(data["_atom_site_label"])): - try: # If site type symbol exists, use it. Otherwise, we use the # label. diff --git a/pymatgen/symmetry/bandstructure.py b/pymatgen/symmetry/bandstructure.py index 05a9cdf753e..a8659ff6137 100644 --- a/pymatgen/symmetry/bandstructure.py +++ b/pymatgen/symmetry/bandstructure.py @@ -92,7 +92,6 @@ def __init__( self._label_index = None if path_type != "all": - if path_type == "latimer_munro": self._kpath = self._get_lm_kpath(has_magmoms, magmom_axis, symprec, angle_tolerance, atol).kpath elif path_type == "setyawan_curtarolo": @@ -103,7 +102,6 @@ def __init__( self._hin_tmat = hin_dat._tmat else: - if has_magmoms: raise ValueError("Cannot select 'all' with non-zero magmoms.") @@ -249,7 +247,7 @@ def _get_klabels(self, lm_bs, sc_bs, hin_bs, rpg): ) labels = {"setyawan_curtarolo": {}, "latimer_munro": {}, "hinuma": {}} - for (a, b) in pairs: + for a, b in pairs: [(a_type, a_path)] = list(a.items()) [(b_type, b_path)] = list(b.items()) @@ -270,11 +268,11 @@ def _get_klabels(self, lm_bs, sc_bs, hin_bs, rpg): a_to_b_labels = {} unlabeled = {} - for (label_a, coord_a) in a_path["kpoints"].items(): + for label_a, coord_a in a_path["kpoints"].items(): coord_a_t = np.dot(rpg[np.argmax(sc_count)], coord_a) assigned = False - for (label_b, coord_b) in b_path["kpoints"].items(): + for label_b, coord_b in b_path["kpoints"].items(): if np.allclose(coord_b, coord_a_t, atol=self._atol): a_to_b_labels[label_a] = label_b assigned = True @@ -283,7 +281,7 @@ def _get_klabels(self, lm_bs, sc_bs, hin_bs, rpg): if not assigned: unlabeled[label_a] = coord_a - for (label_a, coord_a) in unlabeled.items(): + for label_a, coord_a in unlabeled.items(): for op in rpg: coord_a_t = np.dot(op, coord_a) key = [ @@ -364,7 +362,6 @@ def get_continuous_path(bandstructure): branch = bandstructure.branches[ind] if branch["name"] not in processed: - if tuple(branch["name"].split("-")) in plot_axis: new_branches.append(branch) processed.append(branch["name"]) @@ -382,7 +379,6 @@ def get_continuous_path(bandstructure): # Obtain new values for entry in distances_map: - branch = new_branches[entry[0]] if not entry[1]: @@ -400,13 +396,11 @@ def get_continuous_path(bandstructure): # eigenvals for spin in spins: for n, band in enumerate(bandstructure.bands[spin]): - new_bands[spin][n] = np.concatenate((new_bands[spin][n], band[start:stop:step])) # projections for spin in spins: for n, band in enumerate(bandstructure.projections[spin]): - new_projections[spin][n] += band[start:stop:step].tolist() for spin in spins: diff --git a/pymatgen/symmetry/kpath.py b/pymatgen/symmetry/kpath.py index 2f3d1d46afb..02bbdae0586 100644 --- a/pymatgen/symmetry/kpath.py +++ b/pymatgen/symmetry/kpath.py @@ -1017,7 +1017,6 @@ def __init__(self, structure: Structure, symprec: float = 0.01, angle_tolerance= @staticmethod def _trans_sc_to_Hin(sub_class): - if sub_class in [ "cP1", "cP2", @@ -1298,7 +1297,6 @@ def _get_ksymm_kpath(self, has_magmoms, magmom_axis, axis_specified, symprec, an orbit_cosines = [] for orbit in key_points_inds_orbits[:-1]: - orbit_cosines.append( sorted( sorted( @@ -1388,7 +1386,7 @@ def _choose_path( line_orbits_in_path = [] point_orbits_in_path = [] - for (i, little_group) in enumerate(little_groups_lines): + for i, little_group in enumerate(little_groups_lines): add_rep = False nC2 = 0 nC3 = 0 @@ -1416,7 +1414,7 @@ def _choose_path( ind1 = l[1] found0 = False found1 = False - for (j, orbit) in enumerate(key_points_inds_orbits): + for j, orbit in enumerate(key_points_inds_orbits): if ind0 in orbit: point_orbits_in_path.append(j) found0 = True @@ -1455,7 +1453,7 @@ def _choose_path( pass if connect: l = (key_points_inds_orbits[ind][0], gamma_ind) - for (j, orbit) in enumerate(key_lines_inds_orbits): + for j, orbit in enumerate(key_lines_inds_orbits): if l in orbit: line_orbits_in_path.append(j) break @@ -1475,8 +1473,8 @@ def _get_key_points(self): # pymatgen gives BZ in Cartesian coordinates; convert to fractional in # the primitive basis for reciprocal space - for (i, facet) in enumerate(bz): - for (j, vert) in enumerate(facet): + for i, facet in enumerate(bz): + for j, vert in enumerate(facet): vert = self._rec_lattice.get_fractional_coords(vert) bz[i][j] = vert pop = [] @@ -1490,18 +1488,18 @@ def _get_key_points(self): bz = [bz[i] for i in range(len(bz)) if i not in pop] # use vertex points to calculate edge- and face- centers - for (i, facet) in enumerate(bz): + for i, facet in enumerate(bz): bz_as_key_point_inds.append([]) - for (j, vert) in enumerate(facet): + for j, vert in enumerate(facet): edge_center = (vert + facet[j + 1]) / 2.0 if j != len(facet) - 1 else (vert + facet[0]) / 2.0 duplicatevert = False duplicateedge = False - for (k, point) in enumerate(key_points): + for k, point in enumerate(key_points): if np.allclose(vert, point, atol=self._atol): bz_as_key_point_inds[i].append(k) duplicatevert = True break - for (k, point) in enumerate(key_points): + for k, point in enumerate(key_points): if np.allclose(edge_center, point, atol=self._atol): bz_as_key_point_inds[i].append(k) duplicateedge = True @@ -1568,7 +1566,7 @@ def _get_key_lines(key_points, bz_as_key_point_inds): # not the face center point (don't need to check it since it's not # shared with other facets) face_center_ind = facet_as_key_point_inds[-1] - for (j, ind) in enumerate(facet_as_key_point_inds_bndy): + for j, ind in enumerate(facet_as_key_point_inds_bndy): if ( min(ind, facet_as_key_point_inds_bndy[j - 1]), max(ind, facet_as_key_point_inds_bndy[j - 1]), @@ -1613,7 +1611,6 @@ def _get_key_line_orbits(self, key_points, key_lines, key_points_inds_orbits): p01 = key_points[l0[1]] pmid0 = p00 + e / pi * (p01 - p00) for ind_key in key_lines_copy: - l1 = key_lines_copy[ind_key] p10 = key_points[l1[0]] p11 = key_points[l1[1]] @@ -1671,14 +1668,13 @@ def _get_key_line_orbits(self, key_points, key_lines, key_points_inds_orbits): return key_lines_inds_orbits def _get_little_groups(self, key_points, key_points_inds_orbits, key_lines_inds_orbits): - little_groups_points = [] # elements are lists of indices of recip_point_group. the # list little_groups_points[i] is the little group for the # orbit key_points_inds_orbits[i] - for (i, orbit) in enumerate(key_points_inds_orbits): + for i, orbit in enumerate(key_points_inds_orbits): k0 = key_points[orbit[0]] little_groups_points.append([]) - for (j, op) in enumerate(self._rpg): + for j, op in enumerate(self._rpg): gamma_to = np.dot(op, -1 * k0) + k0 check_gamma = True if not self._all_ints(gamma_to, atol=self._atol): @@ -1691,12 +1687,12 @@ def _get_little_groups(self, key_points, key_points_inds_orbits, key_lines_inds_ little_groups_lines = [] # the little group for the orbit key_points_inds_lines[i] - for (i, orbit) in enumerate(key_lines_inds_orbits): + for i, orbit in enumerate(key_lines_inds_orbits): l0 = orbit[0] v = key_points[l0[1]] - key_points[l0[0]] k0 = key_points[l0[0]] + np.e / pi * v little_groups_lines.append([]) - for (j, op) in enumerate(self._rpg): + for j, op in enumerate(self._rpg): gamma_to = np.dot(op, -1 * k0) + k0 check_gamma = True if not self._all_ints(gamma_to, atol=self._atol): @@ -1851,7 +1847,6 @@ def _get_coset_factor(self, G, H): op2.translation_vector, np.ones(3) * self._atol, ): - is_coset_factor = False break if not is_coset_factor: @@ -2179,7 +2174,6 @@ def _reduce_IRBZ(IRBZ_points, boundaries, g, atol): return [IRBZ_points[i] for i in range(len(IRBZ_points)) if in_reduced_section[i]] def _get_orbit_labels(self, orbit_cosines_orig, key_points_inds_orbits, atol): - orbit_cosines_copy = orbit_cosines_orig.copy() orbit_labels_unsorted = [(len(key_points_inds_orbits) - 1, 26)] orbit_inds_remaining = range(len(key_points_inds_orbits) - 1) diff --git a/pymatgen/symmetry/maggroups.py b/pymatgen/symmetry/maggroups.py index dc5bb5af6ba..d2ee7355644 100644 --- a/pymatgen/symmetry/maggroups.py +++ b/pymatgen/symmetry/maggroups.py @@ -510,7 +510,6 @@ def data_str(self, include_og=True): ).format(d=desc, bns_wyckoff_prefix=bns_wyckoff_prefix) if desc["magtype"] == 4 and include_og: - desc["og_operators"] = " ".join(op_data["str"] for op_data in self._data["og_operators"]) # include all lattice vectors because (1,0,0)+ (0,1,0)+ (0,0,1)+ diff --git a/pymatgen/symmetry/tests/test_analyzer.py b/pymatgen/symmetry/tests/test_analyzer.py index 82a90241052..3d2efdcd18d 100644 --- a/pymatgen/symmetry/tests/test_analyzer.py +++ b/pymatgen/symmetry/tests/test_analyzer.py @@ -90,9 +90,7 @@ def test_get_pointgroup(self): assert self.disordered_sg.get_point_group_symbol() == "4/mmm" def test_get_symmetry_operations(self): - for sg, structure in [(self.sg, self.structure), (self.sg4, self.structure4)]: - pg_ops = sg.get_point_group_operations() frac_symmops = sg.get_symmetry_operations() symmops = sg.get_symmetry_operations(True) diff --git a/pymatgen/symmetry/tests/test_maggroups.py b/pymatgen/symmetry/tests/test_maggroups.py index 054e129c301..38fd7f7ec69 100644 --- a/pymatgen/symmetry/tests/test_maggroups.py +++ b/pymatgen/symmetry/tests/test_maggroups.py @@ -76,7 +76,6 @@ def test_is_compatible(self): assert msg.is_compatible(hexagonal) def test_symmetry_ops(self): - msg_1_symmops = "\n".join(map(str, self.msg_1.symmetry_ops)) msg_1_symmops_ref = """x, y, z, +1 -x+3/4, -y+3/4, z, +1 @@ -150,7 +149,6 @@ def test_symmetry_ops(self): assert msg_4_symmops == msg_4_symmops_ref def test_equivalence_to_spacegroup(self): - # first 230 magnetic space groups have same symmetry operations # as normal space groups, so should give same orbits @@ -170,7 +168,6 @@ def test_equivalence_to_spacegroup(self): assert np.allclose(pp_sg, pp_msg) def test_str(self): - msg = MagneticSpaceGroup([4, 11]) ref_string = """BNS: 4.11 P_b2_1 diff --git a/pymatgen/symmetry/tests/test_settings.py b/pymatgen/symmetry/tests/test_settings.py index 54593118e6e..4664cad1890 100644 --- a/pymatgen/symmetry/tests/test_settings.py +++ b/pymatgen/symmetry/tests/test_settings.py @@ -76,7 +76,6 @@ def test_transform_coords(self): assert np.allclose(coord, ref_coord) def test_transform_symmops(self): - # reference data for this test taken from GENPOS # http://cryst.ehu.es/cryst/get_gen.html diff --git a/pymatgen/transformations/advanced_transformations.py b/pymatgen/transformations/advanced_transformations.py index 34cfeb1e551..dda72ed8708 100644 --- a/pymatgen/transformations/advanced_transformations.py +++ b/pymatgen/transformations/advanced_transformations.py @@ -1831,7 +1831,6 @@ def round_away_from_zero(x): # Repeat process for zero columns if (~arr_rounded.any(axis=0)).any(): - # Check for zero columns in T_rounded zero_col_idxs = np.where(~arr_rounded.any(axis=0))[0] for zero_col_idx in zero_col_idxs: @@ -2160,7 +2159,6 @@ def _get_unique_bestsqs_strucs(sqs, best_only, return_ranked_list, remove_duplic to_return = [{"structure": struct, "objective_function": struct.objective_function} for struct in strucs] for d in to_return: - # delete temporary objective_function attribute del d["structure"].objective_function diff --git a/pymatgen/transformations/tests/test_advanced_transformations.py b/pymatgen/transformations/tests/test_advanced_transformations.py index 443bf67d653..f55ad943631 100644 --- a/pymatgen/transformations/tests/test_advanced_transformations.py +++ b/pymatgen/transformations/tests/test_advanced_transformations.py @@ -683,7 +683,6 @@ def test_return_ranked_list(self): assert True in matches def test_spin(self): - trans = SQSTransformation(scaling=[2, 1, 1], search_time=0.01, instances=1, wd=0) # nonsensical example just for testing purposes diff --git a/pymatgen/vis/structure_vtk.py b/pymatgen/vis/structure_vtk.py index c4f237a7b44..b373ca65f4f 100644 --- a/pymatgen/vis/structure_vtk.py +++ b/pymatgen/vis/structure_vtk.py @@ -95,7 +95,6 @@ def __init__( self.ren_win.AddRenderer(self.ren) self.ren.SetBackground(1, 1, 1) self.title = "Structure Visualizer" - # create a renderwindowinteractor self.iren = vtk.vtkRenderWindowInteractor() self.iren.SetRenderWindow(self.ren_win) self.mapper_map = {} @@ -194,7 +193,7 @@ def display_help(self): """ Display the help for various keyboard shortcuts. """ - helptxt = [ + help_text = [ "h : Toggle help", "A/a, B/b or C/c : Increase/decrease cell by one a, b or c unit vector", "# : Toggle showing of polyhedrons", @@ -206,7 +205,7 @@ def display_help(self): "s: Save view to image.png", "o: Orthogonalize structure", ] - self.helptxt_mapper.SetInput("\n".join(helptxt)) + self.helptxt_mapper.SetInput("\n".join(help_text)) self.helptxt_actor.SetPosition(10, 10) self.helptxt_actor.VisibilityOn() @@ -249,9 +248,9 @@ def set_structure(self, structure: Structure, reset_camera=True, to_unit_cell=Tr self.add_line((0, 0, 0), vec, colors[count]) self.add_text(vec, labels[count], colors[count]) count += 1 - for (vec1, vec2) in itertools.permutations(matrix, 2): + for vec1, vec2 in itertools.permutations(matrix, 2): self.add_line(vec1, vec1 + vec2) - for (vec1, vec2, vec3) in itertools.permutations(matrix, 3): + for vec1, vec2, vec3 in itertools.permutations(matrix, 3): self.add_line(vec1 + vec2, vec1 + vec2 + vec3) if self.show_bonds or self.show_polyhedron: @@ -1209,7 +1208,7 @@ class MultiStructuresInteractorStyle(StructureInteractorStyle): Interactor for MultiStructureVis. """ - def __init__(self, parent): + def __init__(self, parent) -> None: """ Args: parent (): @@ -1240,7 +1239,6 @@ def keyPressEvent(self, obj, event): parent.display_warning("FIRST STRUCTURE") parent.ren_win.Render() else: - parent.istruct -= 1 parent.current_structure = parent.structures[parent.istruct] parent.set_structure(parent.current_structure, reset_camera=False, to_unit_cell=False)