Skip to content

Commit

Permalink
refactor: update type hints
Browse files Browse the repository at this point in the history
  • Loading branch information
mrossinek committed Feb 10, 2022
1 parent ed23adf commit b7db61f
Show file tree
Hide file tree
Showing 15 changed files with 66 additions and 66 deletions.
4 changes: 2 additions & 2 deletions qiskit_nature/properties/grouped_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from __future__ import annotations

from collections.abc import Iterable
from typing import Dict, Generator, Generic, Optional, Type, TypeVar, Union
from typing import Generator, Generic, Optional, Type, TypeVar, Union

import h5py

Expand Down Expand Up @@ -48,7 +48,7 @@ def __init__(self, name: str) -> None:
name: the name of the property group.
"""
super().__init__(name)
self._properties: Dict[str, T] = {}
self._properties: dict[str, T] = {}

def __str__(self) -> str:
string = [super().__str__() + ":"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from __future__ import annotations

import logging
from typing import cast, List, Optional, Tuple
from typing import cast, Optional

import itertools

Expand Down Expand Up @@ -236,19 +236,19 @@ def interpret(self, result: EigenstateResult) -> None:
result.total_angular_momentum.append(None)


def _calc_s_x_squared_ints(num_modes: int) -> Tuple[np.ndarray, np.ndarray]:
def _calc_s_x_squared_ints(num_modes: int) -> tuple[np.ndarray, np.ndarray]:
return _calc_squared_ints(num_modes, _modify_s_x_squared_ints_neq, _modify_s_x_squared_ints_eq)


def _calc_s_y_squared_ints(num_modes: int) -> Tuple[np.ndarray, np.ndarray]:
def _calc_s_y_squared_ints(num_modes: int) -> tuple[np.ndarray, np.ndarray]:
return _calc_squared_ints(num_modes, _modify_s_y_squared_ints_neq, _modify_s_y_squared_ints_eq)


def _calc_s_z_squared_ints(num_modes: int) -> Tuple[np.ndarray, np.ndarray]:
def _calc_s_z_squared_ints(num_modes: int) -> tuple[np.ndarray, np.ndarray]:
return _calc_squared_ints(num_modes, _modify_s_z_squared_ints_neq, _modify_s_z_squared_ints_eq)


def _calc_squared_ints(num_modes: int, func_neq, func_eq) -> Tuple[np.ndarray, np.ndarray]:
def _calc_squared_ints(num_modes: int, func_neq, func_eq) -> tuple[np.ndarray, np.ndarray]:
# calculates 1- and 2-body integrals for a given angular momentum axis (x or y or z,
# specified by func_neq and func_eq)
num_modes_2 = num_modes // 2
Expand Down Expand Up @@ -356,7 +356,7 @@ def _modify_s_z_squared_ints_eq(h_2: np.ndarray, p_ind: int, num_modes_2: int) -


def _add_values_to_s_squared_ints(
h_2: np.ndarray, indices: List[Tuple[int, int, int, int]], values: List[int]
h_2: np.ndarray, indices: list[tuple[int, int, int, int]], values: list[int]
) -> np.ndarray:
for index, value in zip(indices, values):
h_2[index] += value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

from typing import List, Optional
from typing import Optional

import h5py

Expand Down Expand Up @@ -97,6 +97,6 @@ def from_hdf5(h5py_group: h5py.Group) -> ElectronicBasisTransform:
)

@staticmethod
def _render_coefficients(coeffs) -> List[str]:
def _render_coefficients(coeffs) -> list[str]:
nonzero = coeffs.nonzero()
return [f"\t{indices} = {value}" for value, *indices in zip(coeffs[nonzero], *nonzero)]
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

from typing import Dict, List, Optional, Tuple, cast
from typing import Optional, cast

import h5py

Expand All @@ -33,7 +33,7 @@
# components. However when using Z2Symmetries, if the dipole component operator does not commute
# with the symmetry then no evaluation is done and None will be used as the 'value' indicating no
# measurement of the observable took place
DipoleTuple = Tuple[Optional[float], Optional[float], Optional[float]]
DipoleTuple = tuple[Optional[float], Optional[float], Optional[float]]


class DipoleMoment(IntegralProperty):
Expand All @@ -45,8 +45,8 @@ class DipoleMoment(IntegralProperty):
def __init__(
self,
axis: str,
electronic_integrals: List[ElectronicIntegrals],
shift: Optional[Dict[str, complex]] = None,
electronic_integrals: list[ElectronicIntegrals],
shift: Optional[dict[str, complex]] = None,
) -> None:
"""
Args:
Expand Down Expand Up @@ -143,8 +143,8 @@ class ElectronicDipoleMoment(GroupedProperty[DipoleMoment], ElectronicProperty):

