diff --git a/qiskit/algorithms/amplitude_amplifiers/amplification_problem.py b/qiskit/algorithms/amplitude_amplifiers/amplification_problem.py index e8e7da676c2d..8259ad130e67 100644 --- a/qiskit/algorithms/amplitude_amplifiers/amplification_problem.py +++ b/qiskit/algorithms/amplitude_amplifiers/amplification_problem.py @@ -50,74 +50,18 @@ def __init__(self, applied on the measurement outcome of these qubits. is_good_state: A function to check whether a string represents a good state. """ - self._oracle = oracle - self._state_preparation = state_preparation - self._grover_operator = grover_operator - self._post_processing = post_processing - self._objective_qubits = objective_qubits - self._is_good_state = is_good_state - - @property - def oracle(self) -> Union[QuantumCircuit, Statevector]: - """Return the oracle. - - Returns: - The oracle. - """ - return self._oracle - - @oracle.setter - def oracle(self, oracle: Union[QuantumCircuit, Statevector]) -> None: - """Set the oracle. - - Args: - oracle: The oracle. - """ - self._oracle = oracle - - @property - def state_preparation(self) -> QuantumCircuit: - r"""Get the state preparation operator :math:`\mathcal{A}`. - - Returns: - The :math:`\mathcal{A}` operator as `QuantumCircuit`. - """ - if self._state_preparation is None: - state_preparation = QuantumCircuit(self.oracle.num_qubits) - state_preparation.h(state_preparation.qubits) - return state_preparation - - return self._state_preparation - - @state_preparation.setter - def state_preparation(self, state_preparation: Optional[QuantumCircuit]) -> None: - r"""Set the :math:`\mathcal{A}` operator. If None, a layer of Hadamard gates is used. - - Args: - state_preparation: The new :math:`\mathcal{A}` operator or None. - """ - self._state_preparation = state_preparation + self.oracle = oracle - @property - def post_processing(self) -> Callable[[str], Any]: - """Apply post processing to the input value. - - Returns: - A handle to the post processing function. Acts as identity by default. - """ - if self._post_processing is None: - return lambda x: x - - return self._post_processing - - @post_processing.setter - def post_processing(self, post_processing: Callable[[str], Any]) -> None: - """Set the post processing function. + if state_preparation: + self.state_preparation = state_preparation + else: + self.state_preparation = QuantumCircuit(oracle.num_qubits) + self.state_preparation.h(range(oracle.num_qubits)) - Args: - post_processing: A handle to the post processing function. - """ - self._post_processing = post_processing + self.grover_operator = grover_operator or GroverOperator(oracle, self.state_preparation) + self.post_processing = post_processing or (lambda x: x) + self._objective_qubits = objective_qubits + self._is_good_state = is_good_state @property def objective_qubits(self) -> List[int]: @@ -174,29 +118,3 @@ def is_good_state(self, is_good_state: A function to determine whether a bitstring represents a good state. """ self._is_good_state = is_good_state - - @property - def grover_operator(self) -> Optional[QuantumCircuit]: - r"""Get the :math:`\mathcal{Q}` operator, or Grover operator. - - If the Grover operator is not set, we try to build it from the :math:`\mathcal{A}` operator - and `objective_qubits`. This only works if `objective_qubits` is a list of integers. - - Returns: - The Grover operator, or None if neither the Grover operator nor the - :math:`\mathcal{A}` operator is set. - """ - if self._grover_operator is None: - return GroverOperator(self.oracle, self.state_preparation) - return self._grover_operator - - @grover_operator.setter - def grover_operator(self, grover_operator: Optional[QuantumCircuit]) -> None: - r"""Set the :math:`\mathcal{Q}` operator. - - If None, this operator is constructed from the ``oracle`` and ``state_preparation``. - - Args: - grover_operator: The new :math:`\mathcal{Q}` operator or None. - """ - self._grover_operator = grover_operator diff --git a/qiskit/algorithms/amplitude_amplifiers/amplitude_amplifier.py b/qiskit/algorithms/amplitude_amplifiers/amplitude_amplifier.py index 0e228e342469..290a20e1231f 100644 --- a/qiskit/algorithms/amplitude_amplifiers/amplitude_amplifier.py +++ b/qiskit/algorithms/amplitude_amplifiers/amplitude_amplifier.py @@ -13,9 +13,6 @@ """The interface for amplification algorithms and results.""" from abc import ABC, abstractmethod -from typing import Optional, Any, Union, Dict, List - -import numpy as np from .amplification_problem import AmplificationProblem from ..algorithm_result import AlgorithmResult @@ -43,82 +40,6 @@ class AmplitudeAmplifierResult(AlgorithmResult): def __init__(self) -> None: super().__init__() - self._top_measurement = None - self._assignment = None - self._oracle_evaluation = None - - @property - def top_measurement(self) -> Optional[str]: - """The most frequently measured output as bitstring. - - Returns: - The most frequently measured output state. - """ - return self._top_measurement - - @top_measurement.setter - def top_measurement(self, value: str) -> None: - """Set the most frequently measured bitstring. - - Args: - value: A new value for the top measurement. - """ - self._top_measurement = value - - @property - def assignment(self) -> Any: - """The post-processed value of the most likely bitstring. - - Returns: - The output of the ``post_processing`` function of the respective - ``AmplificationProblem``, where the input is the ``top_measurement``. The type - is the same as the return type of the post-processing function. - """ - return self._assignment - - @assignment.setter - def assignment(self, value: Any) -> None: - """Set the value for the assignment. - - Args: - value: A new value for the assignment/solution. - """ - self._assignment = value - - @property - def oracle_evaluation(self) -> bool: - """Whether the classical oracle evaluation of the top measurement was True or False. - - Returns: - The classical oracle evaluation of the top measurement. - """ - return self._oracle_evaluation - - @oracle_evaluation.setter - def oracle_evaluation(self, value: bool) -> None: - """Set the classical oracle evaluation of the top measurement. - - Args: - value: A new value for the classical oracle evaluation. - """ - self._oracle_evaluation = value - - @property - def circuit_results(self) -> Optional[Union[List[np.ndarray], List[Dict[str, int]]]]: - """Return the circuit results. Can be a statevector or counts dictionary.""" - return self._circuit_results - - @circuit_results.setter - def circuit_results(self, value: Union[List[np.ndarray], List[Dict[str, int]]]) -> None: - """Set the circuit results.""" - self._circuit_results = value - - @property - def max_probability(self) -> float: - """Return the maximum sampling probability.""" - return self._max_probability - - @max_probability.setter - def max_probability(self, value: float) -> None: - """Set the maximum sampling probability.""" - self._max_probability = value + self.top_measurement = None + self.assignment = None + self.oracle_evaluation = None diff --git a/qiskit/algorithms/amplitude_amplifiers/grover.py b/qiskit/algorithms/amplitude_amplifiers/grover.py index 75158b42d107..d2a5a8524575 100644 --- a/qiskit/algorithms/amplitude_amplifiers/grover.py +++ b/qiskit/algorithms/amplitude_amplifiers/grover.py @@ -202,7 +202,6 @@ def amplify(self, amplification_problem: AmplificationProblem) -> 'GroverResult' oracle_evaluation = False all_circuit_results = [] max_probability = 0 - shots = 0 for _ in range(max_iterations): # iterate at most to the max number of iterations # get next power and check if allowed @@ -309,24 +308,7 @@ class GroverResult(AmplitudeAmplifierResult): def __init__(self) -> None: super().__init__() - self._iterations = None - self._circuit_results = None - self._shots = None - - @property - def iterations(self) -> List[int]: - """All the powers of the Grover operator that have been tried. - - Returns: - The powers of the Grover operator tested. - """ - return self._iterations - - @iterations.setter - def iterations(self, value: List[int]) -> None: - """Set the powers of the Grover operator that have been tried. - - Args: - value: A new value for the powers. - """ - self._iterations = value + self.iterations = None + self.circuit_results = None + self.shots = None + self.max_probability = None diff --git a/qiskit/algorithms/amplitude_estimators/ae.py b/qiskit/algorithms/amplitude_estimators/ae.py index 641c8c5751dd..89b3df7001c9 100644 --- a/qiskit/algorithms/amplitude_estimators/ae.py +++ b/qiskit/algorithms/amplitude_estimators/ae.py @@ -379,83 +379,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 - - @property - def num_evaluation_qubits(self) -> int: - """Returns the number of evaluation qubits.""" - return self._num_evaluation_qubits - - @num_evaluation_qubits.setter - def num_evaluation_qubits(self, num_evaluation_qubits: int) -> None: - """Set the number of evaluation qubits.""" - self._num_evaluation_qubits = num_evaluation_qubits - - @property - def mle_processed(self) -> float: - """Return the post-processed MLE for the amplitude.""" - return self._mle_processed - - @mle_processed.setter - def mle_processed(self, value: float) -> None: - """Set the post-processed MLE for the amplitude.""" - self._mle_processed = value - - @property - def samples_processed(self) -> Dict[float, float]: - """Return the post-processed measurement samples with their measurement probability.""" - return self._samples_processed - - @samples_processed.setter - def samples_processed(self, value: Dict[float, float]) -> None: - """Set the post-processed measurement samples.""" - self._samples_processed = value - - @property - def mle(self) -> float: - r"""Return the MLE for the amplitude, in $[0, 1]$.""" - return self._mle - - @mle.setter - def mle(self, value: float) -> None: - r"""Set the MLE for the amplitude, in $[0, 1]$.""" - self._mle = value - - @property - def samples(self) -> Dict[float, float]: - """Return the measurement samples with their measurement probability.""" - return self._samples - - @samples.setter - def samples(self, value: Dict[float, float]) -> None: - """Set the measurement samples with their measurement probability.""" - self._samples = value - - @property - def measurements(self) -> Dict[int, float]: - """Return the measurements as integers with their measurement probability.""" - return self._y_measurements - - @measurements.setter - def measurements(self, value: Dict[int, float]) -> None: - """Set the measurements as integers with their measurement probability.""" - self._y_measurements = value - - @property - def max_probability(self) -> float: - """Return the maximum sampling probability.""" - return self._max_probability - - @max_probability.setter - def max_probability(self, value: float) -> None: - """Set the maximum sampling probability.""" - self._max_probability = value + self.num_evaluation_qubits = None + self.mle = None + self.mle_processed = None + self.samples = None + self.samples_processed = None + self.measurements = None + self.max_probability = None def _compute_fisher_information(result: AmplitudeEstimationResult, observed: bool = False) -> float: diff --git a/qiskit/algorithms/amplitude_estimators/amplitude_estimator.py b/qiskit/algorithms/amplitude_estimators/amplitude_estimator.py index 7cdcfa29973c..d96f51f4d681 100644 --- a/qiskit/algorithms/amplitude_estimators/amplitude_estimator.py +++ b/qiskit/algorithms/amplitude_estimators/amplitude_estimator.py @@ -13,8 +13,6 @@ """The Amplitude Estimation interface.""" from abc import abstractmethod -from typing import Union, Optional, Dict, Callable, Tuple -import numpy as np from .estimation_problem import EstimationProblem from ..algorithm_result import AlgorithmResult @@ -39,91 +37,11 @@ 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 - - @property - def circuit_results(self) -> Optional[Union[np.ndarray, Dict[str, int]]]: - """Return the circuit results. Can be a statevector or counts dictionary.""" - return self._circuit_results - - @circuit_results.setter - def circuit_results(self, value: Union[np.ndarray, Dict[str, int]]) -> None: - """Set the circuit results.""" - self._circuit_results = value - - @property - def shots(self) -> int: - """Return the number of shots used. Is 1 for statevector-based simulations.""" - return self._shots - - @shots.setter - def shots(self, value: int) -> None: - """Set the number of shots used.""" - self._shots = value - - @property - def estimation(self) -> float: - r"""Return the estimation for the amplitude in :math:`[0, 1]`.""" - return self._estimation - - @estimation.setter - def estimation(self, value: float) -> None: - r"""Set the estimation for the amplitude in :math:`[0, 1]`.""" - self._estimation = value - - @property - def estimation_processed(self) -> float: - """Return the estimation for the amplitude after the post-processing has been applied.""" - return self._estimation_processed - - @estimation_processed.setter - def estimation_processed(self, value: float) -> None: - """Set the estimation for the amplitude after the post-processing has been applied.""" - self._estimation_processed = value - - @property - def num_oracle_queries(self) -> int: - """Return the number of Grover oracle queries.""" - return self._num_oracle_queries - - @num_oracle_queries.setter - def num_oracle_queries(self, value: int) -> None: - """Set the number of Grover oracle queries.""" - self._num_oracle_queries = value - - @property - def post_processing(self) -> Callable[[float], float]: - """Return a handle to the post processing function.""" - return self._post_processing - - @post_processing.setter - def post_processing(self, post_processing: Callable[[float], float]) -> None: - """Set a handle to the post processing function.""" - self._post_processing = post_processing - - @property - def confidence_interval(self) -> Tuple[float, float]: - """Return the confidence interval for the amplitude (95% interval by default).""" - return self._confidence_interval - - @confidence_interval.setter - def confidence_interval(self, confidence_interval: Tuple[float, float]) -> None: - """Set the confidence interval for the amplitude (95% interval by default).""" - self._confidence_interval = confidence_interval - - @property - def confidence_interval_processed(self) -> Tuple[float, float]: - """Return the post-processed confidence interval (95% interval by default).""" - return self._confidence_interval_processed - - @confidence_interval_processed.setter - def confidence_interval_processed(self, confidence_interval: Tuple[float, float]) -> None: - """Set the post-processed confidence interval (95% interval by default).""" - self._confidence_interval_processed = confidence_interval + 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 diff --git a/qiskit/algorithms/amplitude_estimators/estimation_problem.py b/qiskit/algorithms/amplitude_estimators/estimation_problem.py index f2ce03a241f6..af75d4dd0372 100644 --- a/qiskit/algorithms/amplitude_estimators/estimation_problem.py +++ b/qiskit/algorithms/amplitude_estimators/estimation_problem.py @@ -21,12 +21,14 @@ class EstimationProblem: - """The estimation problem is the input to amplitude estimation algorithm. + r"""The estimation problem is the input to amplitude estimation algorithm. This class contains all problem-specific information required to run an amplitude estimation algorithm. That means, it minimally contains the state preparation and the specification of the good state. It can further hold some post processing on the estimation of the amplitude or a custom Grover operator. + + :QuantumCircuit state_preparation: The :math:`\mathcal{A}` operator as `QuantumCircuit`. """ def __init__(self, @@ -51,29 +53,11 @@ def __init__(self, is_good_state: A function to check whether a string represents a good state. Defaults to all objective qubits being in state :math:`|1\rangle`. """ - self._state_preparation = state_preparation + self.state_preparation = state_preparation self._objective_qubits = objective_qubits self._grover_operator = grover_operator - self._post_processing = post_processing - self._is_good_state = is_good_state - - @property - def state_preparation(self) -> Optional[QuantumCircuit]: - r"""Get the :math:`\mathcal{A}` operator encoding the amplitude :math:`a`. - - Returns: - The :math:`\mathcal{A}` operator as `QuantumCircuit`. - """ - return self._state_preparation - - @state_preparation.setter - def state_preparation(self, state_preparation: QuantumCircuit) -> None: - r"""Set the :math:`\mathcal{A}` operator, that encodes the amplitude to be estimated. - - Args: - state_preparation: The new :math:`\mathcal{A}` operator. - """ - self._state_preparation = state_preparation + self.post_processing = post_processing or (lambda x: x) + self.is_good_state = is_good_state or (lambda x: all(bit == '1' for bit in x)) @property def objective_qubits(self) -> List[int]: @@ -96,50 +80,6 @@ def objective_qubits(self, objective_qubits: Union[int, List[int]]) -> None: """ self._objective_qubits = objective_qubits - @property - def post_processing(self) -> Callable[[float], float]: - """Apply post processing to the input value. - - Returns: - A handle to the post processing function. Acts as identity by default. - """ - if self._post_processing is None: - return lambda x: x - - return self._post_processing - - @post_processing.setter - def post_processing(self, post_processing: Optional[Callable[[float], float]]) -> None: - """Set the post processing function. - - Args: - post_processing: A handle to the post processing function. If set to ``None``, the - identity will be used as post processing. - """ - self._post_processing = post_processing - - @property - def is_good_state(self) -> Callable[[str], bool]: - """Checks whether a bitstring represents a good state. - - Returns: - Handle to the ``is_good_state`` callable. - """ - if self._is_good_state is None: - return lambda x: all(bit == '1' for bit in x) - - return self._is_good_state - - @is_good_state.setter - def is_good_state(self, is_good_state: Optional[Callable[[str], bool]]) -> None: - """Set the ``is_good_state`` function. - - Args: - is_good_state: A function to determine whether a bitstring represents a good state. - If set to ``None``, the good state will be defined as all bits being one. - """ - self._is_good_state = is_good_state - @property def grover_operator(self) -> Optional[QuantumCircuit]: r"""Get the :math:`\mathcal{Q}` operator, or Grover operator. diff --git a/qiskit/algorithms/amplitude_estimators/fae.py b/qiskit/algorithms/amplitude_estimators/fae.py index 70665ab0e6f8..b0b15afc8977 100644 --- a/qiskit/algorithms/amplitude_estimators/fae.py +++ b/qiskit/algorithms/amplitude_estimators/fae.py @@ -258,47 +258,7 @@ 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 - - @property - def success_probability(self) -> int: - """Return the success probability of the algorithm.""" - return self._success_probability - - @success_probability.setter - def success_probability(self, probability: int) -> None: - """Set the success probability of the algorithm.""" - self._success_probability = probability - - @property - def num_steps(self) -> int: - """Return the total number of steps taken in the algorithm.""" - return self._num_steps - - @num_steps.setter - def num_steps(self, num_steps: int) -> None: - """Set the total number of steps taken in the algorithm.""" - self._num_steps = num_steps - - @property - def num_first_state_steps(self) -> int: - """Return the number of steps taken in the first step of algorithm.""" - return self._num_first_state_steps - - @num_first_state_steps.setter - def num_first_state_steps(self, num_steps: int) -> None: - """Set the number of steps taken in the first step of algorithm.""" - self._num_first_state_steps = num_steps - - @property - def theta_intervals(self) -> List[List[float]]: - """Return the confidence intervals for the angles in each iteration.""" - return self._theta_intervals - - @theta_intervals.setter - def theta_intervals(self, value: List[List[float]]) -> None: - """Set the confidence intervals for the angles in each iteration.""" - self._theta_intervals = value + self.success_probability = None + self.num_steps = None + self.num_first_state_steps = None + self.theta_intervals = None diff --git a/qiskit/algorithms/amplitude_estimators/iae.py b/qiskit/algorithms/amplitude_estimators/iae.py index 8112440e681a..212bc513f597 100644 --- a/qiskit/algorithms/amplitude_estimators/iae.py +++ b/qiskit/algorithms/amplitude_estimators/iae.py @@ -413,105 +413,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 - - @property - def alpha(self) -> float: - r"""Return the confidence level :math:`\alpha`.""" - return self._alpha - - @alpha.setter - def alpha(self, value: float) -> None: - r"""Set the confidence level :math:`\alpha`.""" - self._alpha = value - - @property - def epsilon_target(self) -> float: - """Return the target half-width of the confidence interval.""" - return self._epsilon_target - - @epsilon_target.setter - def epsilon_target(self, value: float) -> None: - """Set the target half-width of the confidence interval.""" - self._epsilon_target = value - - @property - def epsilon_estimated(self) -> float: - """Return the estimated half-width of the confidence interval.""" - return self._epsilon_estimated - - @epsilon_estimated.setter - def epsilon_estimated(self, value: float) -> None: - """Set the estimated half-width of the confidence interval.""" - self._epsilon_estimated = value - - @property - def epsilon_estimated_processed(self) -> float: - """Return the post-processed estimated half-width of the confidence interval.""" - return self._epsilon_estimated_processed - - @epsilon_estimated_processed.setter - def epsilon_estimated_processed(self, value: float) -> None: - """Set the post-processed estimated half-width of the confidence interval.""" - self._epsilon_estimated_processed = value - - @property - def estimate_intervals(self) -> List[List[float]]: - """Return the confidence intervals for the estimate in each iteration.""" - return self._estimate_intervals - - @estimate_intervals.setter - def estimate_intervals(self, value: List[List[float]]) -> None: - """Set the confidence intervals for the estimate in each iteration.""" - self._estimate_intervals = value - - @property - def theta_intervals(self) -> List[List[float]]: - """Return the confidence intervals for the angles in each iteration.""" - return self._theta_intervals - - @theta_intervals.setter - def theta_intervals(self, value: List[List[float]]) -> None: - """Set the confidence intervals for the angles in each iteration.""" - self._theta_intervals = value - - @property - def powers(self) -> List[int]: - """Return the powers of the Grover operator in each iteration.""" - return self._powers - - @powers.setter - def powers(self, value: List[int]) -> None: - """Set the powers of the Grover operator in each iteration.""" - self._powers = value - - @property - def ratios(self) -> List[float]: - r"""Return the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`.""" - return self._ratios - - @ratios.setter - def ratios(self, value: List[float]) -> None: - r"""Set the ratios :math:`K_{i+1}/K_{i}` for each iteration :math:`i`.""" - self._ratios = value - - @property - def confidence_interval_processed(self) -> Tuple[float, float]: - """Return the post-processed confidence interval.""" - return self._confidence_interval_processed - - @confidence_interval_processed.setter - def confidence_interval_processed(self, value: Tuple[float, float]) -> None: - """Set the post-processed confidence interval.""" - self._confidence_interval_processed = value + 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 def _chernoff_confint(value: float, shots: int, max_rounds: int, alpha: float diff --git a/qiskit/algorithms/amplitude_estimators/mlae.py b/qiskit/algorithms/amplitude_estimators/mlae.py index 9754a22c732b..7a417d417bb9 100644 --- a/qiskit/algorithms/amplitude_estimators/mlae.py +++ b/qiskit/algorithms/amplitude_estimators/mlae.py @@ -314,61 +314,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 - - @property - def theta(self) -> float: - r"""Return the estimate for the angle :math:`\theta`.""" - return self._theta - - @theta.setter - def theta(self, value: float) -> None: - r"""Set the estimate for the angle :math:`\theta`.""" - self._theta = value - - @property - def minimizer(self) -> callable: - """Return the minimizer used for the search of the likelihood function.""" - return self._minimizer - - @minimizer.setter - def minimizer(self, value: callable) -> None: - """Set the number minimizer used for the search of the likelihood function.""" - self._minimizer = value - - @property - def good_counts(self) -> List[float]: - """Return the percentage of good counts per circuit power.""" - return self._good_counts - - @good_counts.setter - def good_counts(self, counts: List[float]) -> None: - """Set the percentage of good counts per circuit power.""" - self._good_counts = counts - - @property - def evaluation_schedule(self) -> List[int]: - """Return the evaluation schedule for the powers of the Grover operator.""" - return self._evaluation_schedule - - @evaluation_schedule.setter - def evaluation_schedule(self, evaluation_schedule: List[int]) -> None: - """Set the evaluation schedule for the powers of the Grover operator.""" - self._evaluation_schedule = evaluation_schedule - - @property - def fisher_information(self) -> float: - """Return the Fisher information for the estimated amplitude.""" - return self._fisher_information - - @fisher_information.setter - def fisher_information(self, value: float) -> None: - """Set the Fisher information for the estimated amplitude.""" - self._fisher_information = value + self.theta = None + self.minimizer = None + self.good_counts = None + self.evaluation_schedule = None + self.fisher_information = None def _safe_min(array, default=0): diff --git a/qiskit/algorithms/eigen_solvers/eigen_solver.py b/qiskit/algorithms/eigen_solvers/eigen_solver.py index 3e6ee2b68339..84c2b5a17a04 100644 --- a/qiskit/algorithms/eigen_solvers/eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/eigen_solver.py @@ -15,7 +15,6 @@ from abc import ABC, abstractmethod from typing import List, Optional -import numpy as np from qiskit.opflow import OperatorBase from ..algorithm_result import AlgorithmResult @@ -67,36 +66,6 @@ class EigensolverResult(AlgorithmResult): def __init__(self) -> None: super().__init__() - self._eigenvalues = None - self._eigenstates = None - self._aux_operator_eigenvalues = None - - @property - def eigenvalues(self) -> Optional[np.ndarray]: - """ returns eigen values """ - return self._eigenvalues - - @eigenvalues.setter - def eigenvalues(self, value: np.ndarray) -> None: - """ set eigen values """ - self._eigenvalues = value - - @property - def eigenstates(self) -> Optional[np.ndarray]: - """ return eigen states """ - return self._eigenstates - - @eigenstates.setter - def eigenstates(self, value: np.ndarray) -> None: - """ set eigen states """ - self._eigenstates = value - - @property - def aux_operator_eigenvalues(self) -> Optional[np.ndarray]: - """ return aux operator eigen values """ - return self._aux_operator_eigenvalues - - @aux_operator_eigenvalues.setter - def aux_operator_eigenvalues(self, value: np.ndarray) -> None: - """ set aux operator eigen values """ - self._aux_operator_eigenvalues = value + self.eigenvalues = None + self.eigenstates = None + self.aux_operator_eigenvalues = None diff --git a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py index 36ae9a2a3d82..ae05f76f3ead 100755 --- a/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py +++ b/qiskit/algorithms/eigen_solvers/numpy_eigen_solver.py @@ -63,7 +63,7 @@ def __init__(self, self._in_k = k self._k = k - self._filter_criterion = filter_criterion + self.filter_criterion = filter_criterion self._ret = EigensolverResult() @@ -79,18 +79,6 @@ def k(self, k: int) -> None: self._in_k = k self._k = k - @property - def filter_criterion(self) -> Optional[ - Callable[[Union[List, np.ndarray], float, Optional[List[float]]], bool]]: - """ returns the filter criterion if set """ - return self._filter_criterion - - @filter_criterion.setter - def filter_criterion(self, filter_criterion: Optional[ - Callable[[Union[List, np.ndarray], float, Optional[List[float]]], bool]]) -> None: - """ set the filter criterion """ - self._filter_criterion = filter_criterion - @classmethod def supports_aux_operators(cls) -> bool: return True @@ -188,7 +176,7 @@ def compute_eigenvalues( aux_operators = None k_orig = self._k - if self._filter_criterion: + if self.filter_criterion: # need to consider all elements if a filter is set self._k = 2 ** operator.num_qubits @@ -199,7 +187,7 @@ def compute_eigenvalues( self._get_energies(operator, aux_operators) # if a filter is set, loop over the given values and only keep - if self._filter_criterion: + if self.filter_criterion: eigvecs = [] eigvals = [] @@ -212,7 +200,7 @@ def compute_eigenvalues( aux_op = self._ret.aux_operator_eigenvalues[i] else: aux_op = None - if self._filter_criterion(eigvec, eigval, aux_op): + if self.filter_criterion(eigvec, eigval, aux_op): cnt += 1 eigvecs += [eigvec] eigvals += [eigval] diff --git a/qiskit/algorithms/factorizers/shor.py b/qiskit/algorithms/factorizers/shor.py index 99a5a9e5a9f4..90d8622557c7 100644 --- a/qiskit/algorithms/factorizers/shor.py +++ b/qiskit/algorithms/factorizers/shor.py @@ -471,36 +471,6 @@ class ShorResult(AlgorithmResult): def __init__(self) -> None: super().__init__() - self._factors = [] - self._total_counts = 0 - self._successful_counts = 0 - - @property - def factors(self) -> List[List[int]]: - """ returns factors """ - return self._factors - - @factors.setter - def factors(self, value: List[List[int]]) -> None: - """ set factors """ - self._factors = value - - @property - def total_counts(self) -> int: - """ returns total counts """ - return self._total_counts - - @total_counts.setter - def total_counts(self, value: int) -> None: - """ set total counts """ - self._total_counts = value - - @property - def successful_counts(self) -> int: - """ returns successful counts """ - return self._successful_counts - - @successful_counts.setter - def successful_counts(self, value: int) -> None: - """ set successful counts """ - self._successful_counts = value + self.factors = [] + self.total_counts = 0 + self.successful_counts = 0 diff --git a/qiskit/algorithms/linear_solvers/hhl.py b/qiskit/algorithms/linear_solvers/hhl.py index 26ae39eaccfa..9ed3445d5a12 100644 --- a/qiskit/algorithms/linear_solvers/hhl.py +++ b/qiskit/algorithms/linear_solvers/hhl.py @@ -111,14 +111,14 @@ def __init__(self, self._epsilon_s = epsilon / 3 # state preparation self._epsilon_a = epsilon / 6 # hamiltonian simulation - self._scaling = None # scaling of the solution + self.scaling = None # scaling of the solution if quantum_instance is not None: self._sampler = CircuitSampler(quantum_instance) else: self._sampler = None - self._expectation = expectation + self.expectation = expectation # For now the default reciprocal implementation is exact self._exact_reciprocal = True @@ -144,27 +144,6 @@ def quantum_instance(self, quantum_instance: Union[QuantumInstance, """ self._sampler.quantum_instance = quantum_instance - @property - def scaling(self) -> float: - """The scaling of the solution vector.""" - return self._scaling - - @scaling.setter - def scaling(self, scaling: float) -> None: - """Set the new scaling of the solution vector.""" - self._scaling = scaling - - @property - def expectation(self) -> ExpectationBase: - """The expectation value algorithm used to construct the expectation measurement from - the observable. """ - return self._expectation - - @expectation.setter - def expectation(self, expectation: ExpectationBase) -> None: - """Set the expectation value algorithm.""" - self._expectation = expectation - def _get_delta(self, n_l: int, lambda_min: float, lambda_max: float) -> float: """Calculates the scaling factor to represent exactly lambda_min on nl binary digits. @@ -273,15 +252,15 @@ def _calculate_observable(self, solution: QuantumCircuit, expectations = expectations[0] # check if an expectation converter is given - if self._expectation is not None: - expectations = self._expectation.convert(expectations) + if self.expectation is not None: + expectations = self.expectation.convert(expectations) # if otherwise a backend was specified, try to set the best expectation value elif self._sampler is not None: if is_list: op = expectations.oplist[0] else: op = expectations - self._expectation = ExpectationFactory.build(op, self._sampler.quantum_instance) + self.expectation = ExpectationFactory.build(op, self._sampler.quantum_instance) if self._sampler is not None: expectations = self._sampler.convert(expectations) diff --git a/qiskit/algorithms/linear_solvers/linear_solver.py b/qiskit/algorithms/linear_solvers/linear_solver.py index f7c8c25107be..817533623cdd 100644 --- a/qiskit/algorithms/linear_solvers/linear_solver.py +++ b/qiskit/algorithms/linear_solvers/linear_solver.py @@ -17,7 +17,6 @@ import numpy as np from qiskit import QuantumCircuit -from qiskit.result import Result from qiskit.quantum_info.operators.base_operator import BaseOperator from .observables.linear_system_observable import LinearSystemObservable @@ -35,61 +34,10 @@ def __init__(self) -> None: super().__init__() # Set the default to None, if the algorithm knows how to calculate it can override it. - self._state = None - self._observable = None - self._euclidean_norm = None - self._circuit_results = None - - @property - def observable(self) -> Union[float, List[float]]: - """return the (list of) calculated observable(s)""" - return self._observable - - @observable.setter - def observable(self, observable: Union[float, List[float]]) -> None: - """Set the value(s) of the observable(s). - - Args: - observable: The new value(s) of the observable(s). - """ - self._observable = observable - - @property - def state(self) -> Union[QuantumCircuit, np.ndarray]: - """return either the circuit that prepares the solution or the solution as a vector""" - return self._state - - @state.setter - def state(self, state: Union[QuantumCircuit, np.ndarray]) -> None: - """Set the solution state as either the circuit that prepares it or as a vector. - - Args: - state: The new solution state. - """ - self._state = state - - @property - def euclidean_norm(self) -> float: - """return the euclidean norm if the algorithm knows how to calculate it""" - return self._euclidean_norm - - @euclidean_norm.setter - def euclidean_norm(self, norm: float) -> None: - """Set the euclidean norm of the solution. - - Args: - norm: The new euclidean norm of the solution. - """ - self._euclidean_norm = norm - - @property - def circuit_results(self) -> Union[List[float], List[Result]]: - """return the results from the circuits""" - return self._circuit_results - - @circuit_results.setter - def circuit_results(self, results: Union[List[float], List[Result]]): - self._circuit_results = results + self.state = None + self.observable = None + self.euclidean_norm = None + self.circuit_results = None class LinearSolver(ABC): diff --git a/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py b/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py index d8e89bfdcc26..cf45f606eb22 100644 --- a/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py +++ b/qiskit/algorithms/linear_solvers/matrices/linear_system_matrix.py @@ -33,15 +33,10 @@ def __init__(self, num_state_qubits: int, tolerance: float, evolution_time: floa """ super().__init__(name=name) - # define internal parameters + self.tolerance = tolerance + self.evolution_time = evolution_time # makes sure the eigenvalues are contained in [0,1) self._num_state_qubits = None - self._tolerance = None - self._evolution_time = None # makes sure the eigenvalues are contained in [0,1) - - # store parameters self.num_state_qubits = num_state_qubits - self.tolerance = tolerance - self.evolution_time = evolution_time @property def num_state_qubits(self) -> int: @@ -67,33 +62,6 @@ def num_state_qubits(self, num_state_qubits: int) -> None: self._num_state_qubits = num_state_qubits self._reset_registers(num_state_qubits) - @property - def tolerance(self) -> float: - """Return the error tolerance""" - return self._tolerance - - @tolerance.setter - def tolerance(self, tolerance: float) -> None: - """Set the error tolerance - Args: - tolerance: The new error tolerance. - """ - self._tolerance = tolerance - - @property - def evolution_time(self) -> float: - """Return the time of the evolution.""" - return self._evolution_time - - @evolution_time.setter - def evolution_time(self, evolution_time: float) -> None: - """Set the time of the evolution. - - Args: - evolution_time: The new time of the evolution. - """ - self._evolution_time = evolution_time - @abstractmethod def eigs_bounds(self) -> Tuple[float, float]: """Return lower and upper bounds on the eigenvalues of the matrix.""" diff --git a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py index ef83da6af18a..a0bfeef8cce0 100644 --- a/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py +++ b/qiskit/algorithms/linear_solvers/matrices/numpy_matrix.py @@ -53,18 +53,11 @@ def __init__(self, matrix: np.ndarray, tolerance: float = 1e-2, evolution_time: evolution_time: The time of the Hamiltonian simulation. name: The name of the object. """ - - # define internal parameters self._num_state_qubits = None - self._tolerance = None - self._evolution_time = None # makes sure the eigenvalues are contained in [0,1) - self._matrix = None + self.matrix = matrix # store parameters self.num_state_qubits = int(np.log2(matrix.shape[0])) - self.tolerance = tolerance - self.evolution_time = evolution_time - self.matrix = matrix super().__init__(num_state_qubits=int(np.log2(matrix.shape[0])), tolerance=tolerance, evolution_time=evolution_time, name=name) @@ -92,47 +85,6 @@ def num_state_qubits(self, num_state_qubits: int) -> None: self._num_state_qubits = num_state_qubits self._reset_registers(num_state_qubits) - @property - def tolerance(self) -> float: - """Return the error tolerance""" - return self._tolerance - - @tolerance.setter - def tolerance(self, tolerance: float) -> None: - """Set the error tolerance - Args: - tolerance: The new error tolerance. - """ - self._tolerance = tolerance - - @property - def evolution_time(self) -> float: - """Return the time of the evolution.""" - return self._evolution_time - - @evolution_time.setter - def evolution_time(self, evolution_time: float) -> None: - """Set the time of the evolution. - - Args: - evolution_time: The new time of the evolution. - """ - self._evolution_time = evolution_time - - @property - def matrix(self) -> np.ndarray: - """Return the matrix.""" - return self._matrix - - @matrix.setter - def matrix(self, matrix: np.ndarray) -> None: - """Set the matrix. - - Args: - matrix: The new matrix. - """ - self._matrix = matrix - def eigs_bounds(self) -> Tuple[float, float]: """Return lower and upper bounds on the eigenvalues of the matrix.""" matrix_array = self.matrix diff --git a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py index 44cda5d78469..e3d7cb72d9b8 100644 --- a/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py +++ b/qiskit/algorithms/linear_solvers/matrices/tridiagonal_toeplitz.py @@ -71,18 +71,13 @@ def __init__(self, num_state_qubits: int, main_diag: float, off_diag: float, """ # define internal parameters self._num_state_qubits = None - self._main_diag = None - self._off_diag = None - self._tolerance = None - self._evolution_time = None # makes sure the eigenvalues are contained in [0,1) - self._trotter_steps = None - - # store parameters self.main_diag = main_diag self.off_diag = off_diag + self._evolution_time = None # makes sure the eigenvalues are contained in [0,1) + self.trotter_steps = trotter_steps + super().__init__(num_state_qubits=num_state_qubits, tolerance=tolerance, evolution_time=evolution_time, name=name) - self.trotter_steps = trotter_steps @property def num_state_qubits(self) -> int: @@ -108,45 +103,6 @@ def num_state_qubits(self, num_state_qubits: int) -> None: self._num_state_qubits = num_state_qubits self._reset_registers(num_state_qubits) - @property - def main_diag(self) -> float: - """Return the entry in the main diagonal.""" - return self._main_diag - - @main_diag.setter - def main_diag(self, main_diag: float) -> None: - """Set the entry in the main diagonal. - Args: - main_diag: The new entry in the main diagonal. - """ - self._main_diag = main_diag - - @property - def off_diag(self) -> float: - """Return the entry in the off diagonals.""" - return self._off_diag - - @off_diag.setter - def off_diag(self, off_diag: float) -> None: - """Set the entry in the off diagonals. - Args: - off_diag: The new entry in the main diagonal. - """ - self._off_diag = off_diag - - @property - def tolerance(self) -> float: - """Return the error tolerance""" - return self._tolerance - - @tolerance.setter - def tolerance(self, tolerance: float) -> None: - """Set the error tolerance. - Args: - tolerance: The new error tolerance. - """ - self._tolerance = tolerance - @property def evolution_time(self) -> float: """Return the time of the evolution.""" @@ -165,19 +121,6 @@ def evolution_time(self, evolution_time: float) -> None: self.trotter_steps = int(np.ceil(np.sqrt(((evolution_time * np.abs(self.off_diag)) ** 3) / 2 / self.tolerance))) - @property - def trotter_steps(self) -> int: - """Return the number of trotter steps.""" - return self._trotter_steps - - @trotter_steps.setter - def trotter_steps(self, trotter_steps: int) -> None: - """Set the number of trotter steps. - Args: - trotter_steps: The new number of trotter steps. - """ - self._trotter_steps = trotter_steps - @property def matrix(self) -> np.ndarray: """Returns the tridiagonal Toeplitz matrix built according to the main and off diagonal diff --git a/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py b/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py index b88519a90ac9..1dafadee42a6 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py +++ b/qiskit/algorithms/minimum_eigen_solvers/minimum_eigen_solver.py @@ -15,7 +15,6 @@ from abc import ABC, abstractmethod from typing import List, Optional -import numpy as np from qiskit.opflow import OperatorBase from ..algorithm_result import AlgorithmResult @@ -71,36 +70,6 @@ class MinimumEigensolverResult(AlgorithmResult): def __init__(self) -> None: super().__init__() - self._eigenvalue = None - self._eigenstate = None - self._aux_operator_eigenvalues = None - - @property - def eigenvalue(self) -> Optional[complex]: - """ returns eigen value """ - return self._eigenvalue - - @eigenvalue.setter - def eigenvalue(self, value: complex) -> None: - """ set eigen value """ - self._eigenvalue = value - - @property - def eigenstate(self) -> Optional[np.ndarray]: - """ return eigen state """ - return self._eigenstate - - @eigenstate.setter - def eigenstate(self, value: np.ndarray) -> None: - """ set eigen state """ - self._eigenstate = value - - @property - def aux_operator_eigenvalues(self) -> Optional[np.ndarray]: - """ return aux operator eigen values """ - return self._aux_operator_eigenvalues - - @aux_operator_eigenvalues.setter - def aux_operator_eigenvalues(self, value: np.ndarray) -> None: - """ set aux operator eigen values """ - self._aux_operator_eigenvalues = value + self.eigenvalue = None + self.eigenstate = None + self.aux_operator_eigenvalues = None diff --git a/qiskit/algorithms/minimum_eigen_solvers/qaoa.py b/qiskit/algorithms/minimum_eigen_solvers/qaoa.py index 4c41dbf2fbdf..de58832bea59 100644 --- a/qiskit/algorithms/minimum_eigen_solvers/qaoa.py +++ b/qiskit/algorithms/minimum_eigen_solvers/qaoa.py @@ -110,8 +110,8 @@ def __init__(self, validate_min('reps', reps, 1) self._reps = reps - self._mixer = mixer - self._initial_state = initial_state + self.mixer = mixer + self.initial_state = initial_state super().__init__(ansatz=None, optimizer=optimizer, @@ -128,39 +128,7 @@ def _check_operator(self, operator: OperatorBase) -> OperatorBase: if operator.num_qubits != self.ansatz.num_qubits: self.ansatz = QAOAAnsatz(operator, self._reps, - initial_state=self._initial_state, - mixer_operator=self._mixer) + initial_state=self.initial_state, + mixer_operator=self.mixer) operator = super()._check_operator(operator) return operator - - @property - def initial_state(self) -> Optional[QuantumCircuit]: - """ - Returns: - Returns the initial state. - """ - return self._initial_state - - @initial_state.setter - def initial_state(self, initial_state: Optional[QuantumCircuit]) -> None: - """ - Args: - initial_state: Initial state to set. - """ - self._initial_state = initial_state - - @property - def mixer(self) -> Union[QuantumCircuit, OperatorBase]: - """ - Returns: - Returns the mixer. - """ - return self._mixer - - @mixer.setter - def mixer(self, mixer: Union[QuantumCircuit, OperatorBase]) -> None: - """ - Args: - mixer: Mixer to set. - """ - self._mixer = mixer diff --git a/qiskit/algorithms/minimum_eigen_solvers/vqe.py b/qiskit/algorithms/minimum_eigen_solvers/vqe.py index f0b359bfe51f..88e35f103564 100755 --- a/qiskit/algorithms/minimum_eigen_solvers/vqe.py +++ b/qiskit/algorithms/minimum_eigen_solvers/vqe.py @@ -533,14 +533,4 @@ class VQEResult(VariationalResult, MinimumEigensolverResult): def __init__(self) -> None: super().__init__() - self._cost_function_evals = None - - @property - def cost_function_evals(self) -> Optional[int]: - """ Returns number of cost optimizer evaluations """ - return self._cost_function_evals - - @cost_function_evals.setter - def cost_function_evals(self, value: int) -> None: - """ Sets number of cost function evaluations """ - self._cost_function_evals = value + self.cost_function_evals = None diff --git a/qiskit/algorithms/variational_algorithm.py b/qiskit/algorithms/variational_algorithm.py index ff7cb02c14c2..c8fe8b20194c 100644 --- a/qiskit/algorithms/variational_algorithm.py +++ b/qiskit/algorithms/variational_algorithm.py @@ -20,7 +20,7 @@ overridden to opt-out of this infrastructure but still meet the interface requirements. """ -from typing import Optional, Callable, Union, Dict +from typing import Optional, Callable, Union import time import logging from abc import abstractmethod @@ -73,12 +73,11 @@ def __init__(self, self._optimizer = optimizer self._gradient = gradient self._cost_fn = cost_fn - self._initial_point = initial_point + self.initial_point = initial_point self._ansatz = ansatz self._ansatz_params = None if ansatz is not None: self.ansatz = ansatz - self._parameterized_circuits = None @property @@ -122,16 +121,6 @@ def optimizer(self, optimizer: Optimizer): """ Sets optimizer """ self._optimizer = optimizer - @property - def initial_point(self) -> Optional[np.ndarray]: - """ Returns initial point """ - return self._initial_point - - @initial_point.setter - def initial_point(self, initial_point: np.ndarray): - """ Sets initial point """ - self._initial_point = initial_point - def find_minimum(self, initial_point: Optional[np.ndarray] = None, ansatz: Optional[QuantumCircuit] = None, @@ -289,58 +278,8 @@ class VariationalResult(AlgorithmResult): def __init__(self) -> None: super().__init__() - self._optimizer_evals = None - self._optimizer_time = None - self._optimal_value = None - self._optimal_point = None - self._optimal_parameters = None - - @property - def optimizer_evals(self) -> Optional[int]: - """ Returns number of optimizer evaluations """ - return self._optimizer_evals - - @optimizer_evals.setter - def optimizer_evals(self, value: int) -> None: - """ Sets number of optimizer evaluations """ - self._optimizer_evals = value - - @property - def optimizer_time(self) -> Optional[float]: - """ Returns time taken for optimization """ - return self._optimizer_time - - @optimizer_time.setter - def optimizer_time(self, value: float) -> None: - """ Sets time taken for optimization """ - self._optimizer_time = value - - @property - def optimal_value(self) -> Optional[float]: - """ Returns optimal value """ - return self._optimal_value - - @optimal_value.setter - def optimal_value(self, value: int) -> None: - """ Sets optimal value """ - self._optimal_value = value - - @property - def optimal_point(self) -> Optional[np.ndarray]: - """ Returns optimal point """ - return self._optimal_point - - @optimal_point.setter - def optimal_point(self, value: np.ndarray) -> None: - """ Sets optimal point """ - self._optimal_point = value - - @property - def optimal_parameters(self) -> Optional[Dict]: - """ Returns the optimal parameters in a dictionary """ - return self._optimal_parameters - - @optimal_parameters.setter - def optimal_parameters(self, value: Dict) -> None: - """ Sets optimal parameters """ - self._optimal_parameters = value + self.optimizer_evals = None + self.optimizer_time = None + self.optimal_value = None + self.optimal_point = None + self.optimal_parameters = None