Skip to content

Commit

Permalink
Many more type hint tweaks and ignores
Browse files Browse the repository at this point in the history
  • Loading branch information
ml-evs committed Nov 11, 2022
1 parent 1457edd commit cbd91b0
Show file tree
Hide file tree
Showing 26 changed files with 193 additions and 185 deletions.
2 changes: 1 addition & 1 deletion optimade/adapters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
from .references import * # noqa: F403
from .structures import * # noqa: F403

__all__ = exceptions.__all__ + references.__all__ + structures.__all__ # noqa: F405
__all__ = exceptions.__all__ + references.__all__ + structures.__all__ # type: ignore[name-defined] # noqa: F405
24 changes: 13 additions & 11 deletions optimade/adapters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@
and [`StructureResource`][optimade.models.structures.StructureResource]s, respectively.
"""
import re
from typing import Any, Callable, Dict, List, Tuple, Type, Union
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union

from pydantic import BaseModel # pylint: disable=no-name-in-module

from optimade.adapters.logger import LOGGER
from optimade.models import EntryResource
from optimade.models.entries import EntryResource


class EntryAdapter:
Expand All @@ -48,15 +48,17 @@ def __init__(self, entry: dict) -> None:
Parameters:
entry (dict): A JSON OPTIMADE single resource entry.
"""
self._entry = None
self._converted = {}
self._entry: Optional[EntryResource] = None
self._converted: Dict[str, Any] = {}

self.entry = entry
self.entry: EntryResource = entry # type: ignore[assignment]

# Note that these return also the default values for otherwise non-provided properties.
self._common_converters = {
"json": self.entry.json, # Return JSON serialized string, see https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeljson
"dict": self.entry.dict, # Return Python dict, see https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict
# Return JSON serialized string, see https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeljson
"json": self.entry.json, # type: ignore[attr-defined]
# Return Python dict, see https://pydantic-docs.helpmanual.io/usage/exporting_models/#modeldict
"dict": self.entry.dict, # type: ignore[attr-defined]
}

@property
Expand All @@ -67,7 +69,7 @@ def entry(self) -> EntryResource:
The entry resource.
"""
return self._entry
return self._entry # type: ignore[return-value]

@entry.setter
def entry(self, value: dict) -> None:
Expand Down Expand Up @@ -171,12 +173,12 @@ def __getattr__(self, name: str) -> Any:
return res

# Non-valid attribute
entry_resource_name = re.match(
_entry_resource_name = re.match(
r"(<class ')([a-zA-Z_]+\.)*([a-zA-Z_]+)('>)", str(self.ENTRY_RESOURCE)
)
entry_resource_name = (
entry_resource_name.group(3)
if entry_resource_name is not None
_entry_resource_name.group(3)
if _entry_resource_name is not None
else "UNKNOWN RESOURCE"
)
raise AttributeError(
Expand Down
4 changes: 3 additions & 1 deletion optimade/adapters/references/adapter.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Type

from optimade.adapters.base import EntryAdapter
from optimade.models import ReferenceResource

Expand All @@ -19,4 +21,4 @@ class Reference(EntryAdapter):
"""

ENTRY_RESOURCE: ReferenceResource = ReferenceResource
ENTRY_RESOURCE: Type[ReferenceResource] = ReferenceResource
12 changes: 6 additions & 6 deletions optimade/adapters/structures/aiida.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,13 +44,13 @@ def get_aiida_structure_data(optimade_structure: OptimadeStructure) -> Structure
attributes = optimade_structure.attributes

# Convert null/None values to float("nan")
lattice_vectors, adjust_cell = pad_cell(attributes.lattice_vectors)
lattice_vectors, adjust_cell = pad_cell(attributes.lattice_vectors) # type: ignore[arg-type]
structure = StructureData(cell=lattice_vectors)

# If species not provided, infer data from species_at_sites
species: Optional[List[OptimadeStructureSpecies]] = attributes.species
if not species:
species = species_from_species_at_sites(attributes.species_at_sites)
species = species_from_species_at_sites(attributes.species_at_sites) # type: ignore[arg-type]

# Add Kinds
for kind in species:
Expand Down Expand Up @@ -86,18 +86,18 @@ def get_aiida_structure_data(optimade_structure: OptimadeStructure) -> Structure
)

# Add Sites
for index in range(attributes.nsites):
for index in range(attributes.nsites): # type: ignore[arg-type]
# range() to ensure 1-to-1 between kind and site
structure.append_site(
Site(
kind_name=attributes.species_at_sites[index],
position=attributes.cartesian_site_positions[index],
kind_name=attributes.species_at_sites[index], # type: ignore[index]
position=attributes.cartesian_site_positions[index], # type: ignore[index]
)
)

if adjust_cell:
structure._adjust_default_cell(
pbc=[bool(dim.value) for dim in attributes.dimension_types]
pbc=[bool(dim.value) for dim in attributes.dimension_types] # type: ignore[union-attr]
)