def __init__(
self,
dipole_axes: Optional[List[DipoleMoment]] = None,
dipole_shift: Optional[Dict[str, DipoleTuple]] = None,
dipole_axes: Optional[list[DipoleMoment]] = None,
dipole_shift: Optional[dict[str, DipoleTuple]] = None,
nuclear_dipole_moment: Optional[DipoleTuple] = None,
reverse_dipole_sign: bool = False,
) -> None:
Expand Down Expand Up @@ -347,7 +347,7 @@ def interpret(self, result: EigenstateResult) -> None:
axes_order = {"x": 0, "y": 1, "z": 2}
dipole_moment = [None] * 3
for prop in iter(self):
moment: Optional[Tuple[complex, complex]]
moment: Optional[tuple[complex, complex]]
try:
moment = aux_op_eigenvalues[axes_order[prop._axis] + 3]
except KeyError:
Expand All @@ -356,7 +356,7 @@ def interpret(self, result: EigenstateResult) -> None:
dipole_moment[axes_order[prop._axis]] = moment[0].real # type: ignore

result.computed_dipole_moment.append(cast(DipoleTuple, tuple(dipole_moment)))
dipole_shifts: Dict[str, Dict[str, complex]] = {}
dipole_shifts: dict[str, dict[str, complex]] = {}
for prop in self._properties.values():
for name, shift in prop._shift.items():
if name not in dipole_shifts:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

from typing import Dict, List, Optional, cast
from typing import Optional, cast

import h5py
import numpy as np
Expand Down Expand Up @@ -47,8 +47,8 @@ class ElectronicEnergy(IntegralProperty):

def __init__(
self,
electronic_integrals: List[ElectronicIntegrals],
energy_shift: Optional[Dict[str, complex]] = None,
electronic_integrals: list[ElectronicIntegrals],
energy_shift: Optional[dict[str, complex]] = None,
nuclear_repulsion_energy: Optional[float] = None,
reference_energy: Optional[float] = None,
) -> None:
Expand Down Expand Up @@ -203,7 +203,7 @@ def from_legacy_driver_result(cls, result: LegacyDriverResult) -> ElectronicEner

energy_shift = qmol.energy_shift.copy()

integrals: List[ElectronicIntegrals] = []
integrals: list[ElectronicIntegrals] = []
if qmol.hcore is not None:
integrals.append(
OneBodyElectronicIntegrals(ElectronicBasis.AO, (qmol.hcore, qmol.hcore_b))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

from typing import List, Tuple, cast
from typing import cast

import h5py

Expand Down Expand Up @@ -123,7 +123,7 @@ def from_legacy_driver_result(
)
)

geometry: List[Tuple[str, List[float]]] = []
geometry: list[tuple[str, list[float]]] = []
for atom, xyz in zip(qmol.atom_symbol, qmol.atom_xyz):
# QMolecule XYZ defaults to Bohr but Molecule requires Angstrom
geometry.append((atom, xyz * BOHR))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
import itertools
from abc import ABC, abstractmethod
from copy import deepcopy
from typing import Generator, List, Optional, Tuple, Union
from typing import Generator, Optional, Union

import h5py
import numpy as np
Expand Down Expand Up @@ -49,15 +49,15 @@ class ElectronicIntegrals(ABC):

INTEGRAL_TRUNCATION_LEVEL = 1e-12

_MATRIX_REPRESENTATIONS: List[str] = []
_MATRIX_REPRESENTATIONS: list[str] = []

_truncate = 5

