Skip to content

Commit

Permalink
Run pyupgrade --py39-plus to upgrade legacy annotations
Browse files Browse the repository at this point in the history
  • Loading branch information
ml-evs committed Oct 15, 2023
1 parent 5b83300 commit 791b932
Show file tree
Hide file tree
Showing 60 changed files with 405 additions and 414 deletions.
14 changes: 7 additions & 7 deletions optimade/adapters/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
and [`StructureResource`][optimade.models.structures.StructureResource]s, respectively.
"""
import re
from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
from typing import Any, Callable, Optional, Union

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

Expand All @@ -42,18 +42,18 @@ class EntryAdapter:
"""

ENTRY_RESOURCE: Type[EntryResource] = EntryResource
_type_converters: Dict[str, Callable] = {}
_type_ingesters: Dict[str, Callable] = {}
_type_ingesters_by_type: Dict[str, Type] = {}
ENTRY_RESOURCE: type[EntryResource] = EntryResource
_type_converters: dict[str, Callable] = {}
_type_ingesters: dict[str, Callable] = {}
_type_ingesters_by_type: dict[str, type] = {}

def __init__(self, entry: dict) -> None:
"""
Parameters:
entry (dict): A JSON OPTIMADE single resource entry.
"""
self._entry: Optional[EntryResource] = None
self._converted: Dict[str, Any] = {}
self._converted: dict[str, Any] = {}

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

Expand Down Expand Up @@ -164,7 +164,7 @@ def ingest_from(cls, data: Any, format: Optional[str] = None) -> Any:

@staticmethod
def _get_model_attributes(
starting_instances: Union[Tuple[BaseModel, ...], List[BaseModel]], name: str
starting_instances: Union[tuple[BaseModel, ...], list[BaseModel]], name: str
) -> Any:
"""Helper method for retrieving the OPTIMADE model's attribute, supporting "."-nested attributes"""
for res in starting_instances:
Expand Down
4 changes: 1 addition & 3 deletions optimade/adapters/references/adapter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from typing import Type

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

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

ENTRY_RESOURCE: Type[ReferenceResource] = ReferenceResource
ENTRY_RESOURCE: type[ReferenceResource] = ReferenceResource
10 changes: 5 additions & 5 deletions optimade/adapters/structures/adapter.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Callable, Dict, Type
from typing import Callable

from optimade.adapters.base import EntryAdapter
from optimade.models import StructureResource
Expand Down Expand Up @@ -44,8 +44,8 @@ class Structure(EntryAdapter):
"""

ENTRY_RESOURCE: Type[StructureResource] = StructureResource
_type_converters: Dict[str, Callable] = {
ENTRY_RESOURCE: type[StructureResource] = StructureResource
_type_converters: dict[str, Callable] = {
"aiida_structuredata": get_aiida_structure_data,
"ase": get_ase_atoms,
"cif": get_cif,
Expand All @@ -55,12 +55,12 @@ class Structure(EntryAdapter):
"jarvis": get_jarvis_atoms,
}

_type_ingesters: Dict[str, Callable] = {
_type_ingesters: dict[str, Callable] = {
"pymatgen": from_pymatgen,
"ase": from_ase_atoms,
}

_type_ingesters_by_type: Dict[str, Type] = {
_type_ingesters_by_type: dict[str, type] = {
"pymatgen": PymatgenStructure,
"ase": ASEAtoms,
}
4 changes: 2 additions & 2 deletions optimade/adapters/structures/aiida.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
This conversion function relies on the [`aiida-core`](https://github.com/aiidateam/aiida-core) package.
"""
from typing import List, Optional
from typing import Optional
from warnings import warn

from optimade.adapters.structures.utils import pad_cell, species_from_species_at_sites
Expand Down Expand Up @@ -48,7 +48,7 @@ def get_aiida_structure_data(optimade_structure: OptimadeStructure) -> Structure
structure = StructureData(cell=lattice_vectors)

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

