-
Notifications
You must be signed in to change notification settings - Fork 2.4k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix mypy errors (algorithms) #8271
Changes from all commits
b73e91f
7daea48
ac790d9
90a5b15
42526bc
9c320dd
aa3320c
b88d0a4
c0cedca
fd12c02
3ef070e
9d0ef53
eeb99f8
2fcc6da
460e2bd
973268b
2b0fd55
cf3d04c
d94e228
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,19 +11,21 @@ | |
# that they have been altered from the originals. | ||
|
||
"""Grover's search algorithm.""" | ||
from __future__ import annotations | ||
|
||
import itertools | ||
import operator | ||
import warnings | ||
from typing import Iterator, List, Optional, Union | ||
from collections.abc import Iterator, Generator | ||
from typing import Any | ||
|
||
import numpy as np | ||
|
||
from qiskit import ClassicalRegister, QuantumCircuit | ||
from qiskit.algorithms.exceptions import AlgorithmError | ||
from qiskit.primitives import BaseSampler | ||
from qiskit.providers import Backend | ||
from qiskit.quantum_info import partial_trace | ||
from qiskit.quantum_info import partial_trace, Statevector | ||
from qiskit.utils import QuantumInstance, algorithm_globals | ||
from qiskit.utils.deprecation import deprecate_arg, deprecate_func | ||
|
||
|
@@ -120,11 +122,11 @@ class Grover(AmplitudeAmplifier): | |
) | ||
def __init__( | ||
self, | ||
iterations: Optional[Union[List[int], Iterator[int], int]] = None, | ||
growth_rate: Optional[float] = None, | ||
iterations: list[int] | Iterator[int] | int | None = None, | ||
growth_rate: float | None = None, | ||
sample_from_iterations: bool = False, | ||
quantum_instance: Optional[Union[QuantumInstance, Backend]] = None, | ||
sampler: Optional[BaseSampler] = None, | ||
quantum_instance: QuantumInstance | Backend | None = None, | ||
sampler: BaseSampler | None = None, | ||
) -> None: | ||
r""" | ||
Args: | ||
|
@@ -163,7 +165,9 @@ def __init__( | |
|
||
if growth_rate is not None: | ||
# yield iterations ** 1, iterations ** 2, etc. and casts to int | ||
self._iterations = (int(growth_rate**x) for x in itertools.count(1)) | ||
self._iterations: Generator[int, None, None] | list[int] = ( | ||
int(growth_rate**x) for x in itertools.count(1) | ||
) | ||
elif isinstance(iterations, int): | ||
self._iterations = [iterations] | ||
else: | ||
|
@@ -178,7 +182,7 @@ def __init__( | |
sampler = quantum_instance | ||
quantum_instance = None | ||
|
||
self._quantum_instance = None | ||
self._quantum_instance: QuantumInstance | None = None | ||
if quantum_instance is not None: | ||
with warnings.catch_warnings(): | ||
warnings.simplefilter("ignore", category=PendingDeprecationWarning) | ||
|
@@ -191,7 +195,7 @@ def __init__( | |
|
||
@property | ||
@deprecate_func(since="0.23.0", pending=True, is_property=True) | ||
def quantum_instance(self) -> Optional[QuantumInstance]: | ||
def quantum_instance(self) -> QuantumInstance | None: | ||
r"""Pending deprecation\; Get the quantum instance. | ||
|
||
Returns: | ||
|
@@ -201,7 +205,7 @@ def quantum_instance(self) -> Optional[QuantumInstance]: | |
|
||
@quantum_instance.setter | ||
@deprecate_func(since="0.23.0", pending=True, is_property=True) | ||
def quantum_instance(self, quantum_instance: Union[QuantumInstance, Backend]) -> None: | ||
def quantum_instance(self, quantum_instance: QuantumInstance | Backend) -> None: | ||
r"""Pending deprecation\; Set quantum instance. | ||
|
||
Args: | ||
|
@@ -212,7 +216,7 @@ def quantum_instance(self, quantum_instance: Union[QuantumInstance, Backend]) -> | |
self._quantum_instance = quantum_instance | ||
|
||
@property | ||
def sampler(self) -> Optional[BaseSampler]: | ||
def sampler(self) -> BaseSampler | None: | ||
"""Get the sampler. | ||
|
||
Returns: | ||
|
@@ -254,7 +258,7 @@ def amplify(self, amplification_problem: AmplificationProblem) -> "GroverResult" | |
if isinstance(self._iterations, list): | ||
max_iterations = len(self._iterations) | ||
max_power = np.inf # no cap on the power | ||
iterator = iter(self._iterations) | ||
iterator: Iterator[int] = iter(self._iterations) | ||
else: | ||
max_iterations = max(10, 2**amplification_problem.oracle.num_qubits) | ||
max_power = np.ceil( | ||
|
@@ -282,7 +286,7 @@ def amplify(self, amplification_problem: AmplificationProblem) -> "GroverResult" | |
|
||
# sample from [0, power) if specified | ||
if self._sample_from_iterations: | ||
power = algorithm_globals.random.randint(power) | ||
power = algorithm_globals.random.integers(power) | ||
# Run a grover experiment for a given power of the Grover operator. | ||
if self._sampler is not None: | ||
qc = self.construct_circuit(amplification_problem, power, measurement=True) | ||
|
@@ -294,7 +298,7 @@ def amplify(self, amplification_problem: AmplificationProblem) -> "GroverResult" | |
raise AlgorithmError("Sampler job failed.") from exc | ||
|
||
num_bits = len(amplification_problem.objective_qubits) | ||
circuit_results = { | ||
circuit_results: dict[str, Any] | Statevector | np.ndarray = { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is just FYI, the quantum instance is deprecated and will be removed in following qiskit releases. Once the quantum instance is removed, I believe that the |
||
np.binary_repr(k, num_bits): v for k, v in results.quasi_dists[0].items() | ||
} | ||
top_measurement, max_probability = max(circuit_results.items(), key=lambda x: x[1]) | ||
|
@@ -373,7 +377,7 @@ def optimal_num_iterations(num_solutions: int, num_qubits: int) -> int: | |
return round(np.arccos(amplitude) / (2 * np.arcsin(amplitude))) | ||
|
||
def construct_circuit( | ||
self, problem: AmplificationProblem, power: Optional[int] = None, measurement: bool = False | ||
self, problem: AmplificationProblem, power: int | None = None, measurement: bool = False | ||
) -> QuantumCircuit: | ||
"""Construct the circuit for Grover's algorithm with ``power`` Grover operators. | ||
|
||
|
@@ -412,10 +416,10 @@ class GroverResult(AmplitudeAmplifierResult): | |
|
||
def __init__(self) -> None: | ||
super().__init__() | ||
self._iterations = None | ||
self._iterations: list[int] | None = None | ||
|
||
@property | ||
def iterations(self) -> List[int]: | ||
def iterations(self) -> list[int]: | ||
"""All the powers of the Grover operator that have been tried. | ||
|
||
Returns: | ||
|
@@ -424,7 +428,7 @@ def iterations(self) -> List[int]: | |
return self._iterations | ||
|
||
@iterations.setter | ||
def iterations(self, value: List[int]) -> None: | ||
def iterations(self, value: list[int]) -> None: | ||
"""Set the powers of the Grover operator that have been tried. | ||
|
||
Args: | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This annotation is duplicated in the return of
circuit_results
method. You should make a type aliasCircuitResultsT = list[np.ndarray] | list[dict[str, int]] | None
. And I think you have to useOptional
andUnion
for the type alias declaration. Because it is not supported yet until Python 3.10.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actually, you should exclude the
| None
in theCircuitResultsT
declaration, because thecircuit_results
setter doesn't expectNone
.