return structure
8 changes: 4 additions & 4 deletions optimade/adapters/structures/ase.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ def get_ase_atoms(optimade_structure: OptimadeStructure) -> Atoms:
species = attributes.species
# If species is missing, infer data from species_at_sites
if not species:
species = species_from_species_at_sites(attributes.species_at_sites)
species = species_from_species_at_sites(attributes.species_at_sites) # type: ignore[arg-type]

optimade_species: Dict[str, OptimadeStructureSpecies] = {_.name: _ for _ in species}

Expand All @@ -69,9 +69,9 @@ def get_ase_atoms(optimade_structure: OptimadeStructure) -> Atoms:
)

atoms = []
for site_number in range(attributes.nsites):
species_name = attributes.species_at_sites[site_number]
site = attributes.cartesian_site_positions[site_number]
for site_number in range(attributes.nsites): # type: ignore[arg-type]
species_name = attributes.species_at_sites[site_number] # type: ignore[index]
site = attributes.cartesian_site_positions[site_number] # type: ignore[index]

current_species = optimade_species[species_name]

Expand Down
20 changes: 10 additions & 10 deletions optimade/adapters/structures/cif.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

from optimade.adapters.warnings import AdapterPackageNotFound

np = None
np = None # type: ignore[assignment]
NUMPY_NOT_FOUND = "NumPy not found, cannot convert structure to CIF"


