Skip to content

Commit

Permalink
More fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
Randl committed Oct 4, 2022
1 parent 3f55240 commit 432cd4a
Show file tree
Hide file tree
Showing 16 changed files with 64 additions and 54 deletions.
4 changes: 2 additions & 2 deletions qiskit/algorithms/amplitude_amplifiers/amplitude_amplifier.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ def __init__(self) -> None:
self._top_measurement: str | None = None
self._assignment = None
self._oracle_evaluation: bool | None = None
self._circuit_results = None
self._max_probability = None
self._circuit_results: list[np.ndarray] | list[dict[str, int]] | None = None
self._max_probability: float | None = None

@property
def top_measurement(self) -> Optional[str]:
Expand Down
6 changes: 4 additions & 2 deletions qiskit/algorithms/amplitude_amplifiers/grover.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

import itertools
import operator
from typing import Iterator, List, Optional, Union
from typing import Iterator, List, Optional, Union, Mapping
import warnings

import numpy as np
Expand Down Expand Up @@ -156,7 +156,9 @@ def __init__(

if growth_rate is not None:
# yield iterations ** 1, iterations ** 2, etc. and casts to int
self._iterations = map(lambda x: int(growth_rate**x), itertools.count(1))
self._iterations: Optional[
Union[Mapping[int, float], List[int], Iterator[int], int]
] = map(lambda x: int(growth_rate**x), itertools.count(1))
elif isinstance(iterations, int):
self._iterations = [iterations]
else:
Expand Down
6 changes: 3 additions & 3 deletions qiskit/algorithms/amplitude_estimators/ae.py
Original file line number Diff line number Diff line change
Expand Up @@ -419,7 +419,7 @@ def estimate(self, estimation_problem: EstimationProblem) -> "AmplitudeEstimatio
# store the number of oracle queries
result.num_oracle_queries = result.shots * (self._M - 1)

# run the MLE post processing
# run the MLE post-processing
mle = self.compute_mle(result)
result.mle = mle
result.mle_processed = estimation_problem.post_processing(mle)
Expand Down Expand Up @@ -585,7 +585,7 @@ def integrand(x):

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

def _likelihood_ratio_confint(
result: AmplitudeEstimationResult, alpha: float
) -> Tuple[float, 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: 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
self._circuit_results: np.ndarray | dict[str, int] | None = None
self._shots: int | None = None
self._estimation: float | None = None
self._estimation_processed: float | None = None
self._num_oracle_queries: int | None = None
self._post_processing: Callable[[float], float] | None = None
self._confidence_interval: tuple[float, float] | None = None
self._confidence_interval_processed: tuple[float, float] | None = None

@property
def circuit_results(self) -> np.ndarray | dict[str, int] | None:
Expand Down
8 changes: 4 additions & 4 deletions qiskit/algorithms/amplitude_estimators/fae.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,10 +343,10 @@ class FasterAmplitudeEstimationResult(AmplitudeEstimatorResult):

def __init__(self) -> None:
super().__init__()
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
self._success_probability: int | None = None
self._num_steps: int | None = None
self._num_first_state_steps: int | None = None
self._theta_intervals: list[list[float]] | None = None

@property
def success_probability(self) -> int:
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: 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
self._alpha: float | None = None
self._epsilon_target: float | None = None
self._epsilon_estimated: float | None = None
self._epsilon_estimated_processed: float | None = None
self._estimate_intervals: list[list[float]] | None = None
self._theta_intervals: list[list[float]] | None = None
self._powers: list[int] | None = None
self._ratios: list[float] | None = None
self._confidence_interval_processed: tuple[float, float] | None = None

@property
def alpha(self) -> float:
Expand Down
12 changes: 7 additions & 5 deletions qiskit/algorithms/amplitude_estimators/mlae.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,7 +361,7 @@ def estimate(
except Exception as exc:
raise AlgorithmError("The job was not completed successfully. ") from exc

result.circuit_results = []
result.circuit_results: list[dict] = []
shots = ret.metadata[0].get("shots")
if shots is None:
for i, quasi_dist in enumerate(ret.quasi_dists):
Expand Down Expand Up @@ -416,7 +416,7 @@ class MaximumLikelihoodAmplitudeEstimationResult(AmplitudeEstimatorResult):
def __init__(self) -> None:
super().__init__()
self._theta: float | None = None
self._minimizer: callable | None = None
self._minimizer: typing.Callable | None = None
self._good_counts: list[float] | None = None
self._evaluation_schedule: list[int] | None = None
self._fisher_information: float | None = None
Expand All @@ -437,7 +437,7 @@ def minimizer(self) -> callable:
return self._minimizer

@minimizer.setter
def minimizer(self, value: callable) -> None:
def minimizer(self, value: typing.Callable) -> None:
"""Set the number minimizer used for the search of the likelihood function."""
self._minimizer = value

Expand Down Expand Up @@ -579,7 +579,7 @@ def _likelihood_ratio_confint(
result: MaximumLikelihoodAmplitudeEstimationResult,
alpha: float = 0.05,
nevals: int | None = None,
) -> typing.Tuple[float, float]:
) -> tuple[float, float]:
"""Compute the likelihood-ratio confidence interval.
Args:
Expand Down Expand Up @@ -640,7 +640,9 @@ 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: np.ndarray | list[float] = [] # 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
2 changes: 1 addition & 1 deletion qiskit/algorithms/aux_ops_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ def _prepare_result(
A list or a dictionary of tuples (mean, standard deviation).
"""
if isinstance(observables, list):
observables_eigenvalues = [None] * len(observables)
observables_eigenvalues: ListOrDict[Tuple[complex, complex]] = [None] * len(observables)
key_value_iterator = enumerate(observables_results)
else:
observables_eigenvalues = {}
Expand Down
4 changes: 3 additions & 1 deletion qiskit/algorithms/eigen_solvers/vqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -495,7 +495,9 @@ def _eval_aux_ops(
# None operators are already dropped in compute_minimum_eigenvalue if aux_operators is a
# dict.
if isinstance(aux_operators, list):
aux_operator_eigenvalues = [None] * len(aux_operators)
aux_operator_eigenvalues: ListOrDict[Tuple[complex, complex]] = [None] * len(
aux_operators
)
key_value_iterator = enumerate(aux_op_results)
else:
aux_operator_eigenvalues = {}
Expand Down
18 changes: 9 additions & 9 deletions qiskit/algorithms/eigensolvers/vqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,7 +205,7 @@ def compute_eigenvalues(
# Drop None and convert zero values when aux_operators is a dict.
if isinstance(aux_operators, list):
key_op_iterator = enumerate(aux_operators)
converted = [zero_op] * len(aux_operators)
converted: ListOrDict[BaseOperator | PauliSumOp] = [zero_op] * len(aux_operators)
else:
key_op_iterator = aux_operators.items()
converted = {}
Expand Down Expand Up @@ -410,13 +410,13 @@ class VQDResult(EigensolverResult):

def __init__(self) -> None:
super().__init__()
self._cost_function_evals = None
self._optimizer_times = None
self._optimal_values = None
self._optimal_points = None
self._optimal_parameters = None
self._optimizer_results = None
self._optimal_circuits = None
self._cost_function_evals: Sequence[int] | None = None
self._optimizer_times: Sequence[float] | None = None
self._optimal_values: Sequence[float] | None = None
self._optimal_points: Sequence[np.ndarray] | None = None
self._optimal_parameters: Sequence[dict] | None = None
self._optimizer_results: Sequence[OptimizerResult] | None = None
self._optimal_circuits: list[QuantumCircuit] | None = None

@property
def cost_function_evals(self) -> Sequence[int] | None:
Expand Down Expand Up @@ -479,7 +479,7 @@ def optimizer_results(self, value: Sequence[OptimizerResult]) -> None:
self._optimizer_results = value

@property
def optimal_circuits(self) -> list[QuantumCircuit]:
def optimal_circuits(self) -> list[QuantumCircuit] | None:
"""The optimal circuits. Along with the optimal parameters,
these can be used to retrieve the different eigenstates."""
return self._optimal_circuits
Expand Down
3 changes: 2 additions & 1 deletion qiskit/algorithms/gradients/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from collections import defaultdict
from copy import deepcopy
from dataclasses import dataclass
from typing import Sequence

import numpy as np

Expand Down Expand Up @@ -215,7 +216,7 @@ def _param_shift_preprocessing(circuit: QuantumCircuit) -> ParameterShiftGradien
def _make_param_shift_parameter_values(
gradient_circuit_data: ParameterShiftGradientCircuit,
base_parameter_values: list[np.ndarray],
parameter_values: np.ndarray,
parameter_values: Sequence[float],
param_set: set[Parameter],
) -> list[np.ndarray]:
"""Makes parameter values for the parameter shift method. Each parameter value will be added to
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/phase_estimators/phase_estimation_result.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ def filter_phases(self, cutoff: float = 0.0, as_float: bool = True) -> dict:
# But, we chose to apply the unitaries such that the phase is recorded
# in reverse order. So, we reverse the bitstrings here.
binary_phase_string = numpy.binary_repr(idx, self._num_evaluation_qubits)[::-1]
if as_float:
_key = _bit_string_to_phase(binary_phase_string)
if as_float: # TODO: should be not as_float?
_key: str | float = _bit_string_to_phase(binary_phase_string)
else:
_key = binary_phase_string
phases[_key] = amplitude
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def from_pauli_sum(
bound = sum(abs(coeff) for coeff in pauli_sum.coeffs)
return PhaseEstimationScale(bound)
elif isinstance(pauli_sum, Operator):
bound = np.sum(np.abs(np.eigvalsh(pauli_sum)))
bound = np.sum(np.abs(np.eigvalsh(pauli_sum))) # TODO: should be np.linalg.eigvalsh?
return PhaseEstimationScale(bound)
elif isinstance(pauli_sum, BaseOperator):
raise ValueError(
Expand Down
2 changes: 1 addition & 1 deletion qiskit/algorithms/time_evolvers/pvqd/pvqd.py
Original file line number Diff line number Diff line change
Expand Up @@ -368,7 +368,7 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult
)
observable_values = [evaluate_observables(self.initial_parameters)]

fidelities = [1]
fidelities = [1] # TODO: should be float?
parameters = [self.initial_parameters]
times = np.linspace(0, time, num_timesteps + 1).tolist() # +1 to include initial time 0

Expand Down
9 changes: 6 additions & 3 deletions qiskit/algorithms/utils/validate_bounds.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from qiskit.circuit import QuantumCircuit


def validate_bounds(circuit: QuantumCircuit) -> list[tuple(float | None, float | None)]:
def validate_bounds(circuit: QuantumCircuit) -> list[tuple[float | None, float | None]]:
"""
Validate the bounds provided by a quantum circuit against its number of parameters.
If no bounds are obtained, return ``None`` for all lower and upper bounds.
Expand All @@ -31,8 +31,11 @@ def validate_bounds(circuit: QuantumCircuit) -> list[tuple(float | None, float |
Raises:
ValueError: If the number of bounds does not the match the number of circuit parameters.
"""
if hasattr(circuit, "parameter_bounds") and circuit.parameter_bounds is not None:
bounds = circuit.parameter_bounds
if (
hasattr(circuit, "parameter_bounds")
and circuit.parameter_bounds is not None # type: ignore[attr-defined]
):
bounds = circuit.parameter_bounds # type: ignore[attr-defined]
if len(bounds) != circuit.num_parameters:
raise ValueError(
f"The number of bounds ({len(bounds)}) does not match the number of "
Expand Down
4 changes: 2 additions & 2 deletions qiskit/algorithms/variational_algorithm.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@ def __init__(self) -> None:
self._optimal_value: float | None = None
self._optimal_point: np.ndarray | None = None
self._optimal_parameters: Dict | None = None
self._optimizer_result = None
self._optimal_circuit = None
self._optimizer_result: OptimizerResult | None = None
self._optimal_circuit: QuantumCircuit | None = None

@property
def optimizer_evals(self) -> Optional[int]:
Expand Down

0 comments on commit 432cd4a

Please sign in to comment.