def __init__(
self,
num_body_terms: int,
basis: ElectronicBasis,
matrices: Union[np.ndarray, Tuple[Optional[np.ndarray], ...]],
matrices: Union[np.ndarray, tuple[Optional[np.ndarray], ...]],
threshold: float = INTEGRAL_TRUNCATION_LEVEL,
) -> None:
# pylint: disable=line-too-long
Expand Down Expand Up @@ -87,7 +87,7 @@ def __init__(
self._basis = basis
self._num_body_terms = num_body_terms
self._threshold = threshold
self._matrices: Union[np.ndarray, Tuple[Optional[np.ndarray], ...]]
self._matrices: Union[np.ndarray, tuple[Optional[np.ndarray], ...]]
if basis == ElectronicBasis.SO:
self._matrices = np.where(np.abs(matrices) > self._threshold, matrices, 0.0)
else:
Expand Down Expand Up @@ -194,7 +194,7 @@ def __str__(self) -> str:
return "\n".join(string)

@staticmethod
def _render_matrix_as_sparse_list(matrix) -> List[str]:
def _render_matrix_as_sparse_list(matrix) -> list[str]:
string = []
nonzero = matrix.nonzero()
nonzero_count = len(nonzero[0])
Expand Down Expand Up @@ -240,7 +240,7 @@ def _validate_num_body_terms(num_body_terms: int) -> None:

@staticmethod
def _validate_matrices(
matrices: Union[np.ndarray, Tuple[Optional[np.ndarray], ...]],
matrices: Union[np.ndarray, tuple[Optional[np.ndarray], ...]],
basis: ElectronicBasis,
num_body_terms: int,
) -> None:
Expand Down Expand Up @@ -333,7 +333,7 @@ def to_second_q_op(self) -> FermionicOp:
if spin_matrix[indices]
)

def _create_base_op(self, indices: Tuple[int, ...], coeff: complex, length: int) -> FermionicOp:
def _create_base_op(self, indices: tuple[int, ...], coeff: complex, length: int) -> FermionicOp:
"""Creates a single base operator for the given coefficient.
Args:
Expand All @@ -350,7 +350,7 @@ def _create_base_op(self, indices: Tuple[int, ...], coeff: complex, length: int)
return base_op

@abstractmethod
def _calc_coeffs_with_ops(self, indices: Tuple[int, ...]) -> List[Tuple[int, str]]:
def _calc_coeffs_with_ops(self, indices: tuple[int, ...]) -> list[tuple[int, str]]:
"""Maps indices to creation/annihilation operator symbols.
Args:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

from typing import Dict, Generator, List, Optional
from typing import Generator, Optional

import h5py

Expand Down Expand Up @@ -43,8 +43,8 @@ class IntegralProperty(ElectronicProperty):
def __init__(
self,
name: str,
electronic_integrals: List[ElectronicIntegrals],
shift: Optional[Dict[str, complex]] = None,
electronic_integrals: list[ElectronicIntegrals],
shift: Optional[dict[str, complex]] = None,
) -> None:
# pylint: disable=line-too-long
"""
Expand All @@ -55,7 +55,7 @@ def __init__(
shift: an optional dictionary of value shifts.
"""
super().__init__(name)
self._electronic_integrals: Dict[ElectronicBasis, Dict[int, ElectronicIntegrals]] = {}
self._electronic_integrals: dict[ElectronicBasis, dict[int, ElectronicIntegrals]] = {}
for integral in electronic_integrals:
self.add_electronic_integral(integral)
self._shift = shift or {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

from typing import List, Optional, Tuple, Union
from typing import Optional, Union

import numpy as np

Expand All @@ -32,7 +32,7 @@ class OneBodyElectronicIntegrals(ElectronicIntegrals):
def __init__(
self,
basis: ElectronicBasis,
matrices: Union[np.ndarray, Tuple[Optional[np.ndarray], ...]],
matrices: Union[np.ndarray, tuple[Optional[np.ndarray], ...]],
threshold: float = ElectronicIntegrals.INTEGRAL_TRUNCATION_LEVEL,
) -> None:
# pylint: disable=line-too-long
Expand Down Expand Up @@ -108,7 +108,7 @@ def to_spin(self) -> np.ndarray:

return np.where(np.abs(so_matrix) > self._threshold, so_matrix, 0.0)

def _calc_coeffs_with_ops(self, indices: Tuple[int, ...]) -> List[Tuple[int, str]]:
def _calc_coeffs_with_ops(self, indices: tuple[int, ...]) -> list[tuple[int, str]]:
return [(indices[0], "+"), (indices[1], "-")]

def compose(self, other: ElectronicIntegrals, einsum_subscript: str = "ij,ji") -> complex:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

from __future__ import annotations

from typing import List, Optional, Tuple, Union
from typing import Optional, Union

import numpy as np

Expand All @@ -38,7 +38,7 @@ class TwoBodyElectronicIntegrals(ElectronicIntegrals):
def __init__(
self,
basis: ElectronicBasis,
matrices: Union[np.ndarray, Tuple[Optional[np.ndarray], ...]],
matrices: Union[np.ndarray, tuple[Optional[np.ndarray], ...]],
threshold: float = ElectronicIntegrals.INTEGRAL_TRUNCATION_LEVEL,
) -> None:
# pylint: disable=line-too-long
Expand Down Expand Up @@ -122,7 +122,7 @@ def transform_basis(self, transform: ElectronicBasisTransform) -> TwoBodyElectro
(coeff_beta, coeff_beta, coeff_beta, coeff_beta),
(coeff_alpha, coeff_alpha, coeff_beta, coeff_beta),
]
matrices: List[Optional[np.ndarray]] = []
matrices: list[Optional[np.ndarray]] = []
for mat, coeffs in zip(self._matrices, coeff_list):
if mat is None:
matrices.append(None)
Expand Down Expand Up @@ -163,7 +163,7 @@ def to_spin(self) -> np.ndarray:

