diff --git a/pyproject.toml b/pyproject.toml index 529d5126f5e..3e2da3bf703 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -293,12 +293,17 @@ module = ["requests.*", "tabulate.*"] ignore_missing_imports = true [tool.codespell] -ignore-words-list = """ -titel,alls,ans,nd,mater,nwo,te,hart,ontop,ist,ot,fo,nax,coo, -coul,ser,leary,thre,fase,rute,reson,titels,ges,scalr,strat, -struc,hda,nin,ons,pres,kno,loos,lamda,lew,atomate,nempty +# TODO: un-ignore "ist/nd/ot/ontop/CoO" once support file-level ignore with pattern +ignore-words-list = """Nd, Te, titel, Mater, +Hart, Lew, Rute, atomate, +ist, nd, ot, ontop, CoO +""" +# TODO: un-skip lammps/test_inputs.py once support block ignore with pattern +skip = """*.json, +src/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries_files/allcg.txt, +src/pymatgen/entries/MPCompatibility.yaml, +tests/io/lammps/test_inputs.py, """ -skip = "pymatgen/analysis/aflow_prototypes.json" check-filenames = true [tool.pyright] diff --git a/src/pymatgen/analysis/bond_dissociation.py b/src/pymatgen/analysis/bond_dissociation.py index e1acc7188a6..2a89d672e0d 100644 --- a/src/pymatgen/analysis/bond_dissociation.py +++ b/src/pymatgen/analysis/bond_dissociation.py @@ -30,7 +30,7 @@ class BondDissociationEnergies(MSONable): fragments, or, in the case of a ring bond, from the energy of the molecule obtained from breaking the bond and opening the ring. This class should only be called after the energies of the optimized principle molecule and all relevant optimized fragments have been determined, either from quantum - chemistry or elsewhere. It was written to provide the analysis after running an Atomate fragmentation + chemistry or elsewhere. It was written to provide the analysis after running an `atomate` fragmentation workflow. """ diff --git a/src/pymatgen/analysis/chemenv/utils/graph_utils.py b/src/pymatgen/analysis/chemenv/utils/graph_utils.py index 4af375e03df..1dca61ff3e0 100644 --- a/src/pymatgen/analysis/chemenv/utils/graph_utils.py +++ b/src/pymatgen/analysis/chemenv/utils/graph_utils.py @@ -175,8 +175,8 @@ def _is_valid(self, check_strict_ordering=False): if check_strict_ordering: try: sorted_nodes = sorted(self.nodes) - except TypeError as te: - msg = te.args[0] + except TypeError as exc: + msg = exc.args[0] if "'<' not supported between instances of" in msg: return False, "The nodes are not sortable." raise @@ -366,8 +366,8 @@ def _is_valid(self, check_strict_ordering=False): if check_strict_ordering: try: sorted_nodes = sorted(self.nodes) - except TypeError as te: - msg = te.args[0] + except TypeError as exc: + msg = exc.args[0] if "'<' not supported between instances of" in msg: return False, "The nodes are not sortable." raise diff --git a/src/pymatgen/analysis/functional_groups.py b/src/pymatgen/analysis/functional_groups.py index 098299fac33..fb310351805 100644 --- a/src/pymatgen/analysis/functional_groups.py +++ b/src/pymatgen/analysis/functional_groups.py @@ -169,9 +169,7 @@ def get_special_carbon(self, elements=None): neighbor_spec = [str(self.species[n]) for n in neighbors] - ons = sum(n in ["O", "N", "S"] for n in neighbor_spec) - - if len(neighbors) == 4 and ons >= 2: + if len(neighbors) == 4 and sum(n in ["O", "N", "S"] for n in neighbor_spec) >= 2: specials.add(node) # Condition four: oxirane/aziridine/thiirane rings diff --git a/src/pymatgen/analysis/graphs.py b/src/pymatgen/analysis/graphs.py index 64b328e54dd..7cfd8217cad 100644 --- a/src/pymatgen/analysis/graphs.py +++ b/src/pymatgen/analysis/graphs.py @@ -740,10 +740,10 @@ def map_indices(grp: Molecule) -> dict[int, int]: else: if strategy_params is None: strategy_params = {} - strat = strategy(**strategy_params) + _strategy = strategy(**strategy_params) for site in mapping.values(): - neighbors = strat.get_nn_info(self.structure, site) + neighbors = _strategy.get_nn_info(self.structure, site) for neighbor in neighbors: self.add_edge( diff --git a/src/pymatgen/analysis/interface_reactions.py b/src/pymatgen/analysis/interface_reactions.py index c9958be999a..1f42b04fded 100644 --- a/src/pymatgen/analysis/interface_reactions.py +++ b/src/pymatgen/analysis/interface_reactions.py @@ -528,7 +528,7 @@ def _reverse_convert(x: float, factor1: float, factor2: float): return x * factor1 / ((1 - x) * factor2 + x * factor1) @classmethod - def get_chempot_correction(cls, element: str, temp: float, pres: float): + def get_chempot_correction(cls, element: str, temp: float, pres: float): # codespell:ignore pres """Get the normalized correction term Δμ for chemical potential of a gas phase consisting of element at given temperature and pressure, referenced to that in the standard state (T_std = 298.15 K, @@ -539,7 +539,7 @@ def get_chempot_correction(cls, element: str, temp: float, pres: float): Args: element: The string representing the element. temp: The temperature of the gas phase in Kelvin. - pres: The pressure of the gas phase in Pa. + pres: The pressure of the gas phase in Pa. # codespell:ignore pres Returns: The correction of chemical potential in eV/atom of the gas @@ -561,7 +561,7 @@ def get_chempot_correction(cls, element: str, temp: float, pres: float): cp_std = cp_dict[element] s_std = s_dict[element] - pv_correction = ideal_gas_const * temp * np.log(pres / std_pres) + pv_correction = ideal_gas_const * temp * np.log(pres / std_pres) # codespell:ignore pres ts_correction = ( -cp_std * (temp * np.log(temp) - std_temp * np.log(std_temp)) + cp_std * (temp - std_temp) * (1 + np.log(std_temp)) diff --git a/src/pymatgen/analysis/piezo.py b/src/pymatgen/analysis/piezo.py index ef17f54de4e..448b4c48a75 100644 --- a/src/pymatgen/analysis/piezo.py +++ b/src/pymatgen/analysis/piezo.py @@ -46,7 +46,7 @@ def __new__(cls, input_array: ArrayLike, tol: float = 1e-3) -> Self: def from_vasp_voigt(cls, input_vasp_array: ArrayLike) -> Self: """ Args: - input_vasp_array (nd.array): Voigt form of tensor. + input_vasp_array (ArrayLike): Voigt form of tensor. Returns: PiezoTensor diff --git a/src/pymatgen/analysis/piezo_sensitivity.py b/src/pymatgen/analysis/piezo_sensitivity.py index 0733a818a28..ce640af48a0 100644 --- a/src/pymatgen/analysis/piezo_sensitivity.py +++ b/src/pymatgen/analysis/piezo_sensitivity.py @@ -657,7 +657,7 @@ def get_piezo(BEC, IST, FCM, rcond=0.0001): ) K = np.reshape(K, (n_sites, 3, n_sites, 3)).swapaxes(1, 2) - return np.einsum("ikl,ijlm,jmno->kno", BEC, K, IST) * 16.0216559424 + return np.einsum("ikl,ijlm,jmno->kno", BEC, K, IST) * 16.0216559424 # codespell:ignore kno @requires(Phonopy, "phonopy not installed!") diff --git a/src/pymatgen/io/lmto.py b/src/pymatgen/io/lmto.py index c4685993448..1a5d669d4bc 100644 --- a/src/pymatgen/io/lmto.py +++ b/src/pymatgen/io/lmto.py @@ -175,7 +175,7 @@ def from_str(cls, data: str, sigfigs: int = 8) -> Self: "HEADER": [], "VERS": [], "SYMGRP": [], - "STRUC": [], + "STRUC": [], # codespell:ignore struc "CLASS": [], "SITE": [], } @@ -200,7 +200,7 @@ def from_str(cls, data: str, sigfigs: int = 8) -> Self: } atom = None - for cat in ("STRUC", "CLASS", "SITE"): + for cat in ("STRUC", "CLASS", "SITE"): # codespell:ignore struc fields = struct_lines[cat].split("=") for idx, field in enumerate(fields): token = field.split()[-1] diff --git a/src/pymatgen/io/lobster/outputs.py b/src/pymatgen/io/lobster/outputs.py index d9d9276d3b6..bc5f8e17800 100644 --- a/src/pymatgen/io/lobster/outputs.py +++ b/src/pymatgen/io/lobster/outputs.py @@ -768,9 +768,9 @@ def _parse_doscar(self): cdos = np.zeros((ndos, len(line))) cdos[0] = np.array(line) - for nd in range(1, ndos): + for idx_dos in range(1, ndos): line_parts = file.readline().split() - cdos[nd] = np.array(line_parts) + cdos[idx_dos] = np.array(line_parts) dos.append(cdos) line = file.readline() # Read the next line to continue the loop diff --git a/src/pymatgen/io/qchem/outputs.py b/src/pymatgen/io/qchem/outputs.py index fb359464e98..d7525a52ccd 100644 --- a/src/pymatgen/io/qchem/outputs.py +++ b/src/pymatgen/io/qchem/outputs.py @@ -481,7 +481,7 @@ def __init__(self, filename: str): self.text, { "had": r"H_ad = (?:[\-\.0-9]+) \(([\-\.0-9]+) meV\)", - "hda": r"H_da = (?:[\-\.0-9]+) \(([\-\.0-9]+) meV\)", + "hda": r"H_da = (?:[\-\.0-9]+) \(([\-\.0-9]+) meV\)", # codespell:ignore hda "coupling": r"The (?:averaged )?electronic coupling: (?:[\-\.0-9]+) \(([\-\.0-9]+) meV\)", }, ) @@ -490,10 +490,10 @@ def __init__(self, filename: str): self.data["fodft_had_eV"] = None else: self.data["fodft_had_eV"] = float(temp_dict["had"][0][0]) / 1000 - if temp_dict.get("hda") is None or len(temp_dict.get("hda", [])) == 0: + if temp_dict.get("hda") is None or len(temp_dict.get("hda", [])) == 0: # codespell:ignore hda self.data["fodft_hda_eV"] = None else: - self.data["fodft_hda_eV"] = float(temp_dict["hda"][0][0]) / 1000 + self.data["fodft_hda_eV"] = float(temp_dict["hda"][0][0]) / 1000 # codespell:ignore hda if temp_dict.get("coupling") is None or len(temp_dict.get("coupling", [])) == 0: self.data["fodft_coupling_eV"] = None else: @@ -1523,7 +1523,7 @@ def _read_optimization_data(self): self.data["errors"] += ["out_of_opt_cycles"] elif read_pattern( self.text, - {"key": r"UNABLE TO DETERMINE Lamda IN FormD"}, + {"key": r"UNABLE TO DETERMINE Lamda IN FormD"}, # codespell:ignore lamda terminate_on_match=True, ).get("key") == [[]]: self.data["errors"] += ["unable_to_determine_lamda"] @@ -1746,7 +1746,7 @@ def _read_scan_data(self): self.data["errors"] += ["out_of_opt_cycles"] elif read_pattern( self.text, - {"key": r"UNABLE TO DETERMINE Lamda IN FormD"}, + {"key": r"UNABLE TO DETERMINE Lamda IN FormD"}, # codespell:ignore lamda terminate_on_match=True, ).get("key") == [[]]: self.data["errors"] += ["unable_to_determine_lamda"] diff --git a/src/pymatgen/io/res.py b/src/pymatgen/io/res.py index 68f89829f1e..9a45a3b9dc2 100644 --- a/src/pymatgen/io/res.py +++ b/src/pymatgen/io/res.py @@ -305,13 +305,13 @@ def _res_from_structure(cls, structure: Structure) -> Res: def _res_from_entry(cls, entry: ComputedStructureEntry) -> Res: """Produce a res file structure from a pymatgen ComputedStructureEntry.""" seed = entry.data.get("seed") or str(hash(entry)) - pres = float(entry.data.get("pressure", 0)) + pressure = float(entry.data.get("pressure", 0)) isd = float(entry.data.get("isd", 0)) iasd = float(entry.data.get("iasd", 0)) spg, _ = entry.structure.get_space_group_info() rems = [str(x) for x in entry.data.get("rems", [])] return Res( - AirssTITL(seed, pres, entry.structure.volume, entry.energy, isd, iasd, spg, 1), + AirssTITL(seed, pressure, entry.structure.volume, entry.energy, isd, iasd, spg, 1), rems, cls._cell_from_lattice(entry.structure.lattice), cls._sfac_from_sites(list(entry.structure)), diff --git a/src/pymatgen/io/vasp/outputs.py b/src/pymatgen/io/vasp/outputs.py index fac1cacaed8..14b116ffcbf 100644 --- a/src/pymatgen/io/vasp/outputs.py +++ b/src/pymatgen/io/vasp/outputs.py @@ -2495,7 +2495,7 @@ def read_chemical_shielding(self) -> None: List of chemical shieldings in the order of atoms from the OUTCAR. Maryland notation is adopted. """ header_pattern = ( - r"\s+CSA tensor \(J\. Mason, Solid State Nucl\. Magn\. Reson\. 2, " + r"\s+CSA tensor \(J\. Mason, Solid State Nucl\. Magn\. Reson\. 2, " # codespell:ignore reson r"285 \(1993\)\)\s+" r"\s+-{50,}\s+" r"\s+EXCLUDING G=0 CONTRIBUTION\s+INCLUDING G=0 CONTRIBUTION\s+" @@ -3902,23 +3902,23 @@ class Procar(MSONable): Attributes: data (dict): The PROCAR data of the form below. It should VASP uses 1-based indexing, but all indices are converted to 0-based here. - { spin: nd.array accessed with (k-point index, band index, ion index, orbital index) } - weights (np.array): The weights associated with each k-point as an nd.array of length nkpoints. + { spin: np.array accessed with (k-point index, band index, ion index, orbital index) } + weights (np.array): The weights associated with each k-point as an np.array of length nkpoints. phase_factors (dict): Phase factors, where present (e.g. LORBIT = 12). A dict of the form: - { spin: complex nd.array accessed with (k-point index, band index, ion index, orbital index) } + { spin: complex np.array accessed with (k-point index, band index, ion index, orbital index) } nbands (int): Number of bands. nkpoints (int): Number of k-points. nions (int): Number of ions. nspins (int): Number of spins. is_soc (bool): Whether the PROCAR contains spin-orbit coupling (LSORBIT = True) data. - kpoints (np.array): The k-points as an nd.array of shape (nkpoints, 3). + kpoints (np.array): The k-points as an np.array of shape (nkpoints, 3). occupancies (dict): The occupancies of the bands as a dict of the form: - { spin: nd.array accessed with (k-point index, band index) } + { spin: np.array accessed with (k-point index, band index) } eigenvalues (dict): The eigenvalues of the bands as a dict of the form: - { spin: nd.array accessed with (k-point index, band index) } + { spin: np.array accessed with (k-point index, band index) } xyz_data (dict): The PROCAR projections data along the x,y and z magnetisation projection directions, with is_soc = True (see VASP wiki for more info). - { 'x'/'y'/'z': nd.array accessed with (k-point index, band index, ion index, orbital index) } + { 'x'/'y'/'z': np.array accessed with (k-point index, band index, ion index, orbital index) } """ def __init__(self, filename: PathLike | list[PathLike]): diff --git a/src/pymatgen/io/vasp/sets.py b/src/pymatgen/io/vasp/sets.py index 18c5539623b..45898dfef38 100644 --- a/src/pymatgen/io/vasp/sets.py +++ b/src/pymatgen/io/vasp/sets.py @@ -2019,7 +2019,7 @@ def incar_updates(self) -> dict[str, Any]: SIGMA=0.01, ) elif self.mode.lower() == "efg" and self.structure is not None: - isotopes = {ist.split("-")[0]: ist for ist in self.isotopes} + isotopes = {isotope.split("-")[0]: isotope for isotope in self.isotopes} quad_efg = [ float(Species(sp.name).get_nmr_quadrupole_moment(isotopes.get(sp.name))) for sp in self.structure.species diff --git a/src/pymatgen/phonon/bandstructure.py b/src/pymatgen/phonon/bandstructure.py index fee735fb7ef..7b2e60ed263 100644 --- a/src/pymatgen/phonon/bandstructure.py +++ b/src/pymatgen/phonon/bandstructure.py @@ -39,7 +39,7 @@ def get_reasonable_repetitions(n_atoms: int) -> Tuple3Ints: def eigenvectors_from_displacements(disp: np.ndarray, masses: np.ndarray) -> np.ndarray: """Calculate the eigenvectors from the atomic displacements.""" - return np.einsum("nax,a->nax", disp, masses**0.5) + return np.einsum("nax,a->nax", disp, masses**0.5) # codespell:ignore nax def estimate_band_connection(prev_eigvecs, eigvecs, prev_band_order) -> list[int]: diff --git a/src/pymatgen/phonon/thermal_displacements.py b/src/pymatgen/phonon/thermal_displacements.py index 011f873f53e..800a80429fd 100644 --- a/src/pymatgen/phonon/thermal_displacements.py +++ b/src/pymatgen/phonon/thermal_displacements.py @@ -352,7 +352,7 @@ def visualize_directionality_quality_criterion( f"{structure.lattice.alpha} {structure.lattice.beta} {structure.lattice.gamma}\n" ) file.write(" 0.000000 0.000000 0.000000 0.000000 0.000000 0.000000\n") # error on parameters - file.write("STRUC\n") + file.write("STRUC\n") # codespell:ignore struc for site_idx, site in enumerate(structure, start=1): file.write( diff --git a/src/pymatgen/transformations/advanced_transformations.py b/src/pymatgen/transformations/advanced_transformations.py index afda9fb7f8d..2537241b653 100644 --- a/src/pymatgen/transformations/advanced_transformations.py +++ b/src/pymatgen/transformations/advanced_transformations.py @@ -854,19 +854,19 @@ def apply_transformation( trafo = EnumerateStructureTransformation(**enum_kwargs) - alls = trafo.apply_transformation(structure, return_ranked_list=return_ranked_list) + all_structs = trafo.apply_transformation(structure, return_ranked_list=return_ranked_list) # handle the fact that EnumerateStructureTransformation can either # return a single Structure or a list - if isinstance(alls, Structure): + if isinstance(all_structs, Structure): # remove dummy species and replace Spin.up or Spin.down # with spin magnitudes given in mag_species_spin arg - alls = self._remove_dummy_species(alls) - alls = self._add_spin_magnitudes(alls) # type: ignore[arg-type] + all_structs = self._remove_dummy_species(all_structs) + all_structs = self._add_spin_magnitudes(all_structs) # type: ignore[arg-type] else: - for idx, struct in enumerate(alls): - alls[idx]["structure"] = self._remove_dummy_species(struct["structure"]) # type: ignore[index] - alls[idx]["structure"] = self._add_spin_magnitudes(struct["structure"]) # type: ignore[index, arg-type] + for idx, struct in enumerate(all_structs): + all_structs[idx]["structure"] = self._remove_dummy_species(struct["structure"]) # type: ignore[index] + all_structs[idx]["structure"] = self._add_spin_magnitudes(struct["structure"]) # type: ignore[index, arg-type] try: num_to_return = int(return_ranked_list) @@ -874,7 +874,7 @@ def apply_transformation( num_to_return = 1 if num_to_return == 1 or not return_ranked_list: - return alls[0]["structure"] if num_to_return else alls # type: ignore[return-value, index] + return all_structs[0]["structure"] if num_to_return else all_structs # type: ignore[return-value, index] # Remove duplicate structures and group according to energy model matcher = StructureMatcher(comparator=SpinComparator()) @@ -883,7 +883,7 @@ def key(struct: Structure) -> int: return SpacegroupAnalyzer(struct, 0.1).get_space_group_number() out = [] - for _, group in groupby(sorted((dct["structure"] for dct in alls), key=key), key): # type: ignore[arg-type, index] + for _, group in groupby(sorted((dct["structure"] for dct in all_structs), key=key), key): # type: ignore[arg-type, index] group = list(group) # type: ignore[assignment] grouped = matcher.group_structures(group) out.extend([{"structure": g[0], "energy": self.energy_model.get_energy(g[0])} for g in grouped]) diff --git a/src/pymatgen/vis/structure_vtk.py b/src/pymatgen/vis/structure_vtk.py index 7ab576c6458..b50bd08222a 100644 --- a/src/pymatgen/vis/structure_vtk.py +++ b/src/pymatgen/vis/structure_vtk.py @@ -357,7 +357,7 @@ def add_partial_sphere(self, coords, radius, color, start=0, end=360, opacity=1. Adding a partial sphere (to display partial occupancies. Args: - coords (nd.array): Coordinates + coords (np.array): Coordinates radius (float): Radius of sphere color (tuple): RGB color of sphere start (float): Starting angle. diff --git a/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py b/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py index 8f6a00daeb7..18fc1675835 100644 --- a/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py +++ b/tests/analysis/chemenv/coordination_environments/test_coordination_geometries.py @@ -212,7 +212,7 @@ def test_coordination_geometry(self): "PB:7", "ST:7", "ET:7", - "FO:7", + "FO:7", # codespell:ignore fo "C:8", "SA:8", "SBT:8", @@ -389,9 +389,9 @@ def test_coordination_geometry(self): (0, 4, 2): ["T:6"], }, 7: { - (1, 3, 3): ["ET:7", "FO:7"], + (1, 3, 3): ["ET:7", "FO:7"], # codespell:ignore fo (2, 3, 2): ["PB:7", "ST:7", "ET:7"], - (1, 4, 2): ["ST:7", "FO:7"], + (1, 4, 2): ["ST:7", "FO:7"], # codespell:ignore fo (1, 5, 1): ["PB:7"], }, 8: { diff --git a/tests/analysis/diffraction/test_neutron.py b/tests/analysis/diffraction/test_neutron.py index d29d633724c..4de897d85d6 100644 --- a/tests/analysis/diffraction/test_neutron.py +++ b/tests/analysis/diffraction/test_neutron.py @@ -24,33 +24,33 @@ class TestNDCalculator(PymatgenTest): def test_get_pattern(self): struct = self.get_structure("CsCl") c = NDCalculator(wavelength=1.54184) # CuKa radiation - nd = c.get_pattern(struct, two_theta_range=(0, 90)) + pattern = c.get_pattern(struct, two_theta_range=(0, 90)) # Check the first two peaks - assert nd.x[0] == approx(21.107738329639844) - assert nd.hkls[0] == [{"hkl": (1, 0, 0), "multiplicity": 6}] - assert nd.d_hkls[0] == approx(4.2089999999999996) - assert nd.x[1] == approx(30.024695921112777) - assert nd.hkls[1] == [{"hkl": (1, 1, 0), "multiplicity": 12}] - assert nd.d_hkls[1] == approx(2.976212442014178) + assert pattern.x[0] == approx(21.107738329639844) + assert pattern.hkls[0] == [{"hkl": (1, 0, 0), "multiplicity": 6}] + assert pattern.d_hkls[0] == approx(4.2089999999999996) + assert pattern.x[1] == approx(30.024695921112777) + assert pattern.hkls[1] == [{"hkl": (1, 1, 0), "multiplicity": 12}] + assert pattern.d_hkls[1] == approx(2.976212442014178) struct = self.get_structure("LiFePO4") - nd = c.get_pattern(struct, two_theta_range=(0, 90)) - assert nd.x[1] == approx(17.03504233621785) - assert nd.y[1] == approx(46.2985965) + pattern = c.get_pattern(struct, two_theta_range=(0, 90)) + assert pattern.x[1] == approx(17.03504233621785) + assert pattern.y[1] == approx(46.2985965) struct = self.get_structure("Li10GeP2S12") - nd = c.get_pattern(struct, two_theta_range=(0, 90)) - assert nd.x[1] == approx(14.058274883353876) - assert nd.y[1] == approx(3.60588013) + pattern = c.get_pattern(struct, two_theta_range=(0, 90)) + assert pattern.x[1] == approx(14.058274883353876) + assert pattern.y[1] == approx(3.60588013) # Test a hexagonal structure. struct = self.get_structure("Graphite") - nd = c.get_pattern(struct, two_theta_range=(0, 90)) - assert nd.x[0] == approx(26.21057350859598) - assert nd.y[0] == approx(100) - assert nd.x[2] == approx(44.39599754) - assert nd.y[2] == approx(42.62382267) - assert len(nd.hkls[0][0]) == approx(2) + pattern = c.get_pattern(struct, two_theta_range=(0, 90)) + assert pattern.x[0] == approx(26.21057350859598) + assert pattern.y[0] == approx(100) + assert pattern.x[2] == approx(44.39599754) + assert pattern.y[2] == approx(42.62382267) + assert len(pattern.hkls[0][0]) == approx(2) # Test an exception in case of the input element is # not in scattering length table. @@ -58,18 +58,21 @@ def test_get_pattern(self): something = Structure(Lattice.cubic(a=1), ["Cm"], [[0, 0, 0]]) with pytest.raises( ValueError, - match="Unable to calculate ND pattern as there is no scattering coefficients for Cm.", + match=( + "Unable to calculate ND pattern as " # codespell:ignore ND + "there is no scattering coefficients for Cm." + ), ): - nd = c.get_pattern(something, two_theta_range=(0, 90)) + pattern = c.get_pattern(something, two_theta_range=(0, 90)) # Test with Debye-Waller factor struct = self.get_structure("Graphite") c = NDCalculator(wavelength=1.54184, debye_waller_factors={"C": 1}) - nd = c.get_pattern(struct, two_theta_range=(0, 90)) - assert nd.x[0] == approx(26.21057350859598) - assert nd.y[0] == approx(100) - assert nd.x[2] == approx(44.39599754) - assert nd.y[2] == approx(39.471514740) + pattern = c.get_pattern(struct, two_theta_range=(0, 90)) + assert pattern.x[0] == approx(26.21057350859598) + assert pattern.y[0] == approx(100) + assert pattern.x[2] == approx(44.39599754) + assert pattern.y[2] == approx(39.471514740) def test_get_plot(self): struct = self.get_structure("Graphite") diff --git a/tests/analysis/test_bond_valence.py b/tests/analysis/test_bond_valence.py index 8c5ceb2ff78..a2e0db2ce0c 100644 --- a/tests/analysis/test_bond_valence.py +++ b/tests/analysis/test_bond_valence.py @@ -16,19 +16,19 @@ def setUp(self): def test_get_valences(self): struct = Structure.from_file(f"{TEST_DIR}/LiMn2O4.json") - ans = [1, 1, 3, 3, 4, 4, -2, -2, -2, -2, -2, -2, -2, -2] - assert self.analyzer.get_valences(struct) == ans + valences = [1, 1, 3, 3, 4, 4, -2, -2, -2, -2, -2, -2, -2, -2] + assert self.analyzer.get_valences(struct) == valences struct = self.get_structure("LiFePO4") - ans = [1] * 4 + [2] * 4 + [5] * 4 + [-2] * 16 - assert self.analyzer.get_valences(struct) == ans + valences = [1] * 4 + [2] * 4 + [5] * 4 + [-2] * 16 + assert self.analyzer.get_valences(struct) == valences struct = self.get_structure("Li3V2(PO4)3") - ans = [1] * 6 + [3] * 4 + [5] * 6 + [-2] * 24 - assert self.analyzer.get_valences(struct) == ans + valences = [1] * 6 + [3] * 4 + [5] * 6 + [-2] * 24 + assert self.analyzer.get_valences(struct) == valences struct = Structure.from_file(f"{TEST_DIR}/Li4Fe3Mn1(PO4)4.json") - ans = [1] * 4 + [2] * 4 + [5] * 4 + [-2] * 16 - assert self.analyzer.get_valences(struct) == ans + valences = [1] * 4 + [2] * 4 + [5] * 4 + [-2] * 16 + assert self.analyzer.get_valences(struct) == valences struct = self.get_structure("NaFePO4") - assert self.analyzer.get_valences(struct) == ans + assert self.analyzer.get_valences(struct) == valences # trigger ValueError Structure contains elements not in set of BV parameters with pytest.raises( diff --git a/tests/analysis/test_molecule_structure_comparator.py b/tests/analysis/test_molecule_structure_comparator.py index b3b0944e1b2..3875ffb44ec 100644 --- a/tests/analysis/test_molecule_structure_comparator.py +++ b/tests/analysis/test_molecule_structure_comparator.py @@ -178,7 +178,7 @@ def test_get_13_bonds(self): [6, 9], ] bonds_13 = MoleculeStructureComparator.get_13_bonds(priority_bonds) - ans = ( + assert bonds_13 == ( (0, 3), (0, 4), (0, 5), @@ -199,4 +199,3 @@ def test_get_13_bonds(self): (6, 8), (6, 10), ) - assert bonds_13 == tuple(ans) diff --git a/tests/command_line/test_bader_caller.py b/tests/command_line/test_bader_caller.py index 4be631231fe..ad39f8c6b61 100644 --- a/tests/command_line/test_bader_caller.py +++ b/tests/command_line/test_bader_caller.py @@ -32,7 +32,7 @@ def test_init(self): assert analysis.data[0]["charge"] == analysis.get_charge(0) assert analysis.nelectrons == 96 assert analysis.vacuum_charge == approx(0) - ans = [ + results = [ -1.3863218, -1.3812175, -1.3812175, @@ -49,7 +49,7 @@ def test_init(self): 1.024357, ] for idx in range(14): - assert ans[idx] == approx(analysis.get_charge_transfer(idx), abs=1e-3) + assert results[idx] == approx(analysis.get_charge_transfer(idx), abs=1e-3) assert analysis.get_partial_charge(0) == -analysis.get_charge_transfer(0) struct = analysis.get_oxidation_state_decorated_structure() assert struct[0].specie.oxi_state == approx(1.3863218, abs=1e-3) diff --git a/tests/core/test_sites.py b/tests/core/test_sites.py index 5eb81533960..28fb7b07e4c 100644 --- a/tests/core/test_sites.py +++ b/tests/core/test_sites.py @@ -124,7 +124,7 @@ def test_distance_and_image(self): assert (image == [-1, -1, -1]).all() distance, image = self.site.distance_and_image(other_site, [1, 0, 0]) assert distance == approx(19.461500456028563) - # Test that old and new distance algo give the same ans for + # Test that old and new distance algo give the same answer for # "standard lattices" lattice = Lattice(np.eye(3)) site1 = PeriodicSite("Fe", np.array([0.01, 0.02, 0.03]), lattice) diff --git a/tests/core/test_structure.py b/tests/core/test_structure.py index 6461eb2248e..7cb4abcbaf3 100644 --- a/tests/core/test_structure.py +++ b/tests/core/test_structure.py @@ -882,8 +882,7 @@ def test_get_all_neighbors_equal(self): assert norm < 1e-3 def test_get_dist_matrix(self): - ans = [[0.0, 2.3516318], [2.3516318, 0.0]] - assert_allclose(self.struct.distance_matrix, ans) + assert_allclose(self.struct.distance_matrix, [[0.0, 2.3516318], [2.3516318, 0.0]]) def test_to_from_file_and_string(self): for fmt in ("cif", "json", "poscar", "cssr", "pwmat"): @@ -2175,14 +2174,16 @@ def test_get_neighbors_in_shell(self): assert len(nn) == 0 def test_get_dist_matrix(self): - ans = [ - [0.0, 1.089, 1.08899995636, 1.08900040717, 1.08900040717], - [1.089, 0.0, 1.77832952654, 1.7783298026, 1.7783298026], - [1.08899995636, 1.77832952654, 0.0, 1.77833003783, 1.77833003783], - [1.08900040717, 1.7783298026, 1.77833003783, 0.0, 1.77833], - [1.08900040717, 1.7783298026, 1.77833003783, 1.77833, 0.0], - ] - assert_allclose(self.mol.distance_matrix, ans) + assert_allclose( + self.mol.distance_matrix, + [ + [0.0, 1.089, 1.08899995636, 1.08900040717, 1.08900040717], + [1.089, 0.0, 1.77832952654, 1.7783298026, 1.7783298026], + [1.08899995636, 1.77832952654, 0.0, 1.77833003783, 1.77833003783], + [1.08900040717, 1.7783298026, 1.77833003783, 0.0, 1.77833], + [1.08900040717, 1.7783298026, 1.77833003783, 1.77833, 0.0], + ], + ) def test_get_zmatrix(self): mol = IMolecule(["C", "H", "H", "H", "H"], self.coords) diff --git a/tests/io/exciting/test_inputs.py b/tests/io/exciting/test_inputs.py index 6c686c569be..ccbac253944 100644 --- a/tests/io/exciting/test_inputs.py +++ b/tests/io/exciting/test_inputs.py @@ -146,12 +146,12 @@ def test_param_dict(self): "xstype": "BSE", "ngridk": "4 4 4", "ngridq": "4 4 4", - "nempty": "30", + "nempty": "30", # codespell:ignore: nempty "gqmax": "3.0", "broad": "0.07", "tevout": "true", "energywindow": {"intv": "0.0 1.0", "points": "1200"}, - "screening": {"screentype": "full", "nempty": "100"}, + "screening": {"screentype": "full", "nempty": "100"}, # codespell:ignore: nempty "BSE": {"bsetype": "singlet", "nstlbse": "1 5 1 4"}, }, } diff --git a/tests/io/lammps/test_inputs.py b/tests/io/lammps/test_inputs.py index 0e0b5c3effa..15f8ef3fac4 100644 --- a/tests/io/lammps/test_inputs.py +++ b/tests/io/lammps/test_inputs.py @@ -34,7 +34,7 @@ def test_from_file(self): ("units", "metal"), ("atom_style", "full"), ("dimension", "3"), - ("pair_style", "hybrid/overlay morse 15 coul/long 15"), + ("pair_style", "hybrid/overlay morse 15 coul/long 15"), # codespell:ignore coul ("kspace_style", "ewald 1e-4"), ("boundary", "p p p"), ("#", "2) System definition"), @@ -50,7 +50,7 @@ def test_from_file(self): ("pair_coeff", "2 4 morse 0.3147 2.257 2.409"), ("pair_coeff", "3 4 morse 0.4104 2.329 2.200"), ("pair_coeff", "4 4 morse 0.0241 1.359 4.284"), - ("pair_coeff", "* * coul/long"), + ("pair_coeff", "* * coul/long"), # codespell:ignore coul ("#", "Part A : energy minimization"), ("thermo", "1"), ("thermo_style", "custom step lx ly lz press pxx pyy pzz pe"), diff --git a/tests/io/test_fiesta.py b/tests/io/test_fiesta.py index 3e86422e8a5..bcc6904a076 100644 --- a/tests/io/test_fiesta.py +++ b/tests/io/test_fiesta.py @@ -50,7 +50,7 @@ def test_init(self): assert cell_in.molecule.spin_multiplicity == 1 def test_str_and_from_str(self): - ans = ( + result = ( "# number of atoms and species\n 5 2\n# number of valence bands\n 5\n" "# number of points and spacing in eV for correlation grid\n 14 0.500\n" "# relire=1 ou recalculer=0 Exc DFT\n 1\n" @@ -65,8 +65,8 @@ def test_str_and_from_str(self): " 0.0 0.0 1.089 2\n 1.026719 0.0 -0.363 2\n -0.51336 -0.889165 -0.363 2\n -0.51336 0.889165 -0.363 2" "\n " ) - assert str(self.cell_in) == ans - cell_in = FiestaInput.from_str(ans) + assert str(self.cell_in) == result + cell_in = FiestaInput.from_str(result) assert cell_in.GW_options["nc_corr"] == "10" assert cell_in.cohsex_options["eigMethod"] == "C" diff --git a/tests/io/test_nwchem.py b/tests/io/test_nwchem.py index a81dc751ec0..7304ec4a10e 100644 --- a/tests/io/test_nwchem.py +++ b/tests/io/test_nwchem.py @@ -398,14 +398,14 @@ def test_from_str_and_file(self): class TestNwOutput: def test_read(self): - nwo = NwOutput(f"{TEST_DIR}/CH4.nwout") + nw_output = NwOutput(f"{TEST_DIR}/CH4.nwout") nwo_cosmo = NwOutput(f"{TEST_DIR}/N2O4.nwout") - assert nwo[0]["charge"] == 0 - assert nwo[-1]["charge"] == -1 - assert len(nwo) == 5 - assert approx(nwo[0]["energies"][-1], abs=1e-2) == -1102.6224491715582 - assert approx(nwo[2]["energies"][-1], abs=1e-3) == -1102.9986291578023 + assert nw_output[0]["charge"] == 0 + assert nw_output[-1]["charge"] == -1 + assert len(nw_output) == 5 + assert approx(nw_output[0]["energies"][-1], abs=1e-2) == -1102.6224491715582 + assert approx(nw_output[2]["energies"][-1], abs=1e-3) == -1102.9986291578023 assert approx(nwo_cosmo[5]["energies"][0]["cosmo scf"], abs=1e-3) == -11156.354030653656 assert approx(nwo_cosmo[5]["energies"][0]["gas phase"], abs=1e-3) == -11153.374133394364 assert approx(nwo_cosmo[5]["energies"][0]["sol phase"], abs=1e-2) == -11156.353632962995 @@ -416,14 +416,14 @@ def test_read(self): assert approx(nwo_cosmo[7]["energies"][0]["gas phase"], abs=1e-2) == -11165.025443612385 assert approx(nwo_cosmo[7]["energies"][0]["sol phase"], abs=1e-2) == -11165.227959110154 - assert nwo[1]["hessian"][0][0] == approx(4.60187e01) - assert nwo[1]["hessian"][1][2] == approx(-1.14030e-08) - assert nwo[1]["hessian"][2][3] == approx(2.60819e01) - assert nwo[1]["hessian"][6][6] == approx(1.45055e02) - assert nwo[1]["hessian"][11][14] == approx(1.35078e01) + assert nw_output[1]["hessian"][0][0] == approx(4.60187e01) + assert nw_output[1]["hessian"][1][2] == approx(-1.14030e-08) + assert nw_output[1]["hessian"][2][3] == approx(2.60819e01) + assert nw_output[1]["hessian"][6][6] == approx(1.45055e02) + assert nw_output[1]["hessian"][11][14] == approx(1.35078e01) # CH4.nwout, line 722 - assert nwo[0]["forces"][0][3] == approx(-0.001991) + assert nw_output[0]["forces"][0][3] == approx(-0.001991) # N2O4.nwout, line 1071 assert nwo_cosmo[0]["forces"][0][4] == approx(0.011948) @@ -431,47 +431,47 @@ def test_read(self): # There should be four DFT gradients. assert len(nwo_cosmo[0]["forces"]) == 4 - ie = nwo[4]["energies"][-1] - nwo[2]["energies"][-1] - ea = nwo[2]["energies"][-1] - nwo[3]["energies"][-1] + ie = nw_output[4]["energies"][-1] - nw_output[2]["energies"][-1] + ea = nw_output[2]["energies"][-1] - nw_output[3]["energies"][-1] assert approx(ie) == 0.7575358648355177 assert approx(ea, abs=1e-3) == -14.997877958701338 - assert nwo[4]["basis_set"]["C"]["description"] == "6-311++G**" - - nwo = NwOutput(f"{TEST_DIR}/H4C3O3_1.nwout") - assert nwo[-1]["has_error"] - assert nwo[-1]["errors"][0] == "Bad convergence" - - nwo = NwOutput(f"{TEST_DIR}/CH3CH2O.nwout") - assert nwo[-1]["has_error"] - assert nwo[-1]["errors"][0] == "Bad convergence" - - nwo = NwOutput(f"{TEST_DIR}/C1N1Cl1_1.nwout") - assert nwo[-1]["has_error"] - assert nwo[-1]["errors"][0] == "autoz error" - - nwo = NwOutput(f"{TEST_DIR}/anthrachinon_wfs_16_ethyl.nwout") - assert nwo[-1]["has_error"] - assert nwo[-1]["errors"][0] == "Geometry optimization failed" - nwo = NwOutput(f"{TEST_DIR}/anthrachinon_wfs_15_carboxyl.nwout") - assert nwo[1]["frequencies"][0][0] == -70.47 - assert len(nwo[1]["frequencies"][0][1]) == 27 - assert nwo[1]["frequencies"][-1][0] == 3696.74 - assert nwo[1]["frequencies"][-1][1][-1] == (0.20498, -0.94542, -0.00073) - assert nwo[1]["normal_frequencies"][1][0] == -70.72 - assert nwo[1]["normal_frequencies"][3][0] == -61.92 - assert nwo[1]["normal_frequencies"][1][1][-1] == (0.00056, 0.00042, 0.06781) + assert nw_output[4]["basis_set"]["C"]["description"] == "6-311++G**" + + nw_output = NwOutput(f"{TEST_DIR}/H4C3O3_1.nwout") + assert nw_output[-1]["has_error"] + assert nw_output[-1]["errors"][0] == "Bad convergence" + + nw_output = NwOutput(f"{TEST_DIR}/CH3CH2O.nwout") + assert nw_output[-1]["has_error"] + assert nw_output[-1]["errors"][0] == "Bad convergence" + + nw_output = NwOutput(f"{TEST_DIR}/C1N1Cl1_1.nwout") + assert nw_output[-1]["has_error"] + assert nw_output[-1]["errors"][0] == "autoz error" + + nw_output = NwOutput(f"{TEST_DIR}/anthrachinon_wfs_16_ethyl.nwout") + assert nw_output[-1]["has_error"] + assert nw_output[-1]["errors"][0] == "Geometry optimization failed" + nw_output = NwOutput(f"{TEST_DIR}/anthrachinon_wfs_15_carboxyl.nwout") + assert nw_output[1]["frequencies"][0][0] == -70.47 + assert len(nw_output[1]["frequencies"][0][1]) == 27 + assert nw_output[1]["frequencies"][-1][0] == 3696.74 + assert nw_output[1]["frequencies"][-1][1][-1] == (0.20498, -0.94542, -0.00073) + assert nw_output[1]["normal_frequencies"][1][0] == -70.72 + assert nw_output[1]["normal_frequencies"][3][0] == -61.92 + assert nw_output[1]["normal_frequencies"][1][1][-1] == (0.00056, 0.00042, 0.06781) def test_parse_tddft(self): - nwo = NwOutput(f"{TEST_DIR}/phen_tddft.log") - roots = nwo.parse_tddft() + nw_output = NwOutput(f"{TEST_DIR}/phen_tddft.log") + roots = nw_output.parse_tddft() assert len(roots["singlet"]) == 20 assert roots["singlet"][0]["energy"] == approx(3.9291) assert roots["singlet"][0]["osc_strength"] == approx(0.0) assert roots["singlet"][1]["osc_strength"] == approx(0.00177) def test_get_excitation_spectrum(self): - nwo = NwOutput(f"{TEST_DIR}/phen_tddft.log") - spectrum = nwo.get_excitation_spectrum() + nw_output = NwOutput(f"{TEST_DIR}/phen_tddft.log") + spectrum = nw_output.get_excitation_spectrum() assert len(spectrum.x) == 2000 assert spectrum.x[0] == approx(1.9291) assert spectrum.y[0] == approx(0.0) diff --git a/tests/transformations/test_advanced_transformations.py b/tests/transformations/test_advanced_transformations.py index 188b8e8bb28..2f73ace7cd3 100644 --- a/tests/transformations/test_advanced_transformations.py +++ b/tests/transformations/test_advanced_transformations.py @@ -165,24 +165,24 @@ def test_apply_transformation(self): struct_trafo = trans.apply_transformation(struct) oxi_trans = OxidationStateDecorationTransformation({"Li": 1, "Fe": 2, "P": 5, "O": -2}) struct_trafo = oxi_trans.apply_transformation(struct_trafo) - alls = enum_trans.apply_transformation(struct_trafo, 100) - assert len(alls) == expected[idx] + all_structs = enum_trans.apply_transformation(struct_trafo, 100) + assert len(all_structs) == expected[idx] assert isinstance(trans.apply_transformation(struct_trafo), Structure) - for ss in alls: + for ss in all_structs: assert "energy" in ss - alls = enum_trans2.apply_transformation(struct_trafo, 100) - assert len(alls) == expected[idx] + all_structs = enum_trans2.apply_transformation(struct_trafo, 100) + assert len(all_structs) == expected[idx] assert isinstance(trans.apply_transformation(struct_trafo), Structure) - for ss in alls: + for ss in all_structs: assert "num_sites" in ss # make sure it works for non-oxidation state decorated structure trans = SubstitutionTransformation({"Fe": {"Fe": 0.5}}) struct_trafo = trans.apply_transformation(struct) - alls = enum_trans.apply_transformation(struct_trafo, 100) - assert len(alls) == 3 + all_structs = enum_trans.apply_transformation(struct_trafo, 100) + assert len(all_structs) == 3 assert isinstance(trans.apply_transformation(struct_trafo), Structure) - for struct_trafo in alls: + for struct_trafo in all_structs: assert "energy" not in struct_trafo @pytest.mark.skip(reason="dgl don't support torch 2.4.1+, #4073") @@ -192,14 +192,17 @@ def test_m3gnet(self): struct = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_LiFePO4") trans = SubstitutionTransformation({"Fe": {"Fe": 0.5, "Mn": 0.5}}) struct_trafo = trans.apply_transformation(struct) - alls = enum_trans.apply_transformation(struct_trafo, 100) - assert len(alls) == 3 + all_structs = enum_trans.apply_transformation(struct_trafo, 100) + assert len(all_structs) == 3 assert isinstance(trans.apply_transformation(struct_trafo), Structure) - for ss in alls: + for ss in all_structs: assert "energy" in ss # Check ordering of energy/atom - assert alls[0]["energy"] / alls[0]["num_sites"] <= alls[-1]["energy"] / alls[-1]["num_sites"] + assert ( + all_structs[0]["energy"] / all_structs[0]["num_sites"] + <= all_structs[-1]["energy"] / all_structs[-1]["num_sites"] + ) @pytest.mark.skip(reason="dgl don't support torch 2.4.1+, #4073") def test_callable_sort_criteria(self): @@ -219,14 +222,17 @@ def sort_criteria(struct: Structure) -> tuple[Structure, float]: struct = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_LiFePO4") trans = SubstitutionTransformation({"Fe": {"Fe": 0.5, "Mn": 0.5}}) struct_trafo = trans.apply_transformation(struct) - alls = enum_trans.apply_transformation(struct_trafo, 100) - assert len(alls) == 3 + all_structs = enum_trans.apply_transformation(struct_trafo, 100) + assert len(all_structs) == 3 assert isinstance(trans.apply_transformation(struct_trafo), Structure) - for ss in alls: + for ss in all_structs: assert "energy" in ss # Check ordering of energy/atom - assert alls[0]["energy"] / alls[0]["num_sites"] <= alls[-1]["energy"] / alls[-1]["num_sites"] + assert ( + all_structs[0]["energy"] / all_structs[0]["num_sites"] + <= all_structs[-1]["energy"] / all_structs[-1]["num_sites"] + ) def test_max_disordered_sites(self): s_orig = Structure( @@ -298,40 +304,40 @@ def setUp(self): def test_apply_transformation(self): trans = MagOrderingTransformation({"Fe": 5}) struct = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_LiFePO4") - alls = trans.apply_transformation(struct, 10) - assert len(alls) == 3 - spg_analyzer = SpacegroupAnalyzer(alls[0]["structure"], 0.1) + all_structs = trans.apply_transformation(struct, 10) + assert len(all_structs) == 3 + spg_analyzer = SpacegroupAnalyzer(all_structs[0]["structure"], 0.1) assert spg_analyzer.get_space_group_number() == 31 model = IsingModel(5, 5) trans = MagOrderingTransformation({"Fe": 5}, energy_model=model) alls2 = trans.apply_transformation(struct, 10) # Ising model with +J penalizes similar neighbor magmom. - assert alls[0]["structure"] != alls2[0]["structure"] - assert alls[0]["structure"] == alls2[2]["structure"] + assert all_structs[0]["structure"] != alls2[0]["structure"] + assert all_structs[0]["structure"] == alls2[2]["structure"] struct = self.get_structure("Li2O") # Li2O doesn't have magnetism of course, but this is to test the # enumeration. trans = MagOrderingTransformation({"Li+": 1}, max_cell_size=3) - alls = trans.apply_transformation(struct, 100) - # TODO: check this is correct, unclear what len(alls) should be + all_structs = trans.apply_transformation(struct, 100) + # TODO: check this is correct, unclear what len(all_structs) should be # this assert just ensures it doesn't change unexpectedly - assert len(alls) == 12 + assert len(all_structs) == 12 trans = MagOrderingTransformation({"Ni": 5}) - alls = trans.apply_transformation(self.NiO.get_primitive_structure(), return_ranked_list=10) + all_structs = trans.apply_transformation(self.NiO.get_primitive_structure(), return_ranked_list=10) - assert_allclose(self.NiO_AFM_111.lattice.parameters, alls[0]["structure"].lattice.parameters) - assert_allclose(self.NiO_AFM_001.lattice.parameters, alls[1]["structure"].lattice.parameters) + assert_allclose(self.NiO_AFM_111.lattice.parameters, all_structs[0]["structure"].lattice.parameters) + assert_allclose(self.NiO_AFM_001.lattice.parameters, all_structs[1]["structure"].lattice.parameters) def test_ferrimagnetic(self): trans = MagOrderingTransformation({"Fe": 5}, order_parameter=0.75, max_cell_size=1) struct = Structure.from_file(f"{VASP_IN_DIR}/POSCAR_LiFePO4") spg_analyzer = SpacegroupAnalyzer(struct, 0.1) struct = spg_analyzer.get_refined_structure() - alls = trans.apply_transformation(struct, 10) - assert len(alls) == 1 + all_structs = trans.apply_transformation(struct, 10) + assert len(all_structs) == 1 def test_as_from_dict(self): trans = MagOrderingTransformation({"Fe": 5}, order_parameter=0.75) @@ -347,22 +353,22 @@ def test_zero_spin_case(self): # ensure that zero spin case maintains sites and formula struct = self.get_structure("Li2O") trans = MagOrderingTransformation({"Li+": 0.0}, order_parameter=0.5) - alls = trans.apply_transformation(struct) - Li_site = alls.indices_from_symbol("Li")[0] + all_structs = trans.apply_transformation(struct) + Li_site = all_structs.indices_from_symbol("Li")[0] # Ensure s does not have a spin property assert struct[Li_site].specie.spin is None - # ensure sites are assigned a spin property in alls - # assert "spin" in alls[Li_site].specie.properties - assert alls.sites[Li_site].specie.spin == 0 + # ensure sites are assigned a spin property in all_structs + # assert "spin" in all_structs[Li_site].specie.properties + assert all_structs.sites[Li_site].specie.spin == 0 def test_advanced_usage(self): # test spin on just one oxidation state mag_types = {"Fe2+": 5} trans = MagOrderingTransformation(mag_types) - alls = trans.apply_transformation(self.Fe3O4_oxi) - assert isinstance(alls, Structure) - assert str(alls[0].specie) == "Fe2+,spin=5" - assert str(alls[2].specie) == "Fe3+" + all_structs = trans.apply_transformation(self.Fe3O4_oxi) + assert isinstance(all_structs, Structure) + assert str(all_structs[0].specie) == "Fe2+,spin=5" + assert str(all_structs[2].specie) == "Fe3+" # test multiple order parameters # this should only order on Fe3+ site, but assign spin to both @@ -372,15 +378,15 @@ def test_advanced_usage(self): MagOrderParameterConstraint(0.5, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(mag_types, order_parameter=order_parameters) - alls = trans.apply_transformation(self.Fe3O4_oxi) + all_structs = trans.apply_transformation(self.Fe3O4_oxi) # using this 'sorted' syntax because exact order of sites in first # returned structure varies between machines: we just want to ensure # that the order parameter is accurate - assert sorted(str(alls[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=5", "Fe2+,spin=5"]) - assert sorted(str(alls[idx].specie) for idx in range(2, 6)) == sorted( + assert sorted(str(all_structs[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=5", "Fe2+,spin=5"]) + assert sorted(str(all_structs[idx].specie) for idx in range(2, 6)) == sorted( ["Fe3+,spin=5", "Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5"] ) - assert str(alls[0].specie) == "Fe2+,spin=5" + assert str(all_structs[0].specie) == "Fe2+,spin=5" # this should give same results as previously # but with opposite sign on Fe2+ site @@ -390,9 +396,9 @@ def test_advanced_usage(self): MagOrderParameterConstraint(0.5, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(mag_types, order_parameter=order_parameters) - alls = trans.apply_transformation(self.Fe3O4_oxi) - assert sorted(str(alls[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=-5", "Fe2+,spin=-5"]) - assert sorted(str(alls[idx].specie) for idx in range(2, 6)) == sorted( + all_structs = trans.apply_transformation(self.Fe3O4_oxi) + assert sorted(str(all_structs[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=-5", "Fe2+,spin=-5"]) + assert sorted(str(all_structs[idx].specie) for idx in range(2, 6)) == sorted( ["Fe3+,spin=5", "Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5"] ) @@ -403,9 +409,9 @@ def test_advanced_usage(self): MagOrderParameterConstraint(0.25, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(mag_types, order_parameter=order_parameters) - alls = trans.apply_transformation(self.Fe3O4_oxi) - assert sorted(str(alls[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]) - assert sorted(str(alls[idx].specie) for idx in range(2, 6)) == sorted( + all_structs = trans.apply_transformation(self.Fe3O4_oxi) + assert sorted(str(all_structs[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]) + assert sorted(str(all_structs[idx].specie) for idx in range(2, 6)) == sorted( ["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=-5"] ) @@ -431,12 +437,12 @@ def test_advanced_usage(self): ), ] trans = MagOrderingTransformation(mag_types, order_parameter=order_parameters) - alls = trans.apply_transformation(self.Fe3O4) - alls.sort(key=lambda x: x.properties["cn"], reverse=True) - assert sorted(str(alls[idx].specie) for idx in range(4)) == sorted( + all_structs = trans.apply_transformation(self.Fe3O4) + all_structs.sort(key=lambda x: x.properties["cn"], reverse=True) + assert sorted(str(all_structs[idx].specie) for idx in range(4)) == sorted( ["Fe,spin=-5", "Fe,spin=-5", "Fe,spin=5", "Fe,spin=5"] ) - assert sorted(str(alls[idx].specie) for idx in range(4, 6)) == sorted(["Fe,spin=5", "Fe,spin=5"]) + assert sorted(str(all_structs[idx].specie) for idx in range(4, 6)) == sorted(["Fe,spin=5", "Fe,spin=5"]) # now ordering on both sites, equivalent to order_parameter = 0.5 mag_types = {"Fe2+": 5, "Fe3+": 5} @@ -445,13 +451,13 @@ def test_advanced_usage(self): MagOrderParameterConstraint(0.5, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(mag_types, order_parameter=order_parameters) - alls = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=10) - struct = alls[0]["structure"] + all_structs = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=10) + struct = all_structs[0]["structure"] assert sorted(str(struct[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]) assert sorted(str(struct[idx].specie) for idx in range(2, 6)) == sorted( ["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=5"] ) - assert len(alls) == 4 + assert len(all_structs) == 4 # now mixed orderings where neither are equal or 1 mag_types = {"Fe2+": 5, "Fe3+": 5} @@ -460,25 +466,25 @@ def test_advanced_usage(self): MagOrderParameterConstraint(0.25, species_constraints="Fe3+"), ] trans = MagOrderingTransformation(mag_types, order_parameter=order_parameters) - alls = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=100) - struct = alls[0]["structure"] + all_structs = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=100) + struct = all_structs[0]["structure"] assert sorted(str(struct[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]) assert sorted(str(struct[idx].specie) for idx in range(2, 6)) == sorted( ["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=-5"] ) - assert len(alls) == 2 + assert len(all_structs) == 2 # now order on multiple species mag_types = {"Fe2+": 5, "Fe3+": 5} order_parameters = [MagOrderParameterConstraint(0.5, species_constraints=["Fe2+", "Fe3+"])] trans = MagOrderingTransformation(mag_types, order_parameter=order_parameters) - alls = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=10) - struct = alls[0]["structure"] + all_structs = trans.apply_transformation(self.Fe3O4_oxi, return_ranked_list=10) + struct = all_structs[0]["structure"] assert sorted(str(struct[idx].specie) for idx in range(2)) == sorted(["Fe2+,spin=5", "Fe2+,spin=-5"]) assert sorted(str(struct[idx].specie) for idx in range(2, 6)) == sorted( ["Fe3+,spin=5", "Fe3+,spin=-5", "Fe3+,spin=-5", "Fe3+,spin=5"] ) - assert len(alls) == 6 + assert len(all_structs) == 6 @pytest.mark.skipif(not enumlib_present, reason="enum_lib not present.")