Expand Down
3 changes: 1 addition & 2 deletions optimade/adapters/structures/ase.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
For more information on the ASE code see [their documentation](https://wiki.fysik.dtu.dk/ase/).
"""
from typing import Dict

from optimade.adapters.exceptions import ConversionError
from optimade.adapters.structures.utils import (
Expand Down Expand Up @@ -66,7 +65,7 @@ def get_ase_atoms(optimade_structure: OptimadeStructure) -> Atoms:
if not species:
species = species_from_species_at_sites(attributes.species_at_sites) # type: ignore[arg-type]

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

# Since we've made sure there are no species with more than 1 chemical symbol,
# asking for index 0 will always work.
Expand Down
5 changes: 2 additions & 3 deletions optimade/adapters/structures/cif.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
This conversion function relies on the [NumPy](https://numpy.org/) library.
"""
from typing import Dict

from optimade.adapters.structures.utils import (
cell_to_cellpar,
Expand Down Expand Up @@ -123,11 +122,11 @@ def get_cif( # pylint: disable=too-many-locals,too-many-branches
else:
sites = attributes.cartesian_site_positions

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

symbol_occurences: Dict[str, int] = {}
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]
Expand Down
5 changes: 2 additions & 3 deletions optimade/adapters/structures/proteindatabank.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
Warning:
Currently, the PDBx/mmCIF conversion function is not parsing as a complete PDBx/mmCIF file.
"""
from typing import Dict

try:
import numpy as np
Expand Down Expand Up @@ -164,7 +163,7 @@ def get_pdbx_mmcif( # pylint: disable=too-many-locals
else:
sites = attributes.cartesian_site_positions

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

Expand Down Expand Up @@ -240,7 +239,7 @@ def get_pdb( # pylint: disable=too-many-locals

pdb += "MODEL 1\n"

species: Dict[str, OptimadeStructureSpecies] = {
species: dict[str, OptimadeStructureSpecies] = {
species.name: species
for species in attributes.species # type:ignore[union-attr]
}
Expand Down
8 changes: 4 additions & 4 deletions optimade/adapters/structures/pymatgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
For more information on the pymatgen code see [their documentation](https://pymatgen.org).
"""
from typing import Dict, List, Optional, Union
from typing import Optional, Union

from optimade.adapters.structures.utils import (
species_from_species_at_sites,
Expand Down Expand Up @@ -105,9 +105,9 @@ def _get_molecule(optimade_structure: OptimadeStructure) -> Molecule:

def _pymatgen_species(
nsites: int,
species: Optional[List[OptimadeStructureSpecies]],
species_at_sites: List[str],
) -> List[Dict[str, float]]:
species: Optional[list[OptimadeStructureSpecies]],
species_at_sites: list[str],
) -> list[dict[str, float]]:
"""
Create list of {"symbol": "concentration"} per site for values to pymatgen species parameters.
Remove vacancies, if they are present.
Expand Down
39 changes: 20 additions & 19 deletions optimade/adapters/structures/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
Most of these functions rely on the [NumPy](https://numpy.org/) library.
"""
from typing import Iterable, List, Optional, Tuple, Type
from collections.abc import Iterable
from typing import Optional

from optimade.models.structures import Species as OptimadeStructureSpecies
from optimade.models.structures import Vector3D
Expand All @@ -19,7 +20,7 @@
NUMPY_NOT_FOUND = "NumPy not found, cannot convert structure to your desired format"


def valid_lattice_vector(lattice_vec: Tuple[Vector3D, Vector3D, Vector3D]):
def valid_lattice_vector(lattice_vec: tuple[Vector3D, Vector3D, Vector3D]):
if len(lattice_vec) != 3:
return False
for vector in lattice_vec:
Expand All @@ -31,8 +32,8 @@ def valid_lattice_vector(lattice_vec: Tuple[Vector3D, Vector3D, Vector3D]):


def scaled_cell(
cell: Tuple[Vector3D, Vector3D, Vector3D]
) -> Tuple[Vector3D, Vector3D, Vector3D]:
cell: tuple[Vector3D, Vector3D, Vector3D]
) -> tuple[Vector3D, Vector3D, Vector3D]:
"""Return a scaled 3x3 cell from cartesian 3x3 cell (`lattice_vectors`).
This 3x3 matrix can be used to calculate the fractional coordinates from the cartesian_site_positions.
Expand Down Expand Up @@ -62,8 +63,8 @@ def scaled_cell(


def fractional_coordinates(
cell: Tuple[Vector3D, Vector3D, Vector3D], cartesian_positions: List[Vector3D]
) -> List[Vector3D]:
cell: tuple[Vector3D, Vector3D, Vector3D], cartesian_positions: list[Vector3D]
) -> list[Vector3D]:
"""Returns fractional coordinates and wraps coordinates to `[0,1[`.
Note:
Expand Down Expand Up @@ -101,8 +102,8 @@ def fractional_coordinates(


def cell_to_cellpar(
cell: Tuple[Vector3D, Vector3D, Vector3D], radians: bool = False
) -> List[float]:
cell: tuple[Vector3D, Vector3D, Vector3D], radians: bool = False
) -> list[float]:
"""Returns the cell parameters `[a, b, c, alpha, beta, gamma]`.
Angles are in degrees unless `radian=True` is used.
Expand Down Expand Up @@ -161,10 +162,10 @@ def unit_vector(x: Vector3D) -> Vector3D:


def cellpar_to_cell(
cellpar: List[float],
ab_normal: Tuple[int, int, int] = (0, 0, 1),
a_direction: Optional[Tuple[int, int, int]] = None,
) -> List[Vector3D]:
cellpar: list[float],
ab_normal: tuple[int, int, int] = (0, 0, 1),
a_direction: Optional[tuple[int, int, int]] = None,
) -> list[Vector3D]:
"""Return a 3x3 cell matrix from `cellpar=[a,b,c,alpha,beta,gamma]`.
Angles must be in degrees.
Expand Down Expand Up @@ -277,9 +278,9 @@ def cellpar_to_cell(
def _pad_iter_of_iters(
iterable: Iterable[Iterable],
padding: Optional[float] = None,
outer: Optional[Type] = None,
inner: Optional[Type] = None,
) -> Tuple[Iterable[Iterable], bool]:
outer: Optional[type] = None,
inner: Optional[type] = None,
) -> tuple[Iterable[Iterable], bool]:
"""Turn any null/None values into a float in given iterable of iterables"""
try:
padding = float(padding) # type: ignore[arg-type]
Expand All @@ -306,7 +307,7 @@ def _pad_iter_of_iters(


def pad_cell(
lattice_vectors: Tuple[Vector3D, Vector3D, Vector3D],
lattice_vectors: tuple[Vector3D, Vector3D, Vector3D],
padding: Optional[float] = None,
) -> tuple: # Setting this properly makes MkDocs fail.
"""Turn any `null`/`None` values into a `float` in given `tuple` of
Expand All @@ -333,8 +334,8 @@ def pad_cell(


def species_from_species_at_sites(
species_at_sites: List[str],
) -> List[OptimadeStructureSpecies]:
species_at_sites: list[str],
) -> list[OptimadeStructureSpecies]:
"""When a list of species dictionaries is not provided, this function
can be used to infer the species from the provided species_at_sites.
Expand All @@ -357,7 +358,7 @@ def species_from_species_at_sites(
]


def elements_ratios_from_species_at_sites(species_at_sites: List[str]) -> List[float]:
def elements_ratios_from_species_at_sites(species_at_sites: list[str]) -> list[float]:
"""Compute the OPTIMADE `elements_ratios` field from `species_at_sites` in the case where `species_at_sites` refers
to sites wholly occupied by the given elements, e.g., not arbitrary species labels or with partial/mixed occupancy.
Expand Down
14 changes: 8 additions & 6 deletions optimade/client/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,13 +166,13 @@ def _get(
base_urls=base_url,
use_async=use_async,
max_results_per_provider=max_results_per_provider,
include_providers=set(_.strip() for _ in include_providers.split(","))
include_providers={_.strip() for _ in include_providers.split(",")}
if include_providers
else None,
exclude_providers=set(_.strip() for _ in exclude_providers.split(","))
exclude_providers={_.strip() for _ in exclude_providers.split(",")}
if exclude_providers
else None,
exclude_databases=set(_.strip() for _ in exclude_databases.split(","))
exclude_databases={_.strip() for _ in exclude_databases.split(",")}
if exclude_databases
else None,
silent=silent,
Expand Down Expand Up @@ -211,13 +211,15 @@ def _get(

if not output_file:
if pretty_print:
rich.print_json(data=results, indent=2, default=lambda _: _.dict())
rich.print_json(data=results, indent=2, default=lambda _: _.asdict())
else:
sys.stdout.write(json.dumps(results, indent=2, default=lambda _: _.dict()))
sys.stdout.write(
json.dumps(results, indent=2, default=lambda _: _.asdict())
)

if output_file:
with open(output_file, "w") as f:
json.dump(results, f, indent=2, default=lambda _: _.dict())
json.dump(results, f, indent=2, default=lambda _: _.asdict())


if __name__ == "__main__":
Expand Down

0 comments on commit 791b932

Please sign in to comment.