Skip to content

Commit

Permalink
Fix algorithms mypy errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Randl committed Oct 4, 2022
1 parent 86fb555 commit 3f55240
Show file tree
Hide file tree
Showing 34 changed files with 180 additions and 156 deletions.
13 changes: 8 additions & 5 deletions qiskit/algorithms/amplitude_amplifiers/amplification_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def __init__(
if is_good_state is not None:
self._is_good_state = is_good_state
elif hasattr(oracle, "evaluate_bitstring"):
self._is_good_state = oracle.evaluate_bitstring
self._is_good_state = oracle.evaluate_bitstring # type: ignore[union-attr]
else:
self._is_good_state = None

Expand Down Expand Up @@ -167,14 +167,17 @@ def is_good_state(self) -> Callable[[str], bool]:
return self._is_good_state # returns None if no is_good_state arg has been set
elif isinstance(self._is_good_state, list):
if all(isinstance(good_bitstr, str) for good_bitstr in self._is_good_state):
return lambda bitstr: bitstr in self._is_good_state
return lambda bitstr: bitstr in self._is_good_state # type:ignore[operator]
else:
return lambda bitstr: all(
bitstr[good_index] == "1" # type:ignore
for good_index in self._is_good_state
bitstr[good_index] == "1" # type:ignore[index]
for good_index in self._is_good_state # type:ignore[union-attr]
)

return lambda bitstr: bitstr in self._is_good_state.probabilities_dict()
return (
lambda bitstr: bitstr
in self._is_good_state.probabilities_dict() # type:ignore[union-attr]
)

@is_good_state.setter
def is_good_state(
Expand Down
5 changes: 3 additions & 2 deletions qiskit/algorithms/amplitude_amplifiers/amplitude_amplifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
# that they have been altered from the originals.

"""The interface for amplification algorithms and results."""
from __future__ import annotations

from abc import ABC, abstractmethod
from typing import Optional, Any, Union, Dict, List
Expand Down Expand Up @@ -43,9 +44,9 @@ class AmplitudeAmplifierResult(AlgorithmResult):

def __init__(self) -> None:
super().__init__()
self._top_measurement = None
self._top_measurement: str | None = None
self._assignment = None
self._oracle_evaluation = None
self._oracle_evaluation: bool | None = None
self._circuit_results = None
self._max_probability = None

Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/amplitude_amplifiers/grover.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,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:
warnings.warn(
"The quantum_instance argument has been superseded by the sampler argument. "
Expand Down Expand Up @@ -422,7 +422,7 @@ class GroverResult(AmplitudeAmplifierResult):

def __init__(self) -> None:
super().__init__()
self._iterations = None
self._iterations: list[int] | None = None

@property
def iterations(self) -> List[int]:
Expand Down
20 changes: 11 additions & 9 deletions qiskit/algorithms/amplitude_estimators/ae.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,13 +471,13 @@ class AmplitudeEstimationResult(AmplitudeEstimatorResult):

def __init__(self) -> None:
super().__init__()
self._num_evaluation_qubits = None
self._mle = None
self._mle_processed = None
self._samples = None
self._samples_processed = None
self._y_measurements = None
self._max_probability = None
self._num_evaluation_qubits: int | None = None
self._mle: float | None = None
self._mle_processed: float | None = None
self._samples: dict[float, float] | None = None
self._samples_processed: dict[float, float] | None = None
self._y_measurements: dict[int, float] | None = None
self._max_probability: float | None = None

@property
def num_evaluation_qubits(self) -> int:
Expand Down Expand Up @@ -585,7 +585,7 @@ def integrand(x):

def _fisher_confint(
result: AmplitudeEstimationResult, alpha: float, observed: bool = False
) -> list[float]:
) -> Tuple[float, float]:
"""Compute the Fisher information confidence interval for the MLE of the previous run.
Args:
Expand All @@ -605,7 +605,9 @@ def _fisher_confint(
return tuple(result.post_processing(bound) for bound in confint)


def _likelihood_ratio_confint(result: AmplitudeEstimationResult, alpha: float) -> list[float]:
def _likelihood_ratio_confint(
result: AmplitudeEstimationResult, alpha: float
) -> Tuple[float, float]:
"""Compute the likelihood ratio confidence interval for the MLE of the previous run.
Args:
Expand Down
16 changes: 8 additions & 8 deletions qiskit/algorithms/amplitude_estimators/amplitude_estimator.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,14 @@ class AmplitudeEstimatorResult(AlgorithmResult):

def __init__(self) -> None:
super().__init__()
self._circuit_results = None
self._shots = None
self._estimation = None
self._estimation_processed = None
self._num_oracle_queries = None
self._post_processing = None
self._confidence_interval = None
self._confidence_interval_processed = None
self._circuit_results: Optional[Union[np.ndarray, Dict[str, int]]] = None
self._shots: Optional[int] = None
self._estimation: Optional[float] = None
self._estimation_processed: Optional[float] = None
self._num_oracle_queries: Optional[int] = None
self._post_processing: Optional[Callable[[float], float]] = None
self._confidence_interval: Optional[Tuple[float, float]] = None
self._confidence_interval_processed: Optional[Tuple[float, float]] = None

@property
def circuit_results(self) -> np.ndarray | dict[str, int] | None:
Expand Down
11 changes: 6 additions & 5 deletions qiskit/algorithms/amplitude_estimators/fae.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ def cos_estimate(power, shots):
theta = np.mean(theta_ci)
rescaling = 4 if self._rescale else 1
value = (rescaling * np.sin(theta)) ** 2
value_ci = [(rescaling * np.sin(x)) ** 2 for x in theta_ci]
value_ci = [(rescaling * np.sin(x)) ** 2 for x in theta_ci] # TODO should be tuple?

result = FasterAmplitudeEstimationResult()
result.num_oracle_queries = self._num_oracle_calls
Expand Down Expand Up @@ -343,14 +343,15 @@ class FasterAmplitudeEstimationResult(AmplitudeEstimatorResult):

def __init__(self) -> None:
super().__init__()
self._success_probability = None
self._num_steps = None
self._num_first_state_steps = None
self._theta_intervals = None
self._success_probability: Optional[int] = None
self._num_steps: Optional[int] = None
self._num_first_state_steps: Optional[int] = None
self._theta_intervals: Optional[List[List[float]]] = None

@property
def success_probability(self) -> int:
"""Return the success probability of the algorithm."""
# TODO: should be float?
return self._success_probability

@success_probability.setter
Expand Down
18 changes: 9 additions & 9 deletions qiskit/algorithms/amplitude_estimators/iae.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,15 +536,15 @@ class IterativeAmplitudeEstimationResult(AmplitudeEstimatorResult):

def __init__(self) -> None:
super().__init__()
self._alpha = None
self._epsilon_target = None
self._epsilon_estimated = None
self._epsilon_estimated_processed = None
self._estimate_intervals = None
self._theta_intervals = None
self._powers = None
self._ratios = None
self._confidence_interval_processed = None
self._alpha: Optional[float] = None
self._epsilon_target: Optional[float] = None
self._epsilon_estimated: Optional[float] = None
self._epsilon_estimated_processed: Optional[float] = None
self._estimate_intervals: Optional[List[List[float]]] = None
self._theta_intervals: Optional[List[List[float]]] = None
self._powers: Optional[List[int]] = None
self._ratios: Optional[List[float]] = None
self._confidence_interval_processed: Optional[Tuple[float, float]] = None

@property
def alpha(self) -> float:
Expand Down
20 changes: 10 additions & 10 deletions qiskit/algorithms/amplitude_estimators/mlae.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,7 +240,7 @@ def compute_confidence_interval(
AlgorithmError: If `run()` hasn't been called yet.
NotImplementedError: If the method `kind` is not supported.
"""
interval = None
interval: typing.Tuple[float, float] | None = None

# if statevector simulator the estimate is exact
if all(isinstance(data, (list, np.ndarray)) for data in result.circuit_results):
Expand All @@ -265,7 +265,7 @@ def compute_confidence_interval(

def compute_mle(
self,
circuit_results: list[dict[str, int]] | list[np.ndarray],
circuit_results: list[dict[str, int] | np.ndarray],
estimation_problem: EstimationProblem,
num_state_qubits: int | None = None,
return_counts: bool = False,
Expand Down Expand Up @@ -415,11 +415,11 @@ class MaximumLikelihoodAmplitudeEstimationResult(AmplitudeEstimatorResult):

def __init__(self) -> None:
super().__init__()
self._theta = None
self._minimizer = None
self._good_counts = None
self._evaluation_schedule = None
self._fisher_information = None
self._theta: float | None = None
self._minimizer: callable | None = None
self._good_counts: list[float] | None = None
self._evaluation_schedule: list[int] | None = None
self._fisher_information: float | None = None

@property
def theta(self) -> float:
Expand Down Expand Up @@ -579,7 +579,7 @@ def _likelihood_ratio_confint(
result: MaximumLikelihoodAmplitudeEstimationResult,
alpha: float = 0.05,
nevals: int | None = None,
) -> list[float]:
) -> typing.Tuple[float, float]:
"""Compute the likelihood-ratio confidence interval.
Args:
Expand Down Expand Up @@ -627,7 +627,7 @@ def loglikelihood(theta, one_counts, all_counts):


def _get_counts(
circuit_results: list[np.ndarray | list[float], dict[str, int]],
circuit_results: typing.Sequence[np.ndarray | list[float] | dict[str, int]],
estimation_problem: EstimationProblem,
num_state_qubits: int,
) -> tuple[list[float], list[int]]:
Expand All @@ -640,7 +640,7 @@ def _get_counts(
AlgorithmError: If self.run() has not been called yet.
"""
one_hits = [] # h_k: how often 1 has been measured, for a power Q^(m_k)
all_hits = [] # shots_k: how often has been measured at a power Q^(m_k)
all_hits: np.ndarray | list[float] = [] # shots_k: how often has been measured at a power Q^(m_k)
if all(isinstance(data, (list, np.ndarray)) for data in circuit_results):
probabilities = []
num_qubits = int(np.log2(len(circuit_results[0]))) # the total number of qubits
Expand Down
6 changes: 3 additions & 3 deletions qiskit/algorithms/eigen_solvers/eigen_solver.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,9 +97,9 @@ class EigensolverResult(AlgorithmResult):
)
def __init__(self) -> None:
super().__init__()
self._eigenvalues = None
self._eigenstates = None
self._aux_operator_eigenvalues = None
self._eigenvalues: Optional[np.ndarray] = None
self._eigenstates: Optional[np.ndarray] = None
self._aux_operator_eigenvalues: Optional[List[ListOrDict[Tuple[complex, complex]]]] = None

@property
def eigenvalues(self) -> Optional[np.ndarray]:
Expand Down
17 changes: 10 additions & 7 deletions qiskit/algorithms/eigen_solvers/vqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,27 +175,27 @@ def __init__(

# set ansatz -- still supporting pre 0.18.0 sorting

self._ansatz = None
self._ansatz: Optional[QuantumCircuit] = None
self.ansatz = ansatz

self.k = k
self.betas = betas

self._optimizer = None
self._optimizer: Optional[Optimizer] = None
self.optimizer = optimizer

self._initial_point = None
self._initial_point: Optional[np.ndarray] = None
self.initial_point = initial_point
self._gradient = None
self._gradient: Optional[Union[GradientBase, Callable]] = None
self.gradient = gradient
self._quantum_instance = None
self._quantum_instance: Optional[QuantumInstance] = None

if quantum_instance is not None:
self.quantum_instance = quantum_instance

self._eval_time = None
self._eval_count = 0
self._callback = None
self._callback: Optional[Callable[[int, np.ndarray, float, float], None]] = None
self.callback = callback

logger.info(self.print_settings())
Expand Down Expand Up @@ -663,7 +663,10 @@ def get_energy_evaluation(
operator: OperatorBase,
return_expectation: bool = False,
prev_states: Optional[List[np.ndarray]] = None,
) -> Callable[[np.ndarray], Union[float, List[float]]]:
) -> Union[
Callable[[np.ndarray], Union[float, List[float]]],
Tuple[Callable[[np.ndarray], Union[float, List[float]]], ExpectationBase],
]:
"""Returns a function handle to evaluates the energy at given parameters for the ansatz.
This return value is the objective function to be passed to the optimizer for evaluation.
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/evolvers/evolution_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@

"""Evolution problem class."""

from typing import Union, Optional, Dict
from typing import Union, Optional, Dict, Set

from qiskit import QuantumCircuit
from qiskit.circuit import Parameter
Expand Down Expand Up @@ -107,7 +107,7 @@ def validate_params(self) -> None:
t_param_set = set()
if self.t_param is not None:
t_param_set.add(self.t_param)
hamiltonian_dict_param_set = set()
hamiltonian_dict_param_set: Set[Parameter] = set()
if self.param_value_dict is not None:
hamiltonian_dict_param_set = hamiltonian_dict_param_set.union(
set(self.param_value_dict.keys())
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/factorizers/shor.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ def __init__(self, quantum_instance: Optional[Union[QuantumInstance, Backend]] =
quantum_instance: Quantum Instance or Backend
"""
self._quantum_instance = None
self._quantum_instance: Optional[QuantumInstance] = None
if quantum_instance:
self.quantum_instance = quantum_instance

Expand Down Expand Up @@ -496,7 +496,7 @@ class ShorResult(AlgorithmResult):

def __init__(self) -> None:
super().__init__()
self._factors = []
self._factors: Optional[List[List[int]]] = []
self._total_counts = 0
self._successful_counts = 0

Expand Down
13 changes: 8 additions & 5 deletions qiskit/algorithms/linear_solvers/hhl.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,14 +386,14 @@ def construct_circuit(

# Set the tolerance for the matrix approximation
if hasattr(matrix_circuit, "tolerance"):
matrix_circuit.tolerance = self._epsilon_a
matrix_circuit.tolerance = self._epsilon_a # type: ignore[attr-defined]

# check if the matrix can calculate the condition number and store the upper bound
if (
hasattr(matrix_circuit, "condition_bounds")
and matrix_circuit.condition_bounds() is not None
and matrix_circuit.condition_bounds() is not None # type: ignore[attr-defined]
):
kappa = matrix_circuit.condition_bounds()[1]
kappa = matrix_circuit.condition_bounds()[1] # type: ignore[attr-defined]
else:
kappa = 1
# Update the number of qubits required to represent the eigenvalues
Expand All @@ -402,8 +402,11 @@ def construct_circuit(
nl = max(nb + 1, int(np.ceil(np.log2(kappa + 1)))) + neg_vals

# check if the matrix can calculate bounds for the eigenvalues
if hasattr(matrix_circuit, "eigs_bounds") and matrix_circuit.eigs_bounds() is not None:
lambda_min, lambda_max = matrix_circuit.eigs_bounds()
if (
hasattr(matrix_circuit, "eigs_bounds")
and matrix_circuit.eigs_bounds() is not None # type: ignore[attr-defined]
):
lambda_min, lambda_max = matrix_circuit.eigs_bounds() # type: ignore[attr-defined]
# Constant so that the minimum eigenvalue is represented exactly, since it contributes
# the most to the solution of the system. -1 to take into account the sign qubit
delta = self._get_delta(nl - neg_vals, lambda_min, lambda_max)
Expand Down
Loading

0 comments on commit 3f55240

Please sign in to comment.