Skip to content

Commit

Permalink
Fix mypy errors for io.cp2k (#3984)
Browse files Browse the repository at this point in the history
* ignore mypy override error globally

* standardize CP2K names

* pre-commit auto-fixes

* standarize more CP2K names

* old trick: relocate magic methods to the top

* format tweaks

* fix type errors in cp2k inputs

* remove reimport Sequence

* use list[Kpoint] as getter return type

* remove unnecessary cast

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
DanielYang59 and pre-commit-ci[bot] authored Aug 9, 2024
1 parent b01f282 commit 25f0a9c
Show file tree
Hide file tree
Showing 25 changed files with 155 additions and 165 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -285,7 +285,7 @@ ignore_missing_imports = true
namespace_packages = true
explicit_package_bases = true
no_implicit_optional = false
disable_error_code = "annotation-unchecked"
disable_error_code = ["annotation-unchecked", "override"]

[[tool.mypy.overrides]]
module = ["requests.*", "tabulate.*"]
Expand Down
8 changes: 4 additions & 4 deletions src/pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -1490,7 +1490,7 @@ def get_nn_info(self, structure: Structure, n: int):

return siw

def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> StructureGraph: # type: ignore[override]
def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> StructureGraph:
"""
Obtain a MoleculeGraph object using this NearNeighbor
class. Requires the optional dependency networkx
Expand Down Expand Up @@ -1637,7 +1637,7 @@ def get_nn_info(self, structure: Structure, n: int):

return siw

def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> MoleculeGraph: # type: ignore[override]
def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> MoleculeGraph:
"""
Obtain a MoleculeGraph object using this NearNeighbor class.
Expand Down Expand Up @@ -4000,7 +4000,7 @@ def get_nn_data(self, structure: Structure, n: int, length=None):

return self.transform_to_length(self.NNData(nn, cn_weights, cn_nninfo), length)

def get_cn(self, structure: Structure, n: int, **kwargs) -> float: # type: ignore[override]
def get_cn(self, structure: Structure, n: int, **kwargs) -> float:
"""Get coordination number, CN, of site with index n in structure.
Args:
Expand Down Expand Up @@ -4306,7 +4306,7 @@ def extend_structure_molecules(self) -> bool:
"""
return True

def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> StructureGraph: # type: ignore[override]
def get_bonded_structure(self, structure: Structure, decorate: bool = False) -> StructureGraph:
"""
Args:
structure (Structure): Input structure
Expand Down
12 changes: 6 additions & 6 deletions src/pymatgen/core/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def to_str(number: float, rjust: int = 10) -> str:
outs.append(f"{idx} {site.species_string} {' '.join(to_str(coord, 12) for coord in site.frac_coords)}")
return "\n".join(outs)

def copy(self) -> Self: # type: ignore[override]
def copy(self) -> Self:
"""Make a copy of the GrainBoundary."""
return type(self)(
self.lattice,
Expand Down Expand Up @@ -261,7 +261,7 @@ def coincidents(self) -> list[Site]:
coincident_sites.append(self.sites[idx])
return coincident_sites

def as_dict(self) -> dict: # type: ignore[override]
def as_dict(self) -> dict:
"""
Returns:
Dictionary representation of GrainBoundary object.
Expand All @@ -281,7 +281,7 @@ def as_dict(self) -> dict: # type: ignore[override]
}

@classmethod
def from_dict(cls, dct: dict) -> Self: # type: ignore[override]
def from_dict(cls, dct: dict) -> Self:
"""Generate GrainBoundary from a dict created by as_dict().
Args:
Expand Down Expand Up @@ -2580,7 +2580,7 @@ def film(self) -> Structure:
"""A Structure for just the film."""
return Structure.from_sites(self.film_sites)

def copy(self) -> Self: # type: ignore[override]
def copy(self) -> Self:
"""Make a copy of the Interface."""
return type(self).from_dict(self.as_dict())

Expand Down Expand Up @@ -2689,7 +2689,7 @@ def _update_c(self, new_c: float) -> None:
site._lattice = new_lattice # Update the lattice
site.coords = c_coords # Put back into original Cartesian space

def as_dict(self) -> dict: # type: ignore[override]
def as_dict(self) -> dict:
"""MSONable dict."""
return {
**super().as_dict(),
Expand All @@ -2700,7 +2700,7 @@ def as_dict(self) -> dict: # type: ignore[override]
}

@classmethod
def from_dict(cls, dct: dict) -> Self: # type: ignore[override]
def from_dict(cls, dct: dict) -> Self:
"""
Args:
dct: dict.
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/core/ion.py
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ def composition(self) -> Composition:
"""Composition of ion."""
return Composition(self._data)

