From e3233b7b6966ebc66414712cfc4b5d84db9bfc28 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 30 Aug 2022 13:21:25 +0200 Subject: [PATCH 01/58] Implemented observables_evaluator.py with primitives. --- qiskit/algorithms/observables_evaluator.py | 177 ++++++++++++++++++ .../algorithms/test_observables_evaluator.py | 105 +++++++++++ 2 files changed, 282 insertions(+) create mode 100644 qiskit/algorithms/observables_evaluator.py create mode 100644 test/python/algorithms/test_observables_evaluator.py diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py new file mode 100644 index 000000000000..3ed9c6757f91 --- /dev/null +++ b/qiskit/algorithms/observables_evaluator.py @@ -0,0 +1,177 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. +"""Evaluator of auxiliary operators for algorithms.""" + +from typing import Tuple, Union, List, Iterable, Sequence, Optional + +import numpy as np + +from qiskit import QuantumCircuit +from qiskit.opflow import ( + CircuitSampler, + ListOp, + StateFn, + OperatorBase, + ExpectationBase, + PauliSumOp, +) +from qiskit.providers import Backend +from qiskit.quantum_info import Statevector +from qiskit.utils import QuantumInstance + +from .list_or_dict import ListOrDict +from ..primitives import Estimator, EstimatorResult +from ..quantum_info.operators.base_operator import BaseOperator + + +def eval_observables( + estimator: Estimator, + quantum_state: Sequence[QuantumCircuit], + observables: Sequence[Union[BaseOperator, PauliSumOp]], + threshold: float = 1e-12, +) -> ListOrDict[Tuple[complex, complex]]: + """ + Accepts a list or a dictionary of operators and calculates their expectation values - means + and standard deviations. They are calculated with respect to a quantum state provided. A user + can optionally provide a threshold value which filters mean values falling below the threshold. + + Args: + estimator: An estimator primitive used for calculations. + quantum_state: An unparametrized quantum circuit representing a quantum state that + expectation values are computed against. + observables: A sequence of operators whose expectation values are to be + calculated. + threshold: A threshold value that defines which mean values should be neglected (helpful for + ignoring numerical instabilities close to 0). + + Returns: + A list or a dictionary of tuples (mean, standard deviation). + + Raises: + ValueError: If a ``quantum_state`` with free parameters is provided. + """ + + if ( + isinstance( + quantum_state, (QuantumCircuit, OperatorBase) + ) # Statevector cannot be parametrized + and len(quantum_state.parameters) > 0 + ): + raise ValueError( + "A parametrized representation of a quantum_state was provided. It is not " + "allowed - it cannot have free parameters." + ) + + # if type(observables) != Sequence: + # observables = [observables] + # if type(quantum_state) != Sequence: + # quantum_state = [quantum_state] + estimator_job = estimator.run(quantum_state, observables) + expectation_values = estimator_job.result().values + + # compute standard deviations + std_devs = _compute_std_devs(estimator_job, len(expectation_values)) + + # Discard values below threshold + observables_means = expectation_values * (np.abs(expectation_values) > threshold) + # zip means and standard deviations into tuples + observables_results = list(zip(observables_means, std_devs)) + + # Return None eigenvalues for None operators if observables is a list. + # None operators are already dropped in compute_minimum_eigenvalue if observables is a dict. + + return _prepare_result(observables_results, observables) + + +def _prepare_list_op( + quantum_state: Union[ + Statevector, + QuantumCircuit, + OperatorBase, + ], + observables: ListOrDict[OperatorBase], +) -> ListOp: + """ + Accepts a list or a dictionary of operators and converts them to a ``ListOp``. + + Args: + quantum_state: An unparametrized quantum circuit representing a quantum state that + expectation values are computed against. + observables: A list or a dictionary of operators. + + Returns: + A ``ListOp`` that includes all provided observables. + """ + if isinstance(observables, dict): + observables = list(observables.values()) + + if not isinstance(quantum_state, StateFn): + quantum_state = StateFn(quantum_state) + + return ListOp([StateFn(obs, is_measurement=True).compose(quantum_state) for obs in observables]) + + +def _prepare_result( + observables_results: List[Tuple[complex, complex]], + observables: ListOrDict[OperatorBase], +) -> ListOrDict[Tuple[complex, complex]]: + """ + Prepares a list or a dictionary of eigenvalues from ``observables_results`` and + ``observables``. + + Args: + observables_results: A list of of tuples (mean, standard deviation). + observables: A list or a dictionary of operators whose expectation values are to be + calculated. + + Returns: + A list or a dictionary of tuples (mean, standard deviation). + """ + if isinstance(observables, list): + observables_eigenvalues = [None] * len(observables) + key_value_iterator = enumerate(observables_results) + else: + observables_eigenvalues = {} + key_value_iterator = zip(observables.keys(), observables_results) + for key, value in key_value_iterator: + if observables[key] is not None: + observables_eigenvalues[key] = value + return observables_eigenvalues + + +def _compute_std_devs( + estimator_result: EstimatorResult, + results_length: int, +) -> List[Optional[complex]]: + """ + Calculates a list of standard deviations from expectation values of observables provided. + + Args: + estimator_result: An estimator result. + results_length: Number of expectation values calculated. + + Returns: + A list of standard deviations. + """ + if not estimator_result.metadata: + return [0] * results_length + + std_devs = [] + for metadata in estimator_result.metadata: + if metadata and "variance" in metadata.keys() and "shots" in metadata.keys(): + variance = metadata["variance"] + shots = metadata["shots"] + std_devs.append(np.sqrt(variance / shots)) + else: + std_devs.append(0) + + return std_devs diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py new file mode 100644 index 000000000000..2fa4e7e4c913 --- /dev/null +++ b/test/python/algorithms/test_observables_evaluator.py @@ -0,0 +1,105 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. +"""Tests evaluator of auxiliary operators for algorithms.""" + +import unittest +from typing import Tuple, Sequence, List + +import numpy as np +from ddt import ddt, data + +from qiskit.algorithms.observables_evaluator import eval_observables +from qiskit.primitives import Estimator +from test.python.algorithms import QiskitAlgorithmsTestCase +from qiskit.algorithms.list_or_dict import ListOrDict +from qiskit.quantum_info import Statevector +from qiskit import QuantumCircuit +from qiskit.circuit.library import EfficientSU2 +from qiskit.opflow import ( + PauliSumOp, + X, + Z, + I, + OperatorBase, +) +from qiskit.utils import algorithm_globals + + +@ddt +class TestObservablesEvaluator(QiskitAlgorithmsTestCase): + """Tests evaluator of auxiliary operators for algorithms.""" + + def setUp(self): + super().setUp() + self.seed = 50 + algorithm_globals.random_seed = self.seed + + self.threshold = 1e-8 + + def get_exact_expectation(self, ansatz: QuantumCircuit, observables: Sequence[OperatorBase]): + """ + Calculates the exact expectation to be used as an expected result for unit tests. + """ + + # the exact value is a list of (mean, variance) where we expect 0 variance + exact = [ + (Statevector(ansatz).expectation_value(observable), 0) for observable in observables + ] + + return exact + + def _run_test( + self, + expected_result: List[Tuple[complex, complex]], + quantum_state: Sequence[QuantumCircuit], + decimal: int, + observables: Sequence[OperatorBase], + estimator: Estimator, + ): + result = eval_observables(estimator, quantum_state, observables, self.threshold) + + np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) + + @data( + [ + PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), + PauliSumOp.from_list([("II", 2.0)]), + ], + [ + PauliSumOp.from_list([("ZZ", 2.0)]), + ], + ) + def test_eval_observables(self, observables: Sequence[OperatorBase]): + """Tests evaluator of auxiliary operators for algorithms.""" + + ansatz = EfficientSU2(2) + parameters = np.array( + [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], + dtype=float, + ) + + bound_ansatz = ansatz.bind_parameters(parameters) + states = [bound_ansatz] * len(observables) + expected_result = self.get_exact_expectation(bound_ansatz, observables) + estimator = Estimator() + decimal = 6 + self._run_test( + expected_result, + states, + decimal, + observables, + estimator, + ) + + +if __name__ == "__main__": + unittest.main() From d71f50b52b3993eb116fd9af99325f8b7dc89292 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 30 Aug 2022 13:23:27 +0200 Subject: [PATCH 02/58] Added evolvers problems and interfaces to time_evolvers package. --- qiskit/algorithms/time_evolvers/__init__.py | 11 ++ .../time_evolvers/evolution_problem.py | 109 ++++++++++++++++ .../time_evolvers/evolution_result.py | 40 ++++++ .../time_evolvers/imaginary_evolver.py | 37 ++++++ .../algorithms/time_evolvers/real_evolver.py | 37 ++++++ .../algorithms/test_observables_evaluator.py | 4 - .../algorithms/time_evolvers/__init__.py | 11 ++ .../time_evolvers/test_evolution_problem.py | 116 ++++++++++++++++++ .../time_evolvers/test_evolution_result.py | 48 ++++++++ 9 files changed, 409 insertions(+), 4 deletions(-) create mode 100644 qiskit/algorithms/time_evolvers/__init__.py create mode 100644 qiskit/algorithms/time_evolvers/evolution_problem.py create mode 100644 qiskit/algorithms/time_evolvers/evolution_result.py create mode 100644 qiskit/algorithms/time_evolvers/imaginary_evolver.py create mode 100644 qiskit/algorithms/time_evolvers/real_evolver.py create mode 100644 test/python/algorithms/time_evolvers/__init__.py create mode 100644 test/python/algorithms/time_evolvers/test_evolution_problem.py create mode 100644 test/python/algorithms/time_evolvers/test_evolution_result.py diff --git a/qiskit/algorithms/time_evolvers/__init__.py b/qiskit/algorithms/time_evolvers/__init__.py new file mode 100644 index 000000000000..fdb172d367f0 --- /dev/null +++ b/qiskit/algorithms/time_evolvers/__init__.py @@ -0,0 +1,11 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. diff --git a/qiskit/algorithms/time_evolvers/evolution_problem.py b/qiskit/algorithms/time_evolvers/evolution_problem.py new file mode 100644 index 000000000000..175beecd6bf6 --- /dev/null +++ b/qiskit/algorithms/time_evolvers/evolution_problem.py @@ -0,0 +1,109 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Evolution problem class.""" + +from typing import Union, Optional, Dict + +from qiskit import QuantumCircuit +from qiskit.circuit import Parameter +from qiskit.opflow import OperatorBase, StateFn +from ..list_or_dict import ListOrDict + + +class EvolutionProblem: + """Evolution problem class. + + This class is the input to time evolution algorithms and must contain information on the total + evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. + """ + + def __init__( + self, + hamiltonian: OperatorBase, + time: float, + initial_state: Optional[Union[StateFn, QuantumCircuit]] = None, + aux_operators: Optional[ListOrDict[OperatorBase]] = None, + truncation_threshold: float = 1e-12, + t_param: Optional[Parameter] = None, + param_value_dict: Optional[Dict[Parameter, complex]] = None, + ): + """ + Args: + hamiltonian: The Hamiltonian under which to evolve the system. + time: Total time of evolution. + initial_state: The quantum state to be evolved for methods like Trotterization. + For variational time evolutions, where the evolution happens in an ansatz, + this argument is not required. + aux_operators: Optional list of auxiliary operators to be evaluated with the + evolved ``initial_state`` and their expectation values returned. + truncation_threshold: Defines a threshold under which values can be assumed to be 0. + Used when ``aux_operators`` is provided. + t_param: Time parameter in case of a time-dependent Hamiltonian. This + free parameter must be within the ``hamiltonian``. + param_value_dict: Maps free parameters in the problem to values. Depending on the + algorithm, it might refer to e.g. a Hamiltonian or an initial state. + + Raises: + ValueError: If non-positive time of evolution is provided. + """ + + self.t_param = t_param + self.param_value_dict = param_value_dict + self.hamiltonian = hamiltonian + self.time = time + self.initial_state = initial_state + self.aux_operators = aux_operators + self.truncation_threshold = truncation_threshold + + @property + def time(self) -> float: + """Returns time.""" + return self._time + + @time.setter + def time(self, time: float) -> None: + """ + Sets time and validates it. + + Raises: + ValueError: If time is not positive. + """ + if time <= 0: + raise ValueError(f"Evolution time must be > 0 but was {time}.") + self._time = time + + def validate_params(self) -> None: + """ + Checks if all parameters present in the Hamiltonian are also present in the dictionary + that maps them to values. + + Raises: + ValueError: If Hamiltonian parameters cannot be bound with data provided. + """ + if isinstance(self.hamiltonian, OperatorBase): + t_param_set = set() + if self.t_param is not None: + t_param_set.add(self.t_param) + hamiltonian_dict_param_set = set() + if self.param_value_dict is not None: + hamiltonian_dict_param_set = hamiltonian_dict_param_set.union( + set(self.param_value_dict.keys()) + ) + params_set = t_param_set.union(hamiltonian_dict_param_set) + hamiltonian_param_set = set(self.hamiltonian.parameters) + + if hamiltonian_param_set != params_set: + raise ValueError( + f"Provided parameters {params_set} do not match Hamiltonian parameters " + f"{hamiltonian_param_set}." + ) diff --git a/qiskit/algorithms/time_evolvers/evolution_result.py b/qiskit/algorithms/time_evolvers/evolution_result.py new file mode 100644 index 000000000000..1dd91d705d28 --- /dev/null +++ b/qiskit/algorithms/time_evolvers/evolution_result.py @@ -0,0 +1,40 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Class for holding evolution result.""" + +from typing import Optional, Union, Tuple + +from qiskit import QuantumCircuit +from qiskit.algorithms.list_or_dict import ListOrDict +from qiskit.opflow import StateFn, OperatorBase +from ..algorithm_result import AlgorithmResult + + +class EvolutionResult(AlgorithmResult): + """Class for holding evolution result.""" + + def __init__( + self, + evolved_state: Union[StateFn, QuantumCircuit, OperatorBase], + aux_ops_evaluated: Optional[ListOrDict[Tuple[complex, complex]]] = None, + ): + """ + Args: + evolved_state: An evolved quantum state. + aux_ops_evaluated: Optional list of observables for which expected values on an evolved + state are calculated. These values are in fact tuples formatted as (mean, standard + deviation). + """ + + self.evolved_state = evolved_state + self.aux_ops_evaluated = aux_ops_evaluated diff --git a/qiskit/algorithms/time_evolvers/imaginary_evolver.py b/qiskit/algorithms/time_evolvers/imaginary_evolver.py new file mode 100644 index 000000000000..309bb73b08af --- /dev/null +++ b/qiskit/algorithms/time_evolvers/imaginary_evolver.py @@ -0,0 +1,37 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Interface for Quantum Imaginary Time Evolution.""" + +from abc import ABC, abstractmethod + +from .evolution_problem import EvolutionProblem +from .evolution_result import EvolutionResult + + +class ImaginaryEvolver(ABC): + """Interface for Quantum Imaginary Time Evolution.""" + + @abstractmethod + def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: + r"""Perform imaginary time evolution :math:`\exp(-\tau H)|\Psi\rangle`. + + Evolves an initial state :math:`|\Psi\rangle` for an imaginary time :math:`\tau` + under a Hamiltonian :math:`H`, as provided in the ``evolution_problem``. + + Args: + evolution_problem: The definition of the evolution problem. + + Returns: + Evolution result which includes an evolved quantum state. + """ + raise NotImplementedError() diff --git a/qiskit/algorithms/time_evolvers/real_evolver.py b/qiskit/algorithms/time_evolvers/real_evolver.py new file mode 100644 index 000000000000..6107facfe542 --- /dev/null +++ b/qiskit/algorithms/time_evolvers/real_evolver.py @@ -0,0 +1,37 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Interface for Quantum Real Time Evolution.""" + +from abc import ABC, abstractmethod + +from .evolution_problem import EvolutionProblem +from .evolution_result import EvolutionResult + + +class RealEvolver(ABC): + """Interface for Quantum Real Time Evolution.""" + + @abstractmethod + def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: + r"""Perform real time evolution :math:`\exp(-i t H)|\Psi\rangle`. + + Evolves an initial state :math:`|\Psi\rangle` for a time :math:`t` + under a Hamiltonian :math:`H`, as provided in the ``evolution_problem``. + + Args: + evolution_problem: The definition of the evolution problem. + + Returns: + Evolution result which includes an evolved quantum state. + """ + raise NotImplementedError() diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 2fa4e7e4c913..ea9b3560746f 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -20,15 +20,11 @@ from qiskit.algorithms.observables_evaluator import eval_observables from qiskit.primitives import Estimator from test.python.algorithms import QiskitAlgorithmsTestCase -from qiskit.algorithms.list_or_dict import ListOrDict from qiskit.quantum_info import Statevector from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import ( PauliSumOp, - X, - Z, - I, OperatorBase, ) from qiskit.utils import algorithm_globals diff --git a/test/python/algorithms/time_evolvers/__init__.py b/test/python/algorithms/time_evolvers/__init__.py new file mode 100644 index 000000000000..fdb172d367f0 --- /dev/null +++ b/test/python/algorithms/time_evolvers/__init__.py @@ -0,0 +1,11 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. diff --git a/test/python/algorithms/time_evolvers/test_evolution_problem.py b/test/python/algorithms/time_evolvers/test_evolution_problem.py new file mode 100644 index 000000000000..d3dd2f7bc9b2 --- /dev/null +++ b/test/python/algorithms/time_evolvers/test_evolution_problem.py @@ -0,0 +1,116 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""Test evolver problem class.""" +import unittest +from test.python.algorithms import QiskitAlgorithmsTestCase +from ddt import data, ddt, unpack +from numpy.testing import assert_raises + +from qiskit.algorithms.evolvers.evolution_problem import EvolutionProblem +from qiskit.circuit import Parameter +from qiskit.opflow import Y, Z, One, X, Zero + + +@ddt +class TestEvolutionProblem(QiskitAlgorithmsTestCase): + """Test evolver problem class.""" + + def test_init_default(self): + """Tests that all default fields are initialized correctly.""" + hamiltonian = Y + time = 2.5 + initial_state = One + + evo_problem = EvolutionProblem(hamiltonian, time, initial_state) + + expected_hamiltonian = Y + expected_time = 2.5 + expected_initial_state = One + expected_aux_operators = None + expected_t_param = None + expected_param_value_dict = None + + self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) + self.assertEqual(evo_problem.time, expected_time) + self.assertEqual(evo_problem.initial_state, expected_initial_state) + self.assertEqual(evo_problem.aux_operators, expected_aux_operators) + self.assertEqual(evo_problem.t_param, expected_t_param) + self.assertEqual(evo_problem.param_value_dict, expected_param_value_dict) + + def test_init_all(self): + """Tests that all fields are initialized correctly.""" + t_parameter = Parameter("t") + hamiltonian = t_parameter * Z + Y + time = 2 + initial_state = One + aux_operators = [X, Y] + param_value_dict = {t_parameter: 3.2} + + evo_problem = EvolutionProblem( + hamiltonian, + time, + initial_state, + aux_operators, + t_param=t_parameter, + param_value_dict=param_value_dict, + ) + + expected_hamiltonian = Y + t_parameter * Z + expected_time = 2 + expected_initial_state = One + expected_aux_operators = [X, Y] + expected_t_param = t_parameter + expected_param_value_dict = {t_parameter: 3.2} + + self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) + self.assertEqual(evo_problem.time, expected_time) + self.assertEqual(evo_problem.initial_state, expected_initial_state) + self.assertEqual(evo_problem.aux_operators, expected_aux_operators) + self.assertEqual(evo_problem.t_param, expected_t_param) + self.assertEqual(evo_problem.param_value_dict, expected_param_value_dict) + + @data([Y, -1, One], [Y, -1.2, One], [Y, 0, One]) + @unpack + def test_init_errors(self, hamiltonian, time, initial_state): + """Tests expected errors are thrown on invalid time argument.""" + with assert_raises(ValueError): + _ = EvolutionProblem(hamiltonian, time, initial_state) + + def test_validate_params(self): + """Tests expected errors are thrown on parameters mismatch.""" + param_x = Parameter("x") + param_y = Parameter("y") + with self.subTest(msg="Parameter missing in dict."): + hamiltonian = param_x * X + param_y * Y + param_dict = {param_y: 2} + evolution_problem = EvolutionProblem(hamiltonian, 2, Zero, param_value_dict=param_dict) + with assert_raises(ValueError): + evolution_problem.validate_params() + + with self.subTest(msg="Empty dict."): + hamiltonian = param_x * X + param_y * Y + param_dict = {} + evolution_problem = EvolutionProblem(hamiltonian, 2, Zero, param_value_dict=param_dict) + with assert_raises(ValueError): + evolution_problem.validate_params() + + with self.subTest(msg="Extra parameter in dict."): + hamiltonian = param_x * X + param_y * Y + param_dict = {param_y: 2, param_x: 1, Parameter("z"): 1} + evolution_problem = EvolutionProblem(hamiltonian, 2, Zero, param_value_dict=param_dict) + with assert_raises(ValueError): + evolution_problem.validate_params() + + +if __name__ == "__main__": + unittest.main() diff --git a/test/python/algorithms/time_evolvers/test_evolution_result.py b/test/python/algorithms/time_evolvers/test_evolution_result.py new file mode 100644 index 000000000000..5500b283a1cb --- /dev/null +++ b/test/python/algorithms/time_evolvers/test_evolution_result.py @@ -0,0 +1,48 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. +"""Class for testing evolution result.""" +import unittest + +from test.python.algorithms import QiskitAlgorithmsTestCase +from qiskit.algorithms.evolvers.evolution_result import EvolutionResult +from qiskit.opflow import Zero + + +class TestEvolutionResult(QiskitAlgorithmsTestCase): + """Class for testing evolution result and relevant metadata.""" + + def test_init_state(self): + """Tests that a class is initialized correctly with an evolved_state.""" + evolved_state = Zero + evo_result = EvolutionResult(evolved_state=evolved_state) + + expected_state = Zero + expected_aux_ops_evaluated = None + + self.assertEqual(evo_result.evolved_state, expected_state) + self.assertEqual(evo_result.aux_ops_evaluated, expected_aux_ops_evaluated) + + def test_init_observable(self): + """Tests that a class is initialized correctly with an evolved_observable.""" + evolved_state = Zero + evolved_aux_ops_evaluated = [(5j, 5j), (1.0, 8j), (5 + 1j, 6 + 1j)] + evo_result = EvolutionResult(evolved_state, evolved_aux_ops_evaluated) + + expected_state = Zero + expected_aux_ops_evaluated = [(5j, 5j), (1.0, 8j), (5 + 1j, 6 + 1j)] + + self.assertEqual(evo_result.evolved_state, expected_state) + self.assertEqual(evo_result.aux_ops_evaluated, expected_aux_ops_evaluated) + + +if __name__ == "__main__": + unittest.main() From 7a7c82be8f91653f7c857651d09491968c5b3213 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 30 Aug 2022 15:05:55 +0200 Subject: [PATCH 03/58] Mostly updated trotter_qrte.py to use primitives. --- .../time_evolvers/trotterization/__init__.py | 21 ++ .../trotterization/trotter_qrte.py | 183 +++++++++++++++ .../time_evolvers/trotterization/__init__.py | 11 + .../trotterization/test_trotter_qrte.py | 213 ++++++++++++++++++ 4 files changed, 428 insertions(+) create mode 100644 qiskit/algorithms/time_evolvers/trotterization/__init__.py create mode 100644 qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py create mode 100644 test/python/algorithms/time_evolvers/trotterization/__init__.py create mode 100644 test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py diff --git a/qiskit/algorithms/time_evolvers/trotterization/__init__.py b/qiskit/algorithms/time_evolvers/trotterization/__init__.py new file mode 100644 index 000000000000..fe1b8d8aedf2 --- /dev/null +++ b/qiskit/algorithms/time_evolvers/trotterization/__init__.py @@ -0,0 +1,21 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. +"""This package contains Trotterization-based Quantum Real Time Evolution algorithm. +It is compliant with the new Quantum Time Evolution Framework and makes use of +:class:`qiskit.synthesis.evolution.ProductFormula` and +:class:`~qiskit.circuit.library.PauliEvolutionGate` implementations. """ + +from qiskit.algorithms.evolvers.trotterization.trotter_qrte import ( + TrotterQRTE, +) + +__all__ = ["TrotterQRTE"] diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py new file mode 100644 index 000000000000..010dd0b618c8 --- /dev/null +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -0,0 +1,183 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""An algorithm to implement a Trotterization real time-evolution.""" + +from typing import Union, Optional + +from qiskit import QuantumCircuit +from qiskit.algorithms.evolvers import EvolutionProblem, EvolutionResult +from qiskit.algorithms.evolvers.real_evolver import RealEvolver +from qiskit.algorithms.observables_evaluator import eval_observables +from qiskit.opflow import ( + SummedOp, + PauliOp, + CircuitOp, + ExpectationBase, + CircuitSampler, + PauliSumOp, + StateFn, + OperatorBase, +) +from qiskit.circuit.library import PauliEvolutionGate +from qiskit.primitives import Estimator +from qiskit.providers import Backend +from qiskit.synthesis import ProductFormula, LieTrotter +from qiskit.utils import QuantumInstance + + +class TrotterQRTE(RealEvolver): + """Quantum Real Time Evolution using Trotterization. + Type of Trotterization is defined by a ProductFormula provided. + + Examples: + + .. jupyter-execute:: + + from qiskit.opflow import X, Z, Zero + from qiskit.algorithms import EvolutionProblem, TrotterQRTE + + operator = X + Z + initial_state = Zero + time = 1 + evolution_problem = EvolutionProblem(operator, 1, initial_state) + # LieTrotter with 1 rep + trotter_qrte = TrotterQRTE() + evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state + """ + + def __init__( + self, + product_formula: Optional[ProductFormula] = None, + estimator: Estimator = None, + ) -> None: + """ + Args: + product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter + first order product formula with a single repetition. + estimator: An estimator primitive used for calculating expectation values of + EvolutionProblem.aux_operators. + """ + if product_formula is None: + product_formula = LieTrotter() + self.product_formula = product_formula + self.estimator = estimator + + @classmethod + def supports_aux_operators(cls) -> bool: + """ + Whether computing the expectation value of auxiliary operators is supported. + + Returns: + True if ``aux_operators`` expectations in the EvolutionProblem can be evaluated, False + otherwise. + """ + return True + + def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: + """ + Evolves a quantum state for a given time using the Trotterization method + based on a product formula provided. The result is provided in the form of a quantum + circuit. If auxiliary operators are included in the ``evolution_problem``, they are + evaluated on an evolved state using an estimator primitive provided. + + .. note:: + Time-dependent Hamiltonians are not yet supported. + + Args: + evolution_problem: Instance defining evolution problem. For the included Hamiltonian, + ``PauliOp``, ``SummedOp`` or ``PauliSumOp`` are supported by TrotterQRTE. + + Returns: + Evolution result that includes an evolved state as a quantum circuit and, optionally, + auxiliary operators evaluated for a resulting state on an estimator primitive. + + Raises: + ValueError: If ``t_param`` is not set to None in the EvolutionProblem (feature not + currently supported). + ValueError: If the ``initial_state`` is not provided in the EvolutionProblem. + """ + evolution_problem.validate_params() + if evolution_problem.t_param is not None: + raise ValueError( + "TrotterQRTE does not accept a time dependent hamiltonian," + "``t_param`` from the EvolutionProblem should be set to None." + ) + + if evolution_problem.aux_operators is not None and ( + self.estimator is None + ): + raise ValueError( + "aux_operators were provided for evaluations but no ``estimator`` was provided." + ) + hamiltonian = evolution_problem.hamiltonian + if not isinstance(hamiltonian, (PauliOp, PauliSumOp, SummedOp)): + raise ValueError( + "TrotterQRTE only accepts PauliOp | " + f"PauliSumOp | SummedOp, {type(hamiltonian)} provided." + ) + if isinstance(hamiltonian, OperatorBase): + hamiltonian = hamiltonian.bind_parameters(evolution_problem.param_value_dict) + if isinstance(hamiltonian, SummedOp): + hamiltonian = self._summed_op_to_pauli_sum_op(hamiltonian) + # the evolution gate + evolution_gate = CircuitOp( + PauliEvolutionGate(hamiltonian, evolution_problem.time, synthesis=self.product_formula) + ) + + if evolution_problem.initial_state is not None: + initial_state = evolution_problem.initial_state + if isinstance(initial_state, QuantumCircuit): + initial_state = StateFn(initial_state) + evolved_state = evolution_gate @ initial_state + + else: + raise ValueError("``initial_state`` must be provided in the EvolutionProblem.") + + evaluated_aux_ops = None + if evolution_problem.aux_operators is not None: + evaluated_aux_ops = eval_observables( + self.estimator, + evolved_state.primitive, + evolution_problem.aux_operators, + evolution_problem.truncation_threshold, + ) + + return EvolutionResult(evolved_state, evaluated_aux_ops) + + @staticmethod + def _summed_op_to_pauli_sum_op( + hamiltonian: SummedOp, + ) -> Union[PauliSumOp, PauliOp]: + """ + Tries binding parameters in a Hamiltonian. + + Args: + hamiltonian: The Hamiltonian that defines an evolution. + + Returns: + Hamiltonian. + + Raises: + ValueError: If the ``SummedOp`` Hamiltonian contains operators of an invalid type. + """ + # PauliSumOp does not allow parametrized coefficients but after binding the parameters + # we need to convert it into a PauliSumOp for the PauliEvolutionGate. + op_list = [] + for op in hamiltonian.oplist: + if not isinstance(op, PauliOp): + raise ValueError( + "Content of the Hamiltonian not of type PauliOp. The " + f"following type detected: {type(op)}." + ) + op_list.append(op) + return sum(op_list) diff --git a/test/python/algorithms/time_evolvers/trotterization/__init__.py b/test/python/algorithms/time_evolvers/trotterization/__init__.py new file mode 100644 index 000000000000..96c0cf22bec9 --- /dev/null +++ b/test/python/algorithms/time_evolvers/trotterization/__init__.py @@ -0,0 +1,11 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. diff --git a/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py new file mode 100644 index 000000000000..75d30142c049 --- /dev/null +++ b/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py @@ -0,0 +1,213 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +""" Test TrotterQRTE. """ + +import unittest + +from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE +from qiskit.primitives import Estimator +from test.python.opflow import QiskitOpflowTestCase +from ddt import ddt, data, unpack +import numpy as np +from numpy.testing import assert_raises + +from qiskit import BasicAer, QuantumCircuit +from qiskit.circuit.library import ZGate +from qiskit.quantum_info import Statevector +from qiskit.utils import algorithm_globals, QuantumInstance +from qiskit.circuit import Parameter +from qiskit.opflow import ( + X, + Z, + Zero, + VectorStateFn, + StateFn, + I, + Y, + SummedOp, + ExpectationFactory, +) +from qiskit.synthesis import SuzukiTrotter, QDrift + + +@ddt +class TestTrotterQRTE(QiskitOpflowTestCase): + """TrotterQRTE tests.""" + + def setUp(self): + super().setUp() + self.seed = 50 + algorithm_globals.random_seed = self.seed + + @data( + ( + None, + VectorStateFn( + Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j], dims=(2,)) + ), + ), + ( + SuzukiTrotter(), + VectorStateFn(Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j], dims=(2,))), + ), + ) + @unpack + def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): + """Test for default TrotterQRTE on a single qubit.""" + operator = SummedOp([X, Z]) + initial_state = StateFn([1, 0]) + time = 1 + evolution_problem = EvolutionProblem(operator, time, initial_state) + + trotter_qrte = TrotterQRTE(product_formula=product_formula) + evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state + + np.testing.assert_equal(evolution_result_state_circuit.eval(), expected_state) + + def test_trotter_qrte_trotter_single_qubit_aux_ops(self): + """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" + operator = SummedOp([X, Z]) + # LieTrotter with 1 rep + aux_ops = [X, Y] + + initial_state = Zero + time = 3 + evolution_problem = EvolutionProblem(operator, time, initial_state, aux_ops) + estimator = Estimator() + + expected_evolved_state = VectorStateFn( + Statevector([0.98008514 + 0.13970775j, 0.01991486 + 0.13970775j], dims=(2,)) + ) + expected_aux_ops_evaluated = [(0.078073, 0.0), (0.268286, 0.0)] + expected_aux_ops_evaluated_qasm = [ + (0.05799999999999995, 0.011161518713866855), + (0.2495, 0.010826759383582883), + ] + + algorithm_globals.random_seed = 0 + trotter_qrte = TrotterQRTE(estimator=estimator) + evolution_result = trotter_qrte.evolve(evolution_problem) + + np.testing.assert_equal( + evolution_result.evolved_state.eval(), expected_evolved_state + ) + + np.testing.assert_array_almost_equal( + evolution_result.aux_ops_evaluated, expected_aux_ops_evaluated + ) + + @data( + ( + SummedOp([(X ^ Y), (Y ^ X)]), + VectorStateFn( + Statevector( + [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j], dims=(2, 2) + ) + ), + ), + ( + (Z ^ Z) + (Z ^ I) + (I ^ Z), + VectorStateFn( + Statevector( + [-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2) + ) + ), + ), + ( + Y ^ Y, + VectorStateFn( + Statevector( + [0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j], dims=(2, 2) + ) + ), + ), + ) + @unpack + def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): + """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" + # LieTrotter with 1 rep + initial_state = StateFn([1, 0, 0, 0]) + evolution_problem = EvolutionProblem(operator, 1, initial_state) + + trotter_qrte = TrotterQRTE() + evolution_result = trotter_qrte.evolve(evolution_problem) + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + + def test_trotter_qrte_trotter_two_qubits_with_params(self): + """Test for TrotterQRTE on two qubits with a parametrized Hamiltonian.""" + # LieTrotter with 1 rep + initial_state = StateFn([1, 0, 0, 0]) + w_param = Parameter("w") + u_param = Parameter("u") + params_dict = {w_param: 2.0, u_param: 3.0} + operator = w_param * (Z ^ Z) / 2.0 + (Z ^ I) + u_param * (I ^ Z) / 3.0 + time = 1 + evolution_problem = EvolutionProblem( + operator, time, initial_state, param_value_dict=params_dict + ) + expected_state = VectorStateFn( + Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2)) + ) + trotter_qrte = TrotterQRTE() + evolution_result = trotter_qrte.evolve(evolution_problem) + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + + @data( + ( + Zero, + VectorStateFn( + Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) + ), + ), + ( + QuantumCircuit(1).compose(ZGate(), [0]), + VectorStateFn( + Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) + ), + ), + ) + @unpack + def test_trotter_qrte_qdrift(self, initial_state, expected_state): + """Test for TrotterQRTE with QDrift.""" + operator = SummedOp([X, Z]) + time = 1 + evolution_problem = EvolutionProblem(operator, time, initial_state) + + algorithm_globals.random_seed = 0 + trotter_qrte = TrotterQRTE(product_formula=QDrift()) + evolution_result = trotter_qrte.evolve(evolution_problem) + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + + @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) + @unpack + def test_trotter_qrte_trotter_errors(self, t_param, param_value_dict): + """Test TrotterQRTE with raising errors.""" + operator = X * Parameter("t") + Z + initial_state = Zero + time = 1 + algorithm_globals.random_seed = 0 + trotter_qrte = TrotterQRTE() + with assert_raises(ValueError): + evolution_problem = EvolutionProblem( + operator, + time, + initial_state, + t_param=t_param, + param_value_dict=param_value_dict, + ) + _ = trotter_qrte.evolve(evolution_problem) + + +if __name__ == "__main__": + unittest.main() From 54afe2519fc1b435a33a0ffe32ecf7c00a715c7b Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 1 Sep 2022 14:14:15 +0200 Subject: [PATCH 04/58] Added observables_evaluator.py that uses primitives. --- qiskit/algorithms/observables_evaluator.py | 81 ++++--------------- .../algorithms/test_observables_evaluator.py | 3 +- 2 files changed, 18 insertions(+), 66 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 3ed9c6757f91..dba83b308940 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -11,36 +11,26 @@ # that they have been altered from the originals. """Evaluator of auxiliary operators for algorithms.""" -from typing import Tuple, Union, List, Iterable, Sequence, Optional +from typing import Tuple, Union, List, Sequence, Optional import numpy as np from qiskit import QuantumCircuit from qiskit.opflow import ( - CircuitSampler, - ListOp, - StateFn, - OperatorBase, - ExpectationBase, PauliSumOp, ) -from qiskit.providers import Backend -from qiskit.quantum_info import Statevector -from qiskit.utils import QuantumInstance - -from .list_or_dict import ListOrDict from ..primitives import Estimator, EstimatorResult from ..quantum_info.operators.base_operator import BaseOperator def eval_observables( estimator: Estimator, - quantum_state: Sequence[QuantumCircuit], + quantum_state: QuantumCircuit, observables: Sequence[Union[BaseOperator, PauliSumOp]], threshold: float = 1e-12, -) -> ListOrDict[Tuple[complex, complex]]: +) -> List[Tuple[complex, complex]]: """ - Accepts a list or a dictionary of operators and calculates their expectation values - means + Accepts a sequence of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user can optionally provide a threshold value which filters mean values falling below the threshold. @@ -48,22 +38,19 @@ def eval_observables( estimator: An estimator primitive used for calculations. quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. - observables: A sequence of operators whose expectation values are to be - calculated. + observables: A sequence of operators whose expectation values are to be calculated. threshold: A threshold value that defines which mean values should be neglected (helpful for ignoring numerical instabilities close to 0). Returns: - A list or a dictionary of tuples (mean, standard deviation). + A list of tuples (mean, standard deviation). Raises: ValueError: If a ``quantum_state`` with free parameters is provided. """ if ( - isinstance( - quantum_state, (QuantumCircuit, OperatorBase) - ) # Statevector cannot be parametrized + isinstance(quantum_state, QuantumCircuit) # Statevector cannot be parametrized and len(quantum_state.parameters) > 0 ): raise ValueError( @@ -71,10 +58,7 @@ def eval_observables( "allowed - it cannot have free parameters." ) - # if type(observables) != Sequence: - # observables = [observables] - # if type(quantum_state) != Sequence: - # quantum_state = [quantum_state] + quantum_state = [quantum_state] * len(observables) estimator_job = estimator.run(quantum_state, observables) expectation_values = estimator_job.result().values @@ -87,61 +71,30 @@ def eval_observables( observables_results = list(zip(observables_means, std_devs)) # Return None eigenvalues for None operators if observables is a list. - # None operators are already dropped in compute_minimum_eigenvalue if observables is a dict. return _prepare_result(observables_results, observables) -def _prepare_list_op( - quantum_state: Union[ - Statevector, - QuantumCircuit, - OperatorBase, - ], - observables: ListOrDict[OperatorBase], -) -> ListOp: - """ - Accepts a list or a dictionary of operators and converts them to a ``ListOp``. - - Args: - quantum_state: An unparametrized quantum circuit representing a quantum state that - expectation values are computed against. - observables: A list or a dictionary of operators. - - Returns: - A ``ListOp`` that includes all provided observables. - """ - if isinstance(observables, dict): - observables = list(observables.values()) - - if not isinstance(quantum_state, StateFn): - quantum_state = StateFn(quantum_state) - - return ListOp([StateFn(obs, is_measurement=True).compose(quantum_state) for obs in observables]) - - def _prepare_result( observables_results: List[Tuple[complex, complex]], - observables: ListOrDict[OperatorBase], -) -> ListOrDict[Tuple[complex, complex]]: + observables: Sequence[BaseOperator], +) -> List[Tuple[complex, complex]]: """ - Prepares a list or a dictionary of eigenvalues from ``observables_results`` and + Prepares a list of eigenvalues and standard deviations from ``observables_results`` and ``observables``. Args: observables_results: A list of of tuples (mean, standard deviation). - observables: A list or a dictionary of operators whose expectation values are to be + observables: A list of operators whose expectation values are to be calculated. Returns: - A list or a dictionary of tuples (mean, standard deviation). + A list of tuples (mean, standard deviation). """ - if isinstance(observables, list): - observables_eigenvalues = [None] * len(observables) - key_value_iterator = enumerate(observables_results) - else: - observables_eigenvalues = {} - key_value_iterator = zip(observables.keys(), observables_results) + + observables_eigenvalues = [None] * len(observables) + key_value_iterator = enumerate(observables_results) + for key, value in key_value_iterator: if observables[key] is not None: observables_eigenvalues[key] = value diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index ea9b3560746f..88e256084fea 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -13,13 +13,12 @@ import unittest from typing import Tuple, Sequence, List - +from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data from qiskit.algorithms.observables_evaluator import eval_observables from qiskit.primitives import Estimator -from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit.quantum_info import Statevector from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 From d2b67d9cda8dfbfd857ec1f711f3bf8a77750de8 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 1 Sep 2022 14:15:25 +0200 Subject: [PATCH 05/58] Added observables_evaluator.py that uses primitives. --- test/python/algorithms/test_observables_evaluator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 88e256084fea..f9716fb0ee64 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -83,7 +83,7 @@ def test_eval_observables(self, observables: Sequence[OperatorBase]): ) bound_ansatz = ansatz.bind_parameters(parameters) - states = [bound_ansatz] * len(observables) + states = bound_ansatz expected_result = self.get_exact_expectation(bound_ansatz, observables) estimator = Estimator() decimal = 6 From c1276d2c5a4573fc8428df3c9aafe1cbd3a9c8bb Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 1 Sep 2022 14:15:49 +0200 Subject: [PATCH 06/58] Updated trotter_qrte.py to use primitives. --- .../trotterization/trotter_qrte.py | 8 +------ .../trotterization/test_trotter_qrte.py | 24 +++++++------------ 2 files changed, 9 insertions(+), 23 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 010dd0b618c8..9c41ac748b2a 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -22,17 +22,13 @@ SummedOp, PauliOp, CircuitOp, - ExpectationBase, - CircuitSampler, PauliSumOp, StateFn, OperatorBase, ) from qiskit.circuit.library import PauliEvolutionGate from qiskit.primitives import Estimator -from qiskit.providers import Backend from qiskit.synthesis import ProductFormula, LieTrotter -from qiskit.utils import QuantumInstance class TrotterQRTE(RealEvolver): @@ -113,9 +109,7 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: "``t_param`` from the EvolutionProblem should be set to None." ) - if evolution_problem.aux_operators is not None and ( - self.estimator is None - ): + if evolution_problem.aux_operators is not None and (self.estimator is None): raise ValueError( "aux_operators were provided for evaluations but no ``estimator`` was provided." ) diff --git a/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py index 75d30142c049..91240c6423e1 100644 --- a/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py @@ -13,19 +13,18 @@ """ Test TrotterQRTE. """ import unittest - -from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem -from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE -from qiskit.primitives import Estimator from test.python.opflow import QiskitOpflowTestCase from ddt import ddt, data, unpack import numpy as np from numpy.testing import assert_raises -from qiskit import BasicAer, QuantumCircuit +from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE +from qiskit.primitives import Estimator +from qiskit import QuantumCircuit from qiskit.circuit.library import ZGate -from qiskit.quantum_info import Statevector -from qiskit.utils import algorithm_globals, QuantumInstance +from qiskit.quantum_info import Statevector, Pauli +from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.opflow import ( X, @@ -36,7 +35,6 @@ I, Y, SummedOp, - ExpectationFactory, ) from qiskit.synthesis import SuzukiTrotter, QDrift @@ -79,7 +77,7 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" operator = SummedOp([X, Z]) # LieTrotter with 1 rep - aux_ops = [X, Y] + aux_ops = [Pauli("X"), Pauli("Y")] initial_state = Zero time = 3 @@ -90,18 +88,12 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): Statevector([0.98008514 + 0.13970775j, 0.01991486 + 0.13970775j], dims=(2,)) ) expected_aux_ops_evaluated = [(0.078073, 0.0), (0.268286, 0.0)] - expected_aux_ops_evaluated_qasm = [ - (0.05799999999999995, 0.011161518713866855), - (0.2495, 0.010826759383582883), - ] algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_equal( - evolution_result.evolved_state.eval(), expected_evolved_state - ) + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_evolved_state) np.testing.assert_array_almost_equal( evolution_result.aux_ops_evaluated, expected_aux_ops_evaluated From e06c6c28c0f75a5407127634263d79142ff4ff73 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 1 Sep 2022 14:16:49 +0200 Subject: [PATCH 07/58] Updated imports --- .../algorithms/time_evolvers/trotterization/trotter_qrte.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 9c41ac748b2a..a29a1739a65a 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -15,9 +15,10 @@ from typing import Union, Optional from qiskit import QuantumCircuit -from qiskit.algorithms.evolvers import EvolutionProblem, EvolutionResult -from qiskit.algorithms.evolvers.real_evolver import RealEvolver from qiskit.algorithms.observables_evaluator import eval_observables +from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult +from qiskit.algorithms.time_evolvers.real_evolver import RealEvolver from qiskit.opflow import ( SummedOp, PauliOp, From 5a9bebe9880329dd94089e369d72f3c0bdacee89 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 10:37:51 +0200 Subject: [PATCH 08/58] Updated typehints and limited use of opflow. --- .../time_evolvers/evolution_problem.py | 35 +-- .../time_evolvers/evolution_result.py | 7 +- .../time_evolvers/trotterization/__init__.py | 21 -- .../trotterization/trotter_qrte.py | 178 --------------- .../time_evolvers/test_evolution_problem.py | 26 +-- .../time_evolvers/test_evolution_result.py | 2 +- .../time_evolvers/trotterization/__init__.py | 11 - .../trotterization/test_trotter_qrte.py | 205 ------------------ 8 files changed, 21 insertions(+), 464 deletions(-) delete mode 100644 qiskit/algorithms/time_evolvers/trotterization/__init__.py delete mode 100644 qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py delete mode 100644 test/python/algorithms/time_evolvers/trotterization/__init__.py delete mode 100644 test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py diff --git a/qiskit/algorithms/time_evolvers/evolution_problem.py b/qiskit/algorithms/time_evolvers/evolution_problem.py index 175beecd6bf6..8ea90f77f690 100644 --- a/qiskit/algorithms/time_evolvers/evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/evolution_problem.py @@ -12,12 +12,13 @@ """Evolution problem class.""" -from typing import Union, Optional, Dict +from typing import Dict from qiskit import QuantumCircuit from qiskit.circuit import Parameter -from qiskit.opflow import OperatorBase, StateFn +from qiskit.opflow import PauliSumOp from ..list_or_dict import ListOrDict +from ...quantum_info.operators.base_operator import BaseOperator class EvolutionProblem: @@ -29,13 +30,14 @@ class EvolutionProblem: def __init__( self, - hamiltonian: OperatorBase, + hamiltonian: BaseOperator | PauliSumOp, time: float, - initial_state: Optional[Union[StateFn, QuantumCircuit]] = None, - aux_operators: Optional[ListOrDict[OperatorBase]] = None, + initial_state: QuantumCircuit | None = None, + aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, - t_param: Optional[Parameter] = None, - param_value_dict: Optional[Dict[Parameter, complex]] = None, + t_param: Parameter | None = None, + param_value_dict: Dict[Parameter, complex] + | None = None, # parametrization will become supported in BaseOperator soon ): """ Args: @@ -90,20 +92,5 @@ def validate_params(self) -> None: Raises: ValueError: If Hamiltonian parameters cannot be bound with data provided. """ - if isinstance(self.hamiltonian, OperatorBase): - t_param_set = set() - if self.t_param is not None: - t_param_set.add(self.t_param) - hamiltonian_dict_param_set = set() - if self.param_value_dict is not None: - hamiltonian_dict_param_set = hamiltonian_dict_param_set.union( - set(self.param_value_dict.keys()) - ) - params_set = t_param_set.union(hamiltonian_dict_param_set) - hamiltonian_param_set = set(self.hamiltonian.parameters) - - if hamiltonian_param_set != params_set: - raise ValueError( - f"Provided parameters {params_set} do not match Hamiltonian parameters " - f"{hamiltonian_param_set}." - ) + if isinstance(self.hamiltonian, PauliSumOp) and self.hamiltonian.parameters: + raise ValueError("A global parametrized coefficient for PauliSumOp is not allowed.") diff --git a/qiskit/algorithms/time_evolvers/evolution_result.py b/qiskit/algorithms/time_evolvers/evolution_result.py index 1dd91d705d28..55a3fad31032 100644 --- a/qiskit/algorithms/time_evolvers/evolution_result.py +++ b/qiskit/algorithms/time_evolvers/evolution_result.py @@ -12,11 +12,10 @@ """Class for holding evolution result.""" -from typing import Optional, Union, Tuple +from typing import Tuple from qiskit import QuantumCircuit from qiskit.algorithms.list_or_dict import ListOrDict -from qiskit.opflow import StateFn, OperatorBase from ..algorithm_result import AlgorithmResult @@ -25,8 +24,8 @@ class EvolutionResult(AlgorithmResult): def __init__( self, - evolved_state: Union[StateFn, QuantumCircuit, OperatorBase], - aux_ops_evaluated: Optional[ListOrDict[Tuple[complex, complex]]] = None, + evolved_state: QuantumCircuit, + aux_ops_evaluated: ListOrDict[Tuple[complex, complex]] | None = None, ): """ Args: diff --git a/qiskit/algorithms/time_evolvers/trotterization/__init__.py b/qiskit/algorithms/time_evolvers/trotterization/__init__.py deleted file mode 100644 index fe1b8d8aedf2..000000000000 --- a/qiskit/algorithms/time_evolvers/trotterization/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2021, 2022. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. -"""This package contains Trotterization-based Quantum Real Time Evolution algorithm. -It is compliant with the new Quantum Time Evolution Framework and makes use of -:class:`qiskit.synthesis.evolution.ProductFormula` and -:class:`~qiskit.circuit.library.PauliEvolutionGate` implementations. """ - -from qiskit.algorithms.evolvers.trotterization.trotter_qrte import ( - TrotterQRTE, -) - -__all__ = ["TrotterQRTE"] diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py deleted file mode 100644 index a29a1739a65a..000000000000 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ /dev/null @@ -1,178 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2021, 2022. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -"""An algorithm to implement a Trotterization real time-evolution.""" - -from typing import Union, Optional - -from qiskit import QuantumCircuit -from qiskit.algorithms.observables_evaluator import eval_observables -from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem -from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult -from qiskit.algorithms.time_evolvers.real_evolver import RealEvolver -from qiskit.opflow import ( - SummedOp, - PauliOp, - CircuitOp, - PauliSumOp, - StateFn, - OperatorBase, -) -from qiskit.circuit.library import PauliEvolutionGate -from qiskit.primitives import Estimator -from qiskit.synthesis import ProductFormula, LieTrotter - - -class TrotterQRTE(RealEvolver): - """Quantum Real Time Evolution using Trotterization. - Type of Trotterization is defined by a ProductFormula provided. - - Examples: - - .. jupyter-execute:: - - from qiskit.opflow import X, Z, Zero - from qiskit.algorithms import EvolutionProblem, TrotterQRTE - - operator = X + Z - initial_state = Zero - time = 1 - evolution_problem = EvolutionProblem(operator, 1, initial_state) - # LieTrotter with 1 rep - trotter_qrte = TrotterQRTE() - evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state - """ - - def __init__( - self, - product_formula: Optional[ProductFormula] = None, - estimator: Estimator = None, - ) -> None: - """ - Args: - product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter - first order product formula with a single repetition. - estimator: An estimator primitive used for calculating expectation values of - EvolutionProblem.aux_operators. - """ - if product_formula is None: - product_formula = LieTrotter() - self.product_formula = product_formula - self.estimator = estimator - - @classmethod - def supports_aux_operators(cls) -> bool: - """ - Whether computing the expectation value of auxiliary operators is supported. - - Returns: - True if ``aux_operators`` expectations in the EvolutionProblem can be evaluated, False - otherwise. - """ - return True - - def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: - """ - Evolves a quantum state for a given time using the Trotterization method - based on a product formula provided. The result is provided in the form of a quantum - circuit. If auxiliary operators are included in the ``evolution_problem``, they are - evaluated on an evolved state using an estimator primitive provided. - - .. note:: - Time-dependent Hamiltonians are not yet supported. - - Args: - evolution_problem: Instance defining evolution problem. For the included Hamiltonian, - ``PauliOp``, ``SummedOp`` or ``PauliSumOp`` are supported by TrotterQRTE. - - Returns: - Evolution result that includes an evolved state as a quantum circuit and, optionally, - auxiliary operators evaluated for a resulting state on an estimator primitive. - - Raises: - ValueError: If ``t_param`` is not set to None in the EvolutionProblem (feature not - currently supported). - ValueError: If the ``initial_state`` is not provided in the EvolutionProblem. - """ - evolution_problem.validate_params() - if evolution_problem.t_param is not None: - raise ValueError( - "TrotterQRTE does not accept a time dependent hamiltonian," - "``t_param`` from the EvolutionProblem should be set to None." - ) - - if evolution_problem.aux_operators is not None and (self.estimator is None): - raise ValueError( - "aux_operators were provided for evaluations but no ``estimator`` was provided." - ) - hamiltonian = evolution_problem.hamiltonian - if not isinstance(hamiltonian, (PauliOp, PauliSumOp, SummedOp)): - raise ValueError( - "TrotterQRTE only accepts PauliOp | " - f"PauliSumOp | SummedOp, {type(hamiltonian)} provided." - ) - if isinstance(hamiltonian, OperatorBase): - hamiltonian = hamiltonian.bind_parameters(evolution_problem.param_value_dict) - if isinstance(hamiltonian, SummedOp): - hamiltonian = self._summed_op_to_pauli_sum_op(hamiltonian) - # the evolution gate - evolution_gate = CircuitOp( - PauliEvolutionGate(hamiltonian, evolution_problem.time, synthesis=self.product_formula) - ) - - if evolution_problem.initial_state is not None: - initial_state = evolution_problem.initial_state - if isinstance(initial_state, QuantumCircuit): - initial_state = StateFn(initial_state) - evolved_state = evolution_gate @ initial_state - - else: - raise ValueError("``initial_state`` must be provided in the EvolutionProblem.") - - evaluated_aux_ops = None - if evolution_problem.aux_operators is not None: - evaluated_aux_ops = eval_observables( - self.estimator, - evolved_state.primitive, - evolution_problem.aux_operators, - evolution_problem.truncation_threshold, - ) - - return EvolutionResult(evolved_state, evaluated_aux_ops) - - @staticmethod - def _summed_op_to_pauli_sum_op( - hamiltonian: SummedOp, - ) -> Union[PauliSumOp, PauliOp]: - """ - Tries binding parameters in a Hamiltonian. - - Args: - hamiltonian: The Hamiltonian that defines an evolution. - - Returns: - Hamiltonian. - - Raises: - ValueError: If the ``SummedOp`` Hamiltonian contains operators of an invalid type. - """ - # PauliSumOp does not allow parametrized coefficients but after binding the parameters - # we need to convert it into a PauliSumOp for the PauliEvolutionGate. - op_list = [] - for op in hamiltonian.oplist: - if not isinstance(op, PauliOp): - raise ValueError( - "Content of the Hamiltonian not of type PauliOp. The " - f"following type detected: {type(op)}." - ) - op_list.append(op) - return sum(op_list) diff --git a/test/python/algorithms/time_evolvers/test_evolution_problem.py b/test/python/algorithms/time_evolvers/test_evolution_problem.py index d3dd2f7bc9b2..d7d55500abfb 100644 --- a/test/python/algorithms/time_evolvers/test_evolution_problem.py +++ b/test/python/algorithms/time_evolvers/test_evolution_problem.py @@ -12,13 +12,15 @@ """Test evolver problem class.""" import unittest + +from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.quantum_info import Pauli, SparsePauliOp from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack from numpy.testing import assert_raises -from qiskit.algorithms.evolvers.evolution_problem import EvolutionProblem from qiskit.circuit import Parameter -from qiskit.opflow import Y, Z, One, X, Zero +from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp @ddt @@ -89,25 +91,9 @@ def test_init_errors(self, hamiltonian, time, initial_state): def test_validate_params(self): """Tests expected errors are thrown on parameters mismatch.""" param_x = Parameter("x") - param_y = Parameter("y") with self.subTest(msg="Parameter missing in dict."): - hamiltonian = param_x * X + param_y * Y - param_dict = {param_y: 2} - evolution_problem = EvolutionProblem(hamiltonian, 2, Zero, param_value_dict=param_dict) - with assert_raises(ValueError): - evolution_problem.validate_params() - - with self.subTest(msg="Empty dict."): - hamiltonian = param_x * X + param_y * Y - param_dict = {} - evolution_problem = EvolutionProblem(hamiltonian, 2, Zero, param_value_dict=param_dict) - with assert_raises(ValueError): - evolution_problem.validate_params() - - with self.subTest(msg="Extra parameter in dict."): - hamiltonian = param_x * X + param_y * Y - param_dict = {param_y: 2, param_x: 1, Parameter("z"): 1} - evolution_problem = EvolutionProblem(hamiltonian, 2, Zero, param_value_dict=param_dict) + hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x) + evolution_problem = EvolutionProblem(hamiltonian, 2, Zero) with assert_raises(ValueError): evolution_problem.validate_params() diff --git a/test/python/algorithms/time_evolvers/test_evolution_result.py b/test/python/algorithms/time_evolvers/test_evolution_result.py index 5500b283a1cb..3c599f2eb1b4 100644 --- a/test/python/algorithms/time_evolvers/test_evolution_result.py +++ b/test/python/algorithms/time_evolvers/test_evolution_result.py @@ -12,8 +12,8 @@ """Class for testing evolution result.""" import unittest +from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult from test.python.algorithms import QiskitAlgorithmsTestCase -from qiskit.algorithms.evolvers.evolution_result import EvolutionResult from qiskit.opflow import Zero diff --git a/test/python/algorithms/time_evolvers/trotterization/__init__.py b/test/python/algorithms/time_evolvers/trotterization/__init__.py deleted file mode 100644 index 96c0cf22bec9..000000000000 --- a/test/python/algorithms/time_evolvers/trotterization/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2021. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. diff --git a/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py deleted file mode 100644 index 91240c6423e1..000000000000 --- a/test/python/algorithms/time_evolvers/trotterization/test_trotter_qrte.py +++ /dev/null @@ -1,205 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2021, 2022. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. - -""" Test TrotterQRTE. """ - -import unittest -from test.python.opflow import QiskitOpflowTestCase -from ddt import ddt, data, unpack -import numpy as np -from numpy.testing import assert_raises - -from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem -from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE -from qiskit.primitives import Estimator -from qiskit import QuantumCircuit -from qiskit.circuit.library import ZGate -from qiskit.quantum_info import Statevector, Pauli -from qiskit.utils import algorithm_globals -from qiskit.circuit import Parameter -from qiskit.opflow import ( - X, - Z, - Zero, - VectorStateFn, - StateFn, - I, - Y, - SummedOp, -) -from qiskit.synthesis import SuzukiTrotter, QDrift - - -@ddt -class TestTrotterQRTE(QiskitOpflowTestCase): - """TrotterQRTE tests.""" - - def setUp(self): - super().setUp() - self.seed = 50 - algorithm_globals.random_seed = self.seed - - @data( - ( - None, - VectorStateFn( - Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j], dims=(2,)) - ), - ), - ( - SuzukiTrotter(), - VectorStateFn(Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j], dims=(2,))), - ), - ) - @unpack - def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): - """Test for default TrotterQRTE on a single qubit.""" - operator = SummedOp([X, Z]) - initial_state = StateFn([1, 0]) - time = 1 - evolution_problem = EvolutionProblem(operator, time, initial_state) - - trotter_qrte = TrotterQRTE(product_formula=product_formula) - evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state - - np.testing.assert_equal(evolution_result_state_circuit.eval(), expected_state) - - def test_trotter_qrte_trotter_single_qubit_aux_ops(self): - """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" - operator = SummedOp([X, Z]) - # LieTrotter with 1 rep - aux_ops = [Pauli("X"), Pauli("Y")] - - initial_state = Zero - time = 3 - evolution_problem = EvolutionProblem(operator, time, initial_state, aux_ops) - estimator = Estimator() - - expected_evolved_state = VectorStateFn( - Statevector([0.98008514 + 0.13970775j, 0.01991486 + 0.13970775j], dims=(2,)) - ) - expected_aux_ops_evaluated = [(0.078073, 0.0), (0.268286, 0.0)] - - algorithm_globals.random_seed = 0 - trotter_qrte = TrotterQRTE(estimator=estimator) - evolution_result = trotter_qrte.evolve(evolution_problem) - - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_evolved_state) - - np.testing.assert_array_almost_equal( - evolution_result.aux_ops_evaluated, expected_aux_ops_evaluated - ) - - @data( - ( - SummedOp([(X ^ Y), (Y ^ X)]), - VectorStateFn( - Statevector( - [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j], dims=(2, 2) - ) - ), - ), - ( - (Z ^ Z) + (Z ^ I) + (I ^ Z), - VectorStateFn( - Statevector( - [-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2) - ) - ), - ), - ( - Y ^ Y, - VectorStateFn( - Statevector( - [0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j], dims=(2, 2) - ) - ), - ), - ) - @unpack - def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): - """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" - # LieTrotter with 1 rep - initial_state = StateFn([1, 0, 0, 0]) - evolution_problem = EvolutionProblem(operator, 1, initial_state) - - trotter_qrte = TrotterQRTE() - evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) - - def test_trotter_qrte_trotter_two_qubits_with_params(self): - """Test for TrotterQRTE on two qubits with a parametrized Hamiltonian.""" - # LieTrotter with 1 rep - initial_state = StateFn([1, 0, 0, 0]) - w_param = Parameter("w") - u_param = Parameter("u") - params_dict = {w_param: 2.0, u_param: 3.0} - operator = w_param * (Z ^ Z) / 2.0 + (Z ^ I) + u_param * (I ^ Z) / 3.0 - time = 1 - evolution_problem = EvolutionProblem( - operator, time, initial_state, param_value_dict=params_dict - ) - expected_state = VectorStateFn( - Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2)) - ) - trotter_qrte = TrotterQRTE() - evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) - - @data( - ( - Zero, - VectorStateFn( - Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) - ), - ), - ( - QuantumCircuit(1).compose(ZGate(), [0]), - VectorStateFn( - Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) - ), - ), - ) - @unpack - def test_trotter_qrte_qdrift(self, initial_state, expected_state): - """Test for TrotterQRTE with QDrift.""" - operator = SummedOp([X, Z]) - time = 1 - evolution_problem = EvolutionProblem(operator, time, initial_state) - - algorithm_globals.random_seed = 0 - trotter_qrte = TrotterQRTE(product_formula=QDrift()) - evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) - - @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) - @unpack - def test_trotter_qrte_trotter_errors(self, t_param, param_value_dict): - """Test TrotterQRTE with raising errors.""" - operator = X * Parameter("t") + Z - initial_state = Zero - time = 1 - algorithm_globals.random_seed = 0 - trotter_qrte = TrotterQRTE() - with assert_raises(ValueError): - evolution_problem = EvolutionProblem( - operator, - time, - initial_state, - t_param=t_param, - param_value_dict=param_value_dict, - ) - _ = trotter_qrte.evolve(evolution_problem) - - -if __name__ == "__main__": - unittest.main() From 356deae49a90d21fd5b8777be0b9060c29c89aef Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 10:43:04 +0200 Subject: [PATCH 09/58] Updated typehints and limited use of opflow. --- qiskit/algorithms/observables_evaluator.py | 12 ++++++------ test/python/algorithms/test_observables_evaluator.py | 11 +++++++---- 2 files changed, 13 insertions(+), 10 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index dba83b308940..e0096e0a7cf1 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -11,7 +11,7 @@ # that they have been altered from the originals. """Evaluator of auxiliary operators for algorithms.""" -from typing import Tuple, Union, List, Sequence, Optional +from typing import Tuple, List, Sequence import numpy as np @@ -19,14 +19,14 @@ from qiskit.opflow import ( PauliSumOp, ) -from ..primitives import Estimator, EstimatorResult +from ..primitives import EstimatorResult, BaseEstimator from ..quantum_info.operators.base_operator import BaseOperator def eval_observables( - estimator: Estimator, + estimator: BaseEstimator, quantum_state: QuantumCircuit, - observables: Sequence[Union[BaseOperator, PauliSumOp]], + observables: Sequence[BaseOperator | PauliSumOp], threshold: float = 1e-12, ) -> List[Tuple[complex, complex]]: """ @@ -77,7 +77,7 @@ def eval_observables( def _prepare_result( observables_results: List[Tuple[complex, complex]], - observables: Sequence[BaseOperator], + observables: Sequence[BaseOperator | PauliSumOp], ) -> List[Tuple[complex, complex]]: """ Prepares a list of eigenvalues and standard deviations from ``observables_results`` and @@ -104,7 +104,7 @@ def _prepare_result( def _compute_std_devs( estimator_result: EstimatorResult, results_length: int, -) -> List[Optional[complex]]: +) -> List[complex | None]: """ Calculates a list of standard deviations from expectation values of observables provided. diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index f9716fb0ee64..0951c7690f5a 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -13,6 +13,8 @@ import unittest from typing import Tuple, Sequence, List + +from qiskit.quantum_info.operators.base_operator import BaseOperator from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data @@ -24,7 +26,6 @@ from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import ( PauliSumOp, - OperatorBase, ) from qiskit.utils import algorithm_globals @@ -40,7 +41,9 @@ def setUp(self): self.threshold = 1e-8 - def get_exact_expectation(self, ansatz: QuantumCircuit, observables: Sequence[OperatorBase]): + def get_exact_expectation( + self, ansatz: QuantumCircuit, observables: Sequence[BaseOperator | PauliSumOp] + ): """ Calculates the exact expectation to be used as an expected result for unit tests. """ @@ -57,7 +60,7 @@ def _run_test( expected_result: List[Tuple[complex, complex]], quantum_state: Sequence[QuantumCircuit], decimal: int, - observables: Sequence[OperatorBase], + observables: Sequence[BaseOperator | PauliSumOp], estimator: Estimator, ): result = eval_observables(estimator, quantum_state, observables, self.threshold) @@ -73,7 +76,7 @@ def _run_test( PauliSumOp.from_list([("ZZ", 2.0)]), ], ) - def test_eval_observables(self, observables: Sequence[OperatorBase]): + def test_eval_observables(self, observables: Sequence[BaseOperator | PauliSumOp]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) From 14ba35da98ee928632745345e0ebe14f427f36b9 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 11:10:37 +0200 Subject: [PATCH 10/58] Removed files out of scope for this PR. --- qiskit/algorithms/observables_evaluator.py | 130 ------------------ .../algorithms/test_observables_evaluator.py | 103 -------------- .../time_evolvers/test_evolution_problem.py | 5 +- .../time_evolvers/test_evolution_result.py | 3 +- 4 files changed, 3 insertions(+), 238 deletions(-) delete mode 100644 qiskit/algorithms/observables_evaluator.py delete mode 100644 test/python/algorithms/test_observables_evaluator.py diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py deleted file mode 100644 index e0096e0a7cf1..000000000000 --- a/qiskit/algorithms/observables_evaluator.py +++ /dev/null @@ -1,130 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2021, 2022. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. -"""Evaluator of auxiliary operators for algorithms.""" - -from typing import Tuple, List, Sequence - -import numpy as np - -from qiskit import QuantumCircuit -from qiskit.opflow import ( - PauliSumOp, -) -from ..primitives import EstimatorResult, BaseEstimator -from ..quantum_info.operators.base_operator import BaseOperator - - -def eval_observables( - estimator: BaseEstimator, - quantum_state: QuantumCircuit, - observables: Sequence[BaseOperator | PauliSumOp], - threshold: float = 1e-12, -) -> List[Tuple[complex, complex]]: - """ - Accepts a sequence of operators and calculates their expectation values - means - and standard deviations. They are calculated with respect to a quantum state provided. A user - can optionally provide a threshold value which filters mean values falling below the threshold. - - Args: - estimator: An estimator primitive used for calculations. - quantum_state: An unparametrized quantum circuit representing a quantum state that - expectation values are computed against. - observables: A sequence of operators whose expectation values are to be calculated. - threshold: A threshold value that defines which mean values should be neglected (helpful for - ignoring numerical instabilities close to 0). - - Returns: - A list of tuples (mean, standard deviation). - - Raises: - ValueError: If a ``quantum_state`` with free parameters is provided. - """ - - if ( - isinstance(quantum_state, QuantumCircuit) # Statevector cannot be parametrized - and len(quantum_state.parameters) > 0 - ): - raise ValueError( - "A parametrized representation of a quantum_state was provided. It is not " - "allowed - it cannot have free parameters." - ) - - quantum_state = [quantum_state] * len(observables) - estimator_job = estimator.run(quantum_state, observables) - expectation_values = estimator_job.result().values - - # compute standard deviations - std_devs = _compute_std_devs(estimator_job, len(expectation_values)) - - # Discard values below threshold - observables_means = expectation_values * (np.abs(expectation_values) > threshold) - # zip means and standard deviations into tuples - observables_results = list(zip(observables_means, std_devs)) - - # Return None eigenvalues for None operators if observables is a list. - - return _prepare_result(observables_results, observables) - - -def _prepare_result( - observables_results: List[Tuple[complex, complex]], - observables: Sequence[BaseOperator | PauliSumOp], -) -> List[Tuple[complex, complex]]: - """ - Prepares a list of eigenvalues and standard deviations from ``observables_results`` and - ``observables``. - - Args: - observables_results: A list of of tuples (mean, standard deviation). - observables: A list of operators whose expectation values are to be - calculated. - - Returns: - A list of tuples (mean, standard deviation). - """ - - observables_eigenvalues = [None] * len(observables) - key_value_iterator = enumerate(observables_results) - - for key, value in key_value_iterator: - if observables[key] is not None: - observables_eigenvalues[key] = value - return observables_eigenvalues - - -def _compute_std_devs( - estimator_result: EstimatorResult, - results_length: int, -) -> List[complex | None]: - """ - Calculates a list of standard deviations from expectation values of observables provided. - - Args: - estimator_result: An estimator result. - results_length: Number of expectation values calculated. - - Returns: - A list of standard deviations. - """ - if not estimator_result.metadata: - return [0] * results_length - - std_devs = [] - for metadata in estimator_result.metadata: - if metadata and "variance" in metadata.keys() and "shots" in metadata.keys(): - variance = metadata["variance"] - shots = metadata["shots"] - std_devs.append(np.sqrt(variance / shots)) - else: - std_devs.append(0) - - return std_devs diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py deleted file mode 100644 index 0951c7690f5a..000000000000 --- a/test/python/algorithms/test_observables_evaluator.py +++ /dev/null @@ -1,103 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2022. -# -# This code is licensed under the Apache License, Version 2.0. You may -# obtain a copy of this license in the LICENSE.txt file in the root directory -# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. -# -# Any modifications or derivative works of this code must retain this -# copyright notice, and modified files need to carry a notice indicating -# that they have been altered from the originals. -"""Tests evaluator of auxiliary operators for algorithms.""" - -import unittest -from typing import Tuple, Sequence, List - -from qiskit.quantum_info.operators.base_operator import BaseOperator -from test.python.algorithms import QiskitAlgorithmsTestCase -import numpy as np -from ddt import ddt, data - -from qiskit.algorithms.observables_evaluator import eval_observables -from qiskit.primitives import Estimator -from qiskit.quantum_info import Statevector -from qiskit import QuantumCircuit -from qiskit.circuit.library import EfficientSU2 -from qiskit.opflow import ( - PauliSumOp, -) -from qiskit.utils import algorithm_globals - - -@ddt -class TestObservablesEvaluator(QiskitAlgorithmsTestCase): - """Tests evaluator of auxiliary operators for algorithms.""" - - def setUp(self): - super().setUp() - self.seed = 50 - algorithm_globals.random_seed = self.seed - - self.threshold = 1e-8 - - def get_exact_expectation( - self, ansatz: QuantumCircuit, observables: Sequence[BaseOperator | PauliSumOp] - ): - """ - Calculates the exact expectation to be used as an expected result for unit tests. - """ - - # the exact value is a list of (mean, variance) where we expect 0 variance - exact = [ - (Statevector(ansatz).expectation_value(observable), 0) for observable in observables - ] - - return exact - - def _run_test( - self, - expected_result: List[Tuple[complex, complex]], - quantum_state: Sequence[QuantumCircuit], - decimal: int, - observables: Sequence[BaseOperator | PauliSumOp], - estimator: Estimator, - ): - result = eval_observables(estimator, quantum_state, observables, self.threshold) - - np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) - - @data( - [ - PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), - PauliSumOp.from_list([("II", 2.0)]), - ], - [ - PauliSumOp.from_list([("ZZ", 2.0)]), - ], - ) - def test_eval_observables(self, observables: Sequence[BaseOperator | PauliSumOp]): - """Tests evaluator of auxiliary operators for algorithms.""" - - ansatz = EfficientSU2(2) - parameters = np.array( - [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], - dtype=float, - ) - - bound_ansatz = ansatz.bind_parameters(parameters) - states = bound_ansatz - expected_result = self.get_exact_expectation(bound_ansatz, observables) - estimator = Estimator() - decimal = 6 - self._run_test( - expected_result, - states, - decimal, - observables, - estimator, - ) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/python/algorithms/time_evolvers/test_evolution_problem.py b/test/python/algorithms/time_evolvers/test_evolution_problem.py index d7d55500abfb..76683e27cd13 100644 --- a/test/python/algorithms/time_evolvers/test_evolution_problem.py +++ b/test/python/algorithms/time_evolvers/test_evolution_problem.py @@ -13,12 +13,11 @@ """Test evolver problem class.""" import unittest -from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem -from qiskit.quantum_info import Pauli, SparsePauliOp from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack from numpy.testing import assert_raises - +from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.circuit import Parameter from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp diff --git a/test/python/algorithms/time_evolvers/test_evolution_result.py b/test/python/algorithms/time_evolvers/test_evolution_result.py index 3c599f2eb1b4..52b7f3faaf98 100644 --- a/test/python/algorithms/time_evolvers/test_evolution_result.py +++ b/test/python/algorithms/time_evolvers/test_evolution_result.py @@ -11,9 +11,8 @@ # that they have been altered from the originals. """Class for testing evolution result.""" import unittest - -from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult from test.python.algorithms import QiskitAlgorithmsTestCase +from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult from qiskit.opflow import Zero From 4cf6f61b5310e17229ceb594891510ed96cd40e3 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 13:22:22 +0200 Subject: [PATCH 11/58] Added annotations import. --- qiskit/algorithms/time_evolvers/evolution_problem.py | 2 +- qiskit/algorithms/time_evolvers/evolution_result.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/evolution_problem.py b/qiskit/algorithms/time_evolvers/evolution_problem.py index 8ea90f77f690..9db122f96268 100644 --- a/qiskit/algorithms/time_evolvers/evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/evolution_problem.py @@ -11,7 +11,7 @@ # that they have been altered from the originals. """Evolution problem class.""" - +from __future__ import annotations from typing import Dict from qiskit import QuantumCircuit diff --git a/qiskit/algorithms/time_evolvers/evolution_result.py b/qiskit/algorithms/time_evolvers/evolution_result.py index 55a3fad31032..e89c3dba52e8 100644 --- a/qiskit/algorithms/time_evolvers/evolution_result.py +++ b/qiskit/algorithms/time_evolvers/evolution_result.py @@ -11,7 +11,7 @@ # that they have been altered from the originals. """Class for holding evolution result.""" - +from __future__ import annotations from typing import Tuple from qiskit import QuantumCircuit From ebedff25d3df3e57b6ed84e3199fffc00eefab1a Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 14:15:03 +0200 Subject: [PATCH 12/58] Added trotter_qrte.py with unit tests. --- .../time_evolvers/trotterization/__init__.py | 11 + .../trotterization/trotter_qrte.py | 178 +++++++++++++++ .../algorithms/time_evolvers/__init__.py | 11 + .../time_evolvers/test_trotter_qrte.py | 205 ++++++++++++++++++ 4 files changed, 405 insertions(+) create mode 100644 qiskit/algorithms/time_evolvers/trotterization/__init__.py create mode 100644 qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py create mode 100644 test/python/algorithms/time_evolvers/__init__.py create mode 100644 test/python/algorithms/time_evolvers/test_trotter_qrte.py diff --git a/qiskit/algorithms/time_evolvers/trotterization/__init__.py b/qiskit/algorithms/time_evolvers/trotterization/__init__.py new file mode 100644 index 000000000000..fdb172d367f0 --- /dev/null +++ b/qiskit/algorithms/time_evolvers/trotterization/__init__.py @@ -0,0 +1,11 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py new file mode 100644 index 000000000000..a29a1739a65a --- /dev/null +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -0,0 +1,178 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +"""An algorithm to implement a Trotterization real time-evolution.""" + +from typing import Union, Optional + +from qiskit import QuantumCircuit +from qiskit.algorithms.observables_evaluator import eval_observables +from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult +from qiskit.algorithms.time_evolvers.real_evolver import RealEvolver +from qiskit.opflow import ( + SummedOp, + PauliOp, + CircuitOp, + PauliSumOp, + StateFn, + OperatorBase, +) +from qiskit.circuit.library import PauliEvolutionGate +from qiskit.primitives import Estimator +from qiskit.synthesis import ProductFormula, LieTrotter + + +class TrotterQRTE(RealEvolver): + """Quantum Real Time Evolution using Trotterization. + Type of Trotterization is defined by a ProductFormula provided. + + Examples: + + .. jupyter-execute:: + + from qiskit.opflow import X, Z, Zero + from qiskit.algorithms import EvolutionProblem, TrotterQRTE + + operator = X + Z + initial_state = Zero + time = 1 + evolution_problem = EvolutionProblem(operator, 1, initial_state) + # LieTrotter with 1 rep + trotter_qrte = TrotterQRTE() + evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state + """ + + def __init__( + self, + product_formula: Optional[ProductFormula] = None, + estimator: Estimator = None, + ) -> None: + """ + Args: + product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter + first order product formula with a single repetition. + estimator: An estimator primitive used for calculating expectation values of + EvolutionProblem.aux_operators. + """ + if product_formula is None: + product_formula = LieTrotter() + self.product_formula = product_formula + self.estimator = estimator + + @classmethod + def supports_aux_operators(cls) -> bool: + """ + Whether computing the expectation value of auxiliary operators is supported. + + Returns: + True if ``aux_operators`` expectations in the EvolutionProblem can be evaluated, False + otherwise. + """ + return True + + def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: + """ + Evolves a quantum state for a given time using the Trotterization method + based on a product formula provided. The result is provided in the form of a quantum + circuit. If auxiliary operators are included in the ``evolution_problem``, they are + evaluated on an evolved state using an estimator primitive provided. + + .. note:: + Time-dependent Hamiltonians are not yet supported. + + Args: + evolution_problem: Instance defining evolution problem. For the included Hamiltonian, + ``PauliOp``, ``SummedOp`` or ``PauliSumOp`` are supported by TrotterQRTE. + + Returns: + Evolution result that includes an evolved state as a quantum circuit and, optionally, + auxiliary operators evaluated for a resulting state on an estimator primitive. + + Raises: + ValueError: If ``t_param`` is not set to None in the EvolutionProblem (feature not + currently supported). + ValueError: If the ``initial_state`` is not provided in the EvolutionProblem. + """ + evolution_problem.validate_params() + if evolution_problem.t_param is not None: + raise ValueError( + "TrotterQRTE does not accept a time dependent hamiltonian," + "``t_param`` from the EvolutionProblem should be set to None." + ) + + if evolution_problem.aux_operators is not None and (self.estimator is None): + raise ValueError( + "aux_operators were provided for evaluations but no ``estimator`` was provided." + ) + hamiltonian = evolution_problem.hamiltonian + if not isinstance(hamiltonian, (PauliOp, PauliSumOp, SummedOp)): + raise ValueError( + "TrotterQRTE only accepts PauliOp | " + f"PauliSumOp | SummedOp, {type(hamiltonian)} provided." + ) + if isinstance(hamiltonian, OperatorBase): + hamiltonian = hamiltonian.bind_parameters(evolution_problem.param_value_dict) + if isinstance(hamiltonian, SummedOp): + hamiltonian = self._summed_op_to_pauli_sum_op(hamiltonian) + # the evolution gate + evolution_gate = CircuitOp( + PauliEvolutionGate(hamiltonian, evolution_problem.time, synthesis=self.product_formula) + ) + + if evolution_problem.initial_state is not None: + initial_state = evolution_problem.initial_state + if isinstance(initial_state, QuantumCircuit): + initial_state = StateFn(initial_state) + evolved_state = evolution_gate @ initial_state + + else: + raise ValueError("``initial_state`` must be provided in the EvolutionProblem.") + + evaluated_aux_ops = None + if evolution_problem.aux_operators is not None: + evaluated_aux_ops = eval_observables( + self.estimator, + evolved_state.primitive, + evolution_problem.aux_operators, + evolution_problem.truncation_threshold, + ) + + return EvolutionResult(evolved_state, evaluated_aux_ops) + + @staticmethod + def _summed_op_to_pauli_sum_op( + hamiltonian: SummedOp, + ) -> Union[PauliSumOp, PauliOp]: + """ + Tries binding parameters in a Hamiltonian. + + Args: + hamiltonian: The Hamiltonian that defines an evolution. + + Returns: + Hamiltonian. + + Raises: + ValueError: If the ``SummedOp`` Hamiltonian contains operators of an invalid type. + """ + # PauliSumOp does not allow parametrized coefficients but after binding the parameters + # we need to convert it into a PauliSumOp for the PauliEvolutionGate. + op_list = [] + for op in hamiltonian.oplist: + if not isinstance(op, PauliOp): + raise ValueError( + "Content of the Hamiltonian not of type PauliOp. The " + f"following type detected: {type(op)}." + ) + op_list.append(op) + return sum(op_list) diff --git a/test/python/algorithms/time_evolvers/__init__.py b/test/python/algorithms/time_evolvers/__init__.py new file mode 100644 index 000000000000..fdb172d367f0 --- /dev/null +++ b/test/python/algorithms/time_evolvers/__init__.py @@ -0,0 +1,11 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py new file mode 100644 index 000000000000..91240c6423e1 --- /dev/null +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -0,0 +1,205 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. + +""" Test TrotterQRTE. """ + +import unittest +from test.python.opflow import QiskitOpflowTestCase +from ddt import ddt, data, unpack +import numpy as np +from numpy.testing import assert_raises + +from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE +from qiskit.primitives import Estimator +from qiskit import QuantumCircuit +from qiskit.circuit.library import ZGate +from qiskit.quantum_info import Statevector, Pauli +from qiskit.utils import algorithm_globals +from qiskit.circuit import Parameter +from qiskit.opflow import ( + X, + Z, + Zero, + VectorStateFn, + StateFn, + I, + Y, + SummedOp, +) +from qiskit.synthesis import SuzukiTrotter, QDrift + + +@ddt +class TestTrotterQRTE(QiskitOpflowTestCase): + """TrotterQRTE tests.""" + + def setUp(self): + super().setUp() + self.seed = 50 + algorithm_globals.random_seed = self.seed + + @data( + ( + None, + VectorStateFn( + Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j], dims=(2,)) + ), + ), + ( + SuzukiTrotter(), + VectorStateFn(Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j], dims=(2,))), + ), + ) + @unpack + def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): + """Test for default TrotterQRTE on a single qubit.""" + operator = SummedOp([X, Z]) + initial_state = StateFn([1, 0]) + time = 1 + evolution_problem = EvolutionProblem(operator, time, initial_state) + + trotter_qrte = TrotterQRTE(product_formula=product_formula) + evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state + + np.testing.assert_equal(evolution_result_state_circuit.eval(), expected_state) + + def test_trotter_qrte_trotter_single_qubit_aux_ops(self): + """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" + operator = SummedOp([X, Z]) + # LieTrotter with 1 rep + aux_ops = [Pauli("X"), Pauli("Y")] + + initial_state = Zero + time = 3 + evolution_problem = EvolutionProblem(operator, time, initial_state, aux_ops) + estimator = Estimator() + + expected_evolved_state = VectorStateFn( + Statevector([0.98008514 + 0.13970775j, 0.01991486 + 0.13970775j], dims=(2,)) + ) + expected_aux_ops_evaluated = [(0.078073, 0.0), (0.268286, 0.0)] + + algorithm_globals.random_seed = 0 + trotter_qrte = TrotterQRTE(estimator=estimator) + evolution_result = trotter_qrte.evolve(evolution_problem) + + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_evolved_state) + + np.testing.assert_array_almost_equal( + evolution_result.aux_ops_evaluated, expected_aux_ops_evaluated + ) + + @data( + ( + SummedOp([(X ^ Y), (Y ^ X)]), + VectorStateFn( + Statevector( + [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j], dims=(2, 2) + ) + ), + ), + ( + (Z ^ Z) + (Z ^ I) + (I ^ Z), + VectorStateFn( + Statevector( + [-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2) + ) + ), + ), + ( + Y ^ Y, + VectorStateFn( + Statevector( + [0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j], dims=(2, 2) + ) + ), + ), + ) + @unpack + def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): + """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" + # LieTrotter with 1 rep + initial_state = StateFn([1, 0, 0, 0]) + evolution_problem = EvolutionProblem(operator, 1, initial_state) + + trotter_qrte = TrotterQRTE() + evolution_result = trotter_qrte.evolve(evolution_problem) + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + + def test_trotter_qrte_trotter_two_qubits_with_params(self): + """Test for TrotterQRTE on two qubits with a parametrized Hamiltonian.""" + # LieTrotter with 1 rep + initial_state = StateFn([1, 0, 0, 0]) + w_param = Parameter("w") + u_param = Parameter("u") + params_dict = {w_param: 2.0, u_param: 3.0} + operator = w_param * (Z ^ Z) / 2.0 + (Z ^ I) + u_param * (I ^ Z) / 3.0 + time = 1 + evolution_problem = EvolutionProblem( + operator, time, initial_state, param_value_dict=params_dict + ) + expected_state = VectorStateFn( + Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2)) + ) + trotter_qrte = TrotterQRTE() + evolution_result = trotter_qrte.evolve(evolution_problem) + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + + @data( + ( + Zero, + VectorStateFn( + Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) + ), + ), + ( + QuantumCircuit(1).compose(ZGate(), [0]), + VectorStateFn( + Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) + ), + ), + ) + @unpack + def test_trotter_qrte_qdrift(self, initial_state, expected_state): + """Test for TrotterQRTE with QDrift.""" + operator = SummedOp([X, Z]) + time = 1 + evolution_problem = EvolutionProblem(operator, time, initial_state) + + algorithm_globals.random_seed = 0 + trotter_qrte = TrotterQRTE(product_formula=QDrift()) + evolution_result = trotter_qrte.evolve(evolution_problem) + np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + + @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) + @unpack + def test_trotter_qrte_trotter_errors(self, t_param, param_value_dict): + """Test TrotterQRTE with raising errors.""" + operator = X * Parameter("t") + Z + initial_state = Zero + time = 1 + algorithm_globals.random_seed = 0 + trotter_qrte = TrotterQRTE() + with assert_raises(ValueError): + evolution_problem = EvolutionProblem( + operator, + time, + initial_state, + t_param=t_param, + param_value_dict=param_value_dict, + ) + _ = trotter_qrte.evolve(evolution_problem) + + +if __name__ == "__main__": + unittest.main() From a4a51cca555012281307a23199733fe2b8924b71 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 14:29:29 +0200 Subject: [PATCH 13/58] Refactored trotter_qrte.py. --- .../trotterization/trotter_qrte.py | 48 ++++--------------- 1 file changed, 8 insertions(+), 40 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index a29a1739a65a..1220ef57b795 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -12,23 +12,22 @@ """An algorithm to implement a Trotterization real time-evolution.""" -from typing import Union, Optional +from __future__ import annotations -from qiskit import QuantumCircuit from qiskit.algorithms.observables_evaluator import eval_observables + +from qiskit import QuantumCircuit from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult from qiskit.algorithms.time_evolvers.real_evolver import RealEvolver from qiskit.opflow import ( - SummedOp, PauliOp, CircuitOp, PauliSumOp, StateFn, - OperatorBase, ) from qiskit.circuit.library import PauliEvolutionGate -from qiskit.primitives import Estimator +from qiskit.primitives import BaseEstimator from qiskit.synthesis import ProductFormula, LieTrotter @@ -54,8 +53,8 @@ class TrotterQRTE(RealEvolver): def __init__( self, - product_formula: Optional[ProductFormula] = None, - estimator: Estimator = None, + product_formula: ProductFormula | None = None, + estimator: BaseEstimator | None = None, ) -> None: """ Args: @@ -115,15 +114,11 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: "aux_operators were provided for evaluations but no ``estimator`` was provided." ) hamiltonian = evolution_problem.hamiltonian - if not isinstance(hamiltonian, (PauliOp, PauliSumOp, SummedOp)): + if not isinstance(hamiltonian, (PauliOp, PauliSumOp)): raise ValueError( "TrotterQRTE only accepts PauliOp | " - f"PauliSumOp | SummedOp, {type(hamiltonian)} provided." + f"PauliSumOp, {type(hamiltonian)} provided." ) - if isinstance(hamiltonian, OperatorBase): - hamiltonian = hamiltonian.bind_parameters(evolution_problem.param_value_dict) - if isinstance(hamiltonian, SummedOp): - hamiltonian = self._summed_op_to_pauli_sum_op(hamiltonian) # the evolution gate evolution_gate = CircuitOp( PauliEvolutionGate(hamiltonian, evolution_problem.time, synthesis=self.product_formula) @@ -149,30 +144,3 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: return EvolutionResult(evolved_state, evaluated_aux_ops) - @staticmethod - def _summed_op_to_pauli_sum_op( - hamiltonian: SummedOp, - ) -> Union[PauliSumOp, PauliOp]: - """ - Tries binding parameters in a Hamiltonian. - - Args: - hamiltonian: The Hamiltonian that defines an evolution. - - Returns: - Hamiltonian. - - Raises: - ValueError: If the ``SummedOp`` Hamiltonian contains operators of an invalid type. - """ - # PauliSumOp does not allow parametrized coefficients but after binding the parameters - # we need to convert it into a PauliSumOp for the PauliEvolutionGate. - op_list = [] - for op in hamiltonian.oplist: - if not isinstance(op, PauliOp): - raise ValueError( - "Content of the Hamiltonian not of type PauliOp. The " - f"following type detected: {type(op)}." - ) - op_list.append(op) - return sum(op_list) From 39c97356435f69c5f531e9d4d0b999154cacf042 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 14:33:01 +0200 Subject: [PATCH 14/58] Added observables_evaluator.py with primitives. --- qiskit/algorithms/observables_evaluator.py | 130 ++++++++++++++++++ .../algorithms/test_observables_evaluator.py | 100 ++++++++++++++ 2 files changed, 230 insertions(+) create mode 100644 qiskit/algorithms/observables_evaluator.py create mode 100644 test/python/algorithms/test_observables_evaluator.py diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py new file mode 100644 index 000000000000..0a351d9c73aa --- /dev/null +++ b/qiskit/algorithms/observables_evaluator.py @@ -0,0 +1,130 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2021, 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. +"""Evaluator of auxiliary operators for algorithms.""" +from __future__ import annotations +from typing import Tuple, List, Sequence + +import numpy as np + +from qiskit import QuantumCircuit +from qiskit.opflow import ( + PauliSumOp, +) +from ..primitives import EstimatorResult, BaseEstimator +from ..quantum_info.operators.base_operator import BaseOperator + + +def eval_observables( + estimator: BaseEstimator, + quantum_state: QuantumCircuit, + observables: Sequence[BaseOperator | PauliSumOp], + threshold: float = 1e-12, +) -> List[Tuple[complex, complex]]: + """ + Accepts a sequence of operators and calculates their expectation values - means + and standard deviations. They are calculated with respect to a quantum state provided. A user + can optionally provide a threshold value which filters mean values falling below the threshold. + + Args: + estimator: An estimator primitive used for calculations. + quantum_state: An unparametrized quantum circuit representing a quantum state that + expectation values are computed against. + observables: A sequence of operators whose expectation values are to be calculated. + threshold: A threshold value that defines which mean values should be neglected (helpful for + ignoring numerical instabilities close to 0). + + Returns: + A list of tuples (mean, standard deviation). + + Raises: + ValueError: If a ``quantum_state`` with free parameters is provided. + """ + + if ( + isinstance(quantum_state, QuantumCircuit) # Statevector cannot be parametrized + and len(quantum_state.parameters) > 0 + ): + raise ValueError( + "A parametrized representation of a quantum_state was provided. It is not " + "allowed - it cannot have free parameters." + ) + + quantum_state = [quantum_state] * len(observables) + estimator_job = estimator.run(quantum_state, observables) + expectation_values = estimator_job.result().values + + # compute standard deviations + std_devs = _compute_std_devs(estimator_job, len(expectation_values)) + + # Discard values below threshold + observables_means = expectation_values * (np.abs(expectation_values) > threshold) + # zip means and standard deviations into tuples + observables_results = list(zip(observables_means, std_devs)) + + # Return None eigenvalues for None operators if observables is a list. + + return _prepare_result(observables_results, observables) + + +def _prepare_result( + observables_results: List[Tuple[complex, complex]], + observables: Sequence[BaseOperator], +) -> List[Tuple[complex, complex]]: + """ + Prepares a list of eigenvalues and standard deviations from ``observables_results`` and + ``observables``. + + Args: + observables_results: A list of of tuples (mean, standard deviation). + observables: A list of operators whose expectation values are to be + calculated. + + Returns: + A list of tuples (mean, standard deviation). + """ + + observables_eigenvalues = [None] * len(observables) + key_value_iterator = enumerate(observables_results) + + for key, value in key_value_iterator: + if observables[key] is not None: + observables_eigenvalues[key] = value + return observables_eigenvalues + + +def _compute_std_devs( + estimator_result: EstimatorResult, + results_length: int, +) -> List[complex | None]: + """ + Calculates a list of standard deviations from expectation values of observables provided. + + Args: + estimator_result: An estimator result. + results_length: Number of expectation values calculated. + + Returns: + A list of standard deviations. + """ + if not estimator_result.metadata: + return [0] * results_length + + std_devs = [] + for metadata in estimator_result.metadata: + if metadata and "variance" in metadata.keys() and "shots" in metadata.keys(): + variance = metadata["variance"] + shots = metadata["shots"] + std_devs.append(np.sqrt(variance / shots)) + else: + std_devs.append(0) + + return std_devs diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py new file mode 100644 index 000000000000..f9716fb0ee64 --- /dev/null +++ b/test/python/algorithms/test_observables_evaluator.py @@ -0,0 +1,100 @@ +# This code is part of Qiskit. +# +# (C) Copyright IBM 2022. +# +# This code is licensed under the Apache License, Version 2.0. You may +# obtain a copy of this license in the LICENSE.txt file in the root directory +# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. +# +# Any modifications or derivative works of this code must retain this +# copyright notice, and modified files need to carry a notice indicating +# that they have been altered from the originals. +"""Tests evaluator of auxiliary operators for algorithms.""" + +import unittest +from typing import Tuple, Sequence, List +from test.python.algorithms import QiskitAlgorithmsTestCase +import numpy as np +from ddt import ddt, data + +from qiskit.algorithms.observables_evaluator import eval_observables +from qiskit.primitives import Estimator +from qiskit.quantum_info import Statevector +from qiskit import QuantumCircuit +from qiskit.circuit.library import EfficientSU2 +from qiskit.opflow import ( + PauliSumOp, + OperatorBase, +) +from qiskit.utils import algorithm_globals + + +@ddt +class TestObservablesEvaluator(QiskitAlgorithmsTestCase): + """Tests evaluator of auxiliary operators for algorithms.""" + + def setUp(self): + super().setUp() + self.seed = 50 + algorithm_globals.random_seed = self.seed + + self.threshold = 1e-8 + + def get_exact_expectation(self, ansatz: QuantumCircuit, observables: Sequence[OperatorBase]): + """ + Calculates the exact expectation to be used as an expected result for unit tests. + """ + + # the exact value is a list of (mean, variance) where we expect 0 variance + exact = [ + (Statevector(ansatz).expectation_value(observable), 0) for observable in observables + ] + + return exact + + def _run_test( + self, + expected_result: List[Tuple[complex, complex]], + quantum_state: Sequence[QuantumCircuit], + decimal: int, + observables: Sequence[OperatorBase], + estimator: Estimator, + ): + result = eval_observables(estimator, quantum_state, observables, self.threshold) + + np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) + + @data( + [ + PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), + PauliSumOp.from_list([("II", 2.0)]), + ], + [ + PauliSumOp.from_list([("ZZ", 2.0)]), + ], + ) + def test_eval_observables(self, observables: Sequence[OperatorBase]): + """Tests evaluator of auxiliary operators for algorithms.""" + + ansatz = EfficientSU2(2) + parameters = np.array( + [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], + dtype=float, + ) + + bound_ansatz = ansatz.bind_parameters(parameters) + states = bound_ansatz + expected_result = self.get_exact_expectation(bound_ansatz, observables) + estimator = Estimator() + decimal = 6 + self._run_test( + expected_result, + states, + decimal, + observables, + estimator, + ) + + +if __name__ == "__main__": + unittest.main() From 99adde79a0747bd174c7b877fae53beb66622a9f Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 15:32:02 +0200 Subject: [PATCH 15/58] Added ListOrDict support to observables_evaluator.py. --- qiskit/algorithms/observables_evaluator.py | 45 +++++++++++------- .../algorithms/test_observables_evaluator.py | 46 ++++++++++++++----- 2 files changed, 64 insertions(+), 27 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 0a351d9c73aa..18fa2830ff8f 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -11,7 +11,8 @@ # that they have been altered from the originals. """Evaluator of auxiliary operators for algorithms.""" from __future__ import annotations -from typing import Tuple, List, Sequence + +from typing import Tuple, List import numpy as np @@ -19,6 +20,8 @@ from qiskit.opflow import ( PauliSumOp, ) +from . import AlgorithmError +from .list_or_dict import ListOrDict from ..primitives import EstimatorResult, BaseEstimator from ..quantum_info.operators.base_operator import BaseOperator @@ -26,9 +29,9 @@ def eval_observables( estimator: BaseEstimator, quantum_state: QuantumCircuit, - observables: Sequence[BaseOperator | PauliSumOp], + observables: ListOrDict[BaseOperator | PauliSumOp], threshold: float = 1e-12, -) -> List[Tuple[complex, complex]]: +) -> ListOrDict[Tuple[complex, complex]]: """ Accepts a sequence of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user @@ -38,15 +41,17 @@ def eval_observables( estimator: An estimator primitive used for calculations. quantum_state: An unparametrized quantum circuit representing a quantum state that expectation values are computed against. - observables: A sequence of operators whose expectation values are to be calculated. + observables: A list or a dictionary of operators whose expectation values are to be + calculated. threshold: A threshold value that defines which mean values should be neglected (helpful for ignoring numerical instabilities close to 0). Returns: - A list of tuples (mean, standard deviation). + A list or a dictionary of tuples (mean, standard deviation). Raises: ValueError: If a ``quantum_state`` with free parameters is provided. + AlgorithmError: If a primitive job is not successful. """ if ( @@ -57,12 +62,17 @@ def eval_observables( "A parametrized representation of a quantum_state was provided. It is not " "allowed - it cannot have free parameters." ) - + if isinstance(observables, dict): + observables_list = list(observables.values()) + else: + observables_list = observables quantum_state = [quantum_state] * len(observables) - estimator_job = estimator.run(quantum_state, observables) - expectation_values = estimator_job.result().values + try: + estimator_job = estimator.run(quantum_state, observables_list) + expectation_values = estimator_job.result().values + except Exception as exc: + raise AlgorithmError("The primitive job failed!") from exc - # compute standard deviations std_devs = _compute_std_devs(estimator_job, len(expectation_values)) # Discard values below threshold @@ -71,29 +81,32 @@ def eval_observables( observables_results = list(zip(observables_means, std_devs)) # Return None eigenvalues for None operators if observables is a list. - return _prepare_result(observables_results, observables) def _prepare_result( observables_results: List[Tuple[complex, complex]], - observables: Sequence[BaseOperator], -) -> List[Tuple[complex, complex]]: + observables: ListOrDict[BaseOperator | PauliSumOp], +) -> ListOrDict[Tuple[complex, complex]]: """ Prepares a list of eigenvalues and standard deviations from ``observables_results`` and ``observables``. Args: observables_results: A list of of tuples (mean, standard deviation). - observables: A list of operators whose expectation values are to be + observables: A list or a dictionary of operators whose expectation values are to be calculated. Returns: - A list of tuples (mean, standard deviation). + A list or a dictionary of tuples (mean, standard deviation). """ - observables_eigenvalues = [None] * len(observables) - key_value_iterator = enumerate(observables_results) + if isinstance(observables, list): + observables_eigenvalues = [None] * len(observables) + key_value_iterator = enumerate(observables_results) + else: + observables_eigenvalues = {} + key_value_iterator = zip(observables.keys(), observables_results) for key, value in key_value_iterator: if observables[key] is not None: diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index f9716fb0ee64..74ccee63bc9a 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -10,13 +10,16 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Tests evaluator of auxiliary operators for algorithms.""" - +from __future__ import annotations import unittest -from typing import Tuple, Sequence, List +from typing import Tuple + from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, data +from qiskit.algorithms.list_or_dict import ListOrDict +from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.algorithms.observables_evaluator import eval_observables from qiskit.primitives import Estimator from qiskit.quantum_info import Statevector @@ -24,7 +27,6 @@ from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import ( PauliSumOp, - OperatorBase, ) from qiskit.utils import algorithm_globals @@ -40,29 +42,44 @@ def setUp(self): self.threshold = 1e-8 - def get_exact_expectation(self, ansatz: QuantumCircuit, observables: Sequence[OperatorBase]): + def get_exact_expectation( + self, ansatz: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp] + ): """ Calculates the exact expectation to be used as an expected result for unit tests. """ - + if isinstance(observables, dict): + observables_list = list(observables.values()) + else: + observables_list = observables # the exact value is a list of (mean, variance) where we expect 0 variance exact = [ - (Statevector(ansatz).expectation_value(observable), 0) for observable in observables + (Statevector(ansatz).expectation_value(observable), 0) + for observable in observables_list ] + if isinstance(observables, dict): + return dict(zip(observables.keys(), exact)) + return exact def _run_test( self, - expected_result: List[Tuple[complex, complex]], - quantum_state: Sequence[QuantumCircuit], + expected_result: ListOrDict[Tuple[complex, complex]], + quantum_state: QuantumCircuit, decimal: int, - observables: Sequence[OperatorBase], + observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): result = eval_observables(estimator, quantum_state, observables, self.threshold) - np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) + if isinstance(observables, dict): + np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) + np.testing.assert_array_almost_equal( + list(result.values()), list(expected_result.values()), decimal=decimal + ) + else: + np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) @data( [ @@ -72,8 +89,15 @@ def _run_test( [ PauliSumOp.from_list([("ZZ", 2.0)]), ], + { + "op1": PauliSumOp.from_list([("II", 2.0)]), + "op2": PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]), + }, + { + "op1": PauliSumOp.from_list([("ZZ", 2.0)]), + }, ) - def test_eval_observables(self, observables: Sequence[OperatorBase]): + def test_eval_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) From 221ee297ed30046a40164959ac29976318f2c31b Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 5 Sep 2022 16:07:15 +0200 Subject: [PATCH 16/58] Updated trotter_qrte.py unit tests; code refactoring. --- .../trotterization/trotter_qrte.py | 22 +++++++++++--- .../time_evolvers/test_trotter_qrte.py | 30 ++++--------------- 2 files changed, 23 insertions(+), 29 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 1220ef57b795..a8ad2379a6c7 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -68,6 +68,20 @@ def __init__( self.product_formula = product_formula self.estimator = estimator + @property + def estimator(self) -> BaseEstimator | None: + """ + Returns an estimator. + """ + return self.estimator + + @estimator.setter + def estimator(self, estimator: BaseEstimator) -> None: + """ + Sets an estimator. + """ + self.estimator = estimator + @classmethod def supports_aux_operators(cls) -> bool: """ @@ -98,9 +112,11 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: auxiliary operators evaluated for a resulting state on an estimator primitive. Raises: - ValueError: If ``t_param`` is not set to None in the EvolutionProblem (feature not + ValueError: If ``t_param`` is not set to ``None`` in the EvolutionProblem (feature not currently supported). + ValueError: If ``aux_operators` are provided but no ``Estimator`` is provided. ValueError: If the ``initial_state`` is not provided in the EvolutionProblem. + ValueError: If an unsupported Hamiltonian type is provided. """ evolution_problem.validate_params() if evolution_problem.t_param is not None: @@ -116,8 +132,7 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: hamiltonian = evolution_problem.hamiltonian if not isinstance(hamiltonian, (PauliOp, PauliSumOp)): raise ValueError( - "TrotterQRTE only accepts PauliOp | " - f"PauliSumOp, {type(hamiltonian)} provided." + "TrotterQRTE only accepts PauliOp | " f"PauliSumOp, {type(hamiltonian)} provided." ) # the evolution gate evolution_gate = CircuitOp( @@ -143,4 +158,3 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: ) return EvolutionResult(evolved_state, evaluated_aux_ops) - diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 91240c6423e1..1f765f418b85 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -34,7 +34,6 @@ StateFn, I, Y, - SummedOp, ) from qiskit.synthesis import SuzukiTrotter, QDrift @@ -63,7 +62,7 @@ def setUp(self): @unpack def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): """Test for default TrotterQRTE on a single qubit.""" - operator = SummedOp([X, Z]) + operator = X + Z initial_state = StateFn([1, 0]) time = 1 evolution_problem = EvolutionProblem(operator, time, initial_state) @@ -75,7 +74,7 @@ def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state def test_trotter_qrte_trotter_single_qubit_aux_ops(self): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" - operator = SummedOp([X, Z]) + operator = X + Z # LieTrotter with 1 rep aux_ops = [Pauli("X"), Pauli("Y")] @@ -101,7 +100,7 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): @data( ( - SummedOp([(X ^ Y), (Y ^ X)]), + (X ^ Y) + (Y ^ X), VectorStateFn( Statevector( [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j], dims=(2, 2) @@ -129,32 +128,13 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" # LieTrotter with 1 rep - initial_state = StateFn([1, 0, 0, 0]) + initial_state = QuantumCircuit(2) evolution_problem = EvolutionProblem(operator, 1, initial_state) trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) - def test_trotter_qrte_trotter_two_qubits_with_params(self): - """Test for TrotterQRTE on two qubits with a parametrized Hamiltonian.""" - # LieTrotter with 1 rep - initial_state = StateFn([1, 0, 0, 0]) - w_param = Parameter("w") - u_param = Parameter("u") - params_dict = {w_param: 2.0, u_param: 3.0} - operator = w_param * (Z ^ Z) / 2.0 + (Z ^ I) + u_param * (I ^ Z) / 3.0 - time = 1 - evolution_problem = EvolutionProblem( - operator, time, initial_state, param_value_dict=params_dict - ) - expected_state = VectorStateFn( - Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2)) - ) - trotter_qrte = TrotterQRTE() - evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) - @data( ( Zero, @@ -172,7 +152,7 @@ def test_trotter_qrte_trotter_two_qubits_with_params(self): @unpack def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" - operator = SummedOp([X, Z]) + operator = X + Z time = 1 evolution_problem = EvolutionProblem(operator, time, initial_state) From 6462bb03f583ac4c0a936ef6814411c51870f3e1 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 6 Sep 2022 11:51:45 +0200 Subject: [PATCH 17/58] Included CR suggestions. --- qiskit/algorithms/observables_evaluator.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 18fa2830ff8f..43d439088339 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -55,7 +55,7 @@ def eval_observables( """ if ( - isinstance(quantum_state, QuantumCircuit) # Statevector cannot be parametrized + isinstance(quantum_state, QuantumCircuit) # State cannot be parametrized and len(quantum_state.parameters) > 0 ): raise ValueError( @@ -119,7 +119,9 @@ def _compute_std_devs( results_length: int, ) -> List[complex | None]: """ - Calculates a list of standard deviations from expectation values of observables provided. + Calculates a list of standard deviations from expectation values of observables provided. If + the choice of an underlying hardware is not shot-based and hence does not provide variance data, + the standard deviation values will be set to ``None``. Args: estimator_result: An estimator result. @@ -138,6 +140,6 @@ def _compute_std_devs( shots = metadata["shots"] std_devs.append(np.sqrt(variance / shots)) else: - std_devs.append(0) + std_devs.append(None) return std_devs From 604944c94f3eb691056282192d8b149a3b6317ed Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 6 Sep 2022 20:19:27 +0200 Subject: [PATCH 18/58] Applied some CR comments. --- qiskit/algorithms/time_evolvers/evolution_problem.py | 10 ++++++---- qiskit/algorithms/time_evolvers/evolution_result.py | 3 +-- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/evolution_problem.py b/qiskit/algorithms/time_evolvers/evolution_problem.py index 9db122f96268..f33af102351a 100644 --- a/qiskit/algorithms/time_evolvers/evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/evolution_problem.py @@ -12,12 +12,12 @@ """Evolution problem class.""" from __future__ import annotations -from typing import Dict from qiskit import QuantumCircuit -from qiskit.circuit import Parameter +from qiskit.circuit import Parameter, ParameterExpression from qiskit.opflow import PauliSumOp from ..list_or_dict import ListOrDict +from ...quantum_info import Statevector from ...quantum_info.operators.base_operator import BaseOperator @@ -36,7 +36,7 @@ def __init__( aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, - param_value_dict: Dict[Parameter, complex] + param_value_dict: dict[Parameter, complex] | None = None, # parametrization will become supported in BaseOperator soon ): """ @@ -92,5 +92,7 @@ def validate_params(self) -> None: Raises: ValueError: If Hamiltonian parameters cannot be bound with data provided. """ - if isinstance(self.hamiltonian, PauliSumOp) and self.hamiltonian.parameters: + if isinstance(self.hamiltonian, PauliSumOp) and isinstance( + self.hamiltonian.coeff, ParameterExpression + ): raise ValueError("A global parametrized coefficient for PauliSumOp is not allowed.") diff --git a/qiskit/algorithms/time_evolvers/evolution_result.py b/qiskit/algorithms/time_evolvers/evolution_result.py index e89c3dba52e8..6d6730057871 100644 --- a/qiskit/algorithms/time_evolvers/evolution_result.py +++ b/qiskit/algorithms/time_evolvers/evolution_result.py @@ -12,7 +12,6 @@ """Class for holding evolution result.""" from __future__ import annotations -from typing import Tuple from qiskit import QuantumCircuit from qiskit.algorithms.list_or_dict import ListOrDict @@ -25,7 +24,7 @@ class EvolutionResult(AlgorithmResult): def __init__( self, evolved_state: QuantumCircuit, - aux_ops_evaluated: ListOrDict[Tuple[complex, complex]] | None = None, + aux_ops_evaluated: ListOrDict[tuple[complex, complex]] | None = None, ): """ Args: From d287c2f5b06987fbce21b0feb9640e9448f768d8 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 6 Sep 2022 20:28:58 +0200 Subject: [PATCH 19/58] Applied some CR comments. --- qiskit/algorithms/observables_evaluator.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 43d439088339..855a54f3ad79 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -120,8 +120,8 @@ def _compute_std_devs( ) -> List[complex | None]: """ Calculates a list of standard deviations from expectation values of observables provided. If - the choice of an underlying hardware is not shot-based and hence does not provide variance data, - the standard deviation values will be set to ``None``. + there is no variance data available from a primitive, the standard deviation values will be set + to ``None``. Args: estimator_result: An estimator result. @@ -138,8 +138,11 @@ def _compute_std_devs( if metadata and "variance" in metadata.keys() and "shots" in metadata.keys(): variance = metadata["variance"] shots = metadata["shots"] - std_devs.append(np.sqrt(variance / shots)) + if variance is None or shots is None: + std_devs.append(None) + else: + std_devs.append(np.sqrt(variance / shots)) else: - std_devs.append(None) + std_devs.append(0) return std_devs From 23821e0c45843d4978bd1fa21da2e6679780fb18 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Wed, 7 Sep 2022 10:07:10 +0200 Subject: [PATCH 20/58] Added reno. --- ...lution-framework-primitives-c86779b5d0dffd25.yaml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml diff --git a/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml b/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml new file mode 100644 index 000000000000..1ea0b3485541 --- /dev/null +++ b/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml @@ -0,0 +1,12 @@ +--- +features: + - | + Added `~qiskit.algorithms.time_evolvers` package with interfaces that will cover + primitive-enabled time evolution algorithms: + :class:`~qiskit.algorithms.time_evolvers.EvolutionProblem`, + :class:`~qiskit.algorithms.time_evolvers.EvolutionResult`, + :class:`~qiskit.algorithms.time_evolvers.ImaginaryEvolver`, + :class:`~qiskit.algorithms.time_evolvers.RealEvolver`. +deprecations: + - | + `~qiskit.algorithms.evolvers` package will now issue a ``PendingDeprecationWarning``. From 80a2e2bae2e4eb6d84ae44b13a4a86a71c58a81e Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Wed, 7 Sep 2022 10:14:02 +0200 Subject: [PATCH 21/58] Added reno. --- .../observable-eval-primitives-e1fd989e15c7760c.yaml | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml diff --git a/releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml b/releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml new file mode 100644 index 000000000000..a7e30f4fc8b1 --- /dev/null +++ b/releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml @@ -0,0 +1,9 @@ +--- +features: + - | + Added `~qiskit.algorithms.observables_evaluator` with + :class:`~qiskit.primitives.BaseEstimator` as ``init`` parameter. It will soon replace + `~qiskit.algorithms.aux_ops_evaluator`. +deprecations: + - | + Using `~qiskit.algorithms.aux_ops_evaluator` will now issue a ``PendingDeprecationWarning``. From a2960b2bb36a9346160baa92c5696da8266278c5 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Wed, 7 Sep 2022 10:26:34 +0200 Subject: [PATCH 22/58] Accepting Statevector. --- qiskit/algorithms/time_evolvers/evolution_problem.py | 6 +++++- .../time_evolvers/test_evolution_problem.py | 12 ++++++------ 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/evolution_problem.py b/qiskit/algorithms/time_evolvers/evolution_problem.py index f33af102351a..ee2cb4282cee 100644 --- a/qiskit/algorithms/time_evolvers/evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/evolution_problem.py @@ -32,7 +32,7 @@ def __init__( self, hamiltonian: BaseOperator | PauliSumOp, time: float, - initial_state: QuantumCircuit | None = None, + initial_state: QuantumCircuit | Statevector | None = None, aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, @@ -63,6 +63,10 @@ def __init__( self.param_value_dict = param_value_dict self.hamiltonian = hamiltonian self.time = time + if isinstance(initial_state, Statevector): + circuit = QuantumCircuit(initial_state.num_qubits) + circuit.prepare_state(initial_state.data) + initial_state = circuit self.initial_state = initial_state self.aux_operators = aux_operators self.truncation_threshold = truncation_threshold diff --git a/test/python/algorithms/time_evolvers/test_evolution_problem.py b/test/python/algorithms/time_evolvers/test_evolution_problem.py index 76683e27cd13..315245b20ebd 100644 --- a/test/python/algorithms/time_evolvers/test_evolution_problem.py +++ b/test/python/algorithms/time_evolvers/test_evolution_problem.py @@ -12,12 +12,12 @@ """Test evolver problem class.""" import unittest - from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack from numpy.testing import assert_raises +from qiskit import QuantumCircuit from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem -from qiskit.quantum_info import Pauli, SparsePauliOp +from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.circuit import Parameter from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp @@ -48,12 +48,12 @@ def test_init_default(self): self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_dict, expected_param_value_dict) - def test_init_all(self): + @data(QuantumCircuit(1), Statevector([1, 0])) + def test_init_all(self, initial_state): """Tests that all fields are initialized correctly.""" t_parameter = Parameter("t") hamiltonian = t_parameter * Z + Y time = 2 - initial_state = One aux_operators = [X, Y] param_value_dict = {t_parameter: 3.2} @@ -68,14 +68,14 @@ def test_init_all(self): expected_hamiltonian = Y + t_parameter * Z expected_time = 2 - expected_initial_state = One + expected_type = QuantumCircuit expected_aux_operators = [X, Y] expected_t_param = t_parameter expected_param_value_dict = {t_parameter: 3.2} self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) self.assertEqual(evo_problem.time, expected_time) - self.assertEqual(evo_problem.initial_state, expected_initial_state) + self.assertEqual(type(evo_problem.initial_state), expected_type) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) self.assertEqual(evo_problem.param_value_dict, expected_param_value_dict) From 9b5f50a4348f1c9090a982465dff8e3f493c2e57 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Wed, 7 Sep 2022 10:36:37 +0200 Subject: [PATCH 23/58] Added attributes docs. --- .../time_evolvers/evolution_problem.py | 20 ++++++++++++++++++- .../time_evolvers/evolution_result.py | 10 +++++++++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/evolution_problem.py b/qiskit/algorithms/time_evolvers/evolution_problem.py index ee2cb4282cee..8b517c4e04ed 100644 --- a/qiskit/algorithms/time_evolvers/evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/evolution_problem.py @@ -13,6 +13,8 @@ """Evolution problem class.""" from __future__ import annotations +from typing import Mapping + from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression from qiskit.opflow import PauliSumOp @@ -26,6 +28,22 @@ class EvolutionProblem: This class is the input to time evolution algorithms and must contain information on the total evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. + + Attributes: + hamiltonian (BaseOperator | PauliSumOp): The Hamiltonian under which to evolve the system. + initial_state (QuantumCircuit | Statevector | None): The quantum state to be evolved for + methods like Trotterization. For variational time evolutions, where the evolution + happens in an ansatz, this argument is not required. + aux_operators (ListOrDict[BaseOperator | PauliSumOp] | None): Optional list of auxiliary + operators to be evaluated with the evolved ``initial_state`` and their expectation + values returned. + truncation_threshold (float): Defines a threshold under which values can be assumed to be 0. + Used when ``aux_operators`` is provided. + t_param (Parameter | None): Time parameter in case of a time-dependent Hamiltonian. This + free parameter must be within the ``hamiltonian``. + param_value_dict (dict[Parameter, complex] | None): Maps free parameters in the problem to + values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial + state. """ def __init__( @@ -36,7 +54,7 @@ def __init__( aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, - param_value_dict: dict[Parameter, complex] + param_value_dict: Mapping[Parameter, complex] | None = None, # parametrization will become supported in BaseOperator soon ): """ diff --git a/qiskit/algorithms/time_evolvers/evolution_result.py b/qiskit/algorithms/time_evolvers/evolution_result.py index 6d6730057871..d049e68da58d 100644 --- a/qiskit/algorithms/time_evolvers/evolution_result.py +++ b/qiskit/algorithms/time_evolvers/evolution_result.py @@ -19,7 +19,15 @@ class EvolutionResult(AlgorithmResult): - """Class for holding evolution result.""" + """ + Class for holding evolution result. + + Attributes: + evolved_state (QuantumCircuit): An evolved quantum state. + aux_ops_evaluated (ListOrDict[tuple[complex, complex]] | None): Optional list of + observables for which expected values on an evolved state are calculated. These values + are in fact tuples formatted as (mean, standard deviation). + """ def __init__( self, From 4c40e0017575d8468053fdcc3eed039ead28b75e Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Wed, 7 Sep 2022 21:45:36 +0200 Subject: [PATCH 24/58] Support for 0 operator. --- qiskit/algorithms/observables_evaluator.py | 14 ++++++++++++++ .../algorithms/test_observables_evaluator.py | 18 ++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 855a54f3ad79..cc6368c34672 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -66,6 +66,8 @@ def eval_observables( observables_list = list(observables.values()) else: observables_list = observables + + observables_list = _handle_zero_ops(observables_list) quantum_state = [quantum_state] * len(observables) try: estimator_job = estimator.run(quantum_state, observables_list) @@ -84,6 +86,18 @@ def eval_observables( return _prepare_result(observables_results, observables) +def _handle_zero_ops( + observables_list: list[BaseOperator | PauliSumOp], +) -> list[BaseOperator | PauliSumOp]: + """Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp`` + operator.""" + zero_op = PauliSumOp.from_list([("I" * observables_list[0].num_qubits, 0)]) + for ind, observable in enumerate(observables_list): + if observable == 0: + observables_list[ind] = zero_op + return observables_list + + def _prepare_result( observables_results: List[Tuple[complex, complex]], observables: ListOrDict[BaseOperator | PauliSumOp], diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 74ccee63bc9a..23e3cbda3d2a 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -27,6 +27,8 @@ from qiskit.circuit.library import EfficientSU2 from qiskit.opflow import ( PauliSumOp, + X, + Y, ) from qiskit.utils import algorithm_globals @@ -119,6 +121,22 @@ def test_eval_observables(self, observables: ListOrDict[BaseOperator | PauliSumO estimator, ) + def test_eval_observables_zero_op(self): + """Tests if a zero operator is handled correctly.""" + ansatz = EfficientSU2(2) + parameters = np.array( + [1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0, 1.2, 4.2, 1.4, 2.0], + dtype=float, + ) + + bound_ansatz = ansatz.bind_parameters(parameters) + state = bound_ansatz + estimator = Estimator() + observables = [(X ^ X) + (Y ^ Y), 0] + result = eval_observables(estimator, state, observables, self.threshold) + expected_result = [(0.015607318055509564, 0), (0.0, 0)] + np.testing.assert_array_almost_equal(result, expected_result) + if __name__ == "__main__": unittest.main() From 183563b9b39821008244e5a5798b998c5c15cd92 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 8 Sep 2022 14:24:09 +0200 Subject: [PATCH 25/58] Code refactoring. --- .../time_evolvers/trotterization/trotter_qrte.py | 16 ++++++++-------- .../time_evolvers/test_trotter_qrte.py | 7 ++++--- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index a8ad2379a6c7..1d9b20292675 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -21,13 +21,13 @@ from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult from qiskit.algorithms.time_evolvers.real_evolver import RealEvolver from qiskit.opflow import ( - PauliOp, CircuitOp, PauliSumOp, StateFn, ) from qiskit.circuit.library import PauliEvolutionGate from qiskit.primitives import BaseEstimator +from qiskit.quantum_info import Pauli from qiskit.synthesis import ProductFormula, LieTrotter @@ -40,7 +40,7 @@ class TrotterQRTE(RealEvolver): .. jupyter-execute:: from qiskit.opflow import X, Z, Zero - from qiskit.algorithms import EvolutionProblem, TrotterQRTE + from qiskit.algorithms.time_evolvers import EvolutionProblem, TrotterQRTE operator = X + Z initial_state = Zero @@ -66,21 +66,21 @@ def __init__( if product_formula is None: product_formula = LieTrotter() self.product_formula = product_formula - self.estimator = estimator + self._estimator = estimator @property def estimator(self) -> BaseEstimator | None: """ Returns an estimator. """ - return self.estimator + return self._estimator @estimator.setter def estimator(self, estimator: BaseEstimator) -> None: """ Sets an estimator. """ - self.estimator = estimator + self._estimator = estimator @classmethod def supports_aux_operators(cls) -> bool: @@ -105,7 +105,7 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: Args: evolution_problem: Instance defining evolution problem. For the included Hamiltonian, - ``PauliOp``, ``SummedOp`` or ``PauliSumOp`` are supported by TrotterQRTE. + ``Pauli`` or ``PauliSumOp`` are supported by TrotterQRTE. Returns: Evolution result that includes an evolved state as a quantum circuit and, optionally, @@ -130,9 +130,9 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: "aux_operators were provided for evaluations but no ``estimator`` was provided." ) hamiltonian = evolution_problem.hamiltonian - if not isinstance(hamiltonian, (PauliOp, PauliSumOp)): + if not isinstance(hamiltonian, (Pauli, PauliSumOp)): raise ValueError( - "TrotterQRTE only accepts PauliOp | " f"PauliSumOp, {type(hamiltonian)} provided." + f"TrotterQRTE only accepts Pauli | PauliSumOp, {type(hamiltonian)} provided." ) # the evolution gate evolution_gate = CircuitOp( diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 1f765f418b85..0427c17bbb10 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -13,7 +13,8 @@ """ Test TrotterQRTE. """ import unittest -from test.python.opflow import QiskitOpflowTestCase + +from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np from numpy.testing import assert_raises @@ -39,7 +40,7 @@ @ddt -class TestTrotterQRTE(QiskitOpflowTestCase): +class TestTrotterQRTE(QiskitAlgorithmsTestCase): """TrotterQRTE tests.""" def setUp(self): @@ -116,7 +117,7 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): ), ), ( - Y ^ Y, + Pauli("YY"), VectorStateFn( Statevector( [0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j], dims=(2, 2) From 90bed9e5e1a0edd2a27b48b4558ffc8444226108 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 8 Sep 2022 14:28:36 +0200 Subject: [PATCH 26/58] Updated init. --- .../time_evolvers/trotterization/__init__.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/qiskit/algorithms/time_evolvers/trotterization/__init__.py b/qiskit/algorithms/time_evolvers/trotterization/__init__.py index fdb172d367f0..8335588f9576 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/__init__.py +++ b/qiskit/algorithms/time_evolvers/trotterization/__init__.py @@ -9,3 +9,13 @@ # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. +"""This package contains Trotterization-based Quantum Real Time Evolution algorithm. +It is compliant with the new Quantum Time Evolution Framework and makes use of +:class:`qiskit.synthesis.evolution.ProductFormula` and +:class:`~qiskit.circuit.library.PauliEvolutionGate` implementations.""" + +from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import ( + TrotterQRTE, +) + +__all__ = ["TrotterQRTE"] From 2bcf07bec0f7dbe4dc20f02ab0e67d76f329f2b8 Mon Sep 17 00:00:00 2001 From: Manoel Marques Date: Thu, 8 Sep 2022 10:58:08 -0400 Subject: [PATCH 27/58] Add pending deprecation --- qiskit/algorithms/aux_ops_evaluator.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/qiskit/algorithms/aux_ops_evaluator.py b/qiskit/algorithms/aux_ops_evaluator.py index dded8f80645b..63b75e1c92a6 100644 --- a/qiskit/algorithms/aux_ops_evaluator.py +++ b/qiskit/algorithms/aux_ops_evaluator.py @@ -26,10 +26,18 @@ from qiskit.providers import Backend from qiskit.quantum_info import Statevector from qiskit.utils import QuantumInstance +from qiskit.utils.deprecation import deprecate_function from .list_or_dict import ListOrDict +@deprecate_function( + "The eval_observables function has been superseded by the " + "qiskit.algorithms.observables_evaluator.eval_observables function. " + "This function will be deprecated in a future release and subsequently " + "removed after that.", + category=PendingDeprecationWarning, +) def eval_observables( quantum_instance: Union[QuantumInstance, Backend], quantum_state: Union[ @@ -42,10 +50,16 @@ def eval_observables( threshold: float = 1e-12, ) -> ListOrDict[Tuple[complex, complex]]: """ - Accepts a list or a dictionary of operators and calculates their expectation values - means + Pending deprecation: Accepts a list or a dictionary of operators and calculates + their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user can optionally provide a threshold value which filters mean values falling below the threshold. + This function has been superseded by the + :func:`qiskit.algorithms.observables_evaluator.eval_observables` function. + It will be deprecated in a future release and subsequently + removed after that. + Args: quantum_instance: A quantum instance used for calculations. quantum_state: An unparametrized quantum circuit representing a quantum state that From 387ce780dfb32fb41c011955943c45dbf6794046 Mon Sep 17 00:00:00 2001 From: Manoel Marques Date: Thu, 8 Sep 2022 11:13:47 -0400 Subject: [PATCH 28/58] Add pending deprecation for evolvers --- .../algorithms/evolvers/evolution_problem.py | 15 +++++++++++++- .../algorithms/evolvers/evolution_result.py | 17 +++++++++++++++- .../algorithms/evolvers/imaginary_evolver.py | 20 ++++++++++++++++++- qiskit/algorithms/evolvers/pvqd/pvqd.py | 1 + qiskit/algorithms/evolvers/real_evolver.py | 20 ++++++++++++++++++- .../evolvers/trotterization/trotter_qrte.py | 20 ++++++++++++++++++- 6 files changed, 88 insertions(+), 5 deletions(-) diff --git a/qiskit/algorithms/evolvers/evolution_problem.py b/qiskit/algorithms/evolvers/evolution_problem.py index 175beecd6bf6..bc815c7425d5 100644 --- a/qiskit/algorithms/evolvers/evolution_problem.py +++ b/qiskit/algorithms/evolvers/evolution_problem.py @@ -17,16 +17,29 @@ from qiskit import QuantumCircuit from qiskit.circuit import Parameter from qiskit.opflow import OperatorBase, StateFn +from qiskit.utils.deprecation import deprecate_function from ..list_or_dict import ListOrDict class EvolutionProblem: - """Evolution problem class. + """Pending deprecation: Evolution problem class. + + The EvolutionProblem class has been superseded by the + :class:`qiskit.algorithms.time_evolvers.EvolutionProblem` class. + This class will be deprecated in a future release and subsequently + removed after that. This class is the input to time evolution algorithms and must contain information on the total evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. """ + @deprecate_function( + "The EvolutionProblem class has been superseded by the " + "qiskit.algorithms.time_evolvers.EvolutionProblem class. " + "This class will be deprecated in a future release and subsequently " + "removed after that.", + category=PendingDeprecationWarning, + ) def __init__( self, hamiltonian: OperatorBase, diff --git a/qiskit/algorithms/evolvers/evolution_result.py b/qiskit/algorithms/evolvers/evolution_result.py index 1dd91d705d28..1f2c1d50c5de 100644 --- a/qiskit/algorithms/evolvers/evolution_result.py +++ b/qiskit/algorithms/evolvers/evolution_result.py @@ -17,12 +17,27 @@ from qiskit import QuantumCircuit from qiskit.algorithms.list_or_dict import ListOrDict from qiskit.opflow import StateFn, OperatorBase +from qiskit.utils.deprecation import deprecate_function from ..algorithm_result import AlgorithmResult class EvolutionResult(AlgorithmResult): - """Class for holding evolution result.""" + """Pending deprecation: Class for holding evolution result. + The EvolutionResult class has been superseded by the + :class:`qiskit.algorithms.time_evolvers.EvolutionResult` class. + This class will be deprecated in a future release and subsequently + removed after that. + + """ + + @deprecate_function( + "The EvolutionResult class has been superseded by the " + "qiskit.algorithms.time_evolvers.EvolutionResult class. " + "This class will be deprecated in a future release and subsequently " + "removed after that.", + category=PendingDeprecationWarning, + ) def __init__( self, evolved_state: Union[StateFn, QuantumCircuit, OperatorBase], diff --git a/qiskit/algorithms/evolvers/imaginary_evolver.py b/qiskit/algorithms/evolvers/imaginary_evolver.py index 309bb73b08af..520de1bbaae1 100644 --- a/qiskit/algorithms/evolvers/imaginary_evolver.py +++ b/qiskit/algorithms/evolvers/imaginary_evolver.py @@ -14,12 +14,30 @@ from abc import ABC, abstractmethod +from qiskit.utils.deprecation import deprecate_function from .evolution_problem import EvolutionProblem from .evolution_result import EvolutionResult class ImaginaryEvolver(ABC): - """Interface for Quantum Imaginary Time Evolution.""" + """Pending deprecation: Interface for Quantum Imaginary Time Evolution. + + The ImaginaryEvolver interface has been superseded by the + :class:`qiskit.algorithms.time_evolvers.ImaginaryEvolver` interface. + This interface will be deprecated in a future release and subsequently + removed after that. + + """ + + @deprecate_function( + "The ImaginaryEvolver interface has been superseded by the " + "qiskit.algorithms.time_evolvers.ImaginaryEvolver interface. " + "This interface will be deprecated in a future release and subsequently " + "removed after that.", + category=PendingDeprecationWarning, + ) + def __init__(self) -> None: + pass @abstractmethod def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: diff --git a/qiskit/algorithms/evolvers/pvqd/pvqd.py b/qiskit/algorithms/evolvers/pvqd/pvqd.py index e4a1d5893bb5..323f32aa9db5 100644 --- a/qiskit/algorithms/evolvers/pvqd/pvqd.py +++ b/qiskit/algorithms/evolvers/pvqd/pvqd.py @@ -149,6 +149,7 @@ def __init__( a random vector with elements in the interval :math:`[-0.01, 0.01]`. quantum_instance: The backend or quantum instance used to evaluate the circuits. """ + super().__init__() if evolution is None: evolution = LieTrotter() diff --git a/qiskit/algorithms/evolvers/real_evolver.py b/qiskit/algorithms/evolvers/real_evolver.py index 6107facfe542..0ccaad7fa9b2 100644 --- a/qiskit/algorithms/evolvers/real_evolver.py +++ b/qiskit/algorithms/evolvers/real_evolver.py @@ -13,13 +13,31 @@ """Interface for Quantum Real Time Evolution.""" from abc import ABC, abstractmethod +from qiskit.utils.deprecation import deprecate_function from .evolution_problem import EvolutionProblem from .evolution_result import EvolutionResult class RealEvolver(ABC): - """Interface for Quantum Real Time Evolution.""" + """Pending deprecation: Interface for Quantum Real Time Evolution. + + The RealEvolver interface has been superseded by the + :class:`qiskit.algorithms.time_evolvers.RealEvolver` interface. + This interface will be deprecated in a future release and subsequently + removed after that. + + """ + + @deprecate_function( + "The RealEvolver interface has been superseded by the " + "qiskit.algorithms.time_evolvers.RealEvolver interface. " + "This interface will be deprecated in a future release and subsequently " + "removed after that.", + category=PendingDeprecationWarning, + ) + def __init__(self) -> None: + pass @abstractmethod def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: diff --git a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py index 05b8266605b7..e91793570d51 100644 --- a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py @@ -13,6 +13,7 @@ """An algorithm to implement a Trotterization real time-evolution.""" from typing import Union, Optional +import warnings from qiskit import QuantumCircuit from qiskit.algorithms.aux_ops_evaluator import eval_observables @@ -32,10 +33,17 @@ from qiskit.providers import Backend from qiskit.synthesis import ProductFormula, LieTrotter from qiskit.utils import QuantumInstance +from qiskit.utils.deprecation import deprecate_function class TrotterQRTE(RealEvolver): - """Quantum Real Time Evolution using Trotterization. + """Pending deprecation: Quantum Real Time Evolution using Trotterization. + + The TrotterQRTE class has been superseded by the + :class:`qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE` class. + This class will be deprecated in a future release and subsequently + removed after that. + Type of Trotterization is defined by a ProductFormula provided. Examples: @@ -58,6 +66,13 @@ class TrotterQRTE(RealEvolver): evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ + @deprecate_function( + "The TrotterQRTE class has been superseded by the " + "qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE class. " + "This class will be deprecated in a future release and subsequently " + "removed after that.", + category=PendingDeprecationWarning, + ) def __init__( self, product_formula: Optional[ProductFormula] = None, @@ -73,6 +88,9 @@ def __init__( quantum_instance: A quantum instance used for calculating expectation values of EvolutionProblem.aux_operators. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if product_formula is None: product_formula = LieTrotter() self._product_formula = product_formula From f5c3eaf6aaf59ff89598fedcce933b0ceb874782 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 8 Sep 2022 18:00:21 +0200 Subject: [PATCH 29/58] Code refactoring. --- qiskit/algorithms/observables_evaluator.py | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index cc6368c34672..2bfa92ed4e63 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -12,8 +12,6 @@ """Evaluator of auxiliary operators for algorithms.""" from __future__ import annotations -from typing import Tuple, List - import numpy as np from qiskit import QuantumCircuit @@ -31,7 +29,7 @@ def eval_observables( quantum_state: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp], threshold: float = 1e-12, -) -> ListOrDict[Tuple[complex, complex]]: +) -> ListOrDict[tuple[complex, complex]]: """ Accepts a sequence of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user @@ -99,15 +97,15 @@ def _handle_zero_ops( def _prepare_result( - observables_results: List[Tuple[complex, complex]], + observables_results: list[tuple[complex, complex]], observables: ListOrDict[BaseOperator | PauliSumOp], -) -> ListOrDict[Tuple[complex, complex]]: +) -> ListOrDict[tuple[complex, complex]]: """ Prepares a list of eigenvalues and standard deviations from ``observables_results`` and ``observables``. Args: - observables_results: A list of of tuples (mean, standard deviation). + observables_results: A list of tuples (mean, standard deviation). observables: A list or a dictionary of operators whose expectation values are to be calculated. @@ -131,7 +129,7 @@ def _prepare_result( def _compute_std_devs( estimator_result: EstimatorResult, results_length: int, -) -> List[complex | None]: +) -> list[complex | None]: """ Calculates a list of standard deviations from expectation values of observables provided. If there is no variance data available from a primitive, the standard deviation values will be set From 553714c793706d4cb9e48d22d84f73eb44224229 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 8 Sep 2022 18:01:29 +0200 Subject: [PATCH 30/58] Code refactoring. --- qiskit/algorithms/observables_evaluator.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 2bfa92ed4e63..5c8e14a43406 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -15,9 +15,7 @@ import numpy as np from qiskit import QuantumCircuit -from qiskit.opflow import ( - PauliSumOp, -) +from qiskit.opflow import PauliSumOp from . import AlgorithmError from .list_or_dict import ListOrDict from ..primitives import EstimatorResult, BaseEstimator From a7e2f607afb4cb372afb58b2ef5f3497b02f99a6 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 8 Sep 2022 20:12:04 +0200 Subject: [PATCH 31/58] Renamed classes and linked to algorithms init. --- qiskit/algorithms/__init__.py | 25 +++++++++++++++++++ ...y_evolver.py => imaginary_time_evolver.py} | 8 +++--- .../{real_evolver.py => real_time_evolver.py} | 8 +++--- ...n_problem.py => time_evolution_problem.py} | 2 +- ...ion_result.py => time_evolution_result.py} | 2 +- ...framework-primitives-c86779b5d0dffd25.yaml | 8 +++--- ...blem.py => test_time_evolution_problem.py} | 12 ++++----- ...esult.py => test_time_evolution_result.py} | 8 +++--- 8 files changed, 49 insertions(+), 24 deletions(-) rename qiskit/algorithms/time_evolvers/{imaginary_evolver.py => imaginary_time_evolver.py} (83%) rename qiskit/algorithms/time_evolvers/{real_evolver.py => real_time_evolver.py} (82%) rename qiskit/algorithms/time_evolvers/{evolution_problem.py => time_evolution_problem.py} (99%) rename qiskit/algorithms/time_evolvers/{evolution_result.py => time_evolution_result.py} (97%) rename test/python/algorithms/time_evolvers/{test_evolution_problem.py => test_time_evolution_problem.py} (90%) rename test/python/algorithms/time_evolvers/{test_evolution_result.py => test_time_evolution_result.py} (85%) diff --git a/qiskit/algorithms/__init__.py b/qiskit/algorithms/__init__.py index 30d71a59e59c..b1419d3f4811 100644 --- a/qiskit/algorithms/__init__.py +++ b/qiskit/algorithms/__init__.py @@ -127,6 +127,23 @@ EvolutionProblem +Time Evolvers +-------- + +Primitives-enabled algorithms to evolve quantum states in time. Both real and imaginary time +evolution is possible with algorithms that support them. For machine learning, Quantum Imaginary +Time Evolution might be used to train Quantum Boltzmann Machine Neural Networks for example. + +.. autosummary:: + :toctree: ../stubs/ + :nosignatures: + + RealTimeEvolver + ImaginaryTimeEvolver + TimeEvolutionResult + TimeEvolutionProblem + + Factorizers ----------- @@ -225,6 +242,10 @@ from .evolvers import EvolutionResult, EvolutionProblem from .evolvers.real_evolver import RealEvolver from .evolvers.imaginary_evolver import ImaginaryEvolver +from .time_evolvers.imaginary_time_evolver import ImaginaryTimeEvolver +from .time_evolvers.real_time_evolver import RealTimeEvolver +from .time_evolvers.time_evolution_problem import TimeEvolutionProblem +from .time_evolvers.time_evolution_result import TimeEvolutionResult from .variational_algorithm import VariationalAlgorithm, VariationalResult from .amplitude_amplifiers import Grover, GroverResult, AmplificationProblem, AmplitudeAmplifier from .amplitude_estimators import ( @@ -288,11 +309,15 @@ "NumPyEigensolver", "RealEvolver", "ImaginaryEvolver", + "RealTimeEvolver", + "ImaginaryTimeEvolver", "TrotterQRTE", "VarQITE", "VarQRTE", "EvolutionResult", "EvolutionProblem", + "TimeEvolutionResult", + "TimeEvolutionProblem", "LinearSolverResult", "Eigensolver", "EigensolverResult", diff --git a/qiskit/algorithms/time_evolvers/imaginary_evolver.py b/qiskit/algorithms/time_evolvers/imaginary_time_evolver.py similarity index 83% rename from qiskit/algorithms/time_evolvers/imaginary_evolver.py rename to qiskit/algorithms/time_evolvers/imaginary_time_evolver.py index 309bb73b08af..e62d02e5ab9c 100644 --- a/qiskit/algorithms/time_evolvers/imaginary_evolver.py +++ b/qiskit/algorithms/time_evolvers/imaginary_time_evolver.py @@ -14,15 +14,15 @@ from abc import ABC, abstractmethod -from .evolution_problem import EvolutionProblem -from .evolution_result import EvolutionResult +from .time_evolution_problem import TimeEvolutionProblem +from .time_evolution_result import TimeEvolutionResult -class ImaginaryEvolver(ABC): +class ImaginaryTimeEvolver(ABC): """Interface for Quantum Imaginary Time Evolution.""" @abstractmethod - def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: + def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult: r"""Perform imaginary time evolution :math:`\exp(-\tau H)|\Psi\rangle`. Evolves an initial state :math:`|\Psi\rangle` for an imaginary time :math:`\tau` diff --git a/qiskit/algorithms/time_evolvers/real_evolver.py b/qiskit/algorithms/time_evolvers/real_time_evolver.py similarity index 82% rename from qiskit/algorithms/time_evolvers/real_evolver.py rename to qiskit/algorithms/time_evolvers/real_time_evolver.py index 6107facfe542..587f85d436e2 100644 --- a/qiskit/algorithms/time_evolvers/real_evolver.py +++ b/qiskit/algorithms/time_evolvers/real_time_evolver.py @@ -14,15 +14,15 @@ from abc import ABC, abstractmethod -from .evolution_problem import EvolutionProblem -from .evolution_result import EvolutionResult +from .time_evolution_problem import TimeEvolutionProblem +from .time_evolution_result import TimeEvolutionResult -class RealEvolver(ABC): +class RealTimeEvolver(ABC): """Interface for Quantum Real Time Evolution.""" @abstractmethod - def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: + def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult: r"""Perform real time evolution :math:`\exp(-i t H)|\Psi\rangle`. Evolves an initial state :math:`|\Psi\rangle` for a time :math:`t` diff --git a/qiskit/algorithms/time_evolvers/evolution_problem.py b/qiskit/algorithms/time_evolvers/time_evolution_problem.py similarity index 99% rename from qiskit/algorithms/time_evolvers/evolution_problem.py rename to qiskit/algorithms/time_evolvers/time_evolution_problem.py index 8b517c4e04ed..59868cbe51c6 100644 --- a/qiskit/algorithms/time_evolvers/evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/time_evolution_problem.py @@ -23,7 +23,7 @@ from ...quantum_info.operators.base_operator import BaseOperator -class EvolutionProblem: +class TimeEvolutionProblem: """Evolution problem class. This class is the input to time evolution algorithms and must contain information on the total diff --git a/qiskit/algorithms/time_evolvers/evolution_result.py b/qiskit/algorithms/time_evolvers/time_evolution_result.py similarity index 97% rename from qiskit/algorithms/time_evolvers/evolution_result.py rename to qiskit/algorithms/time_evolvers/time_evolution_result.py index d049e68da58d..2ff47e3d08e5 100644 --- a/qiskit/algorithms/time_evolvers/evolution_result.py +++ b/qiskit/algorithms/time_evolvers/time_evolution_result.py @@ -18,7 +18,7 @@ from ..algorithm_result import AlgorithmResult -class EvolutionResult(AlgorithmResult): +class TimeEvolutionResult(AlgorithmResult): """ Class for holding evolution result. diff --git a/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml b/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml index 1ea0b3485541..bfc708ca9c72 100644 --- a/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml +++ b/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml @@ -3,10 +3,10 @@ features: - | Added `~qiskit.algorithms.time_evolvers` package with interfaces that will cover primitive-enabled time evolution algorithms: - :class:`~qiskit.algorithms.time_evolvers.EvolutionProblem`, - :class:`~qiskit.algorithms.time_evolvers.EvolutionResult`, - :class:`~qiskit.algorithms.time_evolvers.ImaginaryEvolver`, - :class:`~qiskit.algorithms.time_evolvers.RealEvolver`. + :class:`~qiskit.algorithms.time_evolvers.TimeEvolutionProblem`, + :class:`~qiskit.algorithms.time_evolvers.TimeEvolutionResult`, + :class:`~qiskit.algorithms.time_evolvers.ImaginaryTimeEvolver`, + :class:`~qiskit.algorithms.time_evolvers.RealTimeEvolver`. deprecations: - | `~qiskit.algorithms.evolvers` package will now issue a ``PendingDeprecationWarning``. diff --git a/test/python/algorithms/time_evolvers/test_evolution_problem.py b/test/python/algorithms/time_evolvers/test_time_evolution_problem.py similarity index 90% rename from test/python/algorithms/time_evolvers/test_evolution_problem.py rename to test/python/algorithms/time_evolvers/test_time_evolution_problem.py index 315245b20ebd..227583f8aef7 100644 --- a/test/python/algorithms/time_evolvers/test_evolution_problem.py +++ b/test/python/algorithms/time_evolvers/test_time_evolution_problem.py @@ -16,14 +16,14 @@ from ddt import data, ddt, unpack from numpy.testing import assert_raises from qiskit import QuantumCircuit -from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.algorithms import TimeEvolutionProblem from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.circuit import Parameter from qiskit.opflow import Y, Z, One, X, Zero, PauliSumOp @ddt -class TestEvolutionProblem(QiskitAlgorithmsTestCase): +class TestTimeEvolutionProblem(QiskitAlgorithmsTestCase): """Test evolver problem class.""" def test_init_default(self): @@ -32,7 +32,7 @@ def test_init_default(self): time = 2.5 initial_state = One - evo_problem = EvolutionProblem(hamiltonian, time, initial_state) + evo_problem = TimeEvolutionProblem(hamiltonian, time, initial_state) expected_hamiltonian = Y expected_time = 2.5 @@ -57,7 +57,7 @@ def test_init_all(self, initial_state): aux_operators = [X, Y] param_value_dict = {t_parameter: 3.2} - evo_problem = EvolutionProblem( + evo_problem = TimeEvolutionProblem( hamiltonian, time, initial_state, @@ -85,14 +85,14 @@ def test_init_all(self, initial_state): def test_init_errors(self, hamiltonian, time, initial_state): """Tests expected errors are thrown on invalid time argument.""" with assert_raises(ValueError): - _ = EvolutionProblem(hamiltonian, time, initial_state) + _ = TimeEvolutionProblem(hamiltonian, time, initial_state) def test_validate_params(self): """Tests expected errors are thrown on parameters mismatch.""" param_x = Parameter("x") with self.subTest(msg="Parameter missing in dict."): hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x) - evolution_problem = EvolutionProblem(hamiltonian, 2, Zero) + evolution_problem = TimeEvolutionProblem(hamiltonian, 2, Zero) with assert_raises(ValueError): evolution_problem.validate_params() diff --git a/test/python/algorithms/time_evolvers/test_evolution_result.py b/test/python/algorithms/time_evolvers/test_time_evolution_result.py similarity index 85% rename from test/python/algorithms/time_evolvers/test_evolution_result.py rename to test/python/algorithms/time_evolvers/test_time_evolution_result.py index 52b7f3faaf98..26f21ba93627 100644 --- a/test/python/algorithms/time_evolvers/test_evolution_result.py +++ b/test/python/algorithms/time_evolvers/test_time_evolution_result.py @@ -12,17 +12,17 @@ """Class for testing evolution result.""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase -from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult +from qiskit.algorithms import TimeEvolutionResult from qiskit.opflow import Zero -class TestEvolutionResult(QiskitAlgorithmsTestCase): +class TestTimeEvolutionResult(QiskitAlgorithmsTestCase): """Class for testing evolution result and relevant metadata.""" def test_init_state(self): """Tests that a class is initialized correctly with an evolved_state.""" evolved_state = Zero - evo_result = EvolutionResult(evolved_state=evolved_state) + evo_result = TimeEvolutionResult(evolved_state=evolved_state) expected_state = Zero expected_aux_ops_evaluated = None @@ -34,7 +34,7 @@ def test_init_observable(self): """Tests that a class is initialized correctly with an evolved_observable.""" evolved_state = Zero evolved_aux_ops_evaluated = [(5j, 5j), (1.0, 8j), (5 + 1j, 6 + 1j)] - evo_result = EvolutionResult(evolved_state, evolved_aux_ops_evaluated) + evo_result = TimeEvolutionResult(evolved_state, evolved_aux_ops_evaluated) expected_state = Zero expected_aux_ops_evaluated = [(5j, 5j), (1.0, 8j), (5 + 1j, 6 + 1j)] From 5c8725562d8adacc8a30f00e254d59476580411f Mon Sep 17 00:00:00 2001 From: Manoel Marques Date: Thu, 8 Sep 2022 15:35:11 -0400 Subject: [PATCH 32/58] fix docstring --- qiskit/algorithms/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/algorithms/__init__.py b/qiskit/algorithms/__init__.py index 408aac4c922e..ef79ed3431f5 100644 --- a/qiskit/algorithms/__init__.py +++ b/qiskit/algorithms/__init__.py @@ -128,7 +128,7 @@ Time Evolvers --------- +------------- Primitives-enabled algorithms to evolve quantum states in time. Both real and imaginary time evolution is possible with algorithms that support them. For machine learning, Quantum Imaginary From d03bddfe4e76d458bfc992e3956c97f26757e5f2 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 09:41:09 +0200 Subject: [PATCH 33/58] Improved reno. --- ...ion-framework-primitives-c86779b5d0dffd25.yaml | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml b/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml index bfc708ca9c72..2adf8a637293 100644 --- a/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml +++ b/releasenotes/notes/evolution-framework-primitives-c86779b5d0dffd25.yaml @@ -1,12 +1,15 @@ --- features: - | - Added `~qiskit.algorithms.time_evolvers` package with interfaces that will cover + Added :class:`qiskit.algorithms.time_evolvers` package with interfaces that will cover primitive-enabled time evolution algorithms: - :class:`~qiskit.algorithms.time_evolvers.TimeEvolutionProblem`, - :class:`~qiskit.algorithms.time_evolvers.TimeEvolutionResult`, - :class:`~qiskit.algorithms.time_evolvers.ImaginaryTimeEvolver`, - :class:`~qiskit.algorithms.time_evolvers.RealTimeEvolver`. + :class:`qiskit.algorithms.time_evolvers.TimeEvolutionProblem`, + :class:`qiskit.algorithms.time_evolvers.TimeEvolutionResult`, + :class:`qiskit.algorithms.time_evolvers.ImaginaryTimeEvolver`, + :class:`qiskit.algorithms.time_evolvers.RealTimeEvolver`. deprecations: - | - `~qiskit.algorithms.evolvers` package will now issue a ``PendingDeprecationWarning``. + :class:`qiskit.algorithms.evolvers` package will now issue a ``PendingDeprecationWarning``. It + will be deprecated in a future release and subsequently removed after that. This is being + replaced by the new :class:`qiskit.algorithms.time_evolvers` package that will host + primitive-enabled algorithms. From 92d6515e20d0d60757bfef004d302bc8087fdf5d Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 09:46:33 +0200 Subject: [PATCH 34/58] Improved reno. --- .../observable-eval-primitives-e1fd989e15c7760c.yaml | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml b/releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml index a7e30f4fc8b1..43b2c622edbb 100644 --- a/releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml +++ b/releasenotes/notes/observable-eval-primitives-e1fd989e15c7760c.yaml @@ -1,9 +1,12 @@ --- features: - | - Added `~qiskit.algorithms.observables_evaluator` with - :class:`~qiskit.primitives.BaseEstimator` as ``init`` parameter. It will soon replace - `~qiskit.algorithms.aux_ops_evaluator`. + Added :meth:`qiskit.algorithms.observables_evaluator.eval_observables` with + :class:`qiskit.primitives.BaseEstimator` as ``init`` parameter. It will soon replace + :meth:`qiskit.algorithms.aux_ops_evaluator.eval_observables`. deprecations: - | - Using `~qiskit.algorithms.aux_ops_evaluator` will now issue a ``PendingDeprecationWarning``. + Using :meth:`qiskit.algorithms.aux_ops_evaluator.eval_observables` will now issue a + ``PendingDeprecationWarning``. This method will be deprecated in a future release and + subsequently removed after that. This is being replaced by the new + :meth:`qiskit.algorithms.observables_evaluator.eval_observables` primitive-enabled method. From 9ba37ed4287d2ff7e6831d516c8c6aa0a77c683b Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 10:09:43 +0200 Subject: [PATCH 35/58] Returning variances and shots. --- qiskit/algorithms/observables_evaluator.py | 44 +++++++++---------- .../algorithms/test_observables_evaluator.py | 26 +++++++---- 2 files changed, 38 insertions(+), 32 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 5c8e14a43406..6e9b347a1c33 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -27,7 +27,7 @@ def eval_observables( quantum_state: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp], threshold: float = 1e-12, -) -> ListOrDict[tuple[complex, complex]]: +) -> ListOrDict[tuple[complex, tuple[complex | None, int | None]]]: """ Accepts a sequence of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user @@ -71,19 +71,18 @@ def eval_observables( except Exception as exc: raise AlgorithmError("The primitive job failed!") from exc - std_devs = _compute_std_devs(estimator_job, len(expectation_values)) + variance_and_shots = _prep_variance_and_shots(estimator_job, len(expectation_values)) # Discard values below threshold observables_means = expectation_values * (np.abs(expectation_values) > threshold) # zip means and standard deviations into tuples - observables_results = list(zip(observables_means, std_devs)) + observables_results = list(zip(observables_means, variance_and_shots)) - # Return None eigenvalues for None operators if observables is a list. return _prepare_result(observables_results, observables) def _handle_zero_ops( - observables_list: list[BaseOperator | PauliSumOp], + observables_list: list[BaseOperator | PauliSumOp | int], ) -> list[BaseOperator | PauliSumOp]: """Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp`` operator.""" @@ -95,12 +94,12 @@ def _handle_zero_ops( def _prepare_result( - observables_results: list[tuple[complex, complex]], + observables_results: list[tuple[complex, tuple[complex | None, int | None]]], observables: ListOrDict[BaseOperator | PauliSumOp], -) -> ListOrDict[tuple[complex, complex]]: +) -> ListOrDict[tuple[complex, tuple[complex | None, int | None]]]: """ - Prepares a list of eigenvalues and standard deviations from ``observables_results`` and - ``observables``. + Prepares a list of tuples of eigenvalues and (variance, shots) tuples from + ``observables_results`` and ``observables``. Args: observables_results: A list of tuples (mean, standard deviation). @@ -108,7 +107,7 @@ def _prepare_result( calculated. Returns: - A list or a dictionary of tuples (mean, standard deviation). + A list or a dictionary of tuples (mean, (variance, shots)). """ if isinstance(observables, list): @@ -124,35 +123,32 @@ def _prepare_result( return observables_eigenvalues -def _compute_std_devs( +def _prep_variance_and_shots( estimator_result: EstimatorResult, results_length: int, -) -> list[complex | None]: +) -> list[tuple[complex | None, int | None]]: """ - Calculates a list of standard deviations from expectation values of observables provided. If - there is no variance data available from a primitive, the standard deviation values will be set - to ``None``. + Prepares a list of tuples with variances and shots from results provided by expectation values + calculations. If there is no variance or shots data available from a primitive, the values will + be set to ``0``. Args: estimator_result: An estimator result. results_length: Number of expectation values calculated. Returns: - A list of standard deviations. + A list of tuples of the form (variance, shots). """ if not estimator_result.metadata: - return [0] * results_length + return [(0, 0)] * results_length - std_devs = [] + results = [] for metadata in estimator_result.metadata: if metadata and "variance" in metadata.keys() and "shots" in metadata.keys(): variance = metadata["variance"] shots = metadata["shots"] - if variance is None or shots is None: - std_devs.append(None) - else: - std_devs.append(np.sqrt(variance / shots)) + results.append((variance, shots)) else: - std_devs.append(0) + results.append((0, 0)) - return std_devs + return results diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 23e3cbda3d2a..88f0c7381b61 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -54,9 +54,9 @@ def get_exact_expectation( observables_list = list(observables.values()) else: observables_list = observables - # the exact value is a list of (mean, variance) where we expect 0 variance + # the exact value is a list of (mean, (variance, shots)) where we expect 0 variance and 0 shots exact = [ - (Statevector(ansatz).expectation_value(observable), 0) + (Statevector(ansatz).expectation_value(observable), (0, 0)) for observable in observables_list ] @@ -77,11 +77,21 @@ def _run_test( if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) - np.testing.assert_array_almost_equal( - list(result.values()), list(expected_result.values()), decimal=decimal - ) + means = [element[0] for element in result.values()] + expected_means = [element[0] for element in expected_result.values()] + np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) + + vars_and_shots = [element[1] for element in result.values()] + expected_vars_and_shots = [element[1] for element in expected_result.values()] + np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) else: - np.testing.assert_array_almost_equal(result, expected_result, decimal=decimal) + means = [element[0] for element in result] + expected_means = [element[0] for element in expected_result] + np.testing.assert_array_almost_equal(means, expected_means, decimal=decimal) + + vars_and_shots = [element[1] for element in result] + expected_vars_and_shots = [element[1] for element in expected_result] + np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) @data( [ @@ -134,8 +144,8 @@ def test_eval_observables_zero_op(self): estimator = Estimator() observables = [(X ^ X) + (Y ^ Y), 0] result = eval_observables(estimator, state, observables, self.threshold) - expected_result = [(0.015607318055509564, 0), (0.0, 0)] - np.testing.assert_array_almost_equal(result, expected_result) + expected_result = [(0.015607318055509564, (0, 0)), (0.0, (0, 0))] + np.testing.assert_array_equal(result, expected_result) if __name__ == "__main__": From 76800190163fb6fec727c30381b610a8ced994ba Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 10:17:49 +0200 Subject: [PATCH 36/58] Code refactoring. --- qiskit/algorithms/time_evolvers/time_evolution_problem.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/time_evolution_problem.py b/qiskit/algorithms/time_evolvers/time_evolution_problem.py index 59868cbe51c6..ceb4b97c4175 100644 --- a/qiskit/algorithms/time_evolvers/time_evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/time_evolution_problem.py @@ -13,7 +13,7 @@ """Evolution problem class.""" from __future__ import annotations -from typing import Mapping +from collections.abc import Mapping from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression @@ -54,8 +54,7 @@ def __init__( aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, - param_value_dict: Mapping[Parameter, complex] - | None = None, # parametrization will become supported in BaseOperator soon + param_value_dict: Mapping[Parameter, complex] | None = None, # parametrization will become supported in BaseOperator soon ): """ Args: From 5cd8e19023e0993b46d65c0a76b8a8aa39dc5670 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 13:27:31 +0200 Subject: [PATCH 37/58] Updated classes and applied CR suggestions. --- .../time_evolvers/time_evolution_problem.py | 3 +- .../time_evolvers/trotterization/__init__.py | 4 +-- .../trotterization/trotter_qrte.py | 32 +++++++++++-------- .../time_evolvers/test_trotter_qrte.py | 26 +++++++++------ 4 files changed, 38 insertions(+), 27 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/time_evolution_problem.py b/qiskit/algorithms/time_evolvers/time_evolution_problem.py index ceb4b97c4175..ec058bdfb4b0 100644 --- a/qiskit/algorithms/time_evolvers/time_evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/time_evolution_problem.py @@ -54,7 +54,8 @@ def __init__( aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, - param_value_dict: Mapping[Parameter, complex] | None = None, # parametrization will become supported in BaseOperator soon + param_value_dict: Mapping[Parameter, complex] + | None = None, # parametrization will become supported in BaseOperator soon ): """ Args: diff --git a/qiskit/algorithms/time_evolvers/trotterization/__init__.py b/qiskit/algorithms/time_evolvers/trotterization/__init__.py index 8335588f9576..eda3141296d7 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/__init__.py +++ b/qiskit/algorithms/time_evolvers/trotterization/__init__.py @@ -14,8 +14,6 @@ :class:`qiskit.synthesis.evolution.ProductFormula` and :class:`~qiskit.circuit.library.PauliEvolutionGate` implementations.""" -from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import ( - TrotterQRTE, -) +from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE __all__ = ["TrotterQRTE"] diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 1d9b20292675..16bc4dd59252 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -14,12 +14,14 @@ from __future__ import annotations +import warnings + from qiskit.algorithms.observables_evaluator import eval_observables from qiskit import QuantumCircuit -from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem -from qiskit.algorithms.time_evolvers.evolution_result import EvolutionResult -from qiskit.algorithms.time_evolvers.real_evolver import RealEvolver +from qiskit.algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem +from qiskit.algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult +from qiskit.algorithms.time_evolvers.real_time_evolver import RealTimeEvolver from qiskit.opflow import ( CircuitOp, PauliSumOp, @@ -31,21 +33,25 @@ from qiskit.synthesis import ProductFormula, LieTrotter -class TrotterQRTE(RealEvolver): +class TrotterQRTE(RealTimeEvolver): """Quantum Real Time Evolution using Trotterization. Type of Trotterization is defined by a ProductFormula provided. + Attributes: + product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter + first order product formula with a single repetition. + Examples: - .. jupyter-execute:: + .. code-block:: python from qiskit.opflow import X, Z, Zero - from qiskit.algorithms.time_evolvers import EvolutionProblem, TrotterQRTE + from qiskit.algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE operator = X + Z initial_state = Zero time = 1 - evolution_problem = EvolutionProblem(operator, 1, initial_state) + evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) # LieTrotter with 1 rep trotter_qrte = TrotterQRTE() evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state @@ -93,7 +99,7 @@ def supports_aux_operators(cls) -> bool: """ return True - def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: + def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult: """ Evolves a quantum state for a given time using the Trotterization method based on a product formula provided. The result is provided in the form of a quantum @@ -114,7 +120,6 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: Raises: ValueError: If ``t_param`` is not set to ``None`` in the EvolutionProblem (feature not currently supported). - ValueError: If ``aux_operators` are provided but no ``Estimator`` is provided. ValueError: If the ``initial_state`` is not provided in the EvolutionProblem. ValueError: If an unsupported Hamiltonian type is provided. """ @@ -125,9 +130,10 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: "``t_param`` from the EvolutionProblem should be set to None." ) - if evolution_problem.aux_operators is not None and (self.estimator is None): - raise ValueError( - "aux_operators were provided for evaluations but no ``estimator`` was provided." + if evolution_problem.aux_operators is not None and self.estimator is None: + warnings.warn( + "The evolution problem contained aux_operators but no estimator was provided. " + "The algorithm continues without calculating these quantities. " ) hamiltonian = evolution_problem.hamiltonian if not isinstance(hamiltonian, (Pauli, PauliSumOp)): @@ -157,4 +163,4 @@ def evolve(self, evolution_problem: EvolutionProblem) -> EvolutionResult: evolution_problem.truncation_threshold, ) - return EvolutionResult(evolved_state, evaluated_aux_ops) + return TimeEvolutionResult(evolved_state, evaluated_aux_ops) diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 0427c17bbb10..1e09b1ab0fa0 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -19,7 +19,7 @@ import numpy as np from numpy.testing import assert_raises -from qiskit.algorithms.time_evolvers.evolution_problem import EvolutionProblem +from qiskit.algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE from qiskit.primitives import Estimator from qiskit import QuantumCircuit @@ -66,7 +66,7 @@ def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state operator = X + Z initial_state = StateFn([1, 0]) time = 1 - evolution_problem = EvolutionProblem(operator, time, initial_state) + evolution_problem = TimeEvolutionProblem(operator, time, initial_state) trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state @@ -81,13 +81,12 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): initial_state = Zero time = 3 - evolution_problem = EvolutionProblem(operator, time, initial_state, aux_ops) + evolution_problem = TimeEvolutionProblem(operator, time, initial_state, aux_ops) estimator = Estimator() expected_evolved_state = VectorStateFn( Statevector([0.98008514 + 0.13970775j, 0.01991486 + 0.13970775j], dims=(2,)) ) - expected_aux_ops_evaluated = [(0.078073, 0.0), (0.268286, 0.0)] algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) @@ -95,9 +94,16 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_evolved_state) - np.testing.assert_array_almost_equal( - evolution_result.aux_ops_evaluated, expected_aux_ops_evaluated - ) + aux_ops_result = evolution_result.aux_ops_evaluated + expected_aux_ops_result = [(0.078073, (0.0, 0.0)), (0.268286, (0.0, 0.0))] + + means = [element[0] for element in aux_ops_result] + expected_means = [element[0] for element in expected_aux_ops_result] + np.testing.assert_array_almost_equal(means, expected_means) + + vars_and_shots = [element[1] for element in aux_ops_result] + expected_vars_and_shots = [element[1] for element in expected_aux_ops_result] + np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) @data( ( @@ -130,7 +136,7 @@ def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): """Test for TrotterQRTE on two qubits with various types of a Hamiltonian.""" # LieTrotter with 1 rep initial_state = QuantumCircuit(2) - evolution_problem = EvolutionProblem(operator, 1, initial_state) + evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) @@ -155,7 +161,7 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" operator = X + Z time = 1 - evolution_problem = EvolutionProblem(operator, time, initial_state) + evolution_problem = TimeEvolutionProblem(operator, time, initial_state) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) @@ -172,7 +178,7 @@ def test_trotter_qrte_trotter_errors(self, t_param, param_value_dict): algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE() with assert_raises(ValueError): - evolution_problem = EvolutionProblem( + evolution_problem = TimeEvolutionProblem( operator, time, initial_state, From e18ba9020d7e121a550a231222a8510bde76208b Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 13:27:37 +0200 Subject: [PATCH 38/58] Added reno. --- .../trotter-qrte-primitives-8b3e495738b57fc3.yaml | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml diff --git a/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml b/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml new file mode 100644 index 000000000000..700b9329491b --- /dev/null +++ b/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml @@ -0,0 +1,12 @@ +--- +features: + - | + Added :class:`qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE` with + :class:`qiskit.primitives.BaseEstimator` as ``init`` parameter. It will soon replace + :class:`qiskit.algorithms.evolvers.trotterization.TrotterQRTE`. +deprecations: + - | + Using :class:`qiskit.algorithms.evolvers.trotterization.TrotterQRTE` will now issue a + ``PendingDeprecationWarning``. This method will be deprecated in a future release and + subsequently removed after that. This is being replaced by the new + :class:`qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE` primitive-enabled class. From 20940d59018563af8d9ba901273ea7cc213f77b7 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 13:51:52 +0200 Subject: [PATCH 39/58] Reduced use of opflow in tests. --- .../time_evolvers/test_trotter_qrte.py | 31 +++++++++---------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 1e09b1ab0fa0..db916374f395 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -24,17 +24,12 @@ from qiskit.primitives import Estimator from qiskit import QuantumCircuit from qiskit.circuit.library import ZGate -from qiskit.quantum_info import Statevector, Pauli +from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter from qiskit.opflow import ( - X, - Z, - Zero, VectorStateFn, - StateFn, - I, - Y, + PauliSumOp, ) from qiskit.synthesis import SuzukiTrotter, QDrift @@ -63,8 +58,8 @@ def setUp(self): @unpack def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state): """Test for default TrotterQRTE on a single qubit.""" - operator = X + Z - initial_state = StateFn([1, 0]) + operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) + initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) @@ -75,11 +70,11 @@ def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state def test_trotter_qrte_trotter_single_qubit_aux_ops(self): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" - operator = X + Z + operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) # LieTrotter with 1 rep aux_ops = [Pauli("X"), Pauli("Y")] - initial_state = Zero + initial_state = QuantumCircuit(1) time = 3 evolution_problem = TimeEvolutionProblem(operator, time, initial_state, aux_ops) estimator = Estimator() @@ -107,7 +102,7 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): @data( ( - (X ^ Y) + (Y ^ X), + PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), VectorStateFn( Statevector( [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j], dims=(2, 2) @@ -115,7 +110,7 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): ), ), ( - (Z ^ Z) + (Z ^ I) + (I ^ Z), + PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), VectorStateFn( Statevector( [-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2) @@ -144,7 +139,7 @@ def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): @data( ( - Zero, + QuantumCircuit(1), VectorStateFn( Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) ), @@ -159,7 +154,7 @@ def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): @unpack def test_trotter_qrte_qdrift(self, initial_state, expected_state): """Test for TrotterQRTE with QDrift.""" - operator = X + Z + operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) @@ -172,8 +167,10 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): @unpack def test_trotter_qrte_trotter_errors(self, t_param, param_value_dict): """Test TrotterQRTE with raising errors.""" - operator = X * Parameter("t") + Z - initial_state = Zero + operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( + SparsePauliOp([Pauli("Z")]) + ) + initial_state = QuantumCircuit(1) time = 1 algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE() From 1dce47391e218a01838004e285335109b8ad72b9 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 14:36:45 +0200 Subject: [PATCH 40/58] Black fix. --- qiskit/algorithms/time_evolvers/time_evolution_problem.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/qiskit/algorithms/time_evolvers/time_evolution_problem.py b/qiskit/algorithms/time_evolvers/time_evolution_problem.py index ceb4b97c4175..ec058bdfb4b0 100644 --- a/qiskit/algorithms/time_evolvers/time_evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/time_evolution_problem.py @@ -54,7 +54,8 @@ def __init__( aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, - param_value_dict: Mapping[Parameter, complex] | None = None, # parametrization will become supported in BaseOperator soon + param_value_dict: Mapping[Parameter, complex] + | None = None, # parametrization will become supported in BaseOperator soon ): """ Args: From 24aa2bf93ca7ca15f6484d0140ab2a201fde4aa9 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 14:40:10 +0200 Subject: [PATCH 41/58] Unit test fix. --- test/python/algorithms/test_observables_evaluator.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 88f0c7381b61..ddf874017364 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -145,7 +145,13 @@ def test_eval_observables_zero_op(self): observables = [(X ^ X) + (Y ^ Y), 0] result = eval_observables(estimator, state, observables, self.threshold) expected_result = [(0.015607318055509564, (0, 0)), (0.0, (0, 0))] - np.testing.assert_array_equal(result, expected_result) + means = [element[0] for element in result] + expected_means = [element[0] for element in expected_result] + np.testing.assert_array_almost_equal(means, expected_means, decimal=0.01) + + vars_and_shots = [element[1] for element in result] + expected_vars_and_shots = [element[1] for element in expected_result] + np.testing.assert_array_equal(vars_and_shots, expected_vars_and_shots) if __name__ == "__main__": From 00d9d11332b5d8ce21cb9d21d5bd79f1604d02eb Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 14:42:13 +0200 Subject: [PATCH 42/58] Reduced use of opflow. --- test/python/algorithms/test_observables_evaluator.py | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index ddf874017364..826f4847a161 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -22,14 +22,10 @@ from qiskit.quantum_info.operators.base_operator import BaseOperator from qiskit.algorithms.observables_evaluator import eval_observables from qiskit.primitives import Estimator -from qiskit.quantum_info import Statevector +from qiskit.quantum_info import Statevector, SparsePauliOp from qiskit import QuantumCircuit from qiskit.circuit.library import EfficientSU2 -from qiskit.opflow import ( - PauliSumOp, - X, - Y, -) +from qiskit.opflow import PauliSumOp from qiskit.utils import algorithm_globals @@ -142,7 +138,7 @@ def test_eval_observables_zero_op(self): bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator() - observables = [(X ^ X) + (Y ^ Y), 0] + observables = [SparsePauliOp(["XX", "YY"]), 0] result = eval_observables(estimator, state, observables, self.threshold) expected_result = [(0.015607318055509564, (0, 0)), (0.0, (0, 0))] means = [element[0] for element in result] From 44b7959b20bf06cf352b46c779339e2e25b453c4 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 9 Sep 2022 15:48:09 +0200 Subject: [PATCH 43/58] Handle empty inputs gracefully. --- qiskit/algorithms/observables_evaluator.py | 9 +++++---- test/python/algorithms/test_observables_evaluator.py | 5 ++++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 6e9b347a1c33..8b5520eb5055 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -86,10 +86,11 @@ def _handle_zero_ops( ) -> list[BaseOperator | PauliSumOp]: """Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp`` operator.""" - zero_op = PauliSumOp.from_list([("I" * observables_list[0].num_qubits, 0)]) - for ind, observable in enumerate(observables_list): - if observable == 0: - observables_list[ind] = zero_op + if observables_list: + zero_op = PauliSumOp.from_list([("I" * observables_list[0].num_qubits, 0)]) + for ind, observable in enumerate(observables_list): + if observable == 0: + observables_list[ind] = zero_op return observables_list diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 826f4847a161..95a03a051b09 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -50,7 +50,8 @@ def get_exact_expectation( observables_list = list(observables.values()) else: observables_list = observables - # the exact value is a list of (mean, (variance, shots)) where we expect 0 variance and 0 shots + # the exact value is a list of (mean, (variance, shots)) where we expect 0 variance and + # 0 shots exact = [ (Statevector(ansatz).expectation_value(observable), (0, 0)) for observable in observables_list @@ -104,6 +105,8 @@ def _run_test( { "op1": PauliSumOp.from_list([("ZZ", 2.0)]), }, + [], + {}, ) def test_eval_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]): """Tests evaluator of auxiliary operators for algorithms.""" From d3c601e2e66e5fb8efd085ea761d02cdfd2e77de Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Sun, 11 Sep 2022 10:30:26 +0200 Subject: [PATCH 44/58] Applied CR comments. --- qiskit/algorithms/evolvers/evolution_problem.py | 4 ++-- qiskit/algorithms/evolvers/evolution_result.py | 4 ++-- qiskit/algorithms/evolvers/imaginary_evolver.py | 4 ++-- qiskit/algorithms/evolvers/real_evolver.py | 4 ++-- .../time_evolvers/time_evolution_problem.py | 13 ++++++------- .../time_evolvers/time_evolution_result.py | 4 ++-- .../time_evolvers/test_time_evolution_problem.py | 6 +++--- 7 files changed, 19 insertions(+), 20 deletions(-) diff --git a/qiskit/algorithms/evolvers/evolution_problem.py b/qiskit/algorithms/evolvers/evolution_problem.py index bc815c7425d5..cd34c5a34f8a 100644 --- a/qiskit/algorithms/evolvers/evolution_problem.py +++ b/qiskit/algorithms/evolvers/evolution_problem.py @@ -25,7 +25,7 @@ class EvolutionProblem: """Pending deprecation: Evolution problem class. The EvolutionProblem class has been superseded by the - :class:`qiskit.algorithms.time_evolvers.EvolutionProblem` class. + :class:`qiskit.algorithms.time_evolvers.TimeEvolutionProblem` class. This class will be deprecated in a future release and subsequently removed after that. @@ -35,7 +35,7 @@ class EvolutionProblem: @deprecate_function( "The EvolutionProblem class has been superseded by the " - "qiskit.algorithms.time_evolvers.EvolutionProblem class. " + "qiskit.algorithms.time_evolvers.TimeEvolutionProblem class. " "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, diff --git a/qiskit/algorithms/evolvers/evolution_result.py b/qiskit/algorithms/evolvers/evolution_result.py index 1f2c1d50c5de..9ae567ca91c9 100644 --- a/qiskit/algorithms/evolvers/evolution_result.py +++ b/qiskit/algorithms/evolvers/evolution_result.py @@ -25,7 +25,7 @@ class EvolutionResult(AlgorithmResult): """Pending deprecation: Class for holding evolution result. The EvolutionResult class has been superseded by the - :class:`qiskit.algorithms.time_evolvers.EvolutionResult` class. + :class:`qiskit.algorithms.time_evolvers.TimeEvolutionResult` class. This class will be deprecated in a future release and subsequently removed after that. @@ -33,7 +33,7 @@ class EvolutionResult(AlgorithmResult): @deprecate_function( "The EvolutionResult class has been superseded by the " - "qiskit.algorithms.time_evolvers.EvolutionResult class. " + "qiskit.algorithms.time_evolvers.TimeEvolutionResult class. " "This class will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, diff --git a/qiskit/algorithms/evolvers/imaginary_evolver.py b/qiskit/algorithms/evolvers/imaginary_evolver.py index 520de1bbaae1..37a24d266a30 100644 --- a/qiskit/algorithms/evolvers/imaginary_evolver.py +++ b/qiskit/algorithms/evolvers/imaginary_evolver.py @@ -23,7 +23,7 @@ class ImaginaryEvolver(ABC): """Pending deprecation: Interface for Quantum Imaginary Time Evolution. The ImaginaryEvolver interface has been superseded by the - :class:`qiskit.algorithms.time_evolvers.ImaginaryEvolver` interface. + :class:`qiskit.algorithms.time_evolvers.ImaginaryTimeEvolver` interface. This interface will be deprecated in a future release and subsequently removed after that. @@ -31,7 +31,7 @@ class ImaginaryEvolver(ABC): @deprecate_function( "The ImaginaryEvolver interface has been superseded by the " - "qiskit.algorithms.time_evolvers.ImaginaryEvolver interface. " + "qiskit.algorithms.time_evolvers.ImaginaryTimeEvolver interface. " "This interface will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, diff --git a/qiskit/algorithms/evolvers/real_evolver.py b/qiskit/algorithms/evolvers/real_evolver.py index 0ccaad7fa9b2..c869344a19ba 100644 --- a/qiskit/algorithms/evolvers/real_evolver.py +++ b/qiskit/algorithms/evolvers/real_evolver.py @@ -23,7 +23,7 @@ class RealEvolver(ABC): """Pending deprecation: Interface for Quantum Real Time Evolution. The RealEvolver interface has been superseded by the - :class:`qiskit.algorithms.time_evolvers.RealEvolver` interface. + :class:`qiskit.algorithms.time_evolvers.RealTimeEvolver` interface. This interface will be deprecated in a future release and subsequently removed after that. @@ -31,7 +31,7 @@ class RealEvolver(ABC): @deprecate_function( "The RealEvolver interface has been superseded by the " - "qiskit.algorithms.time_evolvers.RealEvolver interface. " + "qiskit.algorithms.time_evolvers.RealTimeEvolver interface. " "This interface will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, diff --git a/qiskit/algorithms/time_evolvers/time_evolution_problem.py b/qiskit/algorithms/time_evolvers/time_evolution_problem.py index ec058bdfb4b0..9b2226f4764f 100644 --- a/qiskit/algorithms/time_evolvers/time_evolution_problem.py +++ b/qiskit/algorithms/time_evolvers/time_evolution_problem.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -"""Evolution problem class.""" +"""Time evolution problem class.""" from __future__ import annotations from collections.abc import Mapping @@ -24,7 +24,7 @@ class TimeEvolutionProblem: - """Evolution problem class. + """Time evolution problem class. This class is the input to time evolution algorithms and must contain information on the total evolution time, a quantum state to be evolved and under which Hamiltonian the state is evolved. @@ -41,7 +41,7 @@ class TimeEvolutionProblem: Used when ``aux_operators`` is provided. t_param (Parameter | None): Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. - param_value_dict (dict[Parameter, complex] | None): Maps free parameters in the problem to + param_value_map (dict[Parameter, complex] | None): Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. """ @@ -54,8 +54,7 @@ def __init__( aux_operators: ListOrDict[BaseOperator | PauliSumOp] | None = None, truncation_threshold: float = 1e-12, t_param: Parameter | None = None, - param_value_dict: Mapping[Parameter, complex] - | None = None, # parametrization will become supported in BaseOperator soon + param_value_map: Mapping[Parameter, complex] | None = None, ): """ Args: @@ -70,7 +69,7 @@ def __init__( Used when ``aux_operators`` is provided. t_param: Time parameter in case of a time-dependent Hamiltonian. This free parameter must be within the ``hamiltonian``. - param_value_dict: Maps free parameters in the problem to values. Depending on the + param_value_map: Maps free parameters in the problem to values. Depending on the algorithm, it might refer to e.g. a Hamiltonian or an initial state. Raises: @@ -78,7 +77,7 @@ def __init__( """ self.t_param = t_param - self.param_value_dict = param_value_dict + self.param_value_map = param_value_map self.hamiltonian = hamiltonian self.time = time if isinstance(initial_state, Statevector): diff --git a/qiskit/algorithms/time_evolvers/time_evolution_result.py b/qiskit/algorithms/time_evolvers/time_evolution_result.py index 2ff47e3d08e5..60c900945543 100644 --- a/qiskit/algorithms/time_evolvers/time_evolution_result.py +++ b/qiskit/algorithms/time_evolvers/time_evolution_result.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -"""Class for holding evolution result.""" +"""Class for holding time evolution result.""" from __future__ import annotations from qiskit import QuantumCircuit @@ -20,7 +20,7 @@ class TimeEvolutionResult(AlgorithmResult): """ - Class for holding evolution result. + Class for holding time evolution result. Attributes: evolved_state (QuantumCircuit): An evolved quantum state. diff --git a/test/python/algorithms/time_evolvers/test_time_evolution_problem.py b/test/python/algorithms/time_evolvers/test_time_evolution_problem.py index 227583f8aef7..83a7fd4d5e3a 100644 --- a/test/python/algorithms/time_evolvers/test_time_evolution_problem.py +++ b/test/python/algorithms/time_evolvers/test_time_evolution_problem.py @@ -46,7 +46,7 @@ def test_init_default(self): self.assertEqual(evo_problem.initial_state, expected_initial_state) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) - self.assertEqual(evo_problem.param_value_dict, expected_param_value_dict) + self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) @data(QuantumCircuit(1), Statevector([1, 0])) def test_init_all(self, initial_state): @@ -63,7 +63,7 @@ def test_init_all(self, initial_state): initial_state, aux_operators, t_param=t_parameter, - param_value_dict=param_value_dict, + param_value_map=param_value_dict, ) expected_hamiltonian = Y + t_parameter * Z @@ -78,7 +78,7 @@ def test_init_all(self, initial_state): self.assertEqual(type(evo_problem.initial_state), expected_type) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) self.assertEqual(evo_problem.t_param, expected_t_param) - self.assertEqual(evo_problem.param_value_dict, expected_param_value_dict) + self.assertEqual(evo_problem.param_value_map, expected_param_value_dict) @data([Y, -1, One], [Y, -1.2, One], [Y, 0, One]) @unpack From 773b1241b8e44134ac7a0138d50f09aca06e30e9 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Sun, 11 Sep 2022 18:13:49 +0200 Subject: [PATCH 45/58] Applied CR comments. --- qiskit/algorithms/__init__.py | 3 +++ qiskit/algorithms/observables_evaluator.py | 16 +++++++++------- .../algorithms/test_observables_evaluator.py | 10 +++++----- 3 files changed, 17 insertions(+), 12 deletions(-) diff --git a/qiskit/algorithms/__init__.py b/qiskit/algorithms/__init__.py index c13f00cb1e60..34b11e6b07b2 100644 --- a/qiskit/algorithms/__init__.py +++ b/qiskit/algorithms/__init__.py @@ -240,6 +240,7 @@ :toctree: ../stubs/ eval_observables + estimate_observables Utility classes --------------- @@ -293,6 +294,7 @@ ) from .exceptions import AlgorithmError from .aux_ops_evaluator import eval_observables +from .observables_evaluator import estimate_observables from .evolvers.trotterization import TrotterQRTE from .evolvers.variational.var_qite import VarQITE from .evolvers.variational.var_qrte import VarQRTE @@ -352,4 +354,5 @@ "IterativePhaseEstimation", "AlgorithmError", "eval_observables", + "estimate_observables", ] diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 8b5520eb5055..ac2f95db2d85 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -22,7 +22,7 @@ from ..quantum_info.operators.base_operator import BaseOperator -def eval_observables( +def estimate_observables( estimator: BaseEstimator, quantum_state: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp], @@ -145,11 +145,13 @@ def _prep_variance_and_shots( results = [] for metadata in estimator_result.metadata: - if metadata and "variance" in metadata.keys() and "shots" in metadata.keys(): - variance = metadata["variance"] - shots = metadata["shots"] - results.append((variance, shots)) - else: - results.append((0, 0)) + variance, shots = 0.0, 0 + if metadata: + if "variance" in metadata.keys(): + variance = metadata["variance"] + if "shots" in metadata.keys(): + shots = metadata["shots"] + + results.append((variance, shots)) return results diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 95a03a051b09..bcff77cdd5b4 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -20,7 +20,7 @@ from qiskit.algorithms.list_or_dict import ListOrDict from qiskit.quantum_info.operators.base_operator import BaseOperator -from qiskit.algorithms.observables_evaluator import eval_observables +from qiskit.algorithms import estimate_observables from qiskit.primitives import Estimator from qiskit.quantum_info import Statevector, SparsePauliOp from qiskit import QuantumCircuit @@ -70,7 +70,7 @@ def _run_test( observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): - result = eval_observables(estimator, quantum_state, observables, self.threshold) + result = estimate_observables(estimator, quantum_state, observables, self.threshold) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) @@ -108,7 +108,7 @@ def _run_test( [], {}, ) - def test_eval_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]): + def test_estimate_observables(self, observables: ListOrDict[BaseOperator | PauliSumOp]): """Tests evaluator of auxiliary operators for algorithms.""" ansatz = EfficientSU2(2) @@ -130,7 +130,7 @@ def test_eval_observables(self, observables: ListOrDict[BaseOperator | PauliSumO estimator, ) - def test_eval_observables_zero_op(self): + def test_estimate_observables_zero_op(self): """Tests if a zero operator is handled correctly.""" ansatz = EfficientSU2(2) parameters = np.array( @@ -142,7 +142,7 @@ def test_eval_observables_zero_op(self): state = bound_ansatz estimator = Estimator() observables = [SparsePauliOp(["XX", "YY"]), 0] - result = eval_observables(estimator, state, observables, self.threshold) + result = estimate_observables(estimator, state, observables, self.threshold) expected_result = [(0.015607318055509564, (0, 0)), (0.0, (0, 0))] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] From 3d706a7040129ac7978e241a42ea733e99bb3b3d Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 12 Sep 2022 07:35:31 +0200 Subject: [PATCH 46/58] Updated method names. --- .../algorithms/time_evolvers/trotterization/trotter_qrte.py | 4 ++-- test/python/algorithms/time_evolvers/test_trotter_qrte.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 16bc4dd59252..59ef28c64341 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -16,7 +16,7 @@ import warnings -from qiskit.algorithms.observables_evaluator import eval_observables +from qiskit.algorithms.observables_evaluator import estimate_observables from qiskit import QuantumCircuit from qiskit.algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem @@ -156,7 +156,7 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult evaluated_aux_ops = None if evolution_problem.aux_operators is not None: - evaluated_aux_ops = eval_observables( + evaluated_aux_ops = estimate_observables( self.estimator, evolved_state.primitive, evolution_problem.aux_operators, diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index db916374f395..e3b7b7f0cc85 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -180,7 +180,7 @@ def test_trotter_qrte_trotter_errors(self, t_param, param_value_dict): time, initial_state, t_param=t_param, - param_value_dict=param_value_dict, + param_value_map=param_value_dict, ) _ = trotter_qrte.evolve(evolution_problem) From d248e44cdb104e768f9dcba1bdc5e2aea2ccffb3 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 15 Sep 2022 10:28:43 +0200 Subject: [PATCH 47/58] Applied CR comments. --- qiskit/algorithms/aux_ops_evaluator.py | 2 +- qiskit/algorithms/observables_evaluator.py | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/qiskit/algorithms/aux_ops_evaluator.py b/qiskit/algorithms/aux_ops_evaluator.py index 63b75e1c92a6..9ce9349a7de8 100644 --- a/qiskit/algorithms/aux_ops_evaluator.py +++ b/qiskit/algorithms/aux_ops_evaluator.py @@ -33,7 +33,7 @@ @deprecate_function( "The eval_observables function has been superseded by the " - "qiskit.algorithms.observables_evaluator.eval_observables function. " + "qiskit.algorithms.observables_evaluator.estimate_observables function. " "This function will be deprecated in a future release and subsequently " "removed after that.", category=PendingDeprecationWarning, diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index ac2f95db2d85..0ffd92fec61d 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -9,7 +9,7 @@ # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -"""Evaluator of auxiliary operators for algorithms.""" +"""Evaluator of observables for algorithms.""" from __future__ import annotations import numpy as np @@ -27,7 +27,7 @@ def estimate_observables( quantum_state: QuantumCircuit, observables: ListOrDict[BaseOperator | PauliSumOp], threshold: float = 1e-12, -) -> ListOrDict[tuple[complex, tuple[complex | None, int | None]]]: +) -> ListOrDict[tuple[complex, tuple[complex, int]]]: """ Accepts a sequence of operators and calculates their expectation values - means and standard deviations. They are calculated with respect to a quantum state provided. A user @@ -43,7 +43,7 @@ def estimate_observables( ignoring numerical instabilities close to 0). Returns: - A list or a dictionary of tuples (mean, standard deviation). + A list or a dictionary of tuples (mean, (variance, shots)). Raises: ValueError: If a ``quantum_state`` with free parameters is provided. @@ -82,7 +82,7 @@ def estimate_observables( def _handle_zero_ops( - observables_list: list[BaseOperator | PauliSumOp | int], + observables_list: list[BaseOperator | PauliSumOp], ) -> list[BaseOperator | PauliSumOp]: """Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp`` operator.""" @@ -95,15 +95,15 @@ def _handle_zero_ops( def _prepare_result( - observables_results: list[tuple[complex, tuple[complex | None, int | None]]], + observables_results: list[tuple[complex, tuple[complex, int]]], observables: ListOrDict[BaseOperator | PauliSumOp], -) -> ListOrDict[tuple[complex, tuple[complex | None, int | None]]]: +) -> ListOrDict[tuple[complex, tuple[complex, int]]]: """ Prepares a list of tuples of eigenvalues and (variance, shots) tuples from ``observables_results`` and ``observables``. Args: - observables_results: A list of tuples (mean, standard deviation). + observables_results: A list of tuples (mean, (variance, shots)). observables: A list or a dictionary of operators whose expectation values are to be calculated. @@ -112,6 +112,7 @@ def _prepare_result( """ if isinstance(observables, list): + # by construction, all None values will be overwritten observables_eigenvalues = [None] * len(observables) key_value_iterator = enumerate(observables_results) else: @@ -119,15 +120,14 @@ def _prepare_result( key_value_iterator = zip(observables.keys(), observables_results) for key, value in key_value_iterator: - if observables[key] is not None: - observables_eigenvalues[key] = value + observables_eigenvalues[key] = value return observables_eigenvalues def _prep_variance_and_shots( estimator_result: EstimatorResult, results_length: int, -) -> list[tuple[complex | None, int | None]]: +) -> list[tuple[complex, int]]: """ Prepares a list of tuples with variances and shots from results provided by expectation values calculations. If there is no variance or shots data available from a primitive, the values will From fad2caa4ba5336828abd441e19b16a4e73cec689 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 15 Sep 2022 13:24:17 +0200 Subject: [PATCH 48/58] Eliminated cyclic import. --- qiskit/algorithms/observables_evaluator.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 0ffd92fec61d..f6a6c3d8094a 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -16,7 +16,7 @@ from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp -from . import AlgorithmError +from .exceptions import AlgorithmError from .list_or_dict import ListOrDict from ..primitives import EstimatorResult, BaseEstimator from ..quantum_info.operators.base_operator import BaseOperator From 46512f1416f28a9fb59f0f4dda6d3dcadbaf85e0 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 15 Sep 2022 15:15:24 +0200 Subject: [PATCH 49/58] Drafted reduced use of opflow. --- .../trotterization/trotter_qrte.py | 14 ++---- .../time_evolvers/test_trotter_qrte.py | 47 +++++++------------ 2 files changed, 22 insertions(+), 39 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 59ef28c64341..2671501bac1a 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -23,9 +23,7 @@ from qiskit.algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult from qiskit.algorithms.time_evolvers.real_time_evolver import RealTimeEvolver from qiskit.opflow import ( - CircuitOp, PauliSumOp, - StateFn, ) from qiskit.circuit.library import PauliEvolutionGate from qiskit.primitives import BaseEstimator @@ -141,15 +139,13 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult f"TrotterQRTE only accepts Pauli | PauliSumOp, {type(hamiltonian)} provided." ) # the evolution gate - evolution_gate = CircuitOp( - PauliEvolutionGate(hamiltonian, evolution_problem.time, synthesis=self.product_formula) - ) + evolution_gate = PauliEvolutionGate(hamiltonian, evolution_problem.time, synthesis=self.product_formula) if evolution_problem.initial_state is not None: initial_state = evolution_problem.initial_state - if isinstance(initial_state, QuantumCircuit): - initial_state = StateFn(initial_state) - evolved_state = evolution_gate @ initial_state + evolved_state = QuantumCircuit(initial_state.num_qubits) + evolved_state.append(initial_state, evolved_state.qubits) + evolved_state.append(evolution_gate, evolved_state.qubits) else: raise ValueError("``initial_state`` must be provided in the EvolutionProblem.") @@ -158,7 +154,7 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult if evolution_problem.aux_operators is not None: evaluated_aux_ops = estimate_observables( self.estimator, - evolved_state.primitive, + evolved_state, evolution_problem.aux_operators, evolution_problem.truncation_threshold, ) diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index e3b7b7f0cc85..752734365fa9 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -27,10 +27,7 @@ from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter -from qiskit.opflow import ( - VectorStateFn, - PauliSumOp, -) +from qiskit.opflow import PauliSumOp from qiskit.synthesis import SuzukiTrotter, QDrift @@ -46,13 +43,12 @@ def setUp(self): @data( ( None, - VectorStateFn( Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j], dims=(2,)) - ), + , ), ( SuzukiTrotter(), - VectorStateFn(Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j], dims=(2,))), + Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j], dims=(2,)), ), ) @unpack @@ -65,8 +61,9 @@ def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state + print(Statevector.from_instruction(evolution_result_state_circuit)) - np.testing.assert_equal(evolution_result_state_circuit.eval(), expected_state) + np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result_state_circuit), expected_state) def test_trotter_qrte_trotter_single_qubit_aux_ops(self): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" @@ -79,15 +76,14 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): evolution_problem = TimeEvolutionProblem(operator, time, initial_state, aux_ops) estimator = Estimator() - expected_evolved_state = VectorStateFn( - Statevector([0.98008514 + 0.13970775j, 0.01991486 + 0.13970775j], dims=(2,)) - ) + expected_evolved_state = Statevector([0.98008514 + 0.13970775j, 0.01991486 + 0.13970775j]) algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) evolution_result = trotter_qrte.evolve(evolution_problem) + print(evolution_result.evolved_state) - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_evolved_state) + np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result.evolved_state), expected_evolved_state) aux_ops_result = evolution_result.aux_ops_evaluated expected_aux_ops_result = [(0.078073, (0.0, 0.0)), (0.268286, (0.0, 0.0))] @@ -103,26 +99,20 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): @data( ( PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), - VectorStateFn( Statevector( - [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j], dims=(2, 2) - ) + [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j] ), ), ( PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), - VectorStateFn( Statevector( - [-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j], dims=(2, 2) - ) + [-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j] ), ), ( Pauli("YY"), - VectorStateFn( Statevector( - [0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j], dims=(2, 2) - ) + [0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j] ), ), ) @@ -135,20 +125,16 @@ def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + print(evolution_result.evolved_state) + np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result.evolved_state), expected_state) @data( ( QuantumCircuit(1), - VectorStateFn( - Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) - ), - ), + Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), ( QuantumCircuit(1).compose(ZGate(), [0]), - VectorStateFn( - Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j], dims=(2,)) - ), + Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), ), ) @unpack @@ -161,7 +147,8 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_equal(evolution_result.evolved_state.eval(), expected_state) + print(evolution_result.evolved_state) + np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result.evolved_state), expected_state) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack From 430717263040c64c98f1f9c8c6ca3fdab10a3bf2 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 16 Sep 2022 12:58:39 +0200 Subject: [PATCH 50/58] Drafted reduced use of opflow. --- .../time_evolvers/trotterization/trotter_qrte.py | 2 +- test/python/algorithms/time_evolvers/test_trotter_qrte.py | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 2671501bac1a..1cc4b8d79e88 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -144,8 +144,8 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult if evolution_problem.initial_state is not None: initial_state = evolution_problem.initial_state evolved_state = QuantumCircuit(initial_state.num_qubits) - evolved_state.append(initial_state, evolved_state.qubits) evolved_state.append(evolution_gate, evolved_state.qubits) + evolved_state.append(initial_state, evolved_state.qubits) else: raise ValueError("``initial_state`` must be provided in the EvolutionProblem.") diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 752734365fa9..149215af1845 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -43,12 +43,12 @@ def setUp(self): @data( ( None, - Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j], dims=(2,)) + Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]) , ), ( SuzukiTrotter(), - Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j], dims=(2,)), + Statevector([0.29192658 - 0.84147098j, 0.0 - 0.45464871j]), ), ) @unpack @@ -147,7 +147,8 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) - print(evolution_result.evolved_state) + print(Statevector.from_instruction(evolution_result.evolved_state)) + print(expected_state) np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result.evolved_state), expected_state) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) From 112717095f37a698bd5ffeb5e1d3fa3d513019ae Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Fri, 16 Sep 2022 22:17:15 +0200 Subject: [PATCH 51/58] Removed use of opflow. --- .../trotterization/trotter_qrte.py | 14 +++--- .../time_evolvers/test_trotter_qrte.py | 45 +++++++++---------- 2 files changed, 29 insertions(+), 30 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 1cc4b8d79e88..971039957700 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -22,9 +22,7 @@ from qiskit.algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit.algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult from qiskit.algorithms.time_evolvers.real_time_evolver import RealTimeEvolver -from qiskit.opflow import ( - PauliSumOp, -) +from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.primitives import BaseEstimator from qiskit.quantum_info import Pauli @@ -45,13 +43,15 @@ class TrotterQRTE(RealTimeEvolver): from qiskit.opflow import X, Z, Zero from qiskit.algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE + from qiskit.primitives import Estimator operator = X + Z initial_state = Zero time = 1 evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) # LieTrotter with 1 rep - trotter_qrte = TrotterQRTE() + estimator = Estimator() + trotter_qrte = TrotterQRTE(estimator=estimator) evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ @@ -139,13 +139,15 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult f"TrotterQRTE only accepts Pauli | PauliSumOp, {type(hamiltonian)} provided." ) # the evolution gate - evolution_gate = PauliEvolutionGate(hamiltonian, evolution_problem.time, synthesis=self.product_formula) + evolution_gate = PauliEvolutionGate( + hamiltonian, evolution_problem.time, synthesis=self.product_formula + ) if evolution_problem.initial_state is not None: initial_state = evolution_problem.initial_state evolved_state = QuantumCircuit(initial_state.num_qubits) - evolved_state.append(evolution_gate, evolved_state.qubits) evolved_state.append(initial_state, evolved_state.qubits) + evolved_state.append(evolution_gate, evolved_state.qubits) else: raise ValueError("``initial_state`` must be provided in the EvolutionProblem.") diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 149215af1845..c5e57be7443a 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -43,8 +43,7 @@ def setUp(self): @data( ( None, - Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]) - , + Statevector([0.29192658 - 0.45464871j, 0.70807342 - 0.45464871j]), ), ( SuzukiTrotter(), @@ -61,9 +60,10 @@ def test_trotter_qrte_trotter_single_qubit(self, product_formula, expected_state trotter_qrte = TrotterQRTE(product_formula=product_formula) evolution_result_state_circuit = trotter_qrte.evolve(evolution_problem).evolved_state - print(Statevector.from_instruction(evolution_result_state_circuit)) - np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result_state_circuit), expected_state) + np.testing.assert_array_almost_equal( + Statevector.from_instruction(evolution_result_state_circuit).data, expected_state.data + ) def test_trotter_qrte_trotter_single_qubit_aux_ops(self): """Test for default TrotterQRTE on a single qubit with auxiliary operators.""" @@ -81,9 +81,11 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator) evolution_result = trotter_qrte.evolve(evolution_problem) - print(evolution_result.evolved_state) - np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result.evolved_state), expected_evolved_state) + np.testing.assert_array_almost_equal( + Statevector.from_instruction(evolution_result.evolved_state).data, + expected_evolved_state.data, + ) aux_ops_result = evolution_result.aux_ops_evaluated expected_aux_ops_result = [(0.078073, (0.0, 0.0)), (0.268286, (0.0, 0.0))] @@ -99,21 +101,15 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): @data( ( PauliSumOp(SparsePauliOp([Pauli("XY"), Pauli("YX")])), - Statevector( - [-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j] - ), + Statevector([-0.41614684 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.90929743 + 0.0j]), ), ( PauliSumOp(SparsePauliOp([Pauli("ZZ"), Pauli("ZI"), Pauli("IZ")])), - Statevector( - [-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j] - ), + Statevector([-0.9899925 - 0.14112001j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j]), ), ( Pauli("YY"), - Statevector( - [0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j] - ), + Statevector([0.54030231 + 0.0j, 0.0 + 0.0j, 0.0 + 0.0j, 0.0 + 0.84147098j]), ), ) @unpack @@ -125,16 +121,16 @@ def test_trotter_qrte_trotter_two_qubits(self, operator, expected_state): trotter_qrte = TrotterQRTE() evolution_result = trotter_qrte.evolve(evolution_problem) - print(evolution_result.evolved_state) - np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result.evolved_state), expected_state) + + np.testing.assert_array_almost_equal( + Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data + ) @data( - ( - QuantumCircuit(1), - Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), + (QuantumCircuit(1), Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j])), ( QuantumCircuit(1).compose(ZGate(), [0]), - Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), + Statevector([0.23071786 - 0.69436148j, 0.4646314 - 0.49874749j]), ), ) @unpack @@ -147,9 +143,10 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) - print(Statevector.from_instruction(evolution_result.evolved_state)) - print(expected_state) - np.testing.assert_almost_equal(Statevector.from_instruction(evolution_result.evolved_state), expected_state) + + np.testing.assert_array_almost_equal( + Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data + ) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack From b0471c3d39c13006a8c7ab982c7f6971aa1371db Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Mon, 19 Sep 2022 09:33:02 +0200 Subject: [PATCH 52/58] Code refactoring. --- .../trotterization/trotter_qrte.py | 34 ++++++++++--------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 971039957700..7eba9ae7a4f5 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -31,7 +31,7 @@ class TrotterQRTE(RealTimeEvolver): """Quantum Real Time Evolution using Trotterization. - Type of Trotterization is defined by a ProductFormula provided. + Type of Trotterization is defined by a ``ProductFormula`` provided. Attributes: product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter @@ -41,14 +41,16 @@ class TrotterQRTE(RealTimeEvolver): .. code-block:: python - from qiskit.opflow import X, Z, Zero + from qiskit.opflow import PauliSumOp + from qiskit.quantum_info import Pauli, SparsePauliOp + from qiskit import QuantumCircuit from qiskit.algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE from qiskit.primitives import Estimator - operator = X + Z - initial_state = Zero + operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) + initial_state = QuantumCircuit(1) time = 1 - evolution_problem = TimeEvolutionProblem(operator, 1, initial_state) + evolution_problem = TimeEvolutionProblem(operator, time, initial_state) # LieTrotter with 1 rep estimator = Estimator() trotter_qrte = TrotterQRTE(estimator=estimator) @@ -65,7 +67,7 @@ def __init__( product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter first order product formula with a single repetition. estimator: An estimator primitive used for calculating expectation values of - EvolutionProblem.aux_operators. + ``TimeEvolutionProblem.aux_operators``. """ if product_formula is None: product_formula = LieTrotter() @@ -92,8 +94,8 @@ def supports_aux_operators(cls) -> bool: Whether computing the expectation value of auxiliary operators is supported. Returns: - True if ``aux_operators`` expectations in the EvolutionProblem can be evaluated, False - otherwise. + ``True`` if ``aux_operators`` expectations in the ``TimeEvolutionProblem`` can be + evaluated, ``False`` otherwise. """ return True @@ -116,22 +118,22 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult auxiliary operators evaluated for a resulting state on an estimator primitive. Raises: - ValueError: If ``t_param`` is not set to ``None`` in the EvolutionProblem (feature not - currently supported). - ValueError: If the ``initial_state`` is not provided in the EvolutionProblem. + ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem`` + (feature not currently supported). + ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``. ValueError: If an unsupported Hamiltonian type is provided. """ evolution_problem.validate_params() if evolution_problem.t_param is not None: raise ValueError( - "TrotterQRTE does not accept a time dependent hamiltonian," - "``t_param`` from the EvolutionProblem should be set to None." + "TrotterQRTE does not accept a time dependent Hamiltonian," + "``t_param`` from the ``TimeEvolutionProblem`` should be set to ``None``." ) if evolution_problem.aux_operators is not None and self.estimator is None: warnings.warn( - "The evolution problem contained aux_operators but no estimator was provided. " - "The algorithm continues without calculating these quantities. " + "The time evolution problem contained ``aux_operators`` but no estimator was " + "provided. The algorithm continues without calculating these quantities. " ) hamiltonian = evolution_problem.hamiltonian if not isinstance(hamiltonian, (Pauli, PauliSumOp)): @@ -150,7 +152,7 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult evolved_state.append(evolution_gate, evolved_state.qubits) else: - raise ValueError("``initial_state`` must be provided in the EvolutionProblem.") + raise ValueError("``initial_state`` must be provided in the ``TimeEvolutionProblem``.") evaluated_aux_ops = None if evolution_problem.aux_operators is not None: From 8563b2dc99189a4a4b6836c4e0dcbe6e9cf104bd Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 20 Sep 2022 10:57:33 +0200 Subject: [PATCH 53/58] Addressed CR comments. --- .../trotterization/trotter_qrte.py | 38 +++++++++++-------- ...tter-qrte-primitives-8b3e495738b57fc3.yaml | 2 +- 2 files changed, 24 insertions(+), 16 deletions(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py index 7eba9ae7a4f5..d244f718cef4 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/time_evolvers/trotterization/trotter_qrte.py @@ -14,14 +14,11 @@ from __future__ import annotations -import warnings - -from qiskit.algorithms.observables_evaluator import estimate_observables - from qiskit import QuantumCircuit from qiskit.algorithms.time_evolvers.time_evolution_problem import TimeEvolutionProblem from qiskit.algorithms.time_evolvers.time_evolution_result import TimeEvolutionResult from qiskit.algorithms.time_evolvers.real_time_evolver import RealTimeEvolver +from qiskit.algorithms.observables_evaluator import estimate_observables from qiskit.opflow import PauliSumOp from qiskit.circuit.library import PauliEvolutionGate from qiskit.primitives import BaseEstimator @@ -33,10 +30,6 @@ class TrotterQRTE(RealTimeEvolver): """Quantum Real Time Evolution using Trotterization. Type of Trotterization is defined by a ``ProductFormula`` provided. - Attributes: - product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter - first order product formula with a single repetition. - Examples: .. code-block:: python @@ -44,7 +37,8 @@ class TrotterQRTE(RealTimeEvolver): from qiskit.opflow import PauliSumOp from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit import QuantumCircuit - from qiskit.algorithms.time_evolvers import TimeEvolutionProblem, TrotterQRTE + from qiskit.algorithms import TimeEvolutionProblem + from qiskit.algorithms.time_evolvers import TrotterQRTE from qiskit.primitives import Estimator operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) @@ -64,15 +58,27 @@ def __init__( ) -> None: """ Args: - product_formula: A Lie-Trotter-Suzuki product formula. The default is the Lie-Trotter - first order product formula with a single repetition. + product_formula: A Lie-Trotter-Suzuki product formula. If ``None`` provided, the + Lie-Trotter first order product formula with a single repetition is used. estimator: An estimator primitive used for calculating expectation values of ``TimeEvolutionProblem.aux_operators``. """ + + self.product_formula = product_formula + self.estimator = estimator + + @property + def product_formula(self) -> ProductFormula: + """Returns a product formula.""" + return self._product_formula + + @product_formula.setter + def product_formula(self, product_formula: ProductFormula | None): + """Sets a product formula. If ``None`` provided, sets the Lie-Trotter first order product + formula with a single repetition.""" if product_formula is None: product_formula = LieTrotter() - self.product_formula = product_formula - self._estimator = estimator + self._product_formula = product_formula @property def estimator(self) -> BaseEstimator | None: @@ -107,7 +113,7 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult evaluated on an evolved state using an estimator primitive provided. .. note:: - Time-dependent Hamiltonians are not yet supported. + Time-dependent Hamiltonians are not supported. Args: evolution_problem: Instance defining evolution problem. For the included Hamiltonian, @@ -120,6 +126,8 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult Raises: ValueError: If ``t_param`` is not set to ``None`` in the ``TimeEvolutionProblem`` (feature not currently supported). + ValueError: If ``aux_operators`` provided in the time evolution problem but no estimator + provided to the algorithm. ValueError: If the ``initial_state`` is not provided in the ``TimeEvolutionProblem``. ValueError: If an unsupported Hamiltonian type is provided. """ @@ -131,7 +139,7 @@ def evolve(self, evolution_problem: TimeEvolutionProblem) -> TimeEvolutionResult ) if evolution_problem.aux_operators is not None and self.estimator is None: - warnings.warn( + raise ValueError( "The time evolution problem contained ``aux_operators`` but no estimator was " "provided. The algorithm continues without calculating these quantities. " ) diff --git a/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml b/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml index 700b9329491b..70ce6122dba3 100644 --- a/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml +++ b/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml @@ -2,7 +2,7 @@ features: - | Added :class:`qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE` with - :class:`qiskit.primitives.BaseEstimator` as ``init`` parameter. It will soon replace + :class:`qiskit.primitives.BaseEstimator` as ``init`` parameter. It replaces :class:`qiskit.algorithms.evolvers.trotterization.TrotterQRTE`. deprecations: - | From 0f43b02f4d451f4c07647e2f7c67d77b9fe858e9 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 20 Sep 2022 13:23:03 +0200 Subject: [PATCH 54/58] Added more tests for error paths. --- .../time_evolvers/test_trotter_qrte.py | 32 ++++++++++++++++--- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index c5e57be7443a..fbdbb0161590 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -27,7 +27,7 @@ from qiskit.quantum_info import Statevector, Pauli, SparsePauliOp from qiskit.utils import algorithm_globals from qiskit.circuit import Parameter -from qiskit.opflow import PauliSumOp +from qiskit.opflow import PauliSumOp, X, MatrixOp from qiskit.synthesis import SuzukiTrotter, QDrift @@ -150,20 +150,44 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack - def test_trotter_qrte_trotter_errors(self, t_param, param_value_dict): - """Test TrotterQRTE with raising errors.""" + def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): + """Test TrotterQRTE with raising errors for parameters.""" operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) initial_state = QuantumCircuit(1) + self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) + + @data(([Pauli("X"), Pauli("Y")], None)) + @unpack + def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator): + """Test TrotterQRTE with raising errors.""" + operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])) + initial_state = QuantumCircuit(1) + self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) + + @data( + (SparsePauliOp([Pauli("X"), Pauli("Z")]), QuantumCircuit(1)), + (X, QuantumCircuit(1)), + (MatrixOp([[1, 1], [0, 1]]), QuantumCircuit(1)), + (PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp(SparsePauliOp([Pauli("Z")])), None), + ) + @unpack + def test_trotter_qrte_trotter_hamiltonian_errors(self, operator, initial_state): + """Test TrotterQRTE with raising errors for evolution problem content.""" + self._run_error_test(initial_state, operator, None, None, None, None) + + @staticmethod + def _run_error_test(initial_state, operator, aux_ops, estimator, t_param, param_value_dict): time = 1 algorithm_globals.random_seed = 0 - trotter_qrte = TrotterQRTE() + trotter_qrte = TrotterQRTE(estimator=estimator) with assert_raises(ValueError): evolution_problem = TimeEvolutionProblem( operator, time, initial_state, + aux_ops, t_param=t_param, param_value_map=param_value_dict, ) From 7de440da65b01b3577dbcbf13aa5b5a6b76ade6e Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Tue, 20 Sep 2022 14:57:56 +0200 Subject: [PATCH 55/58] Added Trotter section in algorithms init. --- qiskit/algorithms/__init__.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/qiskit/algorithms/__init__.py b/qiskit/algorithms/__init__.py index 987951253ee3..fa8f3f448814 100644 --- a/qiskit/algorithms/__init__.py +++ b/qiskit/algorithms/__init__.py @@ -231,6 +231,7 @@ state_fidelities + Exceptions ---------- @@ -240,6 +241,16 @@ AlgorithmError +Trotterization-based Quantum Real Time Evolution +------------------------------------------------ + +Package for primitives-enabled Trotterization-based quantum time evolution algorithm - TrotterQRTE. + +.. autosummary:: + :toctree: ../stubs/ + + time_evolvers.trotterization + Utility methods --------------- @@ -251,6 +262,7 @@ eval_observables estimate_observables + Utility classes --------------- From e7032ff952d66ab67b6590acb24b3148ab6549d5 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Wed, 21 Sep 2022 11:50:25 +0200 Subject: [PATCH 56/58] Changed init. --- .../time_evolvers/trotterization/__init__.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/qiskit/algorithms/time_evolvers/trotterization/__init__.py b/qiskit/algorithms/time_evolvers/trotterization/__init__.py index eda3141296d7..c5e7e128728d 100644 --- a/qiskit/algorithms/time_evolvers/trotterization/__init__.py +++ b/qiskit/algorithms/time_evolvers/trotterization/__init__.py @@ -12,7 +12,17 @@ """This package contains Trotterization-based Quantum Real Time Evolution algorithm. It is compliant with the new Quantum Time Evolution Framework and makes use of :class:`qiskit.synthesis.evolution.ProductFormula` and -:class:`~qiskit.circuit.library.PauliEvolutionGate` implementations.""" +:class:`~qiskit.circuit.library.PauliEvolutionGate` implementations. + +Trotterization-based Quantum Real Time Evolution +------------------------------------------------ + +.. autosummary:: + :toctree: ../stubs/ + :nosignatures: + + TrotterQRTE +""" from qiskit.algorithms.time_evolvers.trotterization.trotter_qrte import TrotterQRTE From f78ad60c0ee84433cc26e949ab17c1f7af2c9ad5 Mon Sep 17 00:00:00 2001 From: dlasecki Date: Thu, 22 Sep 2022 09:08:32 +0200 Subject: [PATCH 57/58] Apply suggestions from code review Co-authored-by: Steve Wood <40241007+woodsp-ibm@users.noreply.github.com> --- .../notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml b/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml index 70ce6122dba3..1f8b3e25e928 100644 --- a/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml +++ b/releasenotes/notes/trotter-qrte-primitives-8b3e495738b57fc3.yaml @@ -3,10 +3,10 @@ features: - | Added :class:`qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE` with :class:`qiskit.primitives.BaseEstimator` as ``init`` parameter. It replaces - :class:`qiskit.algorithms.evolvers.trotterization.TrotterQRTE`. + :class:`qiskit.algorithms.TrotterQRTE`. deprecations: - | - Using :class:`qiskit.algorithms.evolvers.trotterization.TrotterQRTE` will now issue a - ``PendingDeprecationWarning``. This method will be deprecated in a future release and + Using :class:`qiskit.algorithms.TrotterQRTE` will now issue a + ``PendingDeprecationWarning``. This algorithm will be deprecated in a future release and subsequently removed after that. This is being replaced by the new :class:`qiskit.algorithms.time_evolvers.trotterization.TrotterQRTE` primitive-enabled class. From 8f7e73947340d5835cc7f536b25c4d0445d77014 Mon Sep 17 00:00:00 2001 From: Dariusz Lasecki Date: Thu, 22 Sep 2022 09:58:48 +0200 Subject: [PATCH 58/58] Co-located TrotterQRTE with time evolvers in docs. --- qiskit/algorithms/__init__.py | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/qiskit/algorithms/__init__.py b/qiskit/algorithms/__init__.py index fa8f3f448814..931643afc532 100644 --- a/qiskit/algorithms/__init__.py +++ b/qiskit/algorithms/__init__.py @@ -136,6 +136,17 @@ TimeEvolutionProblem +Trotterization-based Quantum Real Time Evolution +------------------------------------------------ + +Package for primitives-enabled Trotterization-based quantum time evolution algorithm - TrotterQRTE. + +.. autosummary:: + :toctree: ../stubs/ + + time_evolvers.trotterization + + Factorizers ----------- @@ -241,16 +252,6 @@ AlgorithmError -Trotterization-based Quantum Real Time Evolution ------------------------------------------------- - -Package for primitives-enabled Trotterization-based quantum time evolution algorithm - TrotterQRTE. - -.. autosummary:: - :toctree: ../stubs/ - - time_evolvers.trotterization - Utility methods ---------------