return np.where(np.abs(so_matrix) > self._threshold, so_matrix, 0.0)

def _calc_coeffs_with_ops(self, indices: Tuple[int, ...]) -> List[Tuple[int, str]]:
def _calc_coeffs_with_ops(self, indices: tuple[int, ...]) -> list[tuple[int, str]]:
return [(indices[0], "+"), (indices[2], "+"), (indices[3], "-"), (indices[1], "-")]

def compose(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from __future__ import annotations

import logging
from typing import List, Optional, Tuple, Union, cast
from typing import Optional, Union, cast

import h5py
import numpy as np
Expand Down Expand Up @@ -47,9 +47,9 @@ class ParticleNumber(ElectronicProperty):
def __init__(
self,
num_spin_orbitals: int,
num_particles: Union[int, Tuple[int, int]],
occupation: Optional[Union[np.ndarray, List[float]]] = None,
occupation_beta: Optional[Union[np.ndarray, List[float]]] = None,
num_particles: Union[int, tuple[int, int]],
occupation: Optional[Union[np.ndarray, list[float]]] = None,
occupation_beta: Optional[Union[np.ndarray, list[float]]] = None,
absolute_tolerance: float = ABSOLUTE_TOLERANCE,
relative_tolerance: float = RELATIVE_TOLERANCE,
) -> None:
Expand Down Expand Up @@ -123,7 +123,7 @@ def num_beta(self, num_beta: int) -> None:
self._num_beta = num_beta

@property
def num_particles(self) -> Tuple[int, int]:
def num_particles(self) -> tuple[int, int]:
"""Returns the number of electrons."""
return (self.num_alpha, self.num_beta)

Expand All @@ -137,7 +137,7 @@ def occupation_alpha(self) -> np.ndarray:
return np.asarray(self._occupation_alpha)

@occupation_alpha.setter
def occupation_alpha(self, occ_alpha: Union[np.ndarray, List[float]]) -> None:
def occupation_alpha(self, occ_alpha: Union[np.ndarray, list[float]]) -> None:
"""Sets the occupation numbers of the alpha-spin orbitals."""
self._occupation_alpha = occ_alpha

Expand All @@ -151,7 +151,7 @@ def occupation_beta(self) -> np.ndarray:
return np.asarray(self._occupation_beta)

@occupation_beta.setter
def occupation_beta(self, occ_beta: Union[np.ndarray, List[float]]) -> None:
def occupation_beta(self, occ_beta: Union[np.ndarray, list[float]]) -> None:
"""Sets the occupation numbers of the beta-spin orbitals."""
self._occupation_beta = occ_beta

Expand Down
Loading

0 comments on commit b7db61f

Please sign in to comment.