def oxi_state_guesses( # type: ignore[override]
def oxi_state_guesses(
self,
oxi_states_override: dict | None = None,
all_oxi_states: bool = False,
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/core/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ def from_dict(
dct: dict,
fmt: str | None = None,
**kwargs,
) -> Self: # type: ignore[override]
) -> Self:
"""Create a Lattice from a dictionary.
If fmt is None, the dict should contain the a, b, c,
Expand Down
4 changes: 2 additions & 2 deletions src/pymatgen/core/sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def __getattr__(self, attr: str) -> Any:
return props[attr]
raise AttributeError(f"{attr=} not found on {type(self).__name__}")

def __getitem__(self, el: Element) -> float: # type: ignore[override]
def __getitem__(self, el: Element) -> float:
"""Get the occupancy for element."""
return self.species[el]

Expand All @@ -102,7 +102,7 @@ def __eq__(self, other: object) -> bool:
and self.properties == other.properties
)

def __hash__(self) -> int: # type: ignore[override]
def __hash__(self) -> int:
"""Minimally effective hash function that just distinguishes between Sites
with different elements.
"""
Expand Down
28 changes: 14 additions & 14 deletions src/pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ def __len__(self) -> Literal[3]:
"""Make neighbor Tuple-like to retain backwards compatibility."""
return 3

def __getitem__(self, idx: int) -> Self | float: # type: ignore[override]
def __getitem__(self, idx: int) -> Self | float:
"""Make neighbor Tuple-like to retain backwards compatibility."""
return (self, self.nn_distance, self.index)[idx]

Expand Down Expand Up @@ -170,7 +170,7 @@ def __len__(self) -> Literal[4]:
"""Make neighbor Tuple-like to retain backwards compatibility."""
return 4

def __getitem__(self, idx: int | slice): # type: ignore[override]
def __getitem__(self, idx: int | slice):
"""Make neighbor Tuple-like to retain backwards compatibility."""
return (self, self.nn_distance, self.index, self.image)[idx]

Expand All @@ -179,12 +179,12 @@ def coords(self) -> NDArray:
"""Cartesian coords."""
return self._lattice.get_cartesian_coords(self._frac_coords)

def as_dict(self) -> dict: # type: ignore[override]
def as_dict(self) -> dict:
"""Note that method calls the super of Site, which is MSONable itself."""
return super(Site, self).as_dict()

@classmethod
def from_dict(cls, dct: dict) -> Self: # type: ignore[override]
def from_dict(cls, dct: dict) -> Self:
"""Get a PeriodicNeighbor from a dict.
Args:
Expand Down Expand Up @@ -2960,7 +2960,7 @@ def from_id(cls, id_: str, source: StructureSources = "Materials Project", **kwa
raise ValueError(f"Invalid source: {source}")

@classmethod
def from_str( # type: ignore[override]
def from_str(
cls,
input_string: str,
fmt: FileFormats,
Expand Down Expand Up @@ -3044,7 +3044,7 @@ def from_str( # type: ignore[override]
return cls.from_sites(struct, properties=struct.properties)

@classmethod
def from_file( # type: ignore[override]
def from_file(
cls,
filename: PathLike,
primitive: bool = False,
Expand Down Expand Up @@ -3774,7 +3774,7 @@ def to(self, filename: str = "", fmt: str = "") -> str | None:
return str(writer)

@classmethod
def from_str( # type: ignore[override]
def from_str(
cls,
input_string: str,
fmt: Literal["xyz", "gjf", "g03", "g09", "com", "inp", "json", "yaml"],
Expand Down Expand Up @@ -3821,7 +3821,7 @@ def from_str( # type: ignore[override]
return cls.from_sites(mol, properties=mol.properties)

@classmethod
def from_file(cls, filename: PathLike) -> Self | None: # type: ignore[override]
def from_file(cls, filename: PathLike) -> Self | None:
"""Read a molecule from a file. Supported formats include xyz,
gaussian input (gjf|g03|g09|com|inp), Gaussian output (.out|and
pymatgen's JSON-serialized molecules. Using openbabel,
Expand Down Expand Up @@ -3933,7 +3933,7 @@ def __init__(

self._sites: list[PeriodicSite] = list(self._sites) # type: ignore[assignment]

def __setitem__( # type: ignore[override]
def __setitem__(
self,
idx: int | slice | Sequence[int] | SpeciesLike,
site: SpeciesLike | PeriodicSite | Sequence | dict[SpeciesLike, float],
Expand Down Expand Up @@ -4018,7 +4018,7 @@ def lattice(self, lattice: ArrayLike | Lattice) -> None:
for site in self:
site.lattice = lattice

def append( # type: ignore[override]
def append(
self,
species: CompositionLike,
coords: ArrayLike,
Expand Down Expand Up @@ -4049,7 +4049,7 @@ def append( # type: ignore[override]
properties=properties,
)

def insert( # type: ignore[override]
def insert(
self,
idx: int,
species: CompositionLike,
Expand Down Expand Up @@ -4765,7 +4765,7 @@ def __init__(
)
self._sites: list[Site] = list(self._sites)

def __setitem__( # type: ignore[override]
def __setitem__(
self,
idx: int | slice | Sequence[int] | SpeciesLike,
site: SpeciesLike | Site | Sequence,
Expand Down Expand Up @@ -4810,7 +4810,7 @@ def __delitem__(self, idx: SupportsIndex | slice) -> None:
"""Deletes a site from the Structure."""
self._sites.__delitem__(idx)

def append( # type: ignore[override]
def append(
self,
species: CompositionLike,
coords: ArrayLike,
Expand Down Expand Up @@ -4874,7 +4874,7 @@ def set_charge_and_spin(

return self

def insert( # type: ignore[override]
def insert(
self,
idx: int,
species: CompositionLike,
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/core/surface.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ def surface_area(self) -> float:
return np.linalg.norm(np.cross(matrix[0], matrix[1]))

@classmethod
def from_dict(cls, dct: dict[str, Any]) -> Self: # type: ignore[override]
def from_dict(cls, dct: dict[str, Any]) -> Self:
"""
Args:
dct: dict.
Expand All @@ -242,7 +242,7 @@ def from_dict(cls, dct: dict[str, Any]) -> Self: # type: ignore[override]
energy=dct["energy"],
)

def as_dict(self, **kwargs) -> dict: # type: ignore[override]
def as_dict(self, **kwargs) -> dict:
"""MSONable dict."""
dct = super().as_dict(**kwargs)
dct["@module"] = type(self).__module__
Expand All @@ -255,7 +255,7 @@ def as_dict(self, **kwargs) -> dict: # type: ignore[override]
dct["energy"] = self.energy
return dct

def copy(self, site_properties: dict[str, Any] | None = None) -> Self: # type: ignore[override]
def copy(self, site_properties: dict[str, Any] | None = None) -> Self:
"""Get a copy of the Slab, with options to update site properties.
Args:
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/electronic_structure/bandstructure.py
Original file line number Diff line number Diff line change
Expand Up @@ -1037,7 +1037,7 @@ def get_projection_on_elements(self) -> dict[Spin, list]:

def get_projections_on_elements_and_orbitals(
self,
el_orb_spec: dict[Element, list], # type: ignore[override]
el_orb_spec: dict[Element, list],
) -> dict[Spin, list]:
"""Get projections on elements and specific orbitals.
Expand Down
6 changes: 3 additions & 3 deletions src/pymatgen/electronic_structure/dos.py
Original file line number Diff line number Diff line change
Expand Up @@ -1397,7 +1397,7 @@ def as_dict(self) -> dict[str, Any]:
class LobsterCompleteDos(CompleteDos):
"""Extended CompleteDos for LOBSTER."""

def get_site_orbital_dos(self, site: PeriodicSite, orbital: str) -> Dos: # type: ignore[override]
def get_site_orbital_dos(self, site: PeriodicSite, orbital: str) -> Dos:
"""Get the DOS for a particular orbital of a particular site.
Args:
Expand Down Expand Up @@ -1448,7 +1448,7 @@ def get_site_t2g_eg_resolved_dos(
"e_g": Dos(self.efermi, self.energies, functools.reduce(add_densities, eg_dos)),
}

def get_spd_dos(self) -> dict[str, Dos]: # type: ignore[override]
def get_spd_dos(self) -> dict[str, Dos]:
"""Get orbital projected DOS.
For example, if 3s and 4s are included in the basis of some element,
Expand All @@ -1469,7 +1469,7 @@ def get_spd_dos(self) -> dict[str, Dos]: # type: ignore[override]

return {orb: Dos(self.efermi, self.energies, densities) for orb, densities in spd_dos.items()} # type: ignore[misc]

def get_element_spd_dos(self, el: SpeciesLike) -> dict[str, Dos]: # type: ignore[override]
def get_element_spd_dos(self, el: SpeciesLike) -> dict[str, Dos]:
"""Get element and s/p/d projected DOS.
Args:
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/entries/compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,7 @@ def get_explanation_dict(self, entry: ComputedEntry) -> dict[str, Any]:
dct["corrections"] = corrections
return dct

def explain(self, entry: ComputedEntry) -> None: # type: ignore[override]
def explain(self, entry: ComputedEntry) -> None:
"""Print an explanation of the corrections that are being applied for a
given compatibility scheme. Inspired by the "explain" methods in many
database methodologies.
Expand Down
2 changes: 1 addition & 1 deletion src/pymatgen/entries/mixing_scheme.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ def __init__(
if hasattr(compat, "check_potcar"):
compat.check_potcar = check_potcar # type: ignore[union-attr]

def process_entries( # type: ignore[override]
def process_entries(
self,
entries: AnyComputedEntry | list[AnyComputedEntry],
clean: bool = True,
Expand Down
Loading

0 comments on commit 25f0a9c

Please sign in to comment.