Skip to content

Commit

Permalink
Cleanup codespell ignore patterns (materialsproject#4175)
Browse files Browse the repository at this point in the history
  • Loading branch information
DanielYang59 authored Nov 16, 2024
1 parent a09e7dd commit c72c9e9
Show file tree
Hide file tree
Showing 30 changed files with 229 additions and 217 deletions.
15 changes: 10 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/bond_dissociation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""

Expand Down
8 changes: 4 additions & 4 deletions src/pymatgen/analysis/chemenv/utils/graph_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
4 changes: 1 addition & 3 deletions src/pymatgen/analysis/functional_groups.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/analysis/interface_reactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
Expand All @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/piezo.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/analysis/piezo_sensitivity.py
Original file line number Diff line number Diff line change
Expand Up @@ -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!")
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/io/lmto.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def from_str(cls, data: str, sigfigs: int = 8) -> Self:
"HEADER": [],
"VERS": [],
"SYMGRP": [],
"STRUC": [],
"STRUC": [], # codespell:ignore struc
"CLASS": [],
"SITE": [],
}
Expand All @@ -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]
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/io/lobster/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 5 additions & 5 deletions src/pymatgen/io/qchem/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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\)",
},
)
Expand All @@ -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:
Expand Down Expand Up @@ -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"]
Expand Down Expand Up @@ -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"]
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/io/res.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)),
Expand Down
16 changes: 8 additions & 8 deletions src/pymatgen/io/vasp/outputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -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+"
Expand Down Expand Up @@ -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]):
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/io/vasp/sets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/phonon/bandstructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/phonon/thermal_displacements.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
18 changes: 9 additions & 9 deletions src/pymatgen/transformations/advanced_transformations.py
Original file line number Diff line number Diff line change
Expand Up @@ -854,27 +854,27 @@ 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)
except ValueError:
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())
Expand All @@ -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])
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/vis/structure_vtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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: {
Expand Down
Loading

0 comments on commit c72c9e9

Please sign in to comment.