Expand All @@ -55,7 +55,7 @@ def get_cif( # pylint: disable=too-many-locals,too-many-branches
# NumPy is needed for calculations
if globals().get("np", None) is None:
warn(NUMPY_NOT_FOUND, AdapterPackageNotFound)
return None
return None # type: ignore[return-value]

cif = """#
# Created from an OPTIMADE structure.
Expand All @@ -71,9 +71,9 @@ def get_cif( # pylint: disable=too-many-locals,too-many-branches

# Do this only if there's three non-zero lattice vectors
# NOTE: This also negates handling of lattice_vectors with null/None values
if valid_lattice_vector(attributes.lattice_vectors):
if valid_lattice_vector(attributes.lattice_vectors): # type:ignore[arg-type]
a_vector, b_vector, c_vector, alpha, beta, gamma = cell_to_cellpar(
attributes.lattice_vectors
attributes.lattice_vectors # type: ignore[arg-type]
)

cif += (
Expand All @@ -96,8 +96,8 @@ def get_cif( # pylint: disable=too-many-locals,too-many-branches
# we calculate the fractional coordinates if this is a 3D structure and we have all the necessary information.
if not hasattr(attributes, "fractional_site_positions"):
attributes.fractional_site_positions = fractional_coordinates(
cell=attributes.lattice_vectors,
cartesian_positions=attributes.cartesian_site_positions,
cell=attributes.lattice_vectors, # type:ignore[arg-type]
cartesian_positions=attributes.cartesian_site_positions, # type:ignore[arg-type]
)

# NOTE: This is otherwise a bit ahead of its time, since this OPTIMADE property is part of an open PR.
Expand All @@ -124,12 +124,12 @@ def get_cif( # pylint: disable=too-many-locals,too-many-branches
sites = attributes.cartesian_site_positions

species: Dict[str, OptimadeStructureSpecies] = {
species.name: species for species in attributes.species
species.name: species for species in attributes.species # type: ignore[union-attr]
}

symbol_occurences = {}
for site_number in range(attributes.nsites):
species_name = attributes.species_at_sites[site_number]
symbol_occurences: Dict[str, int] = {}
for site_number in range(attributes.nsites): # type: ignore[arg-type]
species_name = attributes.species_at_sites[site_number] # type: ignore[index]
site = sites[site_number]

current_species = species[species_name]
Expand Down
2 changes: 1 addition & 1 deletion optimade/adapters/structures/jarvis.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def get_jarvis_atoms(optimade_structure: OptimadeStructure) -> Atoms:

return Atoms(
lattice_mat=attributes.lattice_vectors,
elements=[specie.name for specie in attributes.species],
elements=[specie.name for specie in attributes.species], # type: ignore[union-attr]
coords=attributes.cartesian_site_positions,
cartesian=True,
)
29 changes: 15 additions & 14 deletions optimade/adapters/structures/proteindatabank.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@

from optimade.adapters.warnings import AdapterPackageNotFound

np = None
np = None # type: ignore[assignment]
NUMPY_NOT_FOUND = "NumPy not found, cannot convert structure to your desired format"

from optimade.adapters.structures.utils import (
Expand Down Expand Up @@ -63,7 +63,7 @@ def get_pdbx_mmcif( # pylint: disable=too-many-locals
"""
if globals().get("np", None) is None:
warn(NUMPY_NOT_FOUND, AdapterPackageNotFound)
return None
return None # type: ignore[return-value]

cif = """#
# Created from an OPTIMADE structure.
Expand All @@ -82,9 +82,9 @@ def get_pdbx_mmcif( # pylint: disable=too-many-locals
attributes = optimade_structure.attributes

# Do this only if there's three non-zero lattice vectors
if valid_lattice_vector(attributes.lattice_vectors):
if valid_lattice_vector(attributes.lattice_vectors): # type: ignore[arg-type]
a_vector, b_vector, c_vector, alpha, beta, gamma = cell_to_cellpar(
attributes.lattice_vectors
attributes.lattice_vectors # type: ignore[arg-type]
)

cif += (
Expand All @@ -107,8 +107,8 @@ def get_pdbx_mmcif( # pylint: disable=too-many-locals
# we calculate the fractional coordinates if this is a 3D structure and we have all the necessary information.
if not hasattr(attributes, "fractional_site_positions"):
attributes.fractional_site_positions = fractional_coordinates(
cell=attributes.lattice_vectors,
cartesian_positions=attributes.cartesian_site_positions,
cell=attributes.lattice_vectors, # type: ignore[arg-type]
cartesian_positions=attributes.cartesian_site_positions, # type: ignore[arg-type]
)

# NOTE: The following lines are perhaps needed to create a "valid" PDBx/mmCIF file.
Expand Down Expand Up @@ -165,11 +165,11 @@ def get_pdbx_mmcif( # pylint: disable=too-many-locals
sites = attributes.cartesian_site_positions

species: Dict[str, OptimadeStructureSpecies] = {
species.name: species for species in attributes.species
species.name: species for species in attributes.species # type: ignore[union-attr]
}

for site_number in range(attributes.nsites):
species_name = attributes.species_at_sites[site_number]
for site_number in range(attributes.nsites): # type: ignore[arg-type]
species_name = attributes.species_at_sites[site_number] # type: ignore[index]
site = sites[site_number]

current_species = species[species_name]
Expand Down Expand Up @@ -211,14 +211,14 @@ def get_pdb( # pylint: disable=too-many-locals
"""
if globals().get("np", None) is None:
warn(NUMPY_NOT_FOUND, AdapterPackageNotFound)
return None
return None # type: ignore[return-value]

pdb = ""

attributes = optimade_structure.attributes

rotation = None
if valid_lattice_vector(attributes.lattice_vectors):
if valid_lattice_vector(attributes.lattice_vectors): # type: ignore[arg-type]
currentcell = np.asarray(attributes.lattice_vectors)
cellpar = cell_to_cellpar(currentcell)
exportedcell = cellpar_to_cell(cellpar)
Expand All @@ -241,15 +241,16 @@ def get_pdb( # pylint: disable=too-many-locals
pdb += "MODEL 1\n"

species: Dict[str, OptimadeStructureSpecies] = {
species.name: species for species in attributes.species
species.name: species
for species in attributes.species # type:ignore[union-attr]
}

sites = np.asarray(attributes.cartesian_site_positions)
if rotation is not None:
sites = sites.dot(rotation)

for site_number in range(attributes.nsites):
species_name = attributes.species_at_sites[site_number]
for site_number in range(attributes.nsites): # type: ignore[arg-type]
species_name = attributes.species_at_sites[site_number] # type: ignore[index]
site = sites[site_number]

current_species = species[species_name]
Expand Down
16 changes: 8 additions & 8 deletions optimade/adapters/structures/pymatgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ def get_pymatgen(optimade_structure: OptimadeStructure) -> Union[Structure, Mole
warn(PYMATGEN_NOT_FOUND, AdapterPackageNotFound)
return None

if valid_lattice_vector(optimade_structure.attributes.lattice_vectors) and (
optimade_structure.attributes.nperiodic_dimensions > 0
or any(optimade_structure.attributes.dimension_types)
if valid_lattice_vector(optimade_structure.attributes.lattice_vectors) and ( # type: ignore[arg-type]
optimade_structure.attributes.nperiodic_dimensions > 0 # type: ignore[operator]
or any(optimade_structure.attributes.dimension_types) # type: ignore[arg-type]
):
return _get_structure(optimade_structure)

Expand All @@ -78,9 +78,9 @@ def _get_structure(optimade_structure: OptimadeStructure) -> Structure:
return Structure(
lattice=Lattice(attributes.lattice_vectors, attributes.dimension_types),
species=_pymatgen_species(
nsites=attributes.nsites,
nsites=attributes.nsites, # type: ignore[arg-type]
species=attributes.species,
species_at_sites=attributes.species_at_sites,
species_at_sites=attributes.species_at_sites, # type: ignore[arg-type]
),
coords=attributes.cartesian_site_positions,
coords_are_cartesian=True,
Expand All @@ -94,9 +94,9 @@ def _get_molecule(optimade_structure: OptimadeStructure) -> Molecule:

return Molecule(
species=_pymatgen_species(
nsites=attributes.nsites,
species=attributes.species,
species_at_sites=attributes.species_at_sites,
nsites=attributes.nsites, # type: ignore[arg-type]
species=attributes.species, # type: ignore[arg-type]
species_at_sites=attributes.species_at_sites, # type: ignore[arg-type]
),
coords=attributes.cartesian_site_positions,
)
Expand Down

0 comments on commit cbd91b0

Please sign in to comment.