From 07e5304b0b29e5c51780ea392361e2de65d3364a Mon Sep 17 00:00:00 2001 From: Manoel Marques Date: Mon, 21 Nov 2022 23:21:58 -0500 Subject: [PATCH 01/47] Deprecate QuantumInstance and Opflow --- .../evolvers/trotterization/trotter_qrte.py | 9 ++++-- .../observables/absolute_average.py | 4 ++- .../observables/matrix_functional.py | 10 ++++--- qiskit/opflow/__init__.py | 29 ++++++++++--------- qiskit/opflow/converters/__init__.py | 4 +-- qiskit/opflow/converters/abelian_grouper.py | 13 +++++++-- qiskit/opflow/converters/circuit_sampler.py | 13 +++++++-- qiskit/opflow/converters/converter_base.py | 12 ++++++-- .../opflow/converters/dict_to_circuit_sum.py | 17 ++++++++--- .../opflow/converters/pauli_basis_change.py | 13 +++++++-- .../opflow/converters/two_qubit_reduction.py | 15 ++++++++-- qiskit/opflow/evolutions/__init__.py | 7 +++-- qiskit/opflow/evolutions/evolution_base.py | 15 ++++++++-- qiskit/opflow/evolutions/evolution_factory.py | 11 +++++-- qiskit/opflow/evolutions/evolved_op.py | 14 +++++++-- qiskit/opflow/evolutions/matrix_evolution.py | 15 ++++++++-- .../evolutions/pauli_trotter_evolution.py | 16 +++++++--- .../evolutions/trotterizations/__init__.py | 5 ++-- .../evolutions/trotterizations/qdrift.py | 9 ++++-- .../evolutions/trotterizations/suzuki.py | 9 ++++-- .../evolutions/trotterizations/trotter.py | 9 ++++-- .../trotterizations/trotterization_base.py | 14 +++++++-- .../trotterizations/trotterization_factory.py | 9 ++++-- qiskit/opflow/exceptions.py | 13 +++++++-- qiskit/opflow/expectations/__init__.py | 8 ++--- .../expectations/aer_pauli_expectation.py | 15 ++++++++-- .../opflow/expectations/cvar_expectation.py | 13 +++++++-- .../opflow/expectations/expectation_base.py | 15 ++++++++-- .../expectations/expectation_factory.py | 9 ++++-- .../opflow/expectations/matrix_expectation.py | 17 +++++++++-- .../opflow/expectations/pauli_expectation.py | 13 +++++++-- qiskit/opflow/gradients/__init__.py | 8 ++--- .../gradients/circuit_gradients/__init__.py | 2 +- .../circuit_gradients/circuit_gradient.py | 15 ++++++++-- .../gradients/circuit_gradients/lin_comb.py | 14 +++++++-- .../circuit_gradients/param_shift.py | 14 +++++++-- .../opflow/gradients/circuit_qfis/__init__.py | 2 +- .../gradients/circuit_qfis/circuit_qfi.py | 15 ++++++++-- .../gradients/circuit_qfis/lin_comb_full.py | 14 +++++++-- .../circuit_qfis/overlap_block_diag.py | 15 ++++++++-- .../gradients/circuit_qfis/overlap_diag.py | 16 ++++++++-- qiskit/opflow/gradients/derivative_base.py | 14 +++++++-- qiskit/opflow/gradients/gradient.py | 16 ++++++++-- qiskit/opflow/gradients/gradient_base.py | 14 +++++++-- qiskit/opflow/gradients/hessian.py | 16 ++++++++-- qiskit/opflow/gradients/hessian_base.py | 14 +++++++-- qiskit/opflow/gradients/natural_gradient.py | 14 +++++++-- qiskit/opflow/gradients/qfi.py | 16 ++++++++-- qiskit/opflow/gradients/qfi_base.py | 14 +++++++-- qiskit/opflow/list_ops/__init__.py | 5 ++-- qiskit/opflow/list_ops/composed_op.py | 9 ++++-- qiskit/opflow/list_ops/list_op.py | 16 +++++++--- qiskit/opflow/list_ops/summed_op.py | 9 ++++-- qiskit/opflow/list_ops/tensored_op.py | 11 +++++-- qiskit/opflow/mixins/star_algebra.py | 12 ++++++-- qiskit/opflow/mixins/tensor.py | 12 ++++++-- qiskit/opflow/operator_base.py | 13 +++++++-- qiskit/opflow/operator_globals.py | 9 ++++-- qiskit/opflow/primitive_ops/__init__.py | 4 +-- qiskit/opflow/primitive_ops/circuit_op.py | 15 +++++++--- qiskit/opflow/primitive_ops/matrix_op.py | 16 +++++++--- qiskit/opflow/primitive_ops/pauli_op.py | 15 +++++++--- qiskit/opflow/primitive_ops/pauli_sum_op.py | 16 ++++++---- qiskit/opflow/primitive_ops/primitive_op.py | 14 +++++++-- .../primitive_ops/tapered_pauli_sum_op.py | 14 +++++++-- qiskit/opflow/state_fns/__init__.py | 8 ++--- qiskit/opflow/state_fns/circuit_state_fn.py | 9 ++++-- qiskit/opflow/state_fns/cvar_measurement.py | 9 ++++-- qiskit/opflow/state_fns/dict_state_fn.py | 9 ++++-- qiskit/opflow/state_fns/operator_state_fn.py | 9 ++++-- .../state_fns/sparse_vector_state_fn.py | 9 ++++-- qiskit/opflow/state_fns/state_fn.py | 14 +++++++-- qiskit/opflow/state_fns/vector_state_fn.py | 9 ++++-- qiskit/opflow/utils.py | 21 +++++++++++--- qiskit/test/base.py | 12 +++++++- qiskit/utils/quantum_instance.py | 7 ++++- qiskit/utils/run_circuits.py | 15 ++++++++-- .../deprecate-opflow-qi-32f7e27884deea3f.yaml | 7 +++++ test/python/algorithms/test_shor.py | 19 ++++++++++-- 79 files changed, 748 insertions(+), 207 deletions(-) create mode 100644 releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml diff --git a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py index 323305b4b8c1..33bafc156194 100644 --- a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py @@ -48,18 +48,23 @@ class TrotterQRTE(RealEvolver): Examples:: + import warnings from qiskit.opflow import X, Z, Zero from qiskit.algorithms import EvolutionProblem, TrotterQRTE from qiskit import BasicAer from qiskit.utils import QuantumInstance - operator = X + Z + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + operator = X + Z initial_state = Zero time = 1 evolution_problem = EvolutionProblem(operator, 1, initial_state) # LieTrotter with 1 rep backend = BasicAer.get_backend("statevector_simulator") - quantum_instance = QuantumInstance(backend=backend) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + quantum_instance = QuantumInstance(backend=backend) trotter_qrte = TrotterQRTE(quantum_instance=quantum_instance) evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ diff --git a/qiskit/algorithms/linear_solvers/observables/absolute_average.py b/qiskit/algorithms/linear_solvers/observables/absolute_average.py index ae0b930d944a..1765cfcb305d 100644 --- a/qiskit/algorithms/linear_solvers/observables/absolute_average.py +++ b/qiskit/algorithms/linear_solvers/observables/absolute_average.py @@ -52,7 +52,9 @@ class AbsoluteAverage(LinearSystemObservable): # Observable operator observable_op = observable.observable(num_qubits) - state_vec = (~StateFn(observable_op) @ StateFn(qc)).eval() + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + state_vec = (~StateFn(observable_op) @ StateFn(qc)).eval() # Obtain result result = observable.post_processing(state_vec, num_qubits) diff --git a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py index 0b584ba3b4af..fdee0613df56 100644 --- a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py +++ b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py @@ -61,10 +61,12 @@ class MatrixFunctional(LinearSystemObservable): observable_ops = observable.observable(num_qubits) state_vecs = [] # First is the norm - state_vecs.append((~StateFn(observable_ops[0]) @ StateFn(qcs[0])).eval()) - for i in range(1, len(observable_ops), 2): - state_vecs += [(~StateFn(observable_ops[i]) @ StateFn(qcs[i])).eval(), - (~StateFn(observable_ops[i + 1]) @ StateFn(qcs[i + 1])).eval()] + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + state_vecs.append((~StateFn(observable_ops[0]) @ StateFn(qcs[0])).eval()) + for i in range(1, len(observable_ops), 2): + state_vecs += [(~StateFn(observable_ops[i]) @ StateFn(qcs[i])).eval(), + (~StateFn(observable_ops[i + 1]) @ StateFn(qcs[i + 1])).eval()] # Obtain result result = observable.post_processing(state_vecs, num_qubits) diff --git a/qiskit/opflow/__init__.py b/qiskit/opflow/__init__.py index df980959be75..37f86c5f9764 100644 --- a/qiskit/opflow/__init__.py +++ b/qiskit/opflow/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2020. +# (C) Copyright IBM 2019, 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 @@ -17,7 +17,7 @@ .. currentmodule:: qiskit.opflow -Operators and State functions are the building blocks of Quantum Algorithms. +Deprecation: Operators and State functions are the building blocks of Quantum Algorithms. A library for Quantum Algorithms & Applications is more than a collection of algorithms wrapped in Python functions. It needs to provide tools to make writing @@ -77,8 +77,9 @@ Operator Base Class =================== -The OperatorBase serves as the base class for all Operators, State functions and measurements, and -enforces the presence and consistency of methods to manipulate these objects conveniently. +Deprecation: The OperatorBase serves as the base class for all Operators, State functions +and measurements, and enforces the presence and consistency of methods to manipulate these +objects conveniently. .. autosummary:: :toctree: ../stubs/ @@ -90,8 +91,8 @@ Operator Globals ================ -The :mod:`operator_globals` is a set of immutable Operator instances that are convenient building -blocks to reach for while working with the Operator flow. +Deprecation: The :mod:`operator_globals` is a set of immutable Operator instances that are +convenient building blocks to reach for while working with the Operator flow. One qubit Pauli operators: :attr:`X`, :attr:`Y`, :attr:`Z`, :attr:`I` @@ -108,8 +109,8 @@ Operators --------- -The Operators submodules include the PrimitiveOp, ListOp, and StateFn class groups which -represent the primary Operator modules. +Deprecation: The Operators submodules include the PrimitiveOp, ListOp, and StateFn class +groups which represent the primary Operator modules. .. autosummary:: :toctree: ../stubs/ @@ -122,12 +123,12 @@ Converters ---------- -The Converter submodules include objects which manipulate Operators, usually recursing over an -Operator structure and changing certain Operators' representation. For example, the -:class:`~.expectations.PauliExpectation` traverses an Operator structure, and replaces all of the -:class:`~.state_fns.OperatorStateFn` measurements containing non-diagonal Pauli terms into -diagonalizing circuits following by :class:`~.state_fns.OperatorStateFn` measurement containing -only diagonal Paulis. +Deprecation: The Converter submodules include objects which manipulate Operators, +usually recursing over an Operator structure and changing certain Operators' representation. +For example, the :class:`~.expectations.PauliExpectation` traverses an Operator structure, and +replaces all of the :class:`~.state_fns.OperatorStateFn` measurements containing non-diagonal +Pauli terms into diagonalizing circuits following by :class:`~.state_fns.OperatorStateFn` +measurement containing only diagonal Paulis. .. autosummary:: :toctree: ../stubs/ diff --git a/qiskit/opflow/converters/__init__.py b/qiskit/opflow/converters/__init__.py index 14272be076fd..d017fbf5cffd 100644 --- a/qiskit/opflow/converters/__init__.py +++ b/qiskit/opflow/converters/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -16,7 +16,7 @@ .. currentmodule:: qiskit.opflow.converters -Converters are objects which manipulate Operators, usually traversing an Operator to +Deprecation: Converters are objects which manipulate Operators, usually traversing an Operator to change certain sub-Operators into a desired representation. Often the converted Operator is isomorphic or approximate to the original Operator in some way, but not always. For example, a converter may accept :class:`~qiskit.opflow.primitive_ops.CircuitOp` and return a diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index 1b8b516166a3..d040c4eebfbd 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -13,6 +13,7 @@ """AbelianGrouper Class""" from collections import defaultdict +import warnings from typing import List, Tuple, Union, cast import numpy as np @@ -27,10 +28,11 @@ from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn +from qiskit.utils.deprecation import deprecate_function class AbelianGrouper(ConverterBase): - """The AbelianGrouper converts SummedOps into a sum of Abelian sums. + """Deprecation: The AbelianGrouper converts SummedOps into a sum of Abelian sums. Meaning, it will traverse the Operator, and when it finds a SummedOp, it will evaluate which of the summed sub-Operators commute with one another. It will then convert each of the groups of @@ -41,12 +43,19 @@ class AbelianGrouper(ConverterBase): diagonalized together. """ + @deprecate_function( + "The AbelianGrouper opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, traverse: bool = True) -> None: """ Args: traverse: Whether to convert only the Operator passed to ``convert``, or traverse down that Operator. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._traverse = traverse def convert(self, operator: OperatorBase) -> OperatorBase: diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index e2376ac610ce..34109ca58e1d 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -14,6 +14,7 @@ import logging +import warnings from functools import partial from time import time from typing import Any, Dict, List, Optional, Tuple, Union, cast @@ -32,13 +33,14 @@ from qiskit.providers import Backend from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend from qiskit.utils.quantum_instance import QuantumInstance +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) class CircuitSampler(ConverterBase): """ - The CircuitSampler traverses an Operator and converts any CircuitStateFns into + Deprecation: The CircuitSampler traverses an Operator and converts any CircuitStateFns into approximations of the state function by a DictStateFn or VectorStateFn using a quantum backend. Note that in order to approximate the value of the CircuitStateFn, it must 1) send state function through a depolarizing channel, which will destroy all phase information and @@ -51,6 +53,10 @@ class CircuitSampler(ConverterBase): you are better off using a different CircuitSampler for each Operator to avoid cache thrashing. """ + @deprecate_function( + "The CircuitSampler opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, backend: Union[Backend, QuantumInstance], @@ -76,6 +82,9 @@ def __init__( Raises: ValueError: Set statevector or param_qobj True when not supported by backend. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._quantum_instance = ( backend if isinstance(backend, QuantumInstance) else QuantumInstance(backend=backend) ) diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index 043702a31d8e..c6084eb8730c 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -15,11 +15,12 @@ from abc import ABC, abstractmethod from qiskit.opflow.operator_base import OperatorBase +from qiskit.utils.deprecation import deprecate_function class ConverterBase(ABC): r""" - Converters take an Operator and return a new Operator, generally isomorphic + Deprecation: Converters take an Operator and return a new Operator, generally isomorphic in some way with the first, but with certain desired properties. For example, a converter may accept ``CircuitOp`` and return a ``SummedOp`` of ``PauliOps`` representing the circuit unitary. Converters may not @@ -29,6 +30,13 @@ class ConverterBase(ABC): in the number of qubits unless a clever trick is known (such as the use of sparse matrices).""" + @deprecate_function( + "The ConverterBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + pass + @abstractmethod def convert(self, operator: OperatorBase) -> OperatorBase: """Accept the Operator and return the converted Operator diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index 0b34ddd734ec..4e06d704a752 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,22 +12,28 @@ """DictToCircuitSum Class """ +import warnings from qiskit.opflow.converters.converter_base import ConverterBase from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn +from qiskit.utils.deprecation import deprecate_function class DictToCircuitSum(ConverterBase): r""" - Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` or sums - thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` on - an Operator, but with the added control of choosing whether to convert only ``DictStateFns`` + Deprecation: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` + or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` + on an Operator, but with the added control of choosing whether to convert only ``DictStateFns`` or ``VectorStateFns``, rather than both. """ + @deprecate_function( + "The DictToCircuitSum opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True ) -> None: @@ -38,6 +44,9 @@ def __init__( convert_dicts: Whether to convert VectorStateFn. convert_vectors: Whether to convert DictStateFns. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._traverse = traverse self._convert_dicts = convert_dicts self._convert_vectors = convert_vectors diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index cdc78c227d26..e832cec3d4a1 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ PauliBasisChange Class """ +import warnings from functools import partial, reduce from typing import Callable, List, Optional, Tuple, Union, cast @@ -30,11 +31,12 @@ from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Pauli +from qiskit.utils.deprecation import deprecate_function class PauliBasisChange(ConverterBase): r""" - Converter for changing Paulis into other bases. By default, the diagonal basis + Deprecation: Converter for changing Paulis into other bases. By default, the diagonal basis composed only of Pauli {Z, I}^n is used as the destination basis to which to convert. Meaning, if a Pauli containing X or Y terms is passed in, which cannot be sampled or evolved natively on some Quantum hardware, the Pauli can be replaced by a @@ -55,6 +57,10 @@ class PauliBasisChange(ConverterBase): this method, such as the placement of the CNOT chains. """ + @deprecate_function( + "The PauliBasisChange opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, destination_basis: Optional[Union[Pauli, PauliOp]] = None, @@ -83,6 +89,9 @@ def __init__( beginning and ending operators are equivalent. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if destination_basis is not None: self.destination = destination_basis # type: ignore else: diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index a8a3756016e6..2de080ed4855 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -13,6 +13,7 @@ """ Z2 Symmetry Tapering Converter Class """ import logging +import warnings from typing import List, Tuple, Union, cast from qiskit.opflow.converters.converter_base import ConverterBase @@ -20,14 +21,15 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.tapered_pauli_sum_op import Z2Symmetries from qiskit.quantum_info import Pauli +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) class TwoQubitReduction(ConverterBase): """ - Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli - that has diagonal operators (Z,I) at those positions. + Deprecation: Two qubit reduction converter which eliminates the central and last + qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: It can be used to taper two qubits in parity and binary-tree mapped @@ -35,12 +37,19 @@ class TwoQubitReduction(ConverterBase): sectors, (block spin order) according to the number of particles in the system. """ + @deprecate_function( + "The TwoQubitReduction opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): """ Args: num_particles: number of particles, if it is a list, the first number is alpha and the second number if beta. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if isinstance(num_particles, (tuple, list)): num_alpha = num_particles[0] num_beta = num_particles[1] diff --git a/qiskit/opflow/evolutions/__init__.py b/qiskit/opflow/evolutions/__init__.py index 907781c0d100..b1c136f6cf4c 100644 --- a/qiskit/opflow/evolutions/__init__.py +++ b/qiskit/opflow/evolutions/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -16,8 +16,9 @@ .. currentmodule:: qiskit.opflow.evolutions -Evolutions are converters which traverse an Operator tree, replacing any :class:`EvolvedOp` `e` -with a Schrodinger equation-style evolution :class:`~qiskit.opflow.primitive_ops.CircuitOp` +Deprecation: Evolutions are converters which traverse an Operator tree, replacing +any :class:`EvolvedOp` `e` with a Schrodinger equation-style evolution +:class:`~qiskit.opflow.primitive_ops.CircuitOp` equalling or approximating the matrix exponential of -i * the Operator contained inside (`e.primitive`). The Evolutions are essentially implementations of Hamiltonian Simulation algorithms, including various methods for Trotterization. diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index 7043beedb1c6..fa7686f8e135 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,15 +12,17 @@ """ EvolutionBase Class """ +import warnings from abc import ABC, abstractmethod from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.converters.converter_base import ConverterBase +from qiskit.utils.deprecation import deprecate_function class EvolutionBase(ConverterBase, ABC): r""" - A base for Evolution converters. + Deprecation: A base for Evolution converters. Evolutions are converters which traverse an Operator tree, replacing any ``EvolvedOp`` `e` with a Schrodinger equation-style evolution ``CircuitOp`` equalling or approximating the matrix exponential of -i * the Operator contained inside (`e.primitive`). The Evolutions are @@ -29,6 +31,15 @@ class EvolutionBase(ConverterBase, ABC): """ + @deprecate_function( + "The EvolutionBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + @abstractmethod def convert(self, operator: OperatorBase) -> OperatorBase: """Traverse the operator, replacing any ``EvolutionOps`` with their equivalent evolution diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index 6fda3d7cbffb..f993a702b3f9 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -16,14 +16,19 @@ from qiskit.opflow.evolutions.evolution_base import EvolutionBase from qiskit.opflow.evolutions.pauli_trotter_evolution import PauliTrotterEvolution from qiskit.opflow.evolutions.matrix_evolution import MatrixEvolution +from qiskit.utils.deprecation import deprecate_function class EvolutionFactory: - """A factory class for convenient automatic selection of an Evolution algorithm based on the - Operator to be converted. + """Deprecation: A factory class for convenient automatic selection of an + Evolution algorithm based on the Operator to be converted. """ @staticmethod + @deprecate_function( + "The EvolutionFactory.build opflow method is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def build(operator: OperatorBase = None) -> EvolutionBase: r""" A factory method for convenient automatic selection of an Evolution algorithm based on the diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index e4427e858ec4..e56c32447333 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ EvolutionOp Class """ +import warnings from typing import List, Optional, Set, Union, cast import numpy as np @@ -27,11 +28,12 @@ from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector +from qiskit.utils.deprecation import deprecate_function class EvolvedOp(PrimitiveOp): r""" - Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase + Deprecation: Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase method later, essentially acting as a placeholder. Note that EvolvedOp is a weird case of PrimitiveOp. It happens to be that it fits into the PrimitiveOp interface nearly perfectly, and it essentially represents a placeholder for a PrimitiveOp later, even though it doesn't @@ -39,6 +41,10 @@ class EvolvedOp(PrimitiveOp): but would have ended up copying and pasting a lot of code from PrimitiveOp.""" primitive: PrimitiveOp + @deprecate_function( + "The EvolvedOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: OperatorBase, coeff: Union[complex, ParameterExpression] = 1.0 ) -> None: @@ -47,7 +53,9 @@ def __init__( primitive: The operator being wrapped to signify evolution later. coeff: A coefficient multiplying the operator """ - super().__init__(primitive, coeff=coeff) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return self.primitive.primitive_strings() diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index b26ecf773798..0657c60d0658 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ MatrixEvolution Class """ +import warnings import logging from qiskit.opflow.evolutions.evolution_base import EvolutionBase @@ -20,16 +21,26 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.pauli_op import PauliOp +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) class MatrixEvolution(EvolutionBase): r""" - Performs Evolution by classical matrix exponentiation, constructing a circuit with + Deprecation: Performs Evolution by classical matrix exponentiation, constructing a circuit with ``UnitaryGates`` or ``HamiltonianGates`` containing the exponentiation of the Operator. """ + @deprecate_function( + "The MatrixEvolution opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + def convert(self, operator: OperatorBase) -> OperatorBase: r""" Traverse the operator, replacing ``EvolvedOps`` with ``CircuitOps`` containing diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 5521ba3f86a3..5ddfde839017 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ PauliTrotterEvolution Class """ +import warnings import logging from typing import Optional, Union, cast @@ -32,6 +33,7 @@ from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp +from qiskit.utils.deprecation import deprecate_function # TODO uncomment when we implement Abelian grouped evolution. # from qiskit.opflow.converters.abelian_grouper import AbelianGrouper @@ -41,8 +43,8 @@ class PauliTrotterEvolution(EvolutionBase): r""" - An Evolution algorithm replacing exponentiated sums of Paulis by changing them each to the - Z basis, rotating with an rZ, changing back, and Trotterizing. + Deprecation: An Evolution algorithm replacing exponentiated sums of Paulis by changing + them each to the Z basis, rotating with an rZ, changing back, and Trotterizing. More specifically, we compute basis change circuits for each Pauli into a single-qubit Z, evolve the Z by the desired evolution time with an rZ gate, and change the basis back using @@ -50,6 +52,10 @@ class PauliTrotterEvolution(EvolutionBase): evolution circuits are composed together by Trotterization scheme. """ + @deprecate_function( + "The PauliTrotterEvolution opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, trotter_mode: Optional[Union[str, TrotterizationBase]] = "trotter", @@ -69,7 +75,9 @@ def __init__( # sub-groups, so a single diagonalization circuit can be used for each group # rather than each Pauli. """ - + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if isinstance(trotter_mode, TrotterizationBase): self._trotter = trotter_mode else: diff --git a/qiskit/opflow/evolutions/trotterizations/__init__.py b/qiskit/opflow/evolutions/trotterizations/__init__.py index f177f5ce36c6..e2edec5810b2 100644 --- a/qiskit/opflow/evolutions/trotterizations/__init__.py +++ b/qiskit/opflow/evolutions/trotterizations/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -11,7 +11,8 @@ # that they have been altered from the originals. """ -Trotterization methods - Algorithms for approximating Exponentials of Operator Sums. +Deprecation: Trotterization methods - Algorithms for +approximating Exponentials of Operator Sums. """ diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 89c6ced0b144..83e9a2082620 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 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 @@ -26,16 +26,21 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.utils import algorithm_globals +from qiskit.utils.deprecation import deprecate_function # pylint: disable=invalid-name class QDrift(TrotterizationBase): - """The QDrift Trotterization method, which selects each each term in the + """Deprecation: The QDrift Trotterization method, which selects each each term in the Trotterization randomly, with a probability proportional to its weight. Based on the work of Earl Campbell in https://arxiv.org/abs/1811.08017. """ + @deprecate_function( + "The QDrift opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, reps: int = 1) -> None: r""" Args: diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index 9ba2878d8e76..24604700c4d4 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -23,17 +23,22 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp +from qiskit.utils.deprecation import deprecate_function class Suzuki(TrotterizationBase): r""" - Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum + Deprecation: Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum together by a recursive "bookends" strategy, repeating the whole composed circuit ``reps`` times. Detailed in https://arxiv.org/pdf/quant-ph/0508139.pdf. """ + @deprecate_function( + "The Suzuki opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, reps: int = 1, order: int = 2) -> None: """ Args: diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index a6d8e68b8754..4602a44f7513 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -13,14 +13,19 @@ """ Trotter Class """ from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki +from qiskit.utils.deprecation import deprecate_function class Trotter(Suzuki): r""" - Simple Trotter expansion, composing the evolution circuits of each Operator in the sum + Deprecation: Simple Trotter expansion, composing the evolution circuits of each Operator in the sum together ``reps`` times and dividing the evolution time of each by ``reps``. """ + @deprecate_function( + "The Trotter opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, reps: int = 1) -> None: r""" Args: diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index f76f78e10389..83d444bb80e6 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,21 +12,29 @@ """ Trotterization Algorithm Base """ +import warnings from abc import abstractmethod from qiskit.opflow.evolutions.evolution_base import EvolutionBase from qiskit.opflow.operator_base import OperatorBase +from qiskit.utils.deprecation import deprecate_function # TODO centralize handling of commuting groups class TrotterizationBase(EvolutionBase): - """A base for Trotterization methods, algorithms for approximating exponentiations of + """Deprecation: A base for Trotterization methods, algorithms for approximating exponentiations of operator sums by compositions of exponentiations. """ + @deprecate_function( + "The TrotterizationBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, reps: int = 1) -> None: - + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._reps = reps @property diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index 4f5b071b9775..c2c39d89ae97 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -16,12 +16,17 @@ from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki from qiskit.opflow.evolutions.trotterizations.trotter import Trotter from qiskit.opflow.evolutions.trotterizations.trotterization_base import TrotterizationBase +from qiskit.utils.deprecation import deprecate_function class TrotterizationFactory: - """A factory for conveniently creating TrotterizationBase instances.""" + """Deprecation: A factory for conveniently creating TrotterizationBase instances.""" @staticmethod + @deprecate_function( + "The TrotterizationFactory.build opflow method is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def build(mode: str = "trotter", reps: int = 1) -> TrotterizationBase: """A factory for conveniently creating TrotterizationBase instances. diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index bf80dd3d22c6..544a5c66e666 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2017, 2018. +# (C) Copyright IBM 2017, 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 @@ -13,9 +13,16 @@ """Exception for errors raised by Opflow module.""" from qiskit.exceptions import QiskitError +from qiskit.utils.deprecation import deprecate_function class OpflowError(QiskitError): - """For Opflow specific errors.""" + """Deprecation: For Opflow specific errors.""" - pass + @deprecate_function( + "The OpflowError opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self, *message): + """Set the error message.""" + super().__init__(*message) diff --git a/qiskit/opflow/expectations/__init__.py b/qiskit/opflow/expectations/__init__.py index 8109dc0bad4c..26c0c89a9a45 100644 --- a/qiskit/opflow/expectations/__init__.py +++ b/qiskit/opflow/expectations/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -16,9 +16,9 @@ .. currentmodule:: qiskit.opflow.expectations -Expectations are converters which enable the computation of the expectation value of an -Observable with respect to some state function. They traverse an Operator tree, replacing -:class:`~qiskit.opflow.state_fns.OperatorStateFn` measurements with equivalent +Deprecation: Expectations are converters which enable the computation of the expectation +value of an Observable with respect to some state function. They traverse an Operator tree, +replacing :class:`~qiskit.opflow.state_fns.OperatorStateFn` measurements with equivalent measurements which are more amenable to computation on quantum or classical hardware. For example, if one would like to measure the expectation value of an Operator ``o`` expressed as a sum of Paulis with respect to some state diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index 33790531592a..9c6e5b0a3bd5 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ AerPauliExpectation Class """ +import warnings import logging from functools import reduce from operator import add @@ -28,16 +29,26 @@ from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.quantum_info import SparsePauliOp +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) class AerPauliExpectation(ExpectationBase): - r"""An Expectation converter for using Aer's operator snapshot to + r"""Deprecation: An Expectation converter for using Aer's operator snapshot to take expectations of quantum state circuits over Pauli observables. """ + @deprecate_function( + "The AerPauliExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + def convert(self, operator: OperatorBase) -> OperatorBase: """Accept an Operator and return a new Operator with the Pauli measurements replaced by AerSnapshot-based expectation circuits. diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 641c17f9619f..27f144d0cfdd 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """The CVaR (Conditional Value at Risk) expectation class.""" +import warnings from typing import Optional, Union from qiskit.opflow.expectations.aer_pauli_expectation import AerPauliExpectation @@ -20,10 +21,11 @@ from qiskit.opflow.list_ops import ComposedOp, ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns import CVaRMeasurement, OperatorStateFn +from qiskit.utils.deprecation import deprecate_function class CVaRExpectation(ExpectationBase): - r"""Compute the Conditional Value at Risk (CVaR) expectation value. + r"""Deprecation: Compute the Conditional Value at Risk (CVaR) expectation value. The standard approach to calculating the expectation value of a Hamiltonian w.r.t. a state is to take the sample mean of the measurement outcomes. This corresponds to an estimator @@ -54,6 +56,10 @@ class CVaRExpectation(ExpectationBase): """ + @deprecate_function( + "The CVaRExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) -> None: """ Args: @@ -64,6 +70,9 @@ def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) Raises: NotImplementedError: If the ``expectation`` is an AerPauliExpecation. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self.alpha = alpha if isinstance(expectation, AerPauliExpectation): raise NotImplementedError("AerPauliExpecation currently not supported.") diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index 5de7de7dbd3d..716caab60e5a 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ ExpectationBase Class """ +import warnings from abc import abstractmethod from typing import Union @@ -19,11 +20,12 @@ from qiskit.opflow.converters import ConverterBase from qiskit.opflow.operator_base import OperatorBase +from qiskit.utils.deprecation import deprecate_function class ExpectationBase(ConverterBase): r""" - A base for Expectation value converters. Expectations are converters which enable the + Deprecation: A base for Expectation value converters. Expectations are converters which enable the computation of the expectation value of an Observable with respect to some state function. They traverse an Operator tree, replacing OperatorStateFn measurements with equivalent measurements which are more amenable to computation on quantum or classical hardware. For @@ -37,6 +39,15 @@ class ExpectationBase(ConverterBase): """ + @deprecate_function( + "The ExpectationBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + @abstractmethod def convert(self, operator: OperatorBase) -> OperatorBase: """Accept an Operator and return a new Operator with the measurements replaced by diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 182d7993809a..7d95895ccfc0 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -24,16 +24,21 @@ from qiskit.providers import Backend from qiskit.utils.backend_utils import has_aer, is_aer_qasm, is_statevector_backend from qiskit.utils.quantum_instance import QuantumInstance +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) class ExpectationFactory: - """A factory class for convenient automatic selection of an Expectation based on the + """Deprecation: factory class for convenient automatic selection of an Expectation based on the Operator to be converted and backend used to sample the expectation value. """ @staticmethod + @deprecate_function( + "The ExpectationFactory.build opflow method is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def build( operator: OperatorBase, backend: Optional[Union[Backend, QuantumInstance]] = None, diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index 917ae069f7a5..2c6b5d0fe782 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,17 +12,28 @@ """ MatrixExpectation Class """ +import warnings from typing import Union from qiskit.opflow.expectations.expectation_base import ExpectationBase from qiskit.opflow.list_ops import ComposedOp, ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn +from qiskit.utils.deprecation import deprecate_function class MatrixExpectation(ExpectationBase): - """An Expectation converter which converts Operator measurements to be matrix-based so they - can be evaluated by matrix multiplication.""" + """Deprecation: An Expectation converter which converts Operator measurements to + be matrix-based so they can be evaluated by matrix multiplication.""" + + @deprecate_function( + "The MatrixExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() def convert(self, operator: OperatorBase) -> OperatorBase: """Accept an Operator and return a new Operator with the Pauli measurements replaced by diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index 86fc588514ea..03e5ac016462 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ PauliExpectation Class """ +import warnings import logging from typing import Union @@ -27,13 +28,14 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) class PauliExpectation(ExpectationBase): r""" - An Expectation converter for Pauli-basis observables by changing Pauli measurements to a + Deprecation: An Expectation converter for Pauli-basis observables by changing Pauli measurements to a diagonal ({Z, I}^n) basis and appending circuit post-rotations to the measured state function. Optionally groups the Paulis with the same post-rotations (those that commute with one another, or form Abelian groups) into single measurements to reduce circuit execution @@ -41,6 +43,10 @@ class PauliExpectation(ExpectationBase): """ + @deprecate_function( + "The PauliExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, group_paulis: bool = True) -> None: """ Args: @@ -48,6 +54,9 @@ def __init__(self, group_paulis: bool = True) -> None: have the same diagonalizing circuit. """ + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._grouper = AbelianGrouper() if group_paulis else None def convert(self, operator: OperatorBase) -> OperatorBase: diff --git a/qiskit/opflow/gradients/__init__.py b/qiskit/opflow/gradients/__init__.py index 01c4b02a62eb..af8d40795a54 100644 --- a/qiskit/opflow/gradients/__init__.py +++ b/qiskit/opflow/gradients/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -14,9 +14,9 @@ Gradients (:mod:`qiskit.opflow.gradients`) ========================================== -Given an operator that represents either a quantum state resp. an expectation value, the gradient -framework enables the evaluation of gradients, natural gradients, Hessians, as well as the Quantum -Fisher Information. +Deprecation: Given an operator that represents either a quantum state resp. an expectation value, +the gradient framework enables the evaluation of gradients, natural gradients, +Hessians, as well as the Quantum Fisher Information. Suppose a parameterized quantum state `|ψ(θ)〉 = V(θ)|ψ〉` with input state `|ψ〉` and parameterized Ansatz `V(θ)`, and an Operator `O(ω)`. diff --git a/qiskit/opflow/gradients/circuit_gradients/__init__.py b/qiskit/opflow/gradients/circuit_gradients/__init__.py index eae08898049a..3fe8a5ee582f 100644 --- a/qiskit/opflow/gradients/circuit_gradients/__init__.py +++ b/qiskit/opflow/gradients/circuit_gradients/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index 1b5a303cb0b6..e32946048e23 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,17 +12,19 @@ """CircuitGradient Class """ +import warnings from abc import abstractmethod from typing import List, Union, Optional, Tuple, Set from qiskit import QuantumCircuit, QiskitError, transpile from qiskit.circuit import ParameterExpression, ParameterVector +from qiskit.utils.deprecation import deprecate_function from ...converters.converter_base import ConverterBase from ...operator_base import OperatorBase class CircuitGradient(ConverterBase): - r"""Circuit to gradient operator converter. + r"""Deprecation: Circuit to gradient operator converter. Converter for changing parameterized circuits into operators whose evaluation yields the gradient with respect to the circuit parameters. @@ -35,6 +37,15 @@ class CircuitGradient(ConverterBase): DerivativeBase - uses classical techniques to differentiate operator flow data structures """ + @deprecate_function( + "The CircuitGradient opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + # pylint: disable=arguments-differ @abstractmethod def convert( diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 366fb59fd497..ed0f1542d8d3 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """The module to compute the state gradient with the linear combination method.""" +import warnings from collections.abc import Iterable from copy import deepcopy from functools import partial @@ -50,6 +51,7 @@ ZGate, ) from qiskit.quantum_info import partial_trace +from qiskit.utils.deprecation import deprecate_function from ...operator_base import OperatorBase from ...list_ops.list_op import ListOp from ...list_ops.composed_op import ComposedOp @@ -67,7 +69,7 @@ class LinComb(CircuitGradient): - """Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the + """Deprecation: Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω. This method employs a linear combination of unitaries, @@ -100,6 +102,10 @@ class LinComb(CircuitGradient): } # pylint: disable=signature-differs, arguments-differ + @deprecate_function( + "The LinComb opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, aux_meas_op: OperatorBase = Z): """ Args: @@ -110,7 +116,9 @@ def __init__(self, aux_meas_op: OperatorBase = Z): Raises: ValueError: If the provided auxiliary measurement operator is not supported. """ - super().__init__() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if aux_meas_op not in [Z, -Y, (Z - 1j * Y)]: raise ValueError( "This auxiliary measurement operator is currently not supported. Please choose " diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index 435914f9f342..69c986c68523 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """The module to compute the state gradient with the parameter shift rule.""" +import warnings from collections.abc import Iterable from copy import deepcopy from functools import partial @@ -22,6 +23,7 @@ from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression, ParameterVector +from qiskit.utils.deprecation import deprecate_function from .circuit_gradient import CircuitGradient from ...operator_base import OperatorBase from ...state_fns.state_fn import StateFn @@ -39,13 +41,17 @@ class ParamShift(CircuitGradient): - """Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling + """Deprecation: Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω with the parameter shift method. """ SUPPORTED_GATES = {"x", "y", "z", "h", "rx", "ry", "rz", "p", "u", "cx", "cy", "cz"} + @deprecate_function( + "The ParamShift opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): r""" Args: @@ -57,7 +63,9 @@ def __init__(self, analytic: bool = True, epsilon: float = 1e-6): Raises: ValueError: If method != ``fin_diff`` and ``epsilon`` is not None. """ - + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._analytic = analytic self._epsilon = epsilon diff --git a/qiskit/opflow/gradients/circuit_qfis/__init__.py b/qiskit/opflow/gradients/circuit_qfis/__init__.py index d32126acd523..988b383700c1 100644 --- a/qiskit/opflow/gradients/circuit_qfis/__init__.py +++ b/qiskit/opflow/gradients/circuit_qfis/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 693f713263ae..8339c6ed1bc7 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,16 +12,18 @@ """ CircuitQFI Class """ +import warnings from abc import abstractmethod from typing import List, Union from qiskit.circuit import ParameterExpression, ParameterVector +from qiskit.utils.deprecation import deprecate_function from ...converters.converter_base import ConverterBase from ...operator_base import OperatorBase class CircuitQFI(ConverterBase): - r"""Circuit to Quantum Fisher Information operator converter. + r"""Deprecation: Circuit to Quantum Fisher Information operator converter. Converter for changing parameterized circuits into operators whose evaluation yields Quantum Fisher Information metric tensor @@ -35,6 +37,15 @@ class CircuitQFI(ConverterBase): DerivativeBase - uses classical techniques to differentiate opflow data structures """ + @deprecate_function( + "The CircuitQFI opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + # pylint: disable=arguments-differ @abstractmethod def convert( diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 81865180881f..02c085fb6ebf 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 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 @@ -12,11 +12,13 @@ """The module for Quantum the Fisher Information.""" +import warnings from typing import List, Union import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ParameterVector, ParameterExpression from qiskit.utils.arithmetic import triu_to_dense +from qiskit.utils.deprecation import deprecate_function from ...operator_base import OperatorBase from ...list_ops.list_op import ListOp @@ -29,13 +31,17 @@ class LinCombFull(CircuitQFI): - r"""Compute the full Quantum Fisher Information (QFI). + r"""Deprecation: Compute the full Quantum Fisher Information (QFI). Given a pure, parameterized quantum state this class uses the linear combination of unitaries See also :class:`~qiskit.opflow.QFI`. """ # pylint: disable=signature-differs, arguments-differ + @deprecate_function( + "The LinCombFull opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, aux_meas_op: OperatorBase = Z, @@ -52,7 +58,9 @@ def __init__( Raises: ValueError: If the provided auxiliary measurement operator is not supported. """ - super().__init__() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if aux_meas_op not in [Z, -Y, (Z - 1j * Y)]: raise ValueError( "This auxiliary measurement operator is currently not supported. Please choose " diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index 7daf6486685c..e2f8e0337ad7 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,12 +12,14 @@ """The module for the Quantum Fisher Information.""" +import warnings from typing import List, Union import numpy as np from scipy.linalg import block_diag from qiskit.circuit import Parameter, ParameterVector, ParameterExpression from qiskit.utils.arithmetic import triu_to_dense +from qiskit.utils.deprecation import deprecate_function from ...list_ops.list_op import ListOp from ...primitive_ops.circuit_op import CircuitOp from ...expectations.pauli_expectation import PauliExpectation @@ -32,12 +34,21 @@ class OverlapBlockDiag(CircuitQFI): - r"""Compute the block-diagonal of the QFI given a pure, parameterized quantum state. + r"""Deprecation: Compute the block-diagonal of the QFI given a pure, parameterized quantum state. The blocks are given by all parameterized gates in quantum circuit layer. See also :class:`~qiskit.opflow.QFI`. """ + @deprecate_function( + "The OverlapBlockDiag opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + def convert( self, operator: Union[CircuitOp, CircuitStateFn], diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 9efca9f6791b..ccb6afa9e582 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -11,6 +11,8 @@ # that they have been altered from the originals. """The module for Quantum the Fisher Information.""" + +import warnings import copy from typing import List, Union @@ -18,6 +20,7 @@ from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.circuit.library import RZGate, RXGate, RYGate from qiskit.converters import dag_to_circuit, circuit_to_dag +from qiskit.utils.deprecation import deprecate_function from ...list_ops.list_op import ListOp from ...primitive_ops.circuit_op import CircuitOp from ...expectations.pauli_expectation import PauliExpectation @@ -31,11 +34,20 @@ class OverlapDiag(CircuitQFI): - r"""Compute the diagonal of the QFI given a pure, parameterized quantum state. + r"""Deprecation: Compute the diagonal of the QFI given a pure, parameterized quantum state. See also :class:`~qiskit.opflow.QFI`. """ + @deprecate_function( + "The OverlapDiag opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + def convert( self, operator: Union[CircuitOp, CircuitStateFn], diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 1e1b3fadb5b7..24f9319280ff 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -20,6 +20,7 @@ from qiskit.utils.quantum_instance import QuantumInstance from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.providers import Backend +from qiskit.utils.deprecation import deprecate_function from ..converters.converter_base import ConverterBase from ..expectations import ExpectationBase, PauliExpectation @@ -34,7 +35,7 @@ class DerivativeBase(ConverterBase): - r"""Base class for differentiating opflow objects. + r"""Deprecation: Base class for differentiating opflow objects. Converter for differentiating opflow objects and handling things like properly differentiating combo_fn's and enforcing product rules @@ -48,6 +49,15 @@ class DerivativeBase(ConverterBase): DerivativeBase - uses classical techniques to differentiate opflow data structures """ + @deprecate_function( + "The DerivativeBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() + # pylint: disable=arguments-differ @abstractmethod def convert( diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index 1b7e6fd10333..2c1438ece240 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """The base interface for Opflow's gradient.""" +import warnings from typing import Union, List, Optional import functools import numpy as np @@ -19,6 +20,8 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.utils import optionals as _optionals +from qiskit.utils.deprecation import deprecate_function +from .circuit_gradients.circuit_gradient import CircuitGradient from ..expectations.pauli_expectation import PauliExpectation from .gradient_base import GradientBase from .derivative_base import _coeff_derivative @@ -33,7 +36,16 @@ class Gradient(GradientBase): - """Convert an operator expression to the first-order gradient.""" + """Deprecation: Convert an operator expression to the first-order gradient.""" + + @deprecate_function( + "The Gradient opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(grad_method=grad_method, **kwargs) def convert( self, diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index af38b5150b1c..a7714bbab28f 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,18 +12,24 @@ """The base interface for Aqua's gradient.""" +import warnings from typing import Union +from qiskit.utils.deprecation import deprecate_function from .circuit_gradients.circuit_gradient import CircuitGradient from .derivative_base import DerivativeBase class GradientBase(DerivativeBase): - """Base class for first-order operator gradient. + """Deprecation: Base class for first-order operator gradient. Convert an operator expression to the first-order gradient. """ + @deprecate_function( + "The GradientBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" Args: @@ -35,7 +41,9 @@ def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **k Raises: ValueError: If method != ``fin_diff`` and ``epsilon`` is not None. """ - + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if isinstance(grad_method, CircuitGradient): self._grad_method = grad_method elif grad_method == "param_shift": diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 60a05d131fb4..26c2bf4831c8 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """The module to compute Hessians.""" +import warnings from typing import Union, List, Tuple, Optional import functools import numpy as np @@ -19,6 +20,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.utils import optionals as _optionals +from qiskit.utils.deprecation import deprecate_function from ..operator_globals import Zero, One from ..state_fns.circuit_state_fn import CircuitStateFn from ..state_fns.state_fn import StateFn @@ -33,10 +35,20 @@ from .hessian_base import HessianBase from ..exceptions import OpflowError from ...utils.arithmetic import triu_to_dense +from .circuit_gradients.circuit_gradient import CircuitGradient class Hessian(HessianBase): - """Compute the Hessian of an expected value.""" + """Deprecation: Compute the Hessian of an expected value.""" + + @deprecate_function( + "The Hessian opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(hess_method=hess_method, **kwargs) def convert( self, diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 4ed5b3381821..e8137f78c578 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,15 +12,21 @@ """The module to compute Hessians.""" +import warnings from typing import Union +from qiskit.utils.deprecation import deprecate_function from .circuit_gradients.circuit_gradient import CircuitGradient from .derivative_base import DerivativeBase class HessianBase(DerivativeBase): - """Base class for the Hessian of an expected value.""" + """Deprecation: Base class for the Hessian of an expected value.""" + @deprecate_function( + "The HessianBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" Args: @@ -32,7 +38,9 @@ def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **k Raises: ValueError: If method != ``fin_diff`` and ``epsilon`` is not None. """ - + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if isinstance(hess_method, CircuitGradient): self._hess_method = hess_method elif hess_method == "param_shift": diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index 524bd9c35346..76d5fa25f09a 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2020. +# (C) Copyright IBM 2018, 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 @@ -12,6 +12,7 @@ """ Natural Gradient. """ +import warnings from collections.abc import Iterable from typing import List, Tuple, Callable, Optional, Union import functools @@ -20,6 +21,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.utils import optionals as _optionals +from qiskit.utils.deprecation import deprecate_function from ..operator_base import OperatorBase from ..list_ops.list_op import ListOp from ..list_ops.composed_op import ComposedOp @@ -37,7 +39,7 @@ class NaturalGradient(GradientBase): - r"""Convert an operator expression to the first-order gradient. + r"""Deprecation: Convert an operator expression to the first-order gradient. Given an ill-posed inverse problem @@ -51,6 +53,10 @@ class NaturalGradient(GradientBase): where R(x) represents the penalization term. """ + @deprecate_function( + "The NaturalGradient opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, grad_method: Union[str, CircuitGradient] = "lin_comb", @@ -72,7 +78,9 @@ def __init__( a least square solver is used without regularization kwargs (dict): Optional parameters for a CircuitGradient """ - super().__init__(grad_method) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(grad_method) self._qfi_method = QFI(qfi_method) self._regularization = regularization diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index f9bd289aaa0e..a1b024a27523 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,19 +12,22 @@ """The module for Quantum the Fisher Information.""" +import warnings from typing import List, Union, Optional import functools from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterExpression, ParameterVector +from qiskit.utils.deprecation import deprecate_function from ..list_ops.list_op import ListOp from ..expectations.pauli_expectation import PauliExpectation from ..state_fns.circuit_state_fn import CircuitStateFn from .qfi_base import QFIBase +from .circuit_qfis import CircuitQFI class QFI(QFIBase): - r"""Compute the Quantum Fisher Information (QFI). + r"""Deprecation: Compute the Quantum Fisher Information (QFI). Computes the QFI given a pure, parameterized quantum state, where QFI is: @@ -35,6 +38,15 @@ class QFI(QFIBase): """ + @deprecate_function( + "The QFI opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(qfi_method=qfi_method) + def convert( self, operator: CircuitStateFn, diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index 77686741217b..32f33087689b 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,15 +12,17 @@ """The module for Quantum the Fisher Information.""" +import warnings from typing import Union +from qiskit.utils.deprecation import deprecate_function from .derivative_base import DerivativeBase from .circuit_qfis import CircuitQFI class QFIBase(DerivativeBase): - r"""Base class for Quantum Fisher Information (QFI). + r"""Deprecation: Base class for Quantum Fisher Information (QFI). Compute the Quantum Fisher Information (QFI) given a pure, parameterized quantum state. @@ -29,6 +31,10 @@ class QFIBase(DerivativeBase): [QFI]kl= Re[〈∂kψ|∂lψ〉−〈∂kψ|ψ〉〈ψ|∂lψ〉] * 4. """ + @deprecate_function( + "The QFIBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): r""" Args: @@ -39,7 +45,9 @@ def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): ValueError: if ``qfi_method`` is neither a ``CircuitQFI`` object nor one of the predefined strings. """ - + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() if isinstance(qfi_method, CircuitQFI): self._qfi_method = qfi_method diff --git a/qiskit/opflow/list_ops/__init__.py b/qiskit/opflow/list_ops/__init__.py index d2ae28d1f05b..bd93bffdc9f4 100644 --- a/qiskit/opflow/list_ops/__init__.py +++ b/qiskit/opflow/list_ops/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -16,7 +16,8 @@ .. currentmodule:: qiskit.opflow.list_ops -List Operators are classes for storing and manipulating lists of Operators, State functions, +Deprecation: List Operators are classes for storing and manipulating lists of Operators, +State functions, or Measurements, and include some rule or ``combo_fn`` defining how the Operator functions of the list constituents should be combined to form to cumulative Operator function of the :class:`ListOp`. For example, a :class:`SummedOp` has an addition-based ``combo_fn``, so once diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index a6cf2609bba0..76a5e0e5da8c 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -24,15 +24,20 @@ from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector +from qiskit.utils.deprecation import deprecate_function class ComposedOp(ListOp): - """A class for lazily representing compositions of Operators. Often Operators cannot be + """Deprecation: A class for lazily representing compositions of Operators. Often Operators cannot be efficiently composed with one another, but may be manipulated further so that they can be composed later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be composed, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits or matrices, they can be reduced by composition.""" + @deprecate_function( + "The ComposedOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, oplist: List[OperatorBase], diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index 8a3d9fecb026..fd9f9b456156 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ ListOp Operator Class """ +import warnings from functools import reduce from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Sequence, Union, cast @@ -23,12 +24,13 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.utils import arithmetic +from qiskit.utils.deprecation import deprecate_function class ListOp(OperatorBase): """ - A Class for manipulating List Operators, and parent class to ``SummedOp``, ``ComposedOp``, - and ``TensoredOp``. + Deprecation: A Class for manipulating List Operators, and parent class to ``SummedOp``, + ``ComposedOp`` and ``TensoredOp``. List Operators are classes for storing and manipulating lists of Operators, State functions, or Measurements, and include some rule or ``combo_fn`` defining how the Operator functions @@ -52,6 +54,10 @@ class ListOp(OperatorBase): multiple dimensional lists. """ + @deprecate_function( + "The ListOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, oplist: Sequence[OperatorBase], @@ -72,7 +78,9 @@ def __init__( Note that the default "recombination function" lambda above is essentially the identity - it accepts the list of values, and returns them in a list. """ - super().__init__() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._oplist = self._check_input_types(oplist) self._combo_fn = combo_fn self._coeff = coeff diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index f856f4822acc..378948ba6015 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -21,15 +21,20 @@ from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase +from qiskit.utils.deprecation import deprecate_function class SummedOp(ListOp): - """A class for lazily representing sums of Operators. Often Operators cannot be + """Deprecation: A class for lazily representing sums of Operators. Often Operators cannot be efficiently added to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be added together, and therefore if they reach a point in which they can be, such as after evaluation or conversion to matrices, they can be reduced by addition.""" + @deprecate_function( + "The SummedOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, oplist: List[OperatorBase], diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index 023c325d484f..5a3840bc46c3 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -22,15 +22,20 @@ from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector +from qiskit.utils.deprecation import deprecate_function class TensoredOp(ListOp): - """A class for lazily representing tensor products of Operators. Often Operators cannot be - efficiently tensored to one another, but may be manipulated further so that they can be + """Deprecation: A class for lazily representing tensor products of Operators. Often Operators + cannot be efficiently tensored to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be tensored together, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits, they can be reduced by tensor product.""" + @deprecate_function( + "The TensoredOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, oplist: List[OperatorBase], diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index 30ba75b8ffeb..b8d710fb32ee 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021. +# (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 @@ -16,10 +16,11 @@ from numbers import Integral from qiskit.quantum_info.operators.mixins import MultiplyMixin +from qiskit.utils.deprecation import deprecate_function class StarAlgebraMixin(MultiplyMixin, ABC): - """The star algebra mixin class. + """Deprecation: The star algebra mixin class. Star algebra is an algebra with an adjoint. This class overrides: @@ -39,6 +40,13 @@ class StarAlgebraMixin(MultiplyMixin, ABC): - :meth:`adjoint(self)` """ + @deprecate_function( + "The StarAlgebraMixin opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + pass + # Scalar multiplication @abstractmethod diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index dfec66d5674d..6bc8ec9fffab 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021. +# (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 @@ -14,10 +14,11 @@ from abc import ABC, abstractmethod from numbers import Integral +from qiskit.utils.deprecation import deprecate_function class TensorMixin(ABC): - """The mixin class for tensor operations. + """Deprecation: The mixin class for tensor operations. This class overrides: - ``^``, ``__xor__``, `__rxor__` -> :meth:`tensor` between two operators and @@ -27,6 +28,13 @@ class TensorMixin(ABC): - :meth:``tensorpower(self, other: int)`` """ + @deprecate_function( + "The TensorMixin opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) + def __init__(self) -> None: + pass + def __xor__(self, other): if isinstance(other, Integral): return self.tensorpower(other) diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index 719a8fe99f5a..ff929d90eb22 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 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 @@ -13,6 +13,7 @@ """ OperatorBase Class """ import itertools +import warnings from abc import ABC, abstractmethod from copy import deepcopy from typing import Dict, List, Optional, Set, Tuple, Union, cast @@ -25,10 +26,11 @@ from qiskit.opflow.mixins import StarAlgebraMixin, TensorMixin from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals +from qiskit.utils.deprecation import deprecate_function class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): - """A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are + """Deprecation: A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are defined as functions which take one complex binary function to another. These complex binary functions are represented by StateFns, which are themselves a special class of Operators taking only the ``Zero`` StateFn to the complex binary function they represent. @@ -44,7 +46,14 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): _count = itertools.count() + @deprecate_function( + "The OperatorBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self) -> None: + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._instance_id = next(self._count) @property diff --git a/qiskit/opflow/operator_globals.py b/qiskit/opflow/operator_globals.py index 7fb3796ea8a9..31503b671b6c 100644 --- a/qiskit/opflow/operator_globals.py +++ b/qiskit/opflow/operator_globals.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -20,6 +20,7 @@ from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.state_fns.dict_state_fn import DictStateFn +from qiskit.utils.deprecation import deprecate_function # Digits of precision when returning values from eval functions. Without rounding, 1e-17 or 1e-32 # values often show up in place of 0, etc. @@ -32,8 +33,12 @@ # Immutable convenience objects +@deprecate_function( + "The make_immutable opflow function is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " +) def make_immutable(obj): - """Delete the __setattr__ property to make the object mostly immutable.""" + r"""Deprecate\: Delete the __setattr__ property to make the object mostly immutable.""" # TODO figure out how to get correct error message # def throw_immutability_exception(self, *args): diff --git a/qiskit/opflow/primitive_ops/__init__.py b/qiskit/opflow/primitive_ops/__init__.py index 1af655893599..d5c43ae69313 100644 --- a/qiskit/opflow/primitive_ops/__init__.py +++ b/qiskit/opflow/primitive_ops/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -16,7 +16,7 @@ .. currentmodule:: qiskit.opflow.primitive_ops -Operators are defined to be functions which take State functions to State functions. +Deprecation: Operators are defined to be functions which take State functions to State functions. PrimitiveOps are the classes for representing basic Operators, backed by computational Operator primitives from Terra. These classes (and inheritors) primarily serve to allow the diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 42a9d2657366..3d18783d06ee 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -13,7 +13,7 @@ """CircuitOp Class """ from typing import Dict, List, Optional, Set, Union, cast - +import warnings import numpy as np import qiskit @@ -24,13 +24,18 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector +from qiskit.utils.deprecation import deprecate_function class CircuitOp(PrimitiveOp): - """Class for Operators backed by Terra's ``QuantumCircuit`` module.""" + """Deprecation: Class for Operators backed by Terra's ``QuantumCircuit`` module.""" primitive: QuantumCircuit + @deprecate_function( + "The CircuitOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: Union[Instruction, QuantumCircuit], @@ -59,7 +64,9 @@ def __init__( if len(primitive.clbits) != 0: raise TypeError("CircuitOp does not support QuantumCircuits with ClassicalRegisters.") - super().__init__(primitive, coeff) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(primitive, coeff) self._coeff = coeff def primitive_strings(self) -> Set[str]: diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index 5993bfaba19c..d23e4a99f49e 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -13,7 +13,7 @@ """MatrixOp Class """ from typing import Dict, List, Optional, Set, Union, cast, get_type_hints - +import warnings import numpy as np from scipy.sparse import spmatrix @@ -28,13 +28,19 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Operator, Statevector from qiskit.utils import arithmetic +from qiskit.utils.deprecation import deprecate_function class MatrixOp(PrimitiveOp): - """Class for Operators represented by matrices, backed by Terra's ``Operator`` module.""" + """Deprecation: Class for Operators represented by matrices, + backed by Terra's ``Operator`` module.""" primitive: Operator + @deprecate_function( + "The MatrixOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: Union[list, np.ndarray, spmatrix, Operator], @@ -67,7 +73,9 @@ def __init__( if primitive.input_dims() != primitive.output_dims(): raise ValueError("Cannot handle non-square matrices yet.") - super().__init__(primitive, coeff=coeff) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Matrix"} diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 1699275ef52a..56724993190e 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -14,7 +14,7 @@ from math import pi from typing import Dict, List, Optional, Set, Union, cast - +import warnings import numpy as np from scipy.sparse import spmatrix @@ -28,13 +28,18 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector +from qiskit.utils.deprecation import deprecate_function class PauliOp(PrimitiveOp): - """Class for Operators backed by Terra's ``Pauli`` module.""" + """Deprecation: Class for Operators backed by Terra's ``Pauli`` module.""" primitive: Pauli + @deprecate_function( + "The PauliOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ Args: @@ -46,7 +51,9 @@ def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] """ if not isinstance(primitive, Pauli): raise TypeError(f"PauliOp can only be instantiated with Paulis, not {type(primitive)}") - super().__init__(primitive, coeff=coeff) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Pauli"} diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index 894554341321..d1b392b42744 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -14,7 +14,7 @@ from collections import defaultdict from typing import Dict, List, Optional, Set, Tuple, Union, cast - +import warnings import numpy as np from scipy.sparse import spmatrix @@ -27,13 +27,18 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.quantum_info.operators.custom_iterator import CustomIterator +from qiskit.utils.deprecation import deprecate_function class PauliSumOp(PrimitiveOp): - """Class for Operators backed by Terra's ``SparsePauliOp`` class.""" + """Deprecation: Class for Operators backed by Terra's ``SparsePauliOp`` class.""" primitive: SparsePauliOp + @deprecate_function( + "The PauliSumOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: SparsePauliOp, @@ -53,8 +58,9 @@ def __init__( raise TypeError( f"PauliSumOp can only be instantiated with SparsePauliOp, not {type(primitive)}" ) - - super().__init__(primitive, coeff=coeff) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(primitive, coeff=coeff) self._grouping_type = grouping_type def primitive_strings(self) -> Set[str]: diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index 00ad2d13046b..424d98567699 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ PrimitiveOp Class """ +import warnings from typing import Dict, List, Optional, Set, Union, cast import numpy as np @@ -22,11 +23,12 @@ from qiskit.circuit import Instruction, ParameterExpression from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector +from qiskit.utils.deprecation import deprecate_function class PrimitiveOp(OperatorBase): r""" - A class for representing basic Operators, backed by Operator primitives from + Deprecation: A class for representing basic Operators, backed by Operator primitives from Terra. This class (and inheritors) primarily serves to allow the underlying primitives to "flow" - i.e. interoperability and adherence to the Operator formalism - while the core computational logic mostly remains in the underlying primitives. @@ -92,6 +94,10 @@ def __new__( "factory constructor".format(type(primitive)) ) + @deprecate_function( + "The PrimitiveOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase], @@ -102,7 +108,9 @@ def __init__( primitive: The operator primitive being wrapped. coeff: A coefficient multiplying the primitive. """ - super().__init__() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._primitive = primitive self._coeff = coeff diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index 97cc441b5b49..d840b33e0583 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021. +# (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 @@ -14,6 +14,7 @@ import itertools import logging +import warnings from copy import deepcopy from typing import Dict, List, Optional, Union, cast @@ -27,13 +28,18 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.utils import commutator from qiskit.quantum_info import Pauli, SparsePauliOp +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) class TaperedPauliSumOp(PauliSumOp): - """Class for PauliSumOp after tapering""" + """Deprecation: Class for PauliSumOp after tapering""" + @deprecate_function( + "The TaperedPauliSumOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: SparsePauliOp, @@ -49,7 +55,9 @@ def __init__( Raises: TypeError: invalid parameters. """ - super().__init__(primitive, coeff) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__(primitive, coeff) if not isinstance(z2_symmetries, Z2Symmetries): raise TypeError( f"Argument parameter z2_symmetries must be Z2Symmetries, not {type(z2_symmetries)}" diff --git a/qiskit/opflow/state_fns/__init__.py b/qiskit/opflow/state_fns/__init__.py index 6d71298df145..6c99e0c808cd 100644 --- a/qiskit/opflow/state_fns/__init__.py +++ b/qiskit/opflow/state_fns/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -14,9 +14,9 @@ State Functions (:mod:`qiskit.opflow.state_fns`) ================================================ -State functions are defined to be complex functions over a single binary string (as -compared to an operator, which is defined as a function over two binary strings, or a -function taking a binary function to another binary function). This function may be +Deprecation: State functions are defined to be complex functions over a single binary +string (as compared to an operator, which is defined as a function over two binary strings, +or a function taking a binary function to another binary function). This function may be called by the eval() method. Measurements are defined to be functionals over StateFns, taking them to real values. diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index 7d5b3a2957de..b8e0e74df9e6 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -33,16 +33,21 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector +from qiskit.utils.deprecation import deprecate_function class CircuitStateFn(StateFn): r""" - A class for state functions and measurements which are defined by the action of a + Deprecation: A class for state functions and measurements which are defined by the action of a QuantumCircuit starting from \|0⟩, and stored using Terra's ``QuantumCircuit`` class. """ primitive: QuantumCircuit # TODO allow normalization somehow? + @deprecate_function( + "The CircuitStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: Union[QuantumCircuit, Instruction] = None, diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index dda966dbf0d9..da1637641780 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -28,10 +28,11 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector +from qiskit.utils.deprecation import deprecate_function class CVaRMeasurement(OperatorStateFn): - r"""A specialized measurement class to compute CVaR expectation values. + r"""Deprecation: A specialized measurement class to compute CVaR expectation values. See https://arxiv.org/pdf/1907.04769.pdf for further details. Used in :class:`~qiskit.opflow.CVaRExpectation`, see there for more details. @@ -40,6 +41,10 @@ class CVaRMeasurement(OperatorStateFn): primitive: OperatorBase # TODO allow normalization somehow? + @deprecate_function( + "The CVaRMeasurement opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: OperatorBase = None, diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index bfe2c6e4c68b..6025990433af 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 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 @@ -27,16 +27,21 @@ from qiskit.quantum_info import Statevector from qiskit.result import Result from qiskit.utils import algorithm_globals +from qiskit.utils.deprecation import deprecate_function class DictStateFn(StateFn): - """A class for state functions and measurements which are defined by a lookup table, + """Deprecation: A class for state functions and measurements which are defined by a lookup table, stored in a dict. """ primitive: Dict[str, complex] # TODO allow normalization somehow? + @deprecate_function( + "The DictStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: Union[str, dict, Result] = None, diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index 8d343faadbcf..f4c07d57d0a1 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -26,16 +26,21 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.quantum_info import Statevector +from qiskit.utils.deprecation import deprecate_function class OperatorStateFn(StateFn): r""" - A class for state functions and measurements which are defined by a density Operator, + Deprecation: A class for state functions and measurements which are defined by a density Operator, stored using an ``OperatorBase``. """ primitive: OperatorBase # TODO allow normalization somehow? + @deprecate_function( + "The OperatorStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: OperatorBase, diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index 935241a2e197..369ee9a91775 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 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 @@ -26,10 +26,11 @@ from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals +from qiskit.utils.deprecation import deprecate_function class SparseVectorStateFn(StateFn): - """A class for sparse state functions and measurements in vector representation. + """Deprecation: A class for sparse state functions and measurements in vector representation. This class uses ``scipy.sparse.spmatrix`` for the internal representation. """ @@ -37,6 +38,10 @@ class SparseVectorStateFn(StateFn): primitive: scipy.sparse.spmatrix # TODO allow normalization somehow? + @deprecate_function( + "The SparseVectorStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: scipy.sparse.spmatrix, diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index d4e689d6b42e..77eff6a150a8 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -12,6 +12,7 @@ """ StateFn Class """ +import warnings from typing import Callable, Dict, List, Optional, Set, Tuple, Union import numpy as np @@ -21,11 +22,12 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.result import Result +from qiskit.utils.deprecation import deprecate_function class StateFn(OperatorBase): r""" - A class for representing state functions and measurements. + Deprecation: A class for representing state functions and measurements. State functions are defined to be complex functions over a single binary string (as compared to an operator, which is defined as a function over two binary strings, or a @@ -112,6 +114,10 @@ def __new__( ) # TODO allow normalization somehow? + @deprecate_function( + "The StateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: Union[ @@ -134,7 +140,9 @@ def __init__( coeff: A coefficient by which the state function is multiplied. is_measurement: Whether the StateFn is a measurement operator """ - super().__init__() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + super().__init__() self._primitive = primitive self._is_measurement = is_measurement self._coeff = coeff diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index c70a0487b123..69b84f5e740f 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 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 @@ -26,16 +26,21 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals, arithmetic +from qiskit.utils.deprecation import deprecate_function class VectorStateFn(StateFn): - """A class for state functions and measurements which are defined in vector + """Deprecation: A class for state functions and measurements which are defined in vector representation, and stored using Terra's ``Statevector`` class. """ primitive: Statevector # TODO allow normalization somehow? + @deprecate_function( + "The VectorStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, primitive: Union[list, np.ndarray, Statevector] = None, diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index 439b44ea4661..fc1fbf472cef 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 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 @@ -13,11 +13,16 @@ """ Utility functions for OperatorFlow """ from qiskit.opflow.operator_base import OperatorBase +from qiskit.utils.deprecation import deprecate_function +@deprecate_function( + "The commutator opflow function is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " +) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Compute commutator of `op_a` and `op_b`. + Deprecation: Compute commutator of `op_a` and `op_b`. .. math:: @@ -32,9 +37,13 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: return (op_a @ op_b - op_b @ op_a).reduce() +@deprecate_function( + "The anti_commutator opflow function is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " +) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Compute anti-commutator of `op_a` and `op_b`. + Deprecation: Compute anti-commutator of `op_a` and `op_b`. .. math:: @@ -49,6 +58,10 @@ def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: return (op_a @ op_b + op_b @ op_a).reduce() +@deprecate_function( + "The double_commutator opflow function is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " +) def double_commutator( op_a: OperatorBase, op_b: OperatorBase, @@ -56,7 +69,7 @@ def double_commutator( sign: bool = False, ) -> OperatorBase: r""" - Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. + Deprecation: Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. See McWeeny chapter 13.6 Equation of motion methods (page 479) If `sign` is `False`, it returns diff --git a/qiskit/test/base.py b/qiskit/test/base.py index 3b6853f4a06b..60efcaac9604 100644 --- a/qiskit/test/base.py +++ b/qiskit/test/base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2017, 2018. +# (C) Copyright IBM 2017, 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 @@ -227,6 +227,16 @@ def setUpClass(cls): for msg in allow_DeprecationWarning_message: warnings.filterwarnings("default", category=DeprecationWarning, message=msg) + # ignore opflow, QuantumInstance and deprecated function msgs + warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*opflow.*") + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message=r".*QuantumInstance.*" + ) + warnings.filterwarnings( + "ignore", category=DeprecationWarning, message=r".*find_regs_by_name.*" + ) + warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*run_circuits.*") + class FullQiskitTestCase(QiskitTestCase): """Terra-specific further additions for test cases, if ``testtools`` is available. diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index f72b34d9cc02..ffda8d6469fa 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -38,6 +38,7 @@ CompleteMeasFitter, TensoredMeasFitter, ) +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) @@ -124,7 +125,7 @@ def type_from_instance(meas_instance): class QuantumInstance: - """Quantum Backend including execution setting.""" + """Deprecation: Quantum Backend including execution setting.""" _BACKEND_CONFIG = ["basis_gates", "coupling_map"] _COMPILE_CONFIG = ["initial_layout", "seed_transpiler", "optimization_level"] @@ -143,6 +144,10 @@ class QuantumInstance: "statevector_hpc_gate_opt", ] + _BACKEND_OPTIONS_QASM_ONLY + @deprecate_function( + "The QuantumInstance class is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, backend, diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index 27d3e5e3e27c..f86433c481b3 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 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 @@ -23,6 +23,7 @@ from qiskit.providers import Backend, JobStatus, JobError, Job from qiskit.providers.jobstatus import JOB_FINAL_STATES from qiskit.result import Result +from qiskit.utils.deprecation import deprecate_function from ..exceptions import QiskitError, MissingOptionalLibraryError from .backend_utils import ( is_aer_provider, @@ -39,10 +40,14 @@ logger = logging.getLogger(__name__) +@deprecate_function( + "The find_regs_by_name function is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " +) def find_regs_by_name( circuit: QuantumCircuit, name: str, qreg: bool = True ) -> Optional[Union[QuantumRegister, ClassicalRegister]]: - """Find the registers in the circuits. + """Deprecation: Find the registers in the circuits. Args: circuit: the quantum circuit. @@ -101,6 +106,10 @@ def _safe_get_job_status(job: Job, job_id: str, max_job_retries: int, wait: floa return job_status +@deprecate_function( + "The run_circuits function is deprecated as of Qiskit Terra 0.23.0 " + "and will be removed no sooner than 3 months after the release date. " +) def run_circuits( circuits: Union[QuantumCircuit, List[QuantumCircuit]], backend: Backend, @@ -112,7 +121,7 @@ def run_circuits( max_job_retries: int = 50, ) -> Result: """ - An execution wrapper with Qiskit-Terra, with job auto recover capability. + Deprecation: An execution wrapper with Qiskit-Terra, with job auto recover capability. The auto-recovery feature is only applied for non-simulator backend. This wrapper will try to get the result no matter how long it takes. diff --git a/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml b/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml new file mode 100644 index 000000000000..f9d9bce666be --- /dev/null +++ b/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml @@ -0,0 +1,7 @@ +--- +deprecations: + - | + The module :mod:`qiskit.opflow`, class :class:`qiskit.utils.QuantumInstance` and methods + :meth:`~qiskit.utils.run_circuits.find_regs_by_name`, + :meth:`~qiskit.utils.run_circuits.run_circuits` + have been deprecated and will be removed in a future release. diff --git a/test/python/algorithms/test_shor.py b/test/python/algorithms/test_shor.py index 3b2ce675e03e..8f22714cb97b 100644 --- a/test/python/algorithms/test_shor.py +++ b/test/python/algorithms/test_shor.py @@ -40,7 +40,11 @@ def setUp(self): category=DeprecationWarning, ) self.instance = Shor(quantum_instance=QuantumInstance(backend, shots=1000)) - self.assertTrue("Shor class is deprecated" in str(caught_warnings[0].message)) + for caught_warning in caught_warnings: + if "Shor class is deprecated" in str(caught_warning.message): + return + + self.fail("Shor class is not emitting deprecation message.") @slow_test @idata( @@ -70,8 +74,19 @@ def _test_shor_factoring(self, backend, factors, n_v): with warnings.catch_warnings(record=True) as caught_warnings: warnings.simplefilter("always") + from qiskit_aer import Aer + shor = Shor(quantum_instance=QuantumInstance(Aer.get_backend(backend), shots=1000)) - self.assertTrue("Shor class is deprecated" in str(caught_warnings[0].message)) + found = False + for caught_warning in caught_warnings: + if "Shor class is deprecated" in str(caught_warning.message): + found = True + break + + if not found: + self.fail("Shor class is not emitting deprecation message.") + return + result = shor.factor(N=n_v) self.assertListEqual(result.factors[0], factors) self.assertTrue(result.total_counts >= result.successful_counts) From 0f93f42ab23b7e03fd19d308dd6c5d50164b196a Mon Sep 17 00:00:00 2001 From: Manoel Marques Date: Mon, 12 Dec 2022 12:52:47 -0500 Subject: [PATCH 02/47] Add .. deprecated:: to init modules --- .../evolvers/trotterization/trotter_qrte.py | 9 +- .../observables/absolute_average.py | 11 +- .../observables/matrix_functional.py | 17 +- qiskit/opflow/__init__.py | 14 +- qiskit/opflow/converters/__init__.py | 32 +- qiskit/opflow/converters/abelian_grouper.py | 9 +- qiskit/opflow/converters/circuit_sampler.py | 42 +- qiskit/opflow/converters/converter_base.py | 4 +- .../opflow/converters/dict_to_circuit_sum.py | 9 +- .../opflow/converters/pauli_basis_change.py | 9 +- .../opflow/converters/two_qubit_reduction.py | 9 +- qiskit/opflow/evolutions/__init__.py | 28 +- qiskit/opflow/evolutions/evolution_base.py | 9 +- qiskit/opflow/evolutions/evolution_factory.py | 4 +- qiskit/opflow/evolutions/evolved_op.py | 9 +- qiskit/opflow/evolutions/matrix_evolution.py | 9 +- .../evolutions/pauli_trotter_evolution.py | 9 +- .../evolutions/trotterizations/__init__.py | 7 +- .../evolutions/trotterizations/qdrift.py | 4 +- .../evolutions/trotterizations/suzuki.py | 4 +- .../evolutions/trotterizations/trotter.py | 4 +- .../trotterizations/trotterization_base.py | 9 +- .../trotterizations/trotterization_factory.py | 4 +- qiskit/opflow/exceptions.py | 4 +- qiskit/opflow/expectations/__init__.py | 26 +- .../expectations/aer_pauli_expectation.py | 9 +- .../opflow/expectations/cvar_expectation.py | 9 +- .../opflow/expectations/expectation_base.py | 9 +- .../expectations/expectation_factory.py | 55 +- .../opflow/expectations/matrix_expectation.py | 9 +- .../opflow/expectations/pauli_expectation.py | 9 +- qiskit/opflow/gradients/__init__.py | 11 +- .../gradients/circuit_gradients/__init__.py | 2 +- .../circuit_gradients/circuit_gradient.py | 9 +- .../gradients/circuit_gradients/lin_comb.py | 9 +- .../circuit_gradients/param_shift.py | 9 +- .../opflow/gradients/circuit_qfis/__init__.py | 2 +- .../gradients/circuit_qfis/circuit_qfi.py | 9 +- .../gradients/circuit_qfis/lin_comb_full.py | 9 +- .../circuit_qfis/overlap_block_diag.py | 9 +- .../gradients/circuit_qfis/overlap_diag.py | 9 +- qiskit/opflow/gradients/derivative_base.py | 8 +- qiskit/opflow/gradients/gradient.py | 9 +- qiskit/opflow/gradients/gradient_base.py | 9 +- qiskit/opflow/gradients/hessian.py | 9 +- qiskit/opflow/gradients/hessian_base.py | 9 +- qiskit/opflow/gradients/natural_gradient.py | 9 +- qiskit/opflow/gradients/qfi.py | 9 +- qiskit/opflow/gradients/qfi_base.py | 9 +- qiskit/opflow/list_ops/__init__.py | 33 +- qiskit/opflow/list_ops/composed_op.py | 4 +- qiskit/opflow/list_ops/list_op.py | 9 +- qiskit/opflow/list_ops/summed_op.py | 4 +- qiskit/opflow/list_ops/tensored_op.py | 4 +- qiskit/opflow/mixins/star_algebra.py | 4 +- qiskit/opflow/mixins/tensor.py | 4 +- qiskit/opflow/operator_base.py | 9 +- qiskit/opflow/operator_globals.py | 4 +- qiskit/opflow/primitive_ops/__init__.py | 6 +- qiskit/opflow/primitive_ops/circuit_op.py | 9 +- qiskit/opflow/primitive_ops/matrix_op.py | 9 +- qiskit/opflow/primitive_ops/pauli_op.py | 10 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 10 +- qiskit/opflow/primitive_ops/primitive_op.py | 9 +- .../primitive_ops/tapered_pauli_sum_op.py | 9 +- qiskit/opflow/state_fns/__init__.py | 12 +- qiskit/opflow/state_fns/circuit_state_fn.py | 4 +- qiskit/opflow/state_fns/cvar_measurement.py | 4 +- qiskit/opflow/state_fns/dict_state_fn.py | 4 +- qiskit/opflow/state_fns/operator_state_fn.py | 4 +- .../state_fns/sparse_vector_state_fn.py | 4 +- qiskit/opflow/state_fns/state_fn.py | 9 +- qiskit/opflow/state_fns/vector_state_fn.py | 4 +- qiskit/opflow/utils.py | 8 +- qiskit/test/base.py | 12 +- qiskit/utils/backend_utils.py | 47 +- qiskit/utils/measurement_error_mitigation.py | 25 +- qiskit/utils/mitigation/__init__.py | 6 +- qiskit/utils/mitigation/_filters.py | 15 +- qiskit/utils/mitigation/circuits.py | 21 +- qiskit/utils/mitigation/fitters.py | 13 +- qiskit/utils/quantum_instance.py | 4 +- qiskit/utils/run_circuits.py | 6 +- .../deprecate-opflow-qi-32f7e27884deea3f.yaml | 7 +- .../algorithms/eigensolvers/test_vqd.py | 45 +- .../evolvers/test_evolution_problem.py | 67 +- .../trotterization/test_trotter_qrte.py | 79 +- .../gradients/test_estimator_gradient.py | 6 +- test/python/algorithms/gradients/test_qgt.py | 3 +- .../gradients/test_sampler_gradient.py | 7 +- .../minimum_eigensolvers/test_adapt_vqe.py | 152 ++-- .../minimum_eigensolvers/test_qaoa.py | 86 +- .../minimum_eigensolvers/test_sampling_vqe.py | 20 +- .../minimum_eigensolvers/test_vqe.py | 97 +- .../optimizers/test_gradient_descent.py | 24 +- .../optimizers/test_optimizer_aqgd.py | 121 ++- .../optimizers/test_optimizer_nft.py | 57 +- .../optimizers/test_optimizers_scikitquant.py | 47 +- .../python/algorithms/optimizers/test_spsa.py | 23 +- .../algorithms/test_amplitude_estimators.py | 218 +++-- .../algorithms/test_aux_ops_evaluator.py | 87 +- test/python/algorithms/test_backendv1.py | 123 ++- test/python/algorithms/test_backendv2.py | 82 +- test/python/algorithms/test_grover.py | 123 ++- test/python/algorithms/test_linear_solvers.py | 60 +- .../test_measure_error_mitigation.py | 330 ++++--- .../algorithms/test_numpy_eigen_solver.py | 123 ++- .../test_numpy_minimum_eigen_solver.py | 209 ++++- .../algorithms/test_observables_evaluator.py | 30 +- .../python/algorithms/test_phase_estimator.py | 286 ++++-- test/python/algorithms/test_qaoa.py | 232 +++-- test/python/algorithms/test_shor.py | 17 +- .../algorithms/test_skip_qobj_validation.py | 112 ++- test/python/algorithms/test_vqd.py | 589 +++++++----- test/python/algorithms/test_vqe.py | 841 ++++++++++++------ .../test_scipy_imaginary_evolver.py | 23 +- .../algorithms/time_evolvers/test_pvqd.py | 12 +- .../test_time_evolution_problem.py | 35 +- .../time_evolvers/test_trotter_qrte.py | 60 +- .../variational/test_var_qite.py | 19 +- .../variational/test_var_qrte.py | 19 +- .../circuit/library/test_evolution_gate.py | 174 +++- .../circuit/library/test_evolved_op_ansatz.py | 92 +- .../circuit/library/test_qaoa_ansatz.py | 174 +++- .../circuit/test_circuit_load_from_qpy.py | 79 +- test/python/opflow/opflow_test_case.py | 13 +- .../opflow/test_aer_pauli_expectation.py | 184 ++-- .../python/opflow/test_expectation_factory.py | 14 +- test/python/opflow/test_gradients.py | 211 +++-- test/python/opflow/test_matrix_expectation.py | 110 ++- test/python/opflow/test_pauli_expectation.py | 130 ++- .../python/opflow/test_state_op_meas_evals.py | 82 +- test/python/primitives/test_estimator.py | 20 +- test/python/result/test_sampled_expval.py | 20 +- .../transpiler/test_swap_strategy_router.py | 127 ++- test/python/utils/mitigation/test_meas.py | 409 +++++---- 136 files changed, 4798 insertions(+), 2395 deletions(-) diff --git a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py index 33bafc156194..323305b4b8c1 100644 --- a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py +++ b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py @@ -48,23 +48,18 @@ class TrotterQRTE(RealEvolver): Examples:: - import warnings from qiskit.opflow import X, Z, Zero from qiskit.algorithms import EvolutionProblem, TrotterQRTE from qiskit import BasicAer from qiskit.utils import QuantumInstance - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - operator = X + Z + operator = X + Z initial_state = Zero time = 1 evolution_problem = EvolutionProblem(operator, 1, initial_state) # LieTrotter with 1 rep backend = BasicAer.get_backend("statevector_simulator") - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - quantum_instance = QuantumInstance(backend=backend) + quantum_instance = QuantumInstance(backend=backend) trotter_qrte = TrotterQRTE(quantum_instance=quantum_instance) evolved_state = trotter_qrte.evolve(evolution_problem).evolved_state """ diff --git a/qiskit/algorithms/linear_solvers/observables/absolute_average.py b/qiskit/algorithms/linear_solvers/observables/absolute_average.py index 1765cfcb305d..62694f8d35d5 100644 --- a/qiskit/algorithms/linear_solvers/observables/absolute_average.py +++ b/qiskit/algorithms/linear_solvers/observables/absolute_average.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -31,16 +31,13 @@ class AbsoluteAverage(LinearSystemObservable): Examples:: - import warnings import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms.linear_solvers.observables.absolute_average import \ AbsoluteAverage from qiskit.opflow import StateFn - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - observable = AbsoluteAverage() + observable = AbsoluteAverage() vector = [1.0, -2.1, 3.2, -4.3] init_state = vector / np.linalg.norm(vector) @@ -52,9 +49,7 @@ class AbsoluteAverage(LinearSystemObservable): # Observable operator observable_op = observable.observable(num_qubits) - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - state_vec = (~StateFn(observable_op) @ StateFn(qc)).eval() + state_vec = (~StateFn(observable_op) @ StateFn(qc)).eval() # Obtain result result = observable.post_processing(state_vec, num_qubits) diff --git a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py index fdee0613df56..5882e514abf7 100644 --- a/qiskit/algorithms/linear_solvers/observables/matrix_functional.py +++ b/qiskit/algorithms/linear_solvers/observables/matrix_functional.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -30,7 +30,6 @@ class MatrixFunctional(LinearSystemObservable): Examples:: - import warnings import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms.linear_solvers.observables.matrix_functional import \ @@ -41,9 +40,7 @@ class MatrixFunctional(LinearSystemObservable): tpass = RemoveResetInZeroState() vector = [1.0, -2.1, 3.2, -4.3] - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - observable = MatrixFunctional(1, -1 / 3) + observable = MatrixFunctional(1, -1 / 3) init_state = vector / np.linalg.norm(vector) num_qubits = int(np.log2(len(vector))) @@ -61,12 +58,10 @@ class MatrixFunctional(LinearSystemObservable): observable_ops = observable.observable(num_qubits) state_vecs = [] # First is the norm - with warnings.catch_warnings(): - warnings.simplefilter('ignore') - state_vecs.append((~StateFn(observable_ops[0]) @ StateFn(qcs[0])).eval()) - for i in range(1, len(observable_ops), 2): - state_vecs += [(~StateFn(observable_ops[i]) @ StateFn(qcs[i])).eval(), - (~StateFn(observable_ops[i + 1]) @ StateFn(qcs[i + 1])).eval()] + state_vecs.append((~StateFn(observable_ops[0]) @ StateFn(qcs[0])).eval()) + for i in range(1, len(observable_ops), 2): + state_vecs += [(~StateFn(observable_ops[i]) @ StateFn(qcs[i])).eval(), + (~StateFn(observable_ops[i + 1]) @ StateFn(qcs[i + 1])).eval()] # Obtain result result = observable.post_processing(state_vecs, num_qubits) diff --git a/qiskit/opflow/__init__.py b/qiskit/opflow/__init__.py index 37f86c5f9764..4fb9595244e6 100644 --- a/qiskit/opflow/__init__.py +++ b/qiskit/opflow/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2022. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -17,7 +17,9 @@ .. currentmodule:: qiskit.opflow -Deprecation: Operators and State functions are the building blocks of Quantum Algorithms. +.. deprecated:: 0.24.0 + Operators and State functions are the building blocks of Quantum Algorithms. + A library for Quantum Algorithms & Applications is more than a collection of algorithms wrapped in Python functions. It needs to provide tools to make writing @@ -77,7 +79,7 @@ Operator Base Class =================== -Deprecation: The OperatorBase serves as the base class for all Operators, State functions +The OperatorBase serves as the base class for all Operators, State functions and measurements, and enforces the presence and consistency of methods to manipulate these objects conveniently. @@ -91,7 +93,7 @@ Operator Globals ================ -Deprecation: The :mod:`operator_globals` is a set of immutable Operator instances that are +The :mod:`operator_globals` is a set of immutable Operator instances that are convenient building blocks to reach for while working with the Operator flow. One qubit Pauli operators: @@ -109,7 +111,7 @@ Operators --------- -Deprecation: The Operators submodules include the PrimitiveOp, ListOp, and StateFn class +The Operators submodules include the PrimitiveOp, ListOp, and StateFn class groups which represent the primary Operator modules. .. autosummary:: @@ -123,7 +125,7 @@ Converters ---------- -Deprecation: The Converter submodules include objects which manipulate Operators, +The Converter submodules include objects which manipulate Operators, usually recursing over an Operator structure and changing certain Operators' representation. For example, the :class:`~.expectations.PauliExpectation` traverses an Operator structure, and replaces all of the :class:`~.state_fns.OperatorStateFn` measurements containing non-diagonal diff --git a/qiskit/opflow/converters/__init__.py b/qiskit/opflow/converters/__init__.py index d017fbf5cffd..794d5275dcec 100644 --- a/qiskit/opflow/converters/__init__.py +++ b/qiskit/opflow/converters/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -16,20 +16,22 @@ .. currentmodule:: qiskit.opflow.converters -Deprecation: Converters are objects which manipulate Operators, usually traversing an Operator to -change certain sub-Operators into a desired representation. Often the converted Operator is -isomorphic or approximate to the original Operator in some way, but not always. For example, -a converter may accept :class:`~qiskit.opflow.primitive_ops.CircuitOp` and return a -:class:`~qiskit.opflow.list_ops.SummedOp` of -:class:`~qiskit.opflow.primitive_ops.PauliOp`'s representing the -circuit unitary. Converters may not have polynomial space or time scaling in their operations. -On the contrary, many converters, such as a -:class:`~qiskit.opflow.expectations.MatrixExpectation` or -:class:`~qiskit.opflow.evolutions.MatrixEvolution`, -which convert :class:`~qiskit.opflow.primitive_ops.PauliOp`'s to -:class:`~qiskit.opflow.primitive_ops.MatrixOp`'s internally, will require time or space -exponential in the number of qubits unless a clever trick is known -(such as the use of sparse matrices). +.. deprecated:: 0.24.0 + Converters are objects which manipulate Operators, usually traversing an Operator to + change certain sub-Operators into a desired representation. Often the converted Operator is + isomorphic or approximate to the original Operator in some way, but not always. For example, + a converter may accept :class:`~qiskit.opflow.primitive_ops.CircuitOp` and return a + :class:`~qiskit.opflow.list_ops.SummedOp` of + :class:`~qiskit.opflow.primitive_ops.PauliOp`'s representing the + circuit unitary. Converters may not have polynomial space or time scaling in their operations. + On the contrary, many converters, such as a + :class:`~qiskit.opflow.expectations.MatrixExpectation` or + :class:`~qiskit.opflow.evolutions.MatrixEvolution`, + which convert :class:`~qiskit.opflow.primitive_ops.PauliOp`'s to + :class:`~qiskit.opflow.primitive_ops.MatrixOp`'s internally, will require time or space + exponential in the number of qubits unless a clever trick is known + (such as the use of sparse matrices). + Note: Not all converters are in this module, as :mod:`~qiskit.opflow.expectations` diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index d040c4eebfbd..6eaf0e57e323 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,7 +13,6 @@ """AbelianGrouper Class""" from collections import defaultdict -import warnings from typing import List, Tuple, Union, cast import numpy as np @@ -44,7 +43,7 @@ class AbelianGrouper(ConverterBase): """ @deprecate_function( - "The AbelianGrouper opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The AbelianGrouper opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, traverse: bool = True) -> None: @@ -53,9 +52,7 @@ def __init__(self, traverse: bool = True) -> None: traverse: Whether to convert only the Operator passed to ``convert``, or traverse down that Operator. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._traverse = traverse def convert(self, operator: OperatorBase) -> OperatorBase: diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index 34109ca58e1d..aab8a8af855e 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -54,7 +54,7 @@ class CircuitSampler(ConverterBase): """ @deprecate_function( - "The CircuitSampler opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The CircuitSampler opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -82,15 +82,17 @@ def __init__( Raises: ValueError: Set statevector or param_qobj True when not supported by backend. """ + super().__init__() with warnings.catch_warnings(): warnings.simplefilter("ignore") - super().__init__() - self._quantum_instance = ( - backend if isinstance(backend, QuantumInstance) else QuantumInstance(backend=backend) - ) - self._statevector = ( - statevector if statevector is not None else self.quantum_instance.is_statevector - ) + self._quantum_instance = ( + backend + if isinstance(backend, QuantumInstance) + else QuantumInstance(backend=backend) + ) + self._statevector = ( + statevector if statevector is not None else self.quantum_instance.is_statevector + ) self._param_qobj = param_qobj self._attach_results = attach_results @@ -114,17 +116,19 @@ def _check_quantum_instance_and_modes_consistent(self) -> None: Raises: ValueError: statevector or param_qobj are True when not supported by backend. """ - if self._statevector and not is_statevector_backend(self.quantum_instance.backend): - raise ValueError( - "Statevector mode for circuit sampling requires statevector " - "backend, not {}.".format(self.quantum_instance.backend) - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + if self._statevector and not is_statevector_backend(self.quantum_instance.backend): + raise ValueError( + "Statevector mode for circuit sampling requires statevector " + "backend, not {}.".format(self.quantum_instance.backend) + ) - if self._param_qobj and not is_aer_provider(self.quantum_instance.backend): - raise ValueError( - "Parameterized Qobj mode requires Aer " - "backend, not {}.".format(self.quantum_instance.backend) - ) + if self._param_qobj and not is_aer_provider(self.quantum_instance.backend): + raise ValueError( + "Parameterized Qobj mode requires Aer " + "backend, not {}.".format(self.quantum_instance.backend) + ) @property def quantum_instance(self) -> QuantumInstance: diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index c6084eb8730c..f4eed24b44e8 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -31,7 +31,7 @@ class ConverterBase(ABC): matrices).""" @deprecate_function( - "The ConverterBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The ConverterBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index 4e06d704a752..7eb042b2d549 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """DictToCircuitSum Class """ -import warnings from qiskit.opflow.converters.converter_base import ConverterBase from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase @@ -31,7 +30,7 @@ class DictToCircuitSum(ConverterBase): """ @deprecate_function( - "The DictToCircuitSum opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The DictToCircuitSum opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -44,9 +43,7 @@ def __init__( convert_dicts: Whether to convert VectorStateFn. convert_vectors: Whether to convert DictStateFns. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._traverse = traverse self._convert_dicts = convert_dicts self._convert_vectors = convert_vectors diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index e832cec3d4a1..fe621bbdfa42 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ PauliBasisChange Class """ -import warnings from functools import partial, reduce from typing import Callable, List, Optional, Tuple, Union, cast @@ -58,7 +57,7 @@ class PauliBasisChange(ConverterBase): """ @deprecate_function( - "The PauliBasisChange opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The PauliBasisChange opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -89,9 +88,7 @@ def __init__( beginning and ending operators are equivalent. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if destination_basis is not None: self.destination = destination_basis # type: ignore else: diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index 2de080ed4855..939185639a8c 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,7 +13,6 @@ """ Z2 Symmetry Tapering Converter Class """ import logging -import warnings from typing import List, Tuple, Union, cast from qiskit.opflow.converters.converter_base import ConverterBase @@ -38,7 +37,7 @@ class TwoQubitReduction(ConverterBase): """ @deprecate_function( - "The TwoQubitReduction opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The TwoQubitReduction opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): @@ -47,9 +46,7 @@ def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): num_particles: number of particles, if it is a list, the first number is alpha and the second number if beta. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if isinstance(num_particles, (tuple, list)): num_alpha = num_particles[0] num_beta = num_particles[1] diff --git a/qiskit/opflow/evolutions/__init__.py b/qiskit/opflow/evolutions/__init__.py index b1c136f6cf4c..f136c7fe6b6e 100644 --- a/qiskit/opflow/evolutions/__init__.py +++ b/qiskit/opflow/evolutions/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -16,18 +16,20 @@ .. currentmodule:: qiskit.opflow.evolutions -Deprecation: Evolutions are converters which traverse an Operator tree, replacing -any :class:`EvolvedOp` `e` with a Schrodinger equation-style evolution -:class:`~qiskit.opflow.primitive_ops.CircuitOp` -equalling or approximating the matrix exponential of -i * the Operator contained inside -(`e.primitive`). The Evolutions are essentially implementations of Hamiltonian Simulation -algorithms, including various methods for Trotterization. - -The :class:`EvolvedOp` is simply a placeholder signifying that the Operator inside it should be -converted to its exponential by the Evolution converter. All Operators -(not :mod:`~qiskit.opflow.state_fns`) have -``.exp_i()`` methods which either return the exponential of the Operator directly, -or an :class:`EvolvedOp` containing the Operator. +.. deprecated:: 0.24.0 + Evolutions are converters which traverse an Operator tree, replacing + any :class:`EvolvedOp` `e` with a Schrodinger equation-style evolution + :class:`~qiskit.opflow.primitive_ops.CircuitOp` + equalling or approximating the matrix exponential of -i * the Operator contained inside + (`e.primitive`). The Evolutions are essentially implementations of Hamiltonian Simulation + algorithms, including various methods for Trotterization. + + The :class:`EvolvedOp` is simply a placeholder signifying that the Operator inside it should be + converted to its exponential by the Evolution converter. All Operators + (not :mod:`~qiskit.opflow.state_fns`) have + ``.exp_i()`` methods which either return the exponential of the Operator directly, + or an :class:`EvolvedOp` containing the Operator. + Note: Evolutions work with parameterized Operator coefficients, so diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index fa7686f8e135..30aae7f5afe9 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ EvolutionBase Class """ -import warnings from abc import ABC, abstractmethod from qiskit.opflow.operator_base import OperatorBase @@ -32,13 +31,11 @@ class EvolutionBase(ConverterBase, ABC): """ @deprecate_function( - "The EvolutionBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The EvolutionBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() @abstractmethod def convert(self, operator: OperatorBase) -> OperatorBase: diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index f993a702b3f9..b98600796fd9 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -26,7 +26,7 @@ class EvolutionFactory: @staticmethod @deprecate_function( - "The EvolutionFactory.build opflow method is deprecated as of Qiskit Terra 0.23.0 " + "The EvolutionFactory.build opflow method is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def build(operator: OperatorBase = None) -> EvolutionBase: diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index e56c32447333..836eceb905dc 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ EvolutionOp Class """ -import warnings from typing import List, Optional, Set, Union, cast import numpy as np @@ -42,7 +41,7 @@ class EvolvedOp(PrimitiveOp): primitive: PrimitiveOp @deprecate_function( - "The EvolvedOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The EvolvedOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -53,9 +52,7 @@ def __init__( primitive: The operator being wrapped to signify evolution later. coeff: A coefficient multiplying the operator """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(primitive, coeff=coeff) + super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return self.primitive.primitive_strings() diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index 0657c60d0658..e1bf5a60edca 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ MatrixEvolution Class """ -import warnings import logging from qiskit.opflow.evolutions.evolution_base import EvolutionBase @@ -33,13 +32,11 @@ class MatrixEvolution(EvolutionBase): """ @deprecate_function( - "The MatrixEvolution opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The MatrixEvolution opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() def convert(self, operator: OperatorBase) -> OperatorBase: r""" diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 5ddfde839017..a4859ec2b0ab 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ PauliTrotterEvolution Class """ -import warnings import logging from typing import Optional, Union, cast @@ -53,7 +52,7 @@ class PauliTrotterEvolution(EvolutionBase): """ @deprecate_function( - "The PauliTrotterEvolution opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The PauliTrotterEvolution opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -75,9 +74,7 @@ def __init__( # sub-groups, so a single diagonalization circuit can be used for each group # rather than each Pauli. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if isinstance(trotter_mode, TrotterizationBase): self._trotter = trotter_mode else: diff --git a/qiskit/opflow/evolutions/trotterizations/__init__.py b/qiskit/opflow/evolutions/trotterizations/__init__.py index e2edec5810b2..17ddd830fa31 100644 --- a/qiskit/opflow/evolutions/trotterizations/__init__.py +++ b/qiskit/opflow/evolutions/trotterizations/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -11,8 +11,9 @@ # that they have been altered from the originals. """ -Deprecation: Trotterization methods - Algorithms for -approximating Exponentials of Operator Sums. +.. deprecated:: 0.24.0 + Trotterization methods - Algorithms for + approximating Exponentials of Operator Sums. """ diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 83e9a2082620..036d38f6ef12 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -38,7 +38,7 @@ class QDrift(TrotterizationBase): """ @deprecate_function( - "The QDrift opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The QDrift opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, reps: int = 1) -> None: diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index 24604700c4d4..68fce87d85aa 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -36,7 +36,7 @@ class Suzuki(TrotterizationBase): """ @deprecate_function( - "The Suzuki opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The Suzuki opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, reps: int = 1, order: int = 2) -> None: diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index 4602a44f7513..f139185a608d 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -23,7 +23,7 @@ class Trotter(Suzuki): """ @deprecate_function( - "The Trotter opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The Trotter opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, reps: int = 1) -> None: diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 83d444bb80e6..2bcd474109e8 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ Trotterization Algorithm Base """ -import warnings from abc import abstractmethod from qiskit.opflow.evolutions.evolution_base import EvolutionBase @@ -28,13 +27,11 @@ class TrotterizationBase(EvolutionBase): """ @deprecate_function( - "The TrotterizationBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The TrotterizationBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, reps: int = 1) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._reps = reps @property diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index c2c39d89ae97..c6e4f5e5da9d 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -24,7 +24,7 @@ class TrotterizationFactory: @staticmethod @deprecate_function( - "The TrotterizationFactory.build opflow method is deprecated as of Qiskit Terra 0.23.0 " + "The TrotterizationFactory.build opflow method is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def build(mode: str = "trotter", reps: int = 1) -> TrotterizationBase: diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index 544a5c66e666..aba2a3098433 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2017, 2022. +# (C) Copyright IBM 2017, 2023. # # 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 @@ -20,7 +20,7 @@ class OpflowError(QiskitError): """Deprecation: For Opflow specific errors.""" @deprecate_function( - "The OpflowError opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The OpflowError opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, *message): diff --git a/qiskit/opflow/expectations/__init__.py b/qiskit/opflow/expectations/__init__.py index 26c0c89a9a45..5eacf3c04a2f 100644 --- a/qiskit/opflow/expectations/__init__.py +++ b/qiskit/opflow/expectations/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -16,17 +16,19 @@ .. currentmodule:: qiskit.opflow.expectations -Deprecation: Expectations are converters which enable the computation of the expectation -value of an Observable with respect to some state function. They traverse an Operator tree, -replacing :class:`~qiskit.opflow.state_fns.OperatorStateFn` measurements with equivalent -measurements which are more amenable to computation on quantum or classical hardware. -For example, if one would like to measure the -expectation value of an Operator ``o`` expressed as a sum of Paulis with respect to some state -function, but only has access to diagonal measurements on Quantum hardware, we can create a -measurement ~StateFn(o), use a :class:`PauliExpectation` to convert it to a diagonal measurement -and circuit pre-rotations to append to the state, and sample this circuit on Quantum hardware with -a :class:`~qiskit.opflow.converters.CircuitSampler`. All in all, this would be: -``my_sampler.convert(my_expect.convert(~StateFn(o)) @ my_state).eval()``. +.. deprecated:: 0.24.0 + Expectations are converters which enable the computation of the expectation + value of an Observable with respect to some state function. They traverse an Operator tree, + replacing :class:`~qiskit.opflow.state_fns.OperatorStateFn` measurements with equivalent + measurements which are more amenable to computation on quantum or classical hardware. + For example, if one would like to measure the + expectation value of an Operator ``o`` expressed as a sum of Paulis with respect to some state + function, but only has access to diagonal measurements on Quantum hardware, we can create a + measurement ~StateFn(o), use a :class:`PauliExpectation` to convert it to a diagonal measurement + and circuit pre-rotations to append to the state, and sample this circuit on Quantum hardware with + a :class:`~qiskit.opflow.converters.CircuitSampler`. All in all, this would be: + ``my_sampler.convert(my_expect.convert(~StateFn(o)) @ my_state).eval()``. + Expectation Base Class ---------------------- diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index 9c6e5b0a3bd5..b004c95d8bc8 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ AerPauliExpectation Class """ -import warnings import logging from functools import reduce from operator import add @@ -41,13 +40,11 @@ class AerPauliExpectation(ExpectationBase): """ @deprecate_function( - "The AerPauliExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The AerPauliExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() def convert(self, operator: OperatorBase) -> OperatorBase: """Accept an Operator and return a new Operator with the Pauli measurements replaced by diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 27f144d0cfdd..18ea1a6bcec3 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The CVaR (Conditional Value at Risk) expectation class.""" -import warnings from typing import Optional, Union from qiskit.opflow.expectations.aer_pauli_expectation import AerPauliExpectation @@ -57,7 +56,7 @@ class CVaRExpectation(ExpectationBase): """ @deprecate_function( - "The CVaRExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The CVaRExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) -> None: @@ -70,9 +69,7 @@ def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) Raises: NotImplementedError: If the ``expectation`` is an AerPauliExpecation. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self.alpha = alpha if isinstance(expectation, AerPauliExpectation): raise NotImplementedError("AerPauliExpecation currently not supported.") diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index 716caab60e5a..e016f9ada6be 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ ExpectationBase Class """ -import warnings from abc import abstractmethod from typing import Union @@ -40,13 +39,11 @@ class ExpectationBase(ConverterBase): """ @deprecate_function( - "The ExpectationBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The ExpectationBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() @abstractmethod def convert(self, operator: OperatorBase) -> OperatorBase: diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 7d95895ccfc0..f1fa0c7514d1 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,6 +12,7 @@ """ ExpectationFactory Class """ +import warnings import logging from typing import Optional, Union @@ -22,8 +23,8 @@ from qiskit.opflow.expectations.pauli_expectation import PauliExpectation from qiskit.opflow.operator_base import OperatorBase from qiskit.providers import Backend -from qiskit.utils.backend_utils import has_aer, is_aer_qasm, is_statevector_backend -from qiskit.utils.quantum_instance import QuantumInstance +from qiskit.utils.backend_utils import is_aer_qasm, is_statevector_backend +from qiskit.utils import QuantumInstance, optionals from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) @@ -36,7 +37,7 @@ class ExpectationFactory: @staticmethod @deprecate_function( - "The ExpectationFactory.build opflow method is deprecated as of Qiskit Terra 0.23.0 " + "The ExpectationFactory.build opflow method is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def build( @@ -73,10 +74,10 @@ def build( if backend_to_check is None: # If user has Aer but didn't specify a backend, use the Aer fast expectation - if has_aer(): - from qiskit import Aer + if optionals.HAS_AER: + from qiskit_aer import AerSimulator - backend_to_check = Aer.get_backend("qasm_simulator") + backend_to_check = AerSimulator() # If user doesn't have Aer, use statevector_simulator # for < 16 qubits, and qasm with warning for more. else: @@ -98,25 +99,27 @@ def build( # If the user specified Aer qasm backend and is using a # Pauli operator, use the Aer fast expectation if we are including such # custom behaviors. - if is_aer_qasm(backend_to_check) and include_custom: - return AerPauliExpectation() - - # If the user specified a statevector backend (either Aer or BasicAer), - # use a converter to produce a - # Matrix operator and compute using matmul - elif is_statevector_backend(backend_to_check): - if operator.num_qubits >= 16: - logger.warning( - "Note: Using a statevector_simulator with %d qubits can be very expensive. " - "Consider using the Aer qasm_simulator instead to take advantage of Aer's " - "built-in fast Pauli Expectation", - operator.num_qubits, - ) - return MatrixExpectation() - - # All other backends, including IBMQ, BasicAer QASM, go here. - else: - return PauliExpectation() + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + if is_aer_qasm(backend_to_check) and include_custom: + return AerPauliExpectation() + + # If the user specified a statevector backend (either Aer or BasicAer), + # use a converter to produce a + # Matrix operator and compute using matmul + elif is_statevector_backend(backend_to_check): + if operator.num_qubits >= 16: + logger.warning( + "Note: Using a statevector_simulator with %d qubits can be very expensive. " + "Consider using the Aer qasm_simulator instead to take advantage of Aer's " + "built-in fast Pauli Expectation", + operator.num_qubits, + ) + return MatrixExpectation() + + # All other backends, including IBMQ, BasicAer QASM, go here. + else: + return PauliExpectation() elif primitives == {"Matrix"}: return MatrixExpectation() diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index 2c6b5d0fe782..de061eb2207e 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ MatrixExpectation Class """ -import warnings from typing import Union from qiskit.opflow.expectations.expectation_base import ExpectationBase @@ -27,13 +26,11 @@ class MatrixExpectation(ExpectationBase): be matrix-based so they can be evaluated by matrix multiplication.""" @deprecate_function( - "The MatrixExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The MatrixExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() def convert(self, operator: OperatorBase) -> OperatorBase: """Accept an Operator and return a new Operator with the Pauli measurements replaced by diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index 03e5ac016462..8cd9b3be1428 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ PauliExpectation Class """ -import warnings import logging from typing import Union @@ -44,7 +43,7 @@ class PauliExpectation(ExpectationBase): """ @deprecate_function( - "The PauliExpectation opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The PauliExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, group_paulis: bool = True) -> None: @@ -54,9 +53,7 @@ def __init__(self, group_paulis: bool = True) -> None: have the same diagonalizing circuit. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._grouper = AbelianGrouper() if group_paulis else None def convert(self, operator: OperatorBase) -> OperatorBase: diff --git a/qiskit/opflow/gradients/__init__.py b/qiskit/opflow/gradients/__init__.py index af8d40795a54..7c6f5babd3ca 100644 --- a/qiskit/opflow/gradients/__init__.py +++ b/qiskit/opflow/gradients/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -14,13 +14,16 @@ Gradients (:mod:`qiskit.opflow.gradients`) ========================================== -Deprecation: Given an operator that represents either a quantum state resp. an expectation value, -the gradient framework enables the evaluation of gradients, natural gradients, -Hessians, as well as the Quantum Fisher Information. +.. deprecated:: 0.24.0 + Given an operator that represents either a quantum state resp. an expectation value, + the gradient framework enables the evaluation of gradients, natural gradients, + Hessians, as well as the Quantum Fisher Information. + Suppose a parameterized quantum state `|ψ(θ)〉 = V(θ)|ψ〉` with input state `|ψ〉` and parameterized Ansatz `V(θ)`, and an Operator `O(ω)`. + **Gradients** We want to compute one of: diff --git a/qiskit/opflow/gradients/circuit_gradients/__init__.py b/qiskit/opflow/gradients/circuit_gradients/__init__.py index 3fe8a5ee582f..eae08898049a 100644 --- a/qiskit/opflow/gradients/circuit_gradients/__init__.py +++ b/qiskit/opflow/gradients/circuit_gradients/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020. # # 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 diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index e32946048e23..ecab623370a2 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """CircuitGradient Class """ -import warnings from abc import abstractmethod from typing import List, Union, Optional, Tuple, Set @@ -38,13 +37,11 @@ class CircuitGradient(ConverterBase): """ @deprecate_function( - "The CircuitGradient opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The CircuitGradient opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() # pylint: disable=arguments-differ @abstractmethod diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index ed0f1542d8d3..1786c347312c 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module to compute the state gradient with the linear combination method.""" -import warnings from collections.abc import Iterable from copy import deepcopy from functools import partial @@ -103,7 +102,7 @@ class LinComb(CircuitGradient): # pylint: disable=signature-differs, arguments-differ @deprecate_function( - "The LinComb opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The LinComb opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, aux_meas_op: OperatorBase = Z): @@ -116,9 +115,7 @@ def __init__(self, aux_meas_op: OperatorBase = Z): Raises: ValueError: If the provided auxiliary measurement operator is not supported. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if aux_meas_op not in [Z, -Y, (Z - 1j * Y)]: raise ValueError( "This auxiliary measurement operator is currently not supported. Please choose " diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index 69c986c68523..0ddcc3381a12 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module to compute the state gradient with the parameter shift rule.""" -import warnings from collections.abc import Iterable from copy import deepcopy from functools import partial @@ -49,7 +48,7 @@ class ParamShift(CircuitGradient): SUPPORTED_GATES = {"x", "y", "z", "h", "rx", "ry", "rz", "p", "u", "cx", "cy", "cz"} @deprecate_function( - "The ParamShift opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The ParamShift opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): @@ -63,9 +62,7 @@ def __init__(self, analytic: bool = True, epsilon: float = 1e-6): Raises: ValueError: If method != ``fin_diff`` and ``epsilon`` is not None. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._analytic = analytic self._epsilon = epsilon diff --git a/qiskit/opflow/gradients/circuit_qfis/__init__.py b/qiskit/opflow/gradients/circuit_qfis/__init__.py index 988b383700c1..d32126acd523 100644 --- a/qiskit/opflow/gradients/circuit_qfis/__init__.py +++ b/qiskit/opflow/gradients/circuit_qfis/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020. # # 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 diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 8339c6ed1bc7..898e1bb8fd20 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ CircuitQFI Class """ -import warnings from abc import abstractmethod from typing import List, Union @@ -38,13 +37,11 @@ class CircuitQFI(ConverterBase): """ @deprecate_function( - "The CircuitQFI opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The CircuitQFI opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() # pylint: disable=arguments-differ @abstractmethod diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 02c085fb6ebf..5a0c9874fca5 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module for Quantum the Fisher Information.""" -import warnings from typing import List, Union import numpy as np @@ -39,7 +38,7 @@ class LinCombFull(CircuitQFI): # pylint: disable=signature-differs, arguments-differ @deprecate_function( - "The LinCombFull opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The LinCombFull opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -58,9 +57,7 @@ def __init__( Raises: ValueError: If the provided auxiliary measurement operator is not supported. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if aux_meas_op not in [Z, -Y, (Z - 1j * Y)]: raise ValueError( "This auxiliary measurement operator is currently not supported. Please choose " diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index e2f8e0337ad7..827d14cf9007 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module for the Quantum Fisher Information.""" -import warnings from typing import List, Union import numpy as np @@ -41,13 +40,11 @@ class OverlapBlockDiag(CircuitQFI): """ @deprecate_function( - "The OverlapBlockDiag opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The OverlapBlockDiag opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() def convert( self, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index ccb6afa9e582..cc88dc6808cb 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module for Quantum the Fisher Information.""" -import warnings import copy from typing import List, Union @@ -40,13 +39,11 @@ class OverlapDiag(CircuitQFI): """ @deprecate_function( - "The OverlapDiag opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The OverlapDiag opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() def convert( self, diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 24f9319280ff..711083581b49 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -50,13 +50,11 @@ class DerivativeBase(ConverterBase): """ @deprecate_function( - "The DerivativeBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The DerivativeBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() # pylint: disable=arguments-differ @abstractmethod diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index 2c1438ece240..60c289613cec 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The base interface for Opflow's gradient.""" -import warnings from typing import Union, List, Optional import functools import numpy as np @@ -39,13 +38,11 @@ class Gradient(GradientBase): """Deprecation: Convert an operator expression to the first-order gradient.""" @deprecate_function( - "The Gradient opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The Gradient opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(grad_method=grad_method, **kwargs) + super().__init__(grad_method=grad_method, **kwargs) def convert( self, diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index a7714bbab28f..7fda662c4ed1 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The base interface for Aqua's gradient.""" -import warnings from typing import Union from qiskit.utils.deprecation import deprecate_function @@ -27,7 +26,7 @@ class GradientBase(DerivativeBase): """ @deprecate_function( - "The GradientBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The GradientBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): @@ -41,9 +40,7 @@ def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **k Raises: ValueError: If method != ``fin_diff`` and ``epsilon`` is not None. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if isinstance(grad_method, CircuitGradient): self._grad_method = grad_method elif grad_method == "param_shift": diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 26c2bf4831c8..c76fa491103f 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module to compute Hessians.""" -import warnings from typing import Union, List, Tuple, Optional import functools import numpy as np @@ -42,13 +41,11 @@ class Hessian(HessianBase): """Deprecation: Compute the Hessian of an expected value.""" @deprecate_function( - "The Hessian opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The Hessian opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(hess_method=hess_method, **kwargs) + super().__init__(hess_method=hess_method, **kwargs) def convert( self, diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index e8137f78c578..82c3d0cd50be 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module to compute Hessians.""" -import warnings from typing import Union from qiskit.utils.deprecation import deprecate_function @@ -24,7 +23,7 @@ class HessianBase(DerivativeBase): """Deprecation: Base class for the Hessian of an expected value.""" @deprecate_function( - "The HessianBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The HessianBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): @@ -38,9 +37,7 @@ def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **k Raises: ValueError: If method != ``fin_diff`` and ``epsilon`` is not None. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if isinstance(hess_method, CircuitGradient): self._hess_method = hess_method elif hess_method == "param_shift": diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index 76d5fa25f09a..fd0569014c63 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2022. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -12,7 +12,6 @@ """ Natural Gradient. """ -import warnings from collections.abc import Iterable from typing import List, Tuple, Callable, Optional, Union import functools @@ -54,7 +53,7 @@ class NaturalGradient(GradientBase): """ @deprecate_function( - "The NaturalGradient opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The NaturalGradient opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -78,9 +77,7 @@ def __init__( a least square solver is used without regularization kwargs (dict): Optional parameters for a CircuitGradient """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(grad_method) + super().__init__(grad_method) self._qfi_method = QFI(qfi_method) self._regularization = regularization diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index a1b024a27523..7ad0dd4190ba 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module for Quantum the Fisher Information.""" -import warnings from typing import List, Union, Optional import functools @@ -39,13 +38,11 @@ class QFI(QFIBase): """ @deprecate_function( - "The QFI opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The QFI opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(qfi_method=qfi_method) + super().__init__(qfi_method=qfi_method) def convert( self, diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index 32f33087689b..63e39df96917 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """The module for Quantum the Fisher Information.""" -import warnings from typing import Union from qiskit.utils.deprecation import deprecate_function @@ -32,7 +31,7 @@ class QFIBase(DerivativeBase): """ @deprecate_function( - "The QFIBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The QFIBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): @@ -45,9 +44,7 @@ def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): ValueError: if ``qfi_method`` is neither a ``CircuitQFI`` object nor one of the predefined strings. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() if isinstance(qfi_method, CircuitQFI): self._qfi_method = qfi_method diff --git a/qiskit/opflow/list_ops/__init__.py b/qiskit/opflow/list_ops/__init__.py index bd93bffdc9f4..196d73bdc308 100644 --- a/qiskit/opflow/list_ops/__init__.py +++ b/qiskit/opflow/list_ops/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -16,21 +16,22 @@ .. currentmodule:: qiskit.opflow.list_ops -Deprecation: List Operators are classes for storing and manipulating lists of Operators, -State functions, -or Measurements, and include some rule or ``combo_fn`` defining how the Operator functions of the -list constituents should be combined to form to cumulative Operator function of the -:class:`ListOp`. For example, a :class:`SummedOp` has an addition-based ``combo_fn``, so once -the Operators in its list are evaluated against some bitstring to produce a list of results, -we know to add up those results to produce the final result of the :class:`SummedOp`'s evaluation. -In theory, this ``combo_fn`` can be any function over classical complex values, but for convenience -we've chosen for them to be defined over NumPy arrays and values. This way, large numbers of -evaluations, such as after calling :meth:`~ListOp.to_matrix` on the list constituents, -can be efficiently combined. While the combination function is defined over classical values, -it should be understood as the operation by which each Operators' underlying function is -combined to form the underlying Operator function of the :class:`ListOp`. In this way, the -:mod:`.list_ops` are the basis for constructing large and sophisticated Operators, -State Functions, and Measurements. +.. deprecated:: 0.24.0 + List Operators are classes for storing and manipulating lists of Operators, State functions, + or Measurements, and include some rule or ``combo_fn`` defining how the Operator functions of the + list constituents should be combined to form to cumulative Operator function of the + :class:`ListOp`. For example, a :class:`SummedOp` has an addition-based ``combo_fn``, so once + the Operators in its list are evaluated against some bitstring to produce a list of results, + we know to add up those results to produce the final result of the :class:`SummedOp`'s evaluation. + In theory, this ``combo_fn`` can be any function over classical complex values, but for convenience + we've chosen for them to be defined over NumPy arrays and values. This way, large numbers of + evaluations, such as after calling :meth:`~ListOp.to_matrix` on the list constituents, + can be efficiently combined. While the combination function is defined over classical values, + it should be understood as the operation by which each Operators' underlying function is + combined to form the underlying Operator function of the :class:`ListOp`. In this way, the + :mod:`.list_ops` are the basis for constructing large and sophisticated Operators, + State Functions, and Measurements. + The base :class:`ListOp` class is particularly interesting, as its ``combo_fn`` is "the identity list Operation". Meaning, if we understand the ``combo_fn`` as a function from a list of complex diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index 76a5e0e5da8c..3e01f8fb3366 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -35,7 +35,7 @@ class ComposedOp(ListOp): conversion to QuantumCircuits or matrices, they can be reduced by composition.""" @deprecate_function( - "The ComposedOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The ComposedOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index fd9f9b456156..4bdd0c75b38c 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ ListOp Operator Class """ -import warnings from functools import reduce from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Sequence, Union, cast @@ -55,7 +54,7 @@ class ListOp(OperatorBase): """ @deprecate_function( - "The ListOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The ListOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -78,9 +77,7 @@ def __init__( Note that the default "recombination function" lambda above is essentially the identity - it accepts the list of values, and returns them in a list. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._oplist = self._check_input_types(oplist) self._combo_fn = combo_fn self._coeff = coeff diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index 378948ba6015..c558497068f4 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -32,7 +32,7 @@ class SummedOp(ListOp): evaluation or conversion to matrices, they can be reduced by addition.""" @deprecate_function( - "The SummedOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The SummedOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index 5a3840bc46c3..7adfac90d938 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -33,7 +33,7 @@ class TensoredOp(ListOp): conversion to QuantumCircuits, they can be reduced by tensor product.""" @deprecate_function( - "The TensoredOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The TensoredOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index b8d710fb32ee..433186d6204b 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021, 2022. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -41,7 +41,7 @@ class StarAlgebraMixin(MultiplyMixin, ABC): """ @deprecate_function( - "The StarAlgebraMixin opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The StarAlgebraMixin opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index 6bc8ec9fffab..fff1202bfa9a 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021, 2022. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -29,7 +29,7 @@ class TensorMixin(ABC): """ @deprecate_function( - "The TensorMixin opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The TensorMixin opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index ff929d90eb22..a931765dd0a6 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,7 +13,6 @@ """ OperatorBase Class """ import itertools -import warnings from abc import ABC, abstractmethod from copy import deepcopy from typing import Dict, List, Optional, Set, Tuple, Union, cast @@ -47,13 +46,11 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): _count = itertools.count() @deprecate_function( - "The OperatorBase opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The OperatorBase opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self) -> None: - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._instance_id = next(self._count) @property diff --git a/qiskit/opflow/operator_globals.py b/qiskit/opflow/operator_globals.py index 31503b671b6c..23ab364e1794 100644 --- a/qiskit/opflow/operator_globals.py +++ b/qiskit/opflow/operator_globals.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -34,7 +34,7 @@ @deprecate_function( - "The make_immutable opflow function is deprecated as of Qiskit Terra 0.23.0 " + "The make_immutable opflow function is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def make_immutable(obj): diff --git a/qiskit/opflow/primitive_ops/__init__.py b/qiskit/opflow/primitive_ops/__init__.py index d5c43ae69313..f4a7ef1ee223 100644 --- a/qiskit/opflow/primitive_ops/__init__.py +++ b/qiskit/opflow/primitive_ops/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -16,7 +16,9 @@ .. currentmodule:: qiskit.opflow.primitive_ops -Deprecation: Operators are defined to be functions which take State functions to State functions. +.. deprecated:: 0.24.0 + Operators are defined to be functions which take State functions to State functions. + PrimitiveOps are the classes for representing basic Operators, backed by computational Operator primitives from Terra. These classes (and inheritors) primarily serve to allow the diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 3d18783d06ee..9d224821aec7 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,7 +13,6 @@ """CircuitOp Class """ from typing import Dict, List, Optional, Set, Union, cast -import warnings import numpy as np import qiskit @@ -33,7 +32,7 @@ class CircuitOp(PrimitiveOp): primitive: QuantumCircuit @deprecate_function( - "The CircuitOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The CircuitOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -64,9 +63,7 @@ def __init__( if len(primitive.clbits) != 0: raise TypeError("CircuitOp does not support QuantumCircuits with ClassicalRegisters.") - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(primitive, coeff) + super().__init__(primitive, coeff) self._coeff = coeff def primitive_strings(self) -> Set[str]: diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index d23e4a99f49e..bc18780af58f 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,7 +13,6 @@ """MatrixOp Class """ from typing import Dict, List, Optional, Set, Union, cast, get_type_hints -import warnings import numpy as np from scipy.sparse import spmatrix @@ -38,7 +37,7 @@ class MatrixOp(PrimitiveOp): primitive: Operator @deprecate_function( - "The MatrixOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The MatrixOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -73,9 +72,7 @@ def __init__( if primitive.input_dims() != primitive.output_dims(): raise ValueError("Cannot handle non-square matrices yet.") - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(primitive, coeff=coeff) + super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Matrix"} diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 56724993190e..05b57fcee97f 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -14,7 +14,6 @@ from math import pi from typing import Dict, List, Optional, Set, Union, cast -import warnings import numpy as np from scipy.sparse import spmatrix @@ -37,7 +36,7 @@ class PauliOp(PrimitiveOp): primitive: Pauli @deprecate_function( - "The PauliOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The PauliOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: @@ -51,9 +50,8 @@ def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] """ if not isinstance(primitive, Pauli): raise TypeError(f"PauliOp can only be instantiated with Paulis, not {type(primitive)}") - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(primitive, coeff=coeff) + + super().__init__(primitive, coeff=coeff) def primitive_strings(self) -> Set[str]: return {"Pauli"} diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index d1b392b42744..d79f0a53f0a9 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -14,7 +14,6 @@ from collections import defaultdict from typing import Dict, List, Optional, Set, Tuple, Union, cast -import warnings import numpy as np from scipy.sparse import spmatrix @@ -36,7 +35,7 @@ class PauliSumOp(PrimitiveOp): primitive: SparsePauliOp @deprecate_function( - "The PauliSumOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The PauliSumOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -58,9 +57,8 @@ def __init__( raise TypeError( f"PauliSumOp can only be instantiated with SparsePauliOp, not {type(primitive)}" ) - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(primitive, coeff=coeff) + + super().__init__(primitive, coeff=coeff) self._grouping_type = grouping_type def primitive_strings(self) -> Set[str]: diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index 424d98567699..5d14a7808b67 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ PrimitiveOp Class """ -import warnings from typing import Dict, List, Optional, Set, Union, cast import numpy as np @@ -95,7 +94,7 @@ def __new__( ) @deprecate_function( - "The PrimitiveOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The PrimitiveOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -108,9 +107,7 @@ def __init__( primitive: The operator primitive being wrapped. coeff: A coefficient multiplying the primitive. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._primitive = primitive self._coeff = coeff diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index d840b33e0583..b46fa61b5a82 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021, 2022. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -14,7 +14,6 @@ import itertools import logging -import warnings from copy import deepcopy from typing import Dict, List, Optional, Union, cast @@ -37,7 +36,7 @@ class TaperedPauliSumOp(PauliSumOp): """Deprecation: Class for PauliSumOp after tapering""" @deprecate_function( - "The TaperedPauliSumOp opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The TaperedPauliSumOp opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -55,9 +54,7 @@ def __init__( Raises: TypeError: invalid parameters. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__(primitive, coeff) + super().__init__(primitive, coeff) if not isinstance(z2_symmetries, Z2Symmetries): raise TypeError( f"Argument parameter z2_symmetries must be Z2Symmetries, not {type(z2_symmetries)}" diff --git a/qiskit/opflow/state_fns/__init__.py b/qiskit/opflow/state_fns/__init__.py index 6c99e0c808cd..dc019c5485f4 100644 --- a/qiskit/opflow/state_fns/__init__.py +++ b/qiskit/opflow/state_fns/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -14,10 +14,12 @@ State Functions (:mod:`qiskit.opflow.state_fns`) ================================================ -Deprecation: State functions are defined to be complex functions over a single binary -string (as compared to an operator, which is defined as a function over two binary strings, -or a function taking a binary function to another binary function). This function may be -called by the eval() method. +.. deprecated:: 0.24.0 + State functions are defined to be complex functions over a single binary + string (as compared to an operator, which is defined as a function over two binary strings, + or a function taking a binary function to another binary function). This function may be + called by the eval() method. + Measurements are defined to be functionals over StateFns, taking them to real values. Generally, this real value is interpreted to represent the probability of some classical diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index b8e0e74df9e6..277b210a40e5 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -45,7 +45,7 @@ class CircuitStateFn(StateFn): # TODO allow normalization somehow? @deprecate_function( - "The CircuitStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The CircuitStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index da1637641780..19396a7abd8d 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -42,7 +42,7 @@ class CVaRMeasurement(OperatorStateFn): # TODO allow normalization somehow? @deprecate_function( - "The CVaRMeasurement opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The CVaRMeasurement opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index 6025990433af..aca74e48ca62 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -39,7 +39,7 @@ class DictStateFn(StateFn): # TODO allow normalization somehow? @deprecate_function( - "The DictStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The DictStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index f4c07d57d0a1..3ecec4421be5 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -38,7 +38,7 @@ class OperatorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_function( - "The OperatorStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The OperatorStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index 369ee9a91775..983a8533a1fa 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -39,7 +39,7 @@ class SparseVectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_function( - "The SparseVectorStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The SparseVectorStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 77eff6a150a8..9fc9008e62bf 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -12,7 +12,6 @@ """ StateFn Class """ -import warnings from typing import Callable, Dict, List, Optional, Set, Tuple, Union import numpy as np @@ -115,7 +114,7 @@ def __new__( # TODO allow normalization somehow? @deprecate_function( - "The StateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The StateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( @@ -140,9 +139,7 @@ def __init__( coeff: A coefficient by which the state function is multiplied. is_measurement: Whether the StateFn is a measurement operator """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - super().__init__() + super().__init__() self._primitive = primitive self._is_measurement = is_measurement self._coeff = coeff diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index 69b84f5e740f..00534ce85e67 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -38,7 +38,7 @@ class VectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_function( - "The VectorStateFn opflow class is deprecated as of Qiskit Terra 0.23.0 " + "The VectorStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index fc1fbf472cef..c4b252af3409 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -17,7 +17,7 @@ @deprecate_function( - "The commutator opflow function is deprecated as of Qiskit Terra 0.23.0 " + "The commutator opflow function is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @@ -38,7 +38,7 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_function( - "The anti_commutator opflow function is deprecated as of Qiskit Terra 0.23.0 " + "The anti_commutator opflow function is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @@ -59,7 +59,7 @@ def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_function( - "The double_commutator opflow function is deprecated as of Qiskit Terra 0.23.0 " + "The double_commutator opflow function is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def double_commutator( diff --git a/qiskit/test/base.py b/qiskit/test/base.py index 60efcaac9604..3b6853f4a06b 100644 --- a/qiskit/test/base.py +++ b/qiskit/test/base.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2017, 2022. +# (C) Copyright IBM 2017, 2018. # # 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 @@ -227,16 +227,6 @@ def setUpClass(cls): for msg in allow_DeprecationWarning_message: warnings.filterwarnings("default", category=DeprecationWarning, message=msg) - # ignore opflow, QuantumInstance and deprecated function msgs - warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*opflow.*") - warnings.filterwarnings( - "ignore", category=DeprecationWarning, message=r".*QuantumInstance.*" - ) - warnings.filterwarnings( - "ignore", category=DeprecationWarning, message=r".*find_regs_by_name.*" - ) - warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*run_circuits.*") - class FullQiskitTestCase(QiskitTestCase): """Terra-specific further additions for test cases, if ``testtools`` is available. diff --git a/qiskit/utils/backend_utils.py b/qiskit/utils/backend_utils.py index 0dd2733cb2e9..2bc77534cc82 100644 --- a/qiskit/utils/backend_utils.py +++ b/qiskit/utils/backend_utils.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -13,6 +13,7 @@ """ backend utility functions """ import logging +from qiskit.utils.deprecation import deprecate_function logger = logging.getLogger(__name__) @@ -49,6 +50,10 @@ def _get_backend_provider(backend): return provider +@deprecate_function( + "The has_ibmq function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def has_ibmq(): """Check if IBMQ is installed""" if not _PROVIDER_CHECK.checked_ibmq: @@ -66,6 +71,10 @@ def has_ibmq(): return _PROVIDER_CHECK.has_ibmq +@deprecate_function( + "The has_aer function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def has_aer(): """check if Aer is installed""" if not _PROVIDER_CHECK.checked_aer: @@ -82,6 +91,10 @@ def has_aer(): return _PROVIDER_CHECK.has_aer +@deprecate_function( + "The is_aer_provider function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_aer_provider(backend): """Detect whether or not backend is from Aer provider. @@ -102,6 +115,10 @@ def is_aer_provider(backend): return False +@deprecate_function( + "The is_basicaer_provider function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_basicaer_provider(backend): """Detect whether or not backend is from BasicAer provider. @@ -115,6 +132,10 @@ def is_basicaer_provider(backend): return isinstance(_get_backend_provider(backend), BasicAerProvider) +@deprecate_function( + "The is_ibmq_provider function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_ibmq_provider(backend): """Detect whether or not backend is from IBMQ provider. @@ -131,6 +152,10 @@ def is_ibmq_provider(backend): return False +@deprecate_function( + "The is_aer_statevector_backend function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_aer_statevector_backend(backend): """ Return True if backend object is statevector and from Aer provider. @@ -143,6 +168,10 @@ def is_aer_statevector_backend(backend): return is_statevector_backend(backend) and is_aer_provider(backend) +@deprecate_function( + "The is_statevector_backend function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_statevector_backend(backend): """ Return True if backend object is statevector. @@ -168,6 +197,10 @@ def is_statevector_backend(backend): return backend.name.startswith("statevector") +@deprecate_function( + "The is_simulator_backend function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_simulator_backend(backend): """ Return True if backend is a simulator. @@ -183,6 +216,10 @@ def is_simulator_backend(backend): return False +@deprecate_function( + "The is_local_backend function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_local_backend(backend): """ Return True if backend is a local backend. @@ -198,6 +235,10 @@ def is_local_backend(backend): return False +@deprecate_function( + "The is_aer_qasm function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def is_aer_qasm(backend): """ Return True if backend is Aer Qasm simulator @@ -214,6 +255,10 @@ def is_aer_qasm(backend): return ret +@deprecate_function( + "The support_backend_options function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def support_backend_options(backend): """ Return True if backend supports backend_options diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index 9fca4f783921..09f69c5cdabc 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2021. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -27,15 +27,20 @@ CompleteMeasFitter, TensoredMeasFitter, ) +from qiskit.utils.deprecation import deprecate_function # pylint: disable=invalid-name +@deprecate_function( + "The get_measured_qubits function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def get_measured_qubits( transpiled_circuits: List[QuantumCircuit], ) -> Tuple[List[int], Dict[str, List[int]]]: """ - Retrieve the measured qubits from transpiled circuits. + Deprecation: Retrieve the measured qubits from transpiled circuits. Args: transpiled_circuits: a list of transpiled circuits @@ -75,9 +80,13 @@ def get_measured_qubits( return sorted(qubit_index), qubit_mappings +@deprecate_function( + "The get_measured_qubits_from_qobj function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, List[int]]]: """ - Retrieve the measured qubits from transpiled circuits. + Deprecation: Retrieve the measured qubits from transpiled circuits. Args: qobj: qobj @@ -116,6 +125,10 @@ def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, return sorted(qubit_index), qubit_mappings +@deprecate_function( + "The build_measurement_error_mitigation_circuits function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def build_measurement_error_mitigation_circuits( qubit_list: List[int], fitter_cls: Callable, @@ -124,7 +137,7 @@ def build_measurement_error_mitigation_circuits( compile_config: Optional[Dict] = None, mit_pattern: Optional[List[List[int]]] = None, ) -> Tuple[QuantumCircuit, List[str], List[str]]: - """Build measurement error mitigation circuits + """Deprecation: Build measurement error mitigation circuits Args: qubit_list: list of ordered qubits used in the algorithm fitter_cls: CompleteMeasFitter or TensoredMeasFitter @@ -191,6 +204,10 @@ def build_measurement_error_mitigation_circuits( return t_meas_calibs_circuits, state_labels, circlabel +@deprecate_function( + "The build_measurement_error_mitigation_qobj function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def build_measurement_error_mitigation_qobj( qubit_list: List[int], fitter_cls: Callable, diff --git a/qiskit/utils/mitigation/__init__.py b/qiskit/utils/mitigation/__init__.py index 2d2de3040746..f4e96f76a2d4 100644 --- a/qiskit/utils/mitigation/__init__.py +++ b/qiskit/utils/mitigation/__init__.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -21,6 +21,10 @@ .. currentmodule:: qiskit.utils.mitigation +.. deprecated:: 0.24.0 + This module is deprecated and will be removed no sooner than 3 months + after the release date. + .. warning:: The user-facing API stability of this module is not guaranteed except for diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 5fff37e230c9..69cc1e7d87c0 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -31,17 +31,22 @@ from qiskit import QiskitError from qiskit.tools import parallel_map from qiskit.utils.mitigation.circuits import count_keys +from qiskit.utils.deprecation import deprecate_function class MeasurementFilter: """ - Measurement error mitigation filter. + Deprecation: Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. """ + @deprecate_function( + "The MeasurementFilter class is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, cal_matrix: np.matrix, state_labels: list): """ Initialize a measurement error mitigation filter using the cal_matrix @@ -214,12 +219,16 @@ def _apply_correction(self, resultidx, raw_data, method): class TensoredFilter: """ - Tensored measurement error mitigation filter. + Deprecation: Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. """ + @deprecate_function( + "The TensoredFilter class is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): """ Initialize a tensored measurement error mitigation filter using diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index af62d1c36fa5..1139aa47834e 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -19,10 +19,15 @@ use the fitters to produce a filter. """ from typing import List, Tuple, Union +from qiskit.utils.deprecation import deprecate_function +@deprecate_function( + "The count_keys function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def count_keys(num_qubits: int) -> List[str]: - """Return ordered count keys. + """Deprecation: Return ordered count keys. Args: num_qubits: The number of qubits in the generated list. @@ -35,6 +40,10 @@ def count_keys(num_qubits: int) -> List[str]: return [bin(j)[2:].zfill(num_qubits) for j in range(2**num_qubits)] +@deprecate_function( + "The complete_meas_cal function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def complete_meas_cal( qubit_list: List[int] = None, qr: Union[int, List["QuantumRegister"]] = None, @@ -42,7 +51,7 @@ def complete_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[str]]: """ - Return a list of measurement calibration circuits for the full + Deprecation: Return a list of measurement calibration circuits for the full Hilbert space. If the circuit contains :math:`n` qubits, then :math:`2^n` calibration circuits @@ -112,6 +121,10 @@ def complete_meas_cal( return cal_circuits, state_labels +@deprecate_function( + "The tensored_meas_cal function is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " +) def tensored_meas_cal( mit_pattern: List[List[int]] = None, qr: Union[int, List["QuantumRegister"]] = None, @@ -119,7 +132,7 @@ def tensored_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[List[int]]]: """ - Return a list of calibration circuits + Deprecation: Return a list of calibration circuits Args: mit_pattern: Qubits on which to perform the diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index cc9e604126f4..e527d240f337 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -27,13 +27,18 @@ from qiskit import QiskitError from qiskit.utils.mitigation.circuits import count_keys from qiskit.utils.mitigation._filters import MeasurementFilter, TensoredFilter +from qiskit.utils.deprecation import deprecate_function class CompleteMeasFitter: """ - Measurement correction fitter for a full calibration + Deprecation: Measurement correction fitter for a full calibration """ + @deprecate_function( + "The CompleteMeasFitter class is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, results, @@ -211,9 +216,13 @@ def readout_fidelity(self, label_list=None): class TensoredMeasFitter: """ - Measurement correction fitter for a tensored calibration. + Deprecation: Measurement correction fitter for a tensored calibration. """ + @deprecate_function( + "The TensoredMeasFitter class is deprecated as of Qiskit Terra 0.24.0 " + "and will be removed no sooner than 3 months after the release date. " + ) def __init__( self, results, diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index ffda8d6469fa..fb0c2c3f1332 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2022. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -145,7 +145,7 @@ class QuantumInstance: ] + _BACKEND_OPTIONS_QASM_ONLY @deprecate_function( - "The QuantumInstance class is deprecated as of Qiskit Terra 0.23.0 " + "The QuantumInstance class is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def __init__( diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index f86433c481b3..4ed23ac6389d 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2022. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -41,7 +41,7 @@ @deprecate_function( - "The find_regs_by_name function is deprecated as of Qiskit Terra 0.23.0 " + "The find_regs_by_name function is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def find_regs_by_name( @@ -107,7 +107,7 @@ def _safe_get_job_status(job: Job, job_id: str, max_job_retries: int, wait: floa @deprecate_function( - "The run_circuits function is deprecated as of Qiskit Terra 0.23.0 " + "The run_circuits function is deprecated as of Qiskit Terra 0.24.0 " "and will be removed no sooner than 3 months after the release date. " ) def run_circuits( diff --git a/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml b/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml index f9d9bce666be..c2152839d16e 100644 --- a/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml +++ b/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml @@ -1,7 +1,12 @@ --- deprecations: - | - The module :mod:`qiskit.opflow`, class :class:`qiskit.utils.QuantumInstance` and methods + The modules :mod:`qiskit.opflow`, :mod:`qiskit.utils.backend_utils`, + :mod:`qiskit.utils.mitigation`, + :mod:`qiskit.utils.measurement_error_mitigation`, + class :class:`qiskit.utils.QuantumInstance` and methods :meth:`~qiskit.utils.run_circuits.find_regs_by_name`, :meth:`~qiskit.utils.run_circuits.run_circuits` have been deprecated and will be removed in a future release. + Using :class:`~qiskit.utils.QuantumInstance` is superseded by + :class:`~qiskit.primitives.BaseSampler`. diff --git a/test/python/algorithms/eigensolvers/test_vqd.py b/test/python/algorithms/eigensolvers/test_vqd.py index 95efa27f5968..ed46e9b3a036 100644 --- a/test/python/algorithms/eigensolvers/test_vqd.py +++ b/test/python/algorithms/eigensolvers/test_vqd.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022 +# (C) Copyright IBM 2022, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test VQD """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np @@ -255,7 +256,12 @@ def test_aux_operators_list(self, op): aux_op1 = SparsePauliOp.from_list([("II", 2.0)]) aux_op2 = SparsePauliOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) aux_ops = [aux_op1, aux_op2] - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited[:2], decimal=2 ) @@ -269,7 +275,12 @@ def test_aux_operators_list(self, op): # Go again with additional None and zero operators extra_ops = [*aux_ops, None, 0] - result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited[:2], decimal=2 ) @@ -307,7 +318,12 @@ def test_aux_operators_dict(self, op): aux_op1 = SparsePauliOp.from_list([("II", 2.0)]) aux_op2 = SparsePauliOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) self.assertEqual(len(result.eigenvalues), 2) self.assertEqual(result.eigenvalues.dtype, np.complex128) self.assertAlmostEqual(result.eigenvalues[0], -1.85727503, 2) @@ -322,7 +338,12 @@ def test_aux_operators_dict(self, op): # Go again with additional None and zero operators extra_ops = {**aux_ops, "None_operator": None, "zero_operator": 0} - result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) self.assertEqual(len(result.eigenvalues), 2) self.assertEqual(result.eigenvalues.dtype, np.complex128) self.assertAlmostEqual(result.eigenvalues[0], -1.85727503, places=5) @@ -364,7 +385,12 @@ def test_aux_operator_std_dev(self, op): aux_op1 = SparsePauliOp.from_list([("II", 2.0)]) aux_op2 = SparsePauliOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) aux_ops = [aux_op1, aux_op2] - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0][0], 2.0, places=1) @@ -377,7 +403,12 @@ def test_aux_operator_std_dev(self, op): # Go again with additional None and zero operators aux_ops = [*aux_ops, None, 0] - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) self.assertEqual(len(result.aux_operators_evaluated[0]), 4) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0][0], 2.0, places=1) diff --git a/test/python/algorithms/evolvers/test_evolution_problem.py b/test/python/algorithms/evolvers/test_evolution_problem.py index d3dd2f7bc9b2..83e5da257e13 100644 --- a/test/python/algorithms/evolvers/test_evolution_problem.py +++ b/test/python/algorithms/evolvers/test_evolution_problem.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -12,6 +12,7 @@ """Test evolver problem class.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack from numpy.testing import assert_raises @@ -50,29 +51,47 @@ def test_init_default(self): def test_init_all(self): """Tests that all fields are initialized correctly.""" t_parameter = Parameter("t") - hamiltonian = t_parameter * Z + Y + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = t_parameter * Z + Y + self.assertTrue(len(caught_warnings) > 0) 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, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + 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 + self.assertTrue(len(caught_warnings) > 0) - 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) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) + self.assertTrue(len(caught_warnings) > 0) 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) @@ -91,21 +110,39 @@ def test_validate_params(self): param_x = Parameter("x") param_y = Parameter("y") with self.subTest(msg="Parameter missing in dict."): - hamiltonian = param_x * X + param_y * Y + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = param_x * X + param_y * Y + self.assertTrue(len(caught_warnings) > 0) 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 + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = param_x * X + param_y * Y + self.assertTrue(len(caught_warnings) > 0) 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 + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = param_x * X + param_y * Y + self.assertTrue(len(caught_warnings) > 0) 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): diff --git a/test/python/algorithms/evolvers/trotterization/test_trotter_qrte.py b/test/python/algorithms/evolvers/trotterization/test_trotter_qrte.py index fe53f929f5f6..f9786a12ceaa 100644 --- a/test/python/algorithms/evolvers/trotterization/test_trotter_qrte.py +++ b/test/python/algorithms/evolvers/trotterization/test_trotter_qrte.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021, 2022. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -13,7 +13,7 @@ """ Test TrotterQRTE. """ import unittest - +import warnings from test.python.opflow import QiskitOpflowTestCase from ddt import ddt, data, unpack import numpy as np @@ -52,18 +52,24 @@ def setUp(self): algorithm_globals.random_seed = self.seed backend_statevector = BasicAer.get_backend("statevector_simulator") backend_qasm = BasicAer.get_backend("qasm_simulator") - self.quantum_instance = QuantumInstance( - backend=backend_statevector, - shots=1, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) - self.quantum_instance_qasm = QuantumInstance( - backend=backend_qasm, - shots=8000, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.quantum_instance = QuantumInstance( + backend=backend_statevector, + shots=1, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.quantum_instance_qasm = QuantumInstance( + backend=backend_qasm, + shots=8000, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.assertTrue(len(caught_warnings) > 0) self.backends_dict = { "qi_sv": self.quantum_instance, "qi_qasm": self.quantum_instance_qasm, @@ -117,26 +123,31 @@ def test_trotter_qrte_trotter_single_qubit_aux_ops(self): (0.05799999999999995, 0.011161518713866855), (0.2495, 0.010826759383582883), ] - - for backend_name in self.backends_names_not_none: - with self.subTest(msg=f"Test {backend_name} backend."): - algorithm_globals.random_seed = 0 - backend = self.backends_dict[backend_name] - expectation = ExpectationFactory.build( - operator=operator, - backend=backend, - ) - trotter_qrte = TrotterQRTE(quantum_instance=backend, expectation=expectation) - evolution_result = trotter_qrte.evolve(evolution_problem) - - np.testing.assert_equal( - evolution_result.evolved_state.eval(), expected_evolved_state - ) - if backend_name == "qi_qasm": - expected_aux_ops_evaluated = expected_aux_ops_evaluated_qasm - np.testing.assert_array_almost_equal( - evolution_result.aux_ops_evaluated, expected_aux_ops_evaluated - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for backend_name in self.backends_names_not_none: + with self.subTest(msg=f"Test {backend_name} backend."): + algorithm_globals.random_seed = 0 + backend = self.backends_dict[backend_name] + expectation = ExpectationFactory.build( + operator=operator, + backend=backend, + ) + trotter_qrte = TrotterQRTE(quantum_instance=backend, expectation=expectation) + evolution_result = trotter_qrte.evolve(evolution_problem) + + np.testing.assert_equal( + evolution_result.evolved_state.eval(), expected_evolved_state + ) + if backend_name == "qi_qasm": + expected_aux_ops_evaluated = expected_aux_ops_evaluated_qasm + np.testing.assert_array_almost_equal( + evolution_result.aux_ops_evaluated, expected_aux_ops_evaluated + ) + self.assertTrue(len(caught_warnings) > 0) @data( ( diff --git a/test/python/algorithms/gradients/test_estimator_gradient.py b/test/python/algorithms/gradients/test_estimator_gradient.py index 00b9c8079fe3..ce9c345eb507 100644 --- a/test/python/algorithms/gradients/test_estimator_gradient.py +++ b/test/python/algorithms/gradients/test_estimator_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2021. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -14,7 +14,7 @@ """Test Estimator Gradients""" import unittest - +from test.python.algorithms.gradients.logging_primitives import LoggingEstimator import numpy as np from ddt import ddt, data, unpack @@ -35,8 +35,6 @@ from qiskit.quantum_info.random import random_pauli_list from qiskit.test import QiskitTestCase -from .logging_primitives import LoggingEstimator - gradient_factories = [ lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="central"), lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="forward"), diff --git a/test/python/algorithms/gradients/test_qgt.py b/test/python/algorithms/gradients/test_qgt.py index 044fabdbedfa..da2e7f25dda0 100644 --- a/test/python/algorithms/gradients/test_qgt.py +++ b/test/python/algorithms/gradients/test_qgt.py @@ -14,6 +14,7 @@ """Test QGT.""" import unittest +from test.python.algorithms.gradients.logging_primitives import LoggingEstimator from ddt import ddt, data import numpy as np @@ -25,8 +26,6 @@ from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase -from .logging_primitives import LoggingEstimator - @ddt class TestQGT(QiskitTestCase): diff --git a/test/python/algorithms/gradients/test_sampler_gradient.py b/test/python/algorithms/gradients/test_sampler_gradient.py index 7cff9c54561f..c7bb07d831ae 100644 --- a/test/python/algorithms/gradients/test_sampler_gradient.py +++ b/test/python/algorithms/gradients/test_sampler_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2021. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -15,10 +15,9 @@ import unittest from typing import List - +from test.python.algorithms.gradients.logging_primitives import LoggingSampler import numpy as np from ddt import ddt, data - from qiskit import QuantumCircuit from qiskit.algorithms.gradients import ( FiniteDiffSamplerGradient, @@ -33,8 +32,6 @@ from qiskit.result import QuasiDistribution from qiskit.test import QiskitTestCase -from .logging_primitives import LoggingSampler - gradient_factories = [ lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="central"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="forward"), diff --git a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py index 16589a12e8de..910a723d21a0 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test of the AdaptVQE minimum eigensolver """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack @@ -37,59 +38,71 @@ class TestAdaptVQE(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() algorithm_globals.random_seed = 42 - self.h2_op = PauliSumOp.from_list( - [ - ("IIII", -0.8105479805373266), - ("ZZII", -0.2257534922240251), - ("IIZI", +0.12091263261776641), - ("ZIZI", +0.12091263261776641), - ("IZZI", +0.17218393261915543), - ("IIIZ", +0.17218393261915546), - ("IZIZ", +0.1661454325638243), - ("ZZIZ", +0.1661454325638243), - ("IIZZ", -0.2257534922240251), - ("IZZZ", +0.16892753870087926), - ("ZZZZ", +0.17464343068300464), - ("IXIX", +0.04523279994605788), - ("ZXIX", +0.04523279994605788), - ("IXZX", -0.04523279994605788), - ("ZXZX", -0.04523279994605788), - ] - ) - excitation_pool = [ - PauliSumOp( - SparsePauliOp(["IIIY", "IIZY"], coeffs=[0.5 + 0.0j, -0.5 + 0.0j]), coeff=1.0 - ), - PauliSumOp( - SparsePauliOp(["ZYII", "IYZI"], coeffs=[-0.5 + 0.0j, 0.5 + 0.0j]), coeff=1.0 - ), - PauliSumOp( - SparsePauliOp( - ["ZXZY", "IXIY", "IYIX", "ZYZX", "IYZX", "ZYIX", "ZXIY", "IXZY"], - coeffs=[ - -0.125 + 0.0j, - 0.125 + 0.0j, - -0.125 + 0.0j, - 0.125 + 0.0j, - 0.125 + 0.0j, - -0.125 + 0.0j, - 0.125 + 0.0j, - -0.125 + 0.0j, - ], + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.h2_op = PauliSumOp.from_list( + [ + ("IIII", -0.8105479805373266), + ("ZZII", -0.2257534922240251), + ("IIZI", +0.12091263261776641), + ("ZIZI", +0.12091263261776641), + ("IZZI", +0.17218393261915543), + ("IIIZ", +0.17218393261915546), + ("IZIZ", +0.1661454325638243), + ("ZZIZ", +0.1661454325638243), + ("IIZZ", -0.2257534922240251), + ("IZZZ", +0.16892753870087926), + ("ZZZZ", +0.17464343068300464), + ("IXIX", +0.04523279994605788), + ("ZXIX", +0.04523279994605788), + ("IXZX", -0.04523279994605788), + ("ZXZX", -0.04523279994605788), + ] + ) + excitation_pool = [ + PauliSumOp( + SparsePauliOp(["IIIY", "IIZY"], coeffs=[0.5 + 0.0j, -0.5 + 0.0j]), coeff=1.0 + ), + PauliSumOp( + SparsePauliOp(["ZYII", "IYZI"], coeffs=[-0.5 + 0.0j, 0.5 + 0.0j]), coeff=1.0 ), - coeff=1.0, - ), - ] - self.initial_state = QuantumCircuit(QuantumRegister(4)) - self.initial_state.x(0) - self.initial_state.x(1) - self.ansatz = EvolvedOperatorAnsatz(excitation_pool, initial_state=self.initial_state) + PauliSumOp( + SparsePauliOp( + ["ZXZY", "IXIY", "IYIX", "ZYZX", "IYZX", "ZYIX", "ZXIY", "IXZY"], + coeffs=[ + -0.125 + 0.0j, + 0.125 + 0.0j, + -0.125 + 0.0j, + 0.125 + 0.0j, + 0.125 + 0.0j, + -0.125 + 0.0j, + 0.125 + 0.0j, + -0.125 + 0.0j, + ], + ), + coeff=1.0, + ), + ] + self.initial_state = QuantumCircuit(QuantumRegister(4)) + self.initial_state.x(0) + self.initial_state.x(1) + self.ansatz = EvolvedOperatorAnsatz(excitation_pool, initial_state=self.initial_state) + self.assertTrue(len(caught_warnings) > 0) self.optimizer = SLSQP() def test_default(self): """Default execution""" calc = AdaptVQE(VQE(Estimator(), self.ansatz, self.optimizer)) - res = calc.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = calc.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) expected_eigenvalue = -1.85727503 @@ -102,7 +115,13 @@ def test_converged(self): VQE(Estimator(), self.ansatz, self.optimizer), threshold=1e-3, ) - res = calc.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = calc.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res.termination_criterion, TerminationCriterion.CONVERGED) @@ -112,7 +131,13 @@ def test_maximum(self): VQE(Estimator(), self.ansatz, self.optimizer), max_iterations=1, ) - res = calc.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = calc.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res.termination_criterion, TerminationCriterion.MAXIMUM) @@ -152,23 +177,40 @@ def test_vqe_solver(self): """Test to check if the VQE solver remains the same or not""" solver = VQE(Estimator(), self.ansatz, self.optimizer) calc = AdaptVQE(solver) - _ = calc.compute_minimum_eigenvalue(operator=self.h2_op) - - self.assertEqual(solver.ansatz, calc.solver.ansatz) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + _ = calc.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertEqual(solver.ansatz, calc.solver.ansatz) + self.assertTrue(len(caught_warnings) > 0) def test_gradient_calculation(self): """Test to check if the gradient calculation""" solver = VQE(Estimator(), QuantumCircuit(1), self.optimizer) calc = AdaptVQE(solver) calc._excitation_pool = [SparsePauliOp("X")] - res = calc._compute_gradients(operator=SparsePauliOp("Y"), theta=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = calc._compute_gradients(operator=SparsePauliOp("Y"), theta=[]) + self.assertTrue(len(caught_warnings) > 0) # compare with manually computed reference value self.assertAlmostEqual(res[0][0], 2.0) def test_supports_aux_operators(self): """Test that auxiliary operators are supported""" calc = AdaptVQE(VQE(Estimator(), self.ansatz, self.optimizer)) - res = calc.compute_minimum_eigenvalue(operator=self.h2_op, aux_operators=[self.h2_op]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = calc.compute_minimum_eigenvalue(operator=self.h2_op, aux_operators=[self.h2_op]) + self.assertTrue(len(caught_warnings) > 0) expected_eigenvalue = -1.85727503 diff --git a/test/python/algorithms/minimum_eigensolvers/test_qaoa.py b/test/python/algorithms/minimum_eigensolvers/test_qaoa.py index b512664e23cb..5c276b7ec4d2 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_qaoa.py +++ b/test/python/algorithms/minimum_eigensolvers/test_qaoa.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -13,6 +13,7 @@ """Test the QAOA algorithm.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial @@ -81,8 +82,13 @@ def test_qaoa(self, w, reps, mixer, solutions): qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @@ -111,8 +117,13 @@ def test_qaoa_qc_mixer(self, w, prob, solutions): mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @@ -129,7 +140,13 @@ def test_qaoa_qc_mixer_many_parameters(self): mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) @@ -145,7 +162,13 @@ def test_qaoa_qc_mixer_no_parameters(self): mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) @@ -155,7 +178,13 @@ def test_change_operator_size(self): np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): @@ -173,8 +202,13 @@ def test_change_operator_size(self): ] ) ) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): @@ -199,8 +233,13 @@ def cb_callback(eval_count, parameters, mean, metadata): initial_point=init_pt, callback=cb_callback, ) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) @@ -221,7 +260,13 @@ def test_qaoa_random_initial_point(self): ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertLess(result.eigenvalue, -0.97) @@ -235,7 +280,13 @@ def test_optimizer_scipy_callable(self): self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) - result = qaoa.compute_minimum_eigenvalue(qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): @@ -262,7 +313,12 @@ def _get_operator(self, weight_matrix): pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] - return PauliSumOp.from_list(opflow_list), shift + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + return PauliSumOp.from_list(opflow_list), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. diff --git a/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py index e28908bffd85..4171a2c188ff 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -12,8 +12,8 @@ """Test the Sampler VQE.""" - import unittest +import warnings from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase @@ -206,7 +206,13 @@ def test_auxops(self, op): as_list = [Pauli("ZZ"), Pauli("II")] with self.subTest(auxops=as_list): - result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_list) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_list) + self.assertTrue(len(caught_warnings) > 0) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 2) self.assertAlmostEqual(result.aux_operators_evaluated[0][0], -1 + 0j, places=5) @@ -214,7 +220,13 @@ def test_auxops(self, op): as_dict = {"magnetization": SparsePauliOp(["ZI", "IZ"])} with self.subTest(auxops=as_dict): - result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_dict) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_dict) + self.assertTrue(len(caught_warnings) > 0) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated.keys()), 1) self.assertAlmostEqual(result.aux_operators_evaluated["magnetization"][0], 0j, places=5) diff --git a/test/python/algorithms/minimum_eigensolvers/test_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_vqe.py index 31a55d27d438..0fc5ddc4ab6e 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_vqe.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -13,6 +13,7 @@ """Test the variational quantum eigensolver algorithm.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial @@ -208,26 +209,32 @@ def test_gradient_run(self): def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" - qubit_op = PauliSumOp.from_list( - [ - ("IIII", -0.8105479805373266), - ("IIIZ", 0.17218393261915552), - ("IIZZ", -0.22575349222402472), - ("IZZI", 0.1721839326191556), - ("ZZII", -0.22575349222402466), - ("IIZI", 0.1209126326177663), - ("IZZZ", 0.16892753870087912), - ("IXZX", -0.045232799946057854), - ("ZXIX", 0.045232799946057854), - ("IXIX", 0.045232799946057854), - ("ZXZX", -0.045232799946057854), - ("ZZIZ", 0.16614543256382414), - ("IZIZ", 0.16614543256382414), - ("ZZZZ", 0.17464343068300453), - ("ZIZI", 0.1209126326177663), - ] - ) - tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qubit_op = PauliSumOp.from_list( + [ + ("IIII", -0.8105479805373266), + ("IIIZ", 0.17218393261915552), + ("IIZZ", -0.22575349222402472), + ("IZZI", 0.1721839326191556), + ("ZZII", -0.22575349222402466), + ("IIZI", 0.1209126326177663), + ("IZZZ", 0.16892753870087912), + ("IXZX", -0.045232799946057854), + ("ZXIX", 0.045232799946057854), + ("IXIX", 0.045232799946057854), + ("ZXZX", -0.045232799946057854), + ("ZZIZ", 0.16614543256382414), + ("IZIZ", 0.16614543256382414), + ("ZZZZ", 0.17464343068300453), + ("ZIZI", 0.1209126326177663), + ] + ) + tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) + self.assertTrue(len(caught_warnings) > 0) vqe = VQE( Estimator(), self.ry_wavefunction, @@ -406,10 +413,18 @@ def test_aux_operators_list(self): self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list( + [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] + ) + aux_ops = [aux_op1, aux_op2] + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values @@ -421,7 +436,13 @@ def test_aux_operators_list(self): with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values @@ -444,10 +465,18 @@ def test_aux_operators_dict(self): self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list( + [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] + ) + aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) @@ -460,7 +489,13 @@ def test_aux_operators_dict(self): with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values diff --git a/test/python/algorithms/optimizers/test_gradient_descent.py b/test/python/algorithms/optimizers/test_gradient_descent.py index abe15f4b5362..02ae33c12ecb 100644 --- a/test/python/algorithms/optimizers/test_gradient_descent.py +++ b/test/python/algorithms/optimizers/test_gradient_descent.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021, 2022. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -12,13 +12,13 @@ """Tests for the Gradient Descent optimizer.""" +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from qiskit.algorithms.optimizers import GradientDescent, GradientDescentState from qiskit.algorithms.optimizers.steppable_optimizer import TellData, AskData from qiskit.circuit.library import PauliTwoDesign from qiskit.opflow import I, Z, StateFn -from qiskit.test.decorators import slow_test class TestGradientDescent(QiskitAlgorithmsTestCase): @@ -37,13 +37,18 @@ def grad(self, x): """Gradient of the objective function""" return 2 * (np.linalg.norm(x) - 1) * x / np.linalg.norm(x) - @slow_test def test_pauli_two_design(self): """Test standard gradient descent on the Pauli two-design example.""" circuit = PauliTwoDesign(3, reps=3, seed=2) parameters = list(circuit.parameters) - obs = Z ^ Z ^ I - expr = ~StateFn(obs) @ StateFn(circuit) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + obs = Z ^ Z ^ I + expr = ~StateFn(obs) @ StateFn(circuit) + self.assertTrue(len(caught_warnings) > 0) initial_point = np.array( [ @@ -67,8 +72,13 @@ def objective_pauli(x): optimizer = GradientDescent(maxiter=100, learning_rate=0.1, perturbation=0.1) - result = optimizer.minimize(objective_pauli, x0=initial_point) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = optimizer.minimize(objective_pauli, x0=initial_point) + self.assertTrue(len(caught_warnings) > 0) self.assertLess(result.fun, -0.95) # final loss self.assertEqual(result.nfev, 1300) # function evaluations diff --git a/test/python/algorithms/optimizers/test_optimizer_aqgd.py b/test/python/algorithms/optimizers/test_optimizer_aqgd.py index 7beee3eb4782..48d0ff814d2f 100644 --- a/test/python/algorithms/optimizers/test_optimizer_aqgd.py +++ b/test/python/algorithms/optimizers/test_optimizer_aqgd.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2022 +# (C) Copyright IBM 2019, 2023 # # 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 @@ -13,6 +13,7 @@ """ Test of AQGD optimizer """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit.circuit.library import RealAmplitudes from qiskit.utils import QuantumInstance, algorithm_globals, optionals @@ -28,17 +29,22 @@ class TestOptimizerAQGD(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - self.seed = 50 - algorithm_globals.random_seed = self.seed - self.qubit_op = PauliSumOp.from_list( - [ - ("II", -1.052373245772859), - ("IZ", 0.39793742484318045), - ("ZI", -0.39793742484318045), - ("ZZ", -0.01128010425623538), - ("XX", 0.18093119978423156), - ] - ) + algorithm_globals.random_seed = 50 + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.qubit_op = PauliSumOp.from_list( + [ + ("II", -1.052373245772859), + ("IZ", 0.39793742484318045), + ("ZI", -0.39793742484318045), + ("ZZ", -0.01128010425623538), + ("XX", 0.18093119978423156), + ] + ) + self.assertTrue(len(caught_warnings) > 0) @slow_test @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") @@ -46,20 +52,25 @@ def test_simple(self): """test AQGD optimizer with the parameters as single values.""" from qiskit_aer import Aer - q_instance = QuantumInstance( - Aer.get_backend("aer_simulator_statevector"), - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - - aqgd = AQGD(momentum=0.0) - vqe = VQE( - ansatz=RealAmplitudes(), - optimizer=aqgd, - gradient=Gradient("lin_comb"), - quantum_instance=q_instance, - ) - result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + Aer.get_backend("aer_simulator_statevector"), + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + aqgd = AQGD(momentum=0.0) + vqe = VQE( + ansatz=RealAmplitudes(), + optimizer=aqgd, + gradient=Gradient("lin_comb"), + quantum_instance=q_instance, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") @@ -67,15 +78,21 @@ def test_list(self): """test AQGD optimizer with the parameters as lists.""" from qiskit_aer import Aer - q_instance = QuantumInstance( - Aer.get_backend("aer_simulator_statevector"), - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - - aqgd = AQGD(maxiter=[1000, 1000, 1000], eta=[1.0, 0.5, 0.3], momentum=[0.0, 0.5, 0.75]) - vqe = VQE(ansatz=RealAmplitudes(), optimizer=aqgd, quantum_instance=q_instance) - result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + Aer.get_backend("aer_simulator_statevector"), + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + + aqgd = AQGD(maxiter=[1000, 1000, 1000], eta=[1.0, 0.5, 0.3], momentum=[0.0, 0.5, 0.75]) + vqe = VQE(ansatz=RealAmplitudes(), optimizer=aqgd, quantum_instance=q_instance) + result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3) def test_raises_exception(self): @@ -88,20 +105,26 @@ def test_int_values(self): """test AQGD with int values passed as eta and momentum.""" from qiskit_aer import Aer - q_instance = QuantumInstance( - Aer.get_backend("aer_simulator_statevector"), - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - - aqgd = AQGD(maxiter=1000, eta=1, momentum=0) - vqe = VQE( - ansatz=RealAmplitudes(), - optimizer=aqgd, - gradient=Gradient("lin_comb"), - quantum_instance=q_instance, - ) - result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + Aer.get_backend("aer_simulator_statevector"), + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + + aqgd = AQGD(maxiter=1000, eta=1, momentum=0) + vqe = VQE( + ansatz=RealAmplitudes(), + optimizer=aqgd, + gradient=Gradient("lin_comb"), + quantum_instance=q_instance, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=3) diff --git a/test/python/algorithms/optimizers/test_optimizer_nft.py b/test/python/algorithms/optimizers/test_optimizer_nft.py index d920e025b820..67a446e58735 100644 --- a/test/python/algorithms/optimizers/test_optimizer_nft.py +++ b/test/python/algorithms/optimizers/test_optimizer_nft.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test of NFT optimizer """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import BasicAer from qiskit.circuit.library import RealAmplitudes @@ -27,31 +28,41 @@ class TestOptimizerNFT(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - self.seed = 50 - algorithm_globals.random_seed = self.seed - self.qubit_op = PauliSumOp.from_list( - [ - ("II", -1.052373245772859), - ("IZ", 0.39793742484318045), - ("ZI", -0.39793742484318045), - ("ZZ", -0.01128010425623538), - ("XX", 0.18093119978423156), - ] - ) + algorithm_globals.random_seed = 50 + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.qubit_op = PauliSumOp.from_list( + [ + ("II", -1.052373245772859), + ("IZ", 0.39793742484318045), + ("ZI", -0.39793742484318045), + ("ZZ", -0.01128010425623538), + ("XX", 0.18093119978423156), + ] + ) + self.assertTrue(len(caught_warnings) > 0) def test_nft(self): """Test NFT optimizer by using it""" - - vqe = VQE( - ansatz=RealAmplitudes(), - optimizer=NFT(), - quantum_instance=QuantumInstance( - BasicAer.get_backend("statevector_simulator"), - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ), - ) - result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=RealAmplitudes(), + optimizer=NFT(), + quantum_instance=QuantumInstance( + BasicAer.get_backend("statevector_simulator"), + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ), + ) + result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.857275, places=6) diff --git a/test/python/algorithms/optimizers/test_optimizers_scikitquant.py b/test/python/algorithms/optimizers/test_optimizers_scikitquant.py index 70716c4e75c5..7e7c1504f437 100644 --- a/test/python/algorithms/optimizers/test_optimizers_scikitquant.py +++ b/test/python/algorithms/optimizers/test_optimizers_scikitquant.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test of scikit-quant optimizers. """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack @@ -35,25 +36,37 @@ def setUp(self): """Set the problem.""" super().setUp() algorithm_globals.random_seed = 50 - self.qubit_op = PauliSumOp.from_list( - [ - ("II", -1.052373245772859), - ("IZ", 0.39793742484318045), - ("ZI", -0.39793742484318045), - ("ZZ", -0.01128010425623538), - ("XX", 0.18093119978423156), - ] - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.qubit_op = PauliSumOp.from_list( + [ + ("II", -1.052373245772859), + ("IZ", 0.39793742484318045), + ("ZI", -0.39793742484318045), + ("ZZ", -0.01128010425623538), + ("XX", 0.18093119978423156), + ] + ) + self.assertTrue(len(caught_warnings) > 0) def _optimize(self, optimizer): """launch vqe""" - qe = QuantumInstance( - BasicAer.get_backend("statevector_simulator"), - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - vqe = VQE(ansatz=RealAmplitudes(), optimizer=optimizer, quantum_instance=qe) - result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qe = QuantumInstance( + BasicAer.get_backend("statevector_simulator"), + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqe = VQE(ansatz=RealAmplitudes(), optimizer=optimizer, quantum_instance=qe) + result = vqe.compute_minimum_eigenvalue(operator=self.qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.857, places=1) def test_bobyqa(self): diff --git a/test/python/algorithms/optimizers/test_spsa.py b/test/python/algorithms/optimizers/test_spsa.py index 8e48e2801bbf..79cfe1c13c78 100644 --- a/test/python/algorithms/optimizers/test_spsa.py +++ b/test/python/algorithms/optimizers/test_spsa.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -12,6 +12,7 @@ """Tests for the SPSA optimizer.""" +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data @@ -40,8 +41,14 @@ def test_pauli_two_design(self, method): """Test SPSA on the Pauli two-design example.""" circuit = PauliTwoDesign(3, reps=1, seed=1) parameters = list(circuit.parameters) - obs = Z ^ Z ^ I - expr = ~StateFn(obs) @ StateFn(circuit) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + obs = Z ^ Z ^ I + expr = ~StateFn(obs) @ StateFn(circuit) + self.assertTrue(len(caught_warnings) > 0) initial_point = np.array( [0.82311034, 0.02611798, 0.21077064, 0.61842177, 0.09828447, 0.62013131] @@ -202,7 +209,7 @@ def test_qnspsa_fidelity_deprecation(self): """Test using a backend and expectation converter in get_fidelity warns.""" ansatz = PauliTwoDesign(2, reps=1, seed=2) - with self.assertWarns(PendingDeprecationWarning): + with self.assertWarns(DeprecationWarning): _ = QNSPSA.get_fidelity(ansatz, StatevectorSimulatorPy(), MatrixExpectation()) def test_qnspsa_fidelity_primitives(self): @@ -227,7 +234,13 @@ def test_qnspsa_max_evals_grouped(self): """Test using max_evals_grouped with QNSPSA.""" circuit = PauliTwoDesign(3, reps=1, seed=1) num_parameters = circuit.num_parameters - obs = Z ^ Z ^ I + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + obs = Z ^ Z ^ I + self.assertTrue(len(caught_warnings) > 0) estimator = Estimator(options={"seed": 12}) diff --git a/test/python/algorithms/test_amplitude_estimators.py b/test/python/algorithms/test_amplitude_estimators.py index 2b9f3a4721d2..d1fb97d06a49 100644 --- a/test/python/algorithms/test_amplitude_estimators.py +++ b/test/python/algorithms/test_amplitude_estimators.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2022. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -13,6 +13,7 @@ """Test the quantum amplitude estimation algorithm.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import ddt, idata, data, unpack @@ -90,21 +91,34 @@ class TestBernoulli(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - self._statevector = QuantumInstance( - backend=BasicAer.get_backend("statevector_simulator"), - seed_simulator=2, - seed_transpiler=2, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self._statevector = QuantumInstance( + backend=BasicAer.get_backend("statevector_simulator"), + seed_simulator=2, + seed_transpiler=2, + ) + self.assertTrue(len(caught_warnings) > 0) self._sampler = Sampler(options={"seed": 2}) def qasm(shots=100): - return QuantumInstance( - backend=BasicAer.get_backend("qasm_simulator"), - shots=shots, - seed_simulator=2, - seed_transpiler=2, - ) + with warnings.catch_warnings(record=True) as cw: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = QuantumInstance( + backend=BasicAer.get_backend("qasm_simulator"), + shots=shots, + seed_simulator=2, + seed_transpiler=2, + ) + self.assertTrue(len(cw) > 0) + return qi self._qasm = qasm @@ -128,10 +142,17 @@ def sampler_shots(shots=100): @unpack def test_statevector(self, prob, qae, expect): """statevector test""" - qae.quantum_instance = self._statevector - problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae.quantum_instance = self._statevector + problem = EstimationProblem(BernoulliStateIn(prob), 0, BernoulliGrover(prob)) + + result = qae.estimate(problem) + self.assertTrue(len(caught_warnings) > 0) - result = qae.estimate(problem) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( @@ -185,10 +206,17 @@ def test_sampler(self, prob, qae, expect): @unpack def test_qasm(self, prob, shots, qae, expect): """qasm test""" - qae.quantum_instance = self._qasm(shots) - problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae.quantum_instance = self._qasm(shots) + problem = EstimationProblem(BernoulliStateIn(prob), [0], BernoulliGrover(prob)) + + result = qae.estimate(problem) + self.assertTrue(len(caught_warnings) > 0) - result = qae.estimate(problem) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" @@ -373,21 +401,34 @@ class TestSineIntegral(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - self._statevector = QuantumInstance( - backend=BasicAer.get_backend("statevector_simulator"), - seed_simulator=123, - seed_transpiler=41, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self._statevector = QuantumInstance( + backend=BasicAer.get_backend("statevector_simulator"), + seed_simulator=123, + seed_transpiler=41, + ) + self.assertTrue(len(caught_warnings) > 0) self._sampler = Sampler(options={"seed": 123}) def qasm(shots=100): - return QuantumInstance( - backend=BasicAer.get_backend("qasm_simulator"), - shots=shots, - seed_simulator=7192, - seed_transpiler=90000, - ) + with warnings.catch_warnings(record=True) as cw: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = QuantumInstance( + backend=BasicAer.get_backend("qasm_simulator"), + shots=shots, + seed_simulator=7192, + seed_transpiler=90000, + ) + self.assertTrue(len(cw) > 0) + return qi self._qasm = qasm @@ -407,13 +448,15 @@ def sampler_shots(shots=100): @unpack def test_statevector(self, n, qae, expect): """Statevector end-to-end test""" - # construct factories for A and Q - # qae.state_preparation = SineIntegral(n) - qae.quantum_instance = self._statevector - estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) - - # result = qae.run(self._statevector) - result = qae.estimate(estimation_problem) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae.quantum_instance = self._statevector + estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) + result = qae.estimate(estimation_problem) + self.assertTrue(len(caught_warnings) > 0) self._statevector.reset_execution_results() for key, value in expect.items(): self.assertAlmostEqual( @@ -454,10 +497,15 @@ def test_sampler(self, n, qae, expect): def test_qasm(self, n, shots, qae, expect): """QASM simulator end-to-end test.""" # construct factories for A and Q - qae.quantum_instance = self._qasm(shots) - estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) - - result = qae.estimate(estimation_problem) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae.quantum_instance = self._qasm(shots) + estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) + result = qae.estimate(estimation_problem) + self.assertTrue(len(caught_warnings) > 0) for key, value in expect.items(): self.assertAlmostEqual( value, getattr(result, key), places=3, msg=f"estimate `{key}` failed" @@ -510,11 +558,18 @@ def test_sampler_with_shots(self, n, shots, qae, expect): def test_confidence_intervals(self, qae, key, expect): """End-to-end test for all confidence intervals.""" n = 3 - qae.quantum_instance = self._statevector - estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae.quantum_instance = self._statevector + estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) + + # statevector simulator + result = qae.estimate(estimation_problem) + self.assertTrue(len(caught_warnings) > 0) - # statevector simulator - result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() methods = ["lr", "fi", "oi"] # short for likelihood_ratio, fisher, observed_fisher alphas = [0.1, 0.00001, 0.9] # alpha shouldn't matter in statevector @@ -527,8 +582,14 @@ def test_confidence_intervals(self, qae, key, expect): # qasm simulator shots = 100 alpha = 0.01 - qae.quantum_instance = self._qasm(shots) - result = qae.estimate(estimation_problem) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae.quantum_instance = self._qasm(shots) + result = qae.estimate(estimation_problem) + self.assertTrue(len(caught_warnings) > 0) for method, expected_confint in expect.items(): confint = qae.compute_confidence_interval(result, alpha, method) np.testing.assert_array_almost_equal(confint, expected_confint) @@ -537,12 +598,19 @@ def test_confidence_intervals(self, qae, key, expect): def test_iqae_confidence_intervals(self): """End-to-end test for the IQAE confidence interval.""" n = 3 - qae = IterativeAmplitudeEstimation(0.1, 0.01, quantum_instance=self._statevector) - expected_confint = (0.1984050, 0.3511015) - estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae = IterativeAmplitudeEstimation(0.1, 0.01, quantum_instance=self._statevector) + expected_confint = (0.1984050, 0.3511015) + estimation_problem = EstimationProblem(SineIntegral(n), objective_qubits=[n]) + + # statevector simulator + result = qae.estimate(estimation_problem) + self.assertTrue(len(caught_warnings) > 0) - # statevector simulator - result = qae.estimate(estimation_problem) self._statevector.reset_execution_results() confint = result.confidence_interval # confidence interval based on statevector should be empty, as we are sure of the result @@ -551,8 +619,14 @@ def test_iqae_confidence_intervals(self): # qasm simulator shots = 100 - qae.quantum_instance = self._qasm(shots) - result = qae.estimate(estimation_problem) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qae.quantum_instance = self._qasm(shots) + result = qae.estimate(estimation_problem) + self.assertTrue(len(caught_warnings) > 0) confint = result.confidence_interval np.testing.assert_array_almost_equal(confint, expected_confint) self.assertTrue(confint[0] <= result.estimation <= confint[1]) @@ -589,10 +663,15 @@ def test_run_without_rescaling(self): # construct algo without rescaling backend = BasicAer.get_backend("statevector_simulator") - fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, quantum_instance=backend) - - # run the algo - result = fae.estimate(problem) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + fae = FasterAmplitudeEstimation(0.1, 1, rescale=False, quantum_instance=backend) + # run the algo + result = fae.estimate(problem) + self.assertTrue(len(caught_warnings) > 0) # assert the result is correct self.assertAlmostEqual(result.estimation, prob) @@ -664,14 +743,25 @@ def is_good_state(bitstr): ) # construct algo - backend = QuantumInstance( - BasicAer.get_backend(backend_str), seed_simulator=2, seed_transpiler=2 - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + backend = QuantumInstance( + BasicAer.get_backend(backend_str), seed_simulator=2, seed_transpiler=2 + ) + self.assertTrue(len(caught_warnings) > 0) # cannot use rescaling with a custom grover operator - fae = FasterAmplitudeEstimation(0.01, 5, rescale=False, quantum_instance=backend) - - # run the algo - result = fae.estimate(problem) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + fae = FasterAmplitudeEstimation(0.01, 5, rescale=False, quantum_instance=backend) + # run the algo + result = fae.estimate(problem) + self.assertTrue(len(caught_warnings) > 0) # assert the result is correct self.assertAlmostEqual(result.estimation, expect, places=5) diff --git a/test/python/algorithms/test_aux_ops_evaluator.py b/test/python/algorithms/test_aux_ops_evaluator.py index f1727b88b19c..c43cf146085a 100644 --- a/test/python/algorithms/test_aux_ops_evaluator.py +++ b/test/python/algorithms/test_aux_ops_evaluator.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -12,6 +12,7 @@ """Tests evaluator of auxiliary operators for algorithms.""" import unittest +import warnings from typing import Tuple, Union from test.python.algorithms import QiskitAlgorithmsTestCase @@ -45,13 +46,19 @@ def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed - self.h2_op = ( - -1.052373245772859 * (I ^ I) - + 0.39793742484318045 * (I ^ Z) - - 0.39793742484318045 * (Z ^ I) - - 0.01128010425623538 * (Z ^ Z) - + 0.18093119978423156 * (X ^ X) - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.h2_op = ( + -1.052373245772859 * (I ^ I) + + 0.39793742484318045 * (I ^ Z) + - 0.39793742484318045 * (Z ^ I) + - 0.01128010425623538 * (Z ^ Z) + + 0.18093119978423156 * (X ^ X) + ) + self.assertTrue(len(caught_warnings) > 0) self.threshold = 1e-8 self.backend_names = ["statevector_simulator", "qasm_simulator"] @@ -85,10 +92,15 @@ def _run_test( observables: ListOrDict[OperatorBase], quantum_instance: Union[QuantumInstance, Backend], ): - result = eval_observables( - quantum_instance, quantum_state, observables, expectation, self.threshold - ) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = eval_observables( + quantum_instance, quantum_state, observables, expectation, self.threshold + ) + self.assertTrue(len(caught_warnings) > 0) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) np.testing.assert_array_almost_equal( @@ -132,16 +144,22 @@ def test_eval_observables(self, observables: ListOrDict[OperatorBase]): ) # to accommodate for qasm being imperfect with self.subTest(msg=f"Test {backend_name} backend."): backend = BasicAer.get_backend(backend_name) - quantum_instance = QuantumInstance( - backend=backend, - shots=shots, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) - expectation = ExpectationFactory.build( - operator=self.h2_op, - backend=quantum_instance, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + shots=shots, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + expectation = ExpectationFactory.build( + operator=self.h2_op, + backend=quantum_instance, + ) + self.assertTrue(len(caught_warnings) > 0) with self.subTest(msg="Test QuantumCircuit."): self._run_test( @@ -163,17 +181,22 @@ def test_eval_observables(self, observables: ListOrDict[OperatorBase]): observables, quantum_instance, ) - - with self.subTest(msg="Test StateFn."): - statefn = StateFn(bound_ansatz) - self._run_test( - expected_result, - statefn, - decimal, - expectation, - observables, - quantum_instance, + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, ) + with self.subTest(msg="Test StateFn."): + statefn = StateFn(bound_ansatz) + self._run_test( + expected_result, + statefn, + decimal, + expectation, + observables, + quantum_instance, + ) + self.assertTrue(len(caught_warnings) > 0) if __name__ == "__main__": diff --git a/test/python/algorithms/test_backendv1.py b/test/python/algorithms/test_backendv1.py index 75d0615def34..4181eb9d869e 100644 --- a/test/python/algorithms/test_backendv1.py +++ b/test/python/algorithms/test_backendv1.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021, 2022. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -40,43 +40,47 @@ def test_shor_factoring(self): """shor factoring test""" n_v = 15 factors = [3, 5] - qasm_simulator = QuantumInstance( - self._qasm, shots=1000, seed_simulator=self.seed, seed_transpiler=self.seed - ) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) + qasm_simulator = QuantumInstance( + self._qasm, shots=1000, seed_simulator=self.seed, seed_transpiler=self.seed + ) shor = Shor(quantum_instance=qasm_simulator) - self.assertTrue("Shor class is deprecated" in str(caught_warnings[0].message)) - + self.assertTrue(len(caught_warnings) > 0) result = shor.factor(N=n_v) self.assertListEqual(result.factors[0], factors) self.assertTrue(result.total_counts >= result.successful_counts) def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" - h2_op = ( - -1.052373245772859 * (I ^ I) - + 0.39793742484318045 * (I ^ Z) - - 0.39793742484318045 * (Z ^ I) - - 0.01128010425623538 * (Z ^ Z) - + 0.18093119978423156 * (X ^ X) - ) optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") - qasm_simulator = QuantumInstance( - self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed - ) - vqe = VQE( - ansatz=wavefunction, - optimizer=optimizer, - max_evals_grouped=1, - quantum_instance=qasm_simulator, - ) - - result = vqe.compute_minimum_eigenvalue(operator=h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + h2_op = ( + -1.052373245772859 * (I ^ I) + + 0.39793742484318045 * (I ^ Z) + - 0.39793742484318045 * (Z ^ I) + - 0.01128010425623538 * (Z ^ Z) + + 0.18093119978423156 * (X ^ X) + ) + qasm_simulator = QuantumInstance( + self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + max_evals_grouped=1, + quantum_instance=qasm_simulator, + ) + result = vqe.compute_minimum_eigenvalue(operator=h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): @@ -84,12 +88,17 @@ def test_run_circuit_oracle(self): oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) - qi = QuantumInstance( - self._provider.get_backend("fake_vigo"), seed_simulator=12, seed_transpiler=32 - ) - with self.assertWarns(PendingDeprecationWarning): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = QuantumInstance( + self._provider.get_backend("fake_vigo"), seed_simulator=12, seed_transpiler=32 + ) grover = Grover(quantum_instance=qi) - result = grover.amplify(problem) + result = grover.amplify(problem) + self.assertTrue(len(caught_warnings) > 0) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): @@ -99,10 +108,15 @@ def test_run_circuit_oracle_single_experiment_backend(self): problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_vigo") backend._configuration.max_experiments = 1 - qi = QuantumInstance(backend, seed_simulator=12, seed_transpiler=32) - with self.assertWarns(PendingDeprecationWarning): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = QuantumInstance(backend, seed_simulator=12, seed_transpiler=32) grover = Grover(quantum_instance=qi) - result = grover.amplify(problem) + result = grover.amplify(problem) + self.assertTrue(len(caught_warnings) > 0) self.assertIn(result.top_measurement, ["11"]) def test_measurement_error_mitigation_with_vqe(self): @@ -121,27 +135,38 @@ def test_measurement_error_mitigation_with_vqe(self): noise_model.add_all_qubit_readout_error(read_err) backend = self._qasm + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + seed_simulator=167, + seed_transpiler=167, + noise_model=noise_model, + measurement_error_mitigation_cls=CompleteMeasFitter, + ) + h2_hamiltonian = ( + -1.052373245772859 * (I ^ I) + + 0.39793742484318045 * (I ^ Z) + - 0.39793742484318045 * (Z ^ I) + - 0.01128010425623538 * (Z ^ Z) + + 0.18093119978423156 * (X ^ X) + ) + self.assertTrue(len(caught_warnings) > 0) - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=167, - seed_transpiler=167, - noise_model=noise_model, - measurement_error_mitigation_cls=CompleteMeasFitter, - ) - - h2_hamiltonian = ( - -1.052373245772859 * (I ^ I) - + 0.39793742484318045 * (I ^ Z) - - 0.39793742484318045 * (Z ^ I) - - 0.01128010425623538 * (Z ^ Z) - + 0.18093119978423156 * (X ^ X) - ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) - vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) - result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) + result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) + self.assertTrue(len(caught_warnings) > 0) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) diff --git a/test/python/algorithms/test_backendv2.py b/test/python/algorithms/test_backendv2.py index b22608f715ba..a1f8e8a27561 100644 --- a/test/python/algorithms/test_backendv2.py +++ b/test/python/algorithms/test_backendv2.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021, 2022. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -40,43 +40,47 @@ def test_shor_factoring(self): """shor factoring test""" n_v = 15 factors = [3, 5] - qasm_simulator = QuantumInstance( - self._qasm, shots=1000, seed_simulator=self.seed, seed_transpiler=self.seed - ) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) + qasm_simulator = QuantumInstance( + self._qasm, shots=1000, seed_simulator=self.seed, seed_transpiler=self.seed + ) shor = Shor(quantum_instance=qasm_simulator) - self.assertTrue("Shor class is deprecated" in str(caught_warnings[0].message)) - + self.assertTrue(len(caught_warnings) > 0) result = shor.factor(N=n_v) self.assertListEqual(result.factors[0], factors) self.assertTrue(result.total_counts >= result.successful_counts) def test_vqe_qasm(self): """Test the VQE on QASM simulator.""" - h2_op = ( - -1.052373245772859 * (I ^ I) - + 0.39793742484318045 * (I ^ Z) - - 0.39793742484318045 * (Z ^ I) - - 0.01128010425623538 * (Z ^ Z) - + 0.18093119978423156 * (X ^ X) - ) optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") - qasm_simulator = QuantumInstance( - self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed - ) - vqe = VQE( - ansatz=wavefunction, - optimizer=optimizer, - max_evals_grouped=1, - quantum_instance=qasm_simulator, - ) - - result = vqe.compute_minimum_eigenvalue(operator=h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + h2_op = ( + -1.052373245772859 * (I ^ I) + + 0.39793742484318045 * (I ^ Z) + - 0.39793742484318045 * (Z ^ I) + - 0.01128010425623538 * (Z ^ Z) + + 0.18093119978423156 * (X ^ X) + ) + qasm_simulator = QuantumInstance( + self._qasm, shots=1024, seed_simulator=self.seed, seed_transpiler=self.seed + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + max_evals_grouped=1, + quantum_instance=qasm_simulator, + ) + result = vqe.compute_minimum_eigenvalue(operator=h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) def test_run_circuit_oracle(self): @@ -84,12 +88,17 @@ def test_run_circuit_oracle(self): oracle = QuantumCircuit(2) oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) - qi = QuantumInstance( - self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 - ) - with self.assertWarns(PendingDeprecationWarning): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = QuantumInstance( + self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 + ) grover = Grover(quantum_instance=qi) - result = grover.amplify(problem) + result = grover.amplify(problem) + self.assertTrue(len(caught_warnings) > 0) self.assertIn(result.top_measurement, ["11"]) def test_run_circuit_oracle_single_experiment_backend(self): @@ -99,12 +108,17 @@ def test_run_circuit_oracle_single_experiment_backend(self): problem = AmplificationProblem(oracle, is_good_state=["11"]) backend = self._provider.get_backend("fake_yorktown") backend._configuration.max_experiments = 1 - qi = QuantumInstance( - self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 - ) - with self.assertWarns(PendingDeprecationWarning): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = QuantumInstance( + self._provider.get_backend("fake_yorktown"), seed_simulator=12, seed_transpiler=32 + ) grover = Grover(quantum_instance=qi) - result = grover.amplify(problem) + result = grover.amplify(problem) + self.assertTrue(len(caught_warnings) > 0) self.assertIn(result.top_measurement, ["11"]) diff --git a/test/python/algorithms/test_grover.py b/test/python/algorithms/test_grover.py index f0363b6de41b..a235b3430e52 100644 --- a/test/python/algorithms/test_grover.py +++ b/test/python/algorithms/test_grover.py @@ -14,6 +14,7 @@ import itertools import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np @@ -92,12 +93,18 @@ class TestGrover(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - self.statevector = QuantumInstance( - BasicAer.get_backend("statevector_simulator"), seed_simulator=12, seed_transpiler=32 - ) - self.qasm = QuantumInstance( - BasicAer.get_backend("qasm_simulator"), seed_simulator=12, seed_transpiler=32 - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.statevector = QuantumInstance( + BasicAer.get_backend("statevector_simulator"), seed_simulator=12, seed_transpiler=32 + ) + self.qasm = QuantumInstance( + BasicAer.get_backend("qasm_simulator"), seed_simulator=12, seed_transpiler=32 + ) + self.assertTrue(len(caught_warnings) > 0) self._sampler = Sampler() self._sampler_with_shots = Sampler(options={"shots": 1024, "seed": 123}) algorithm_globals.random_seed = 123 @@ -109,7 +116,12 @@ def test_implicit_phase_oracle_is_good_state(self, use_sampler): grover = self._prepare_grover(use_sampler) oracle = PhaseOracle("x & y") problem = AmplificationProblem(oracle) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(result.top_measurement, "11") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None, 2])) @@ -118,7 +130,12 @@ def test_iterations_with_good_state(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) @@ -126,7 +143,12 @@ def test_fixed_iterations_without_good_state(self, use_sampler): """Test the algorithm with iterations as an int and without good state""" grover = self._prepare_grover(use_sampler, iterations=2) problem = AmplificationProblem(Statevector.from_label("111")) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @idata(itertools.product(["ideal", "shots", False], [[1, 2, 3], None])) @@ -135,10 +157,15 @@ def test_iterations_without_good_state(self, use_sampler, iterations): """Test the correct error is thrown for none/list of iterations and without good state""" grover = self._prepare_grover(use_sampler, iterations=iterations) problem = AmplificationProblem(Statevector.from_label("111")) - with self.assertRaisesRegex( - TypeError, "An is_good_state function is required with the provided oracle" - ): - grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.assertRaisesRegex( + TypeError, "An is_good_state function is required with the provided oracle" + ): + grover.amplify(problem) @data("ideal", "shots", False) def test_iterator(self, use_sampler): @@ -155,7 +182,12 @@ def iterator(): grover = self._prepare_grover(use_sampler, iterations=iterator()) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) @@ -163,7 +195,12 @@ def test_growth_rate(self, use_sampler): """Test running the algorithm on a growth rate""" grover = self._prepare_grover(use_sampler, growth_rate=8 / 7) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) @@ -177,7 +214,12 @@ def zero(): grover = self._prepare_grover(use_sampler, iterations=zero()) n = 5 problem = AmplificationProblem(Statevector.from_label("1" * n), is_good_state=["1" * n]) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(len(result.iterations), 2**n) @data("ideal", "shots", False) @@ -186,7 +228,12 @@ def test_max_power(self, use_sampler): lam = 10.0 grover = self._prepare_grover(use_sampler, growth_rate=lam) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(len(result.iterations), 0) @data("ideal", "shots", False) @@ -196,7 +243,12 @@ def test_run_circuit_oracle(self, use_sampler): oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) @@ -205,7 +257,12 @@ def test_run_state_vector_oracle(self, use_sampler): mark_state = Statevector.from_label("11") problem = AmplificationProblem(mark_state, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @data("ideal", "shots", False) @@ -218,7 +275,12 @@ def test_run_custom_grover_operator(self, use_sampler): oracle=oracle, grover_operator=grover_op, is_good_state=["11"] ) grover = self._prepare_grover(use_sampler) - ret = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + ret = grover.amplify(problem) self.assertIn(ret.top_measurement, ["11"]) def test_optimal_num_iterations(self): @@ -253,7 +315,12 @@ def test_circuit_result(self, use_sampler): # is_good_state=['00'] is intentionally selected to obtain a list of results problem = AmplificationProblem(oracle, is_good_state=["00"]) grover = self._prepare_grover(use_sampler, iterations=[1, 2, 3, 4]) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) if use_sampler: for i, dist in enumerate(result.circuit_results): keys, values = zip(*sorted(dist.items())) @@ -279,7 +346,12 @@ def test_max_probability(self, use_sampler): oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertAlmostEqual(result.max_probability, 1.0) @unittest.skipUnless(HAS_TWEEDLEDUM, "tweedledum required for this test") @@ -289,7 +361,12 @@ def test_oracle_evaluation(self, use_sampler): oracle = PhaseOracle("x1 & x2 & (not x3)") problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = self._prepare_grover(use_sampler) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertTrue(result.oracle_evaluation) self.assertEqual("011", result.top_measurement) diff --git a/test/python/algorithms/test_linear_solvers.py b/test/python/algorithms/test_linear_solvers.py index c2cb747e2799..40c70bfcbb54 100644 --- a/test/python/algorithms/test_linear_solvers.py +++ b/test/python/algorithms/test_linear_solvers.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2022. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -85,9 +85,15 @@ def test_matrices(self, matrix, time=1.0, power=1): qc = QuantumCircuit(circ_qubits) qc.append(matrix.power(power).control(), list(range(circ_qubits))) # extract the parts of the circuit matrix corresponding to TridiagonalToeplitz - zero_op = (I + Z) / 2 - one_op = (I - Z) / 2 - proj = Operator((zero_op ^ pow_circ.num_ancillas) ^ (I ^ num_qubits) ^ one_op).data + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + zero_op = (I + Z) / 2 + one_op = (I - Z) / 2 + proj = Operator((zero_op ^ pow_circ.num_ancillas) ^ (I ^ num_qubits) ^ one_op).data + self.assertTrue(len(caught_warnings) > 0) circ_matrix = Operator(qc).data approx_exp = partial_trace( np.dot(proj, circ_matrix), [0] + list(range(num_qubits + 1, circ_qubits)) @@ -155,9 +161,15 @@ def test_absolute_average(self, observable, vector): qc.isometry(init_state, list(range(num_qubits)), None) qc.append(observable.observable_circuit(num_qubits), list(range(num_qubits))) - # Observable operator - observable_op = observable.observable(num_qubits) - state_vec = (~StateFn(observable_op) @ StateFn(qc)).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Observable operator + observable_op = observable.observable(num_qubits) + state_vec = (~StateFn(observable_op) @ StateFn(qc)).eval() + self.assertTrue(len(caught_warnings) > 0) # Obtain result result = observable.post_processing(state_vec, num_qubits) @@ -196,15 +208,21 @@ def test_matrix_functional(self, observable, vector): qcs.append(tpass(qc.decompose())) # Get observables - observable_ops = observable.observable(num_qubits) - state_vecs = [] - # First is the norm - state_vecs.append((~StateFn(observable_ops[0]) @ StateFn(qcs[0])).eval()) - for i in range(1, len(observable_ops), 2): - state_vecs += [ - (~StateFn(observable_ops[i]) @ StateFn(qcs[i])).eval(), - (~StateFn(observable_ops[i + 1]) @ StateFn(qcs[i + 1])).eval(), - ] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + observable_ops = observable.observable(num_qubits) + state_vecs = [] + # First is the norm + state_vecs.append((~StateFn(observable_ops[0]) @ StateFn(qcs[0])).eval()) + for i in range(1, len(observable_ops), 2): + state_vecs += [ + (~StateFn(observable_ops[i]) @ StateFn(qcs[i])).eval(), + (~StateFn(observable_ops[i + 1]) @ StateFn(qcs[i + 1])).eval(), + ] + self.assertTrue(len(caught_warnings) > 0) # Obtain result result = observable.post_processing(state_vecs, num_qubits) @@ -345,8 +363,14 @@ def test_hhl_qi(self): self.assertIsNone(hhl.quantum_instance) # Defaults to None # First set a valid quantum instance and check via getter - qinst = QuantumInstance(backend=BasicAer.get_backend("qasm_simulator")) - hhl.quantum_instance = qinst + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qinst = QuantumInstance(backend=BasicAer.get_backend("qasm_simulator")) + hhl.quantum_instance = qinst + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(hhl.quantum_instance, qinst) # Now set quantum instance back to None and check via getter diff --git a/test/python/algorithms/test_measure_error_mitigation.py b/test/python/algorithms/test_measure_error_mitigation.py index b41129a624c8..f2d8566df6af 100644 --- a/test/python/algorithms/test_measure_error_mitigation.py +++ b/test/python/algorithms/test_measure_error_mitigation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2022. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -13,7 +13,7 @@ """ Test Measurement Error Mitigation """ import unittest - +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np @@ -72,16 +72,22 @@ def test_measurement_error_mitigation_with_diff_qubit_order( CompleteMeasFitter if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter ) backend = Aer.get_backend("aer_simulator") - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=1679, - seed_transpiler=167, - shots=1000, - noise_model=noise_model, - measurement_error_mitigation_cls=fitter_cls, - cals_matrix_refresh_period=0, - mit_pattern=mit_pattern, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + seed_simulator=1679, + seed_transpiler=167, + shots=1000, + noise_model=noise_model, + measurement_error_mitigation_cls=fitter_cls, + cals_matrix_refresh_period=0, + mit_pattern=mit_pattern, + ) + self.assertTrue(len(caught_warnings) > 0) # circuit qc1 = QuantumCircuit(2, 2) qc1.h(0) @@ -94,15 +100,21 @@ def test_measurement_error_mitigation_with_diff_qubit_order( qc2.measure(1, 0) qc2.measure(0, 1) - if fails: - self.assertRaisesRegex( - QiskitError, - "Each element in the mit pattern should have length 1.", - quantum_instance.execute, - [qc1, qc2], + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, ) - else: - quantum_instance.execute([qc1, qc2]) + if fails: + self.assertRaisesRegex( + QiskitError, + "Each element in the mit pattern should have length 1.", + quantum_instance.execute, + [qc1, qc2], + ) + else: + quantum_instance.execute([qc1, qc2]) + self.assertTrue(len(caught_warnings) > 0) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() @@ -114,7 +126,13 @@ def test_measurement_error_mitigation_with_diff_qubit_order( qc3.measure(2, 1) qc3.measure(1, 2) - self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.assertRaises(QiskitError, quantum_instance.execute, [qc1, qc3]) + self.assertTrue(len(caught_warnings) > 0) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @data(("CompleteMeasFitter", None), ("TensoredMeasFitter", [[0], [1]])) @@ -133,27 +151,39 @@ def test_measurement_error_mitigation_with_vqe(self, config): CompleteMeasFitter if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter ) backend = Aer.get_backend("aer_simulator") - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=167, - seed_transpiler=167, - noise_model=noise_model, - measurement_error_mitigation_cls=fitter_cls, - mit_pattern=mit_pattern, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + seed_simulator=167, + seed_transpiler=167, + noise_model=noise_model, + measurement_error_mitigation_cls=fitter_cls, + mit_pattern=mit_pattern, + ) + self.assertTrue(len(caught_warnings) > 0) - h2_hamiltonian = ( - -1.052373245772859 * (I ^ I) - + 0.39793742484318045 * (I ^ Z) - - 0.39793742484318045 * (Z ^ I) - - 0.01128010425623538 * (Z ^ Z) - + 0.18093119978423156 * (X ^ X) - ) optimizer = SPSA(maxiter=200) ansatz = EfficientSU2(2, reps=1) - vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) - result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + h2_hamiltonian = ( + -1.052373245772859 * (I ^ I) + + 0.39793742484318045 * (I ^ Z) + - 0.39793742484318045 * (Z ^ I) + - 0.01128010425623538 * (Z ^ Z) + + 0.18093119978423156 * (X ^ X) + ) + vqe = VQE(ansatz=ansatz, optimizer=optimizer, quantum_instance=quantum_instance) + result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) + self.assertTrue(len(caught_warnings) > 0) self.assertGreater(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertAlmostEqual(result.eigenvalue.real, -1.86, delta=0.05) @@ -182,7 +212,12 @@ def _get_operator(self, weight_matrix): pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] - return PauliSumOp.from_list(opflow_list), shift + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + return PauliSumOp.from_list(opflow_list), shift @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") def test_measurement_error_mitigation_qaoa(self): @@ -196,17 +231,23 @@ def test_measurement_error_mitigation_qaoa(self): initial_point = np.asarray([0.0, 0.0]) # Compute first without noise - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - qaoa = QAOA( - optimizer=COBYLA(maxiter=3), - quantum_instance=quantum_instance, - initial_point=initial_point, - ) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + qaoa = QAOA( + optimizer=COBYLA(maxiter=3), + quantum_instance=quantum_instance, + initial_point=initial_point, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) ref_eigenvalue = result.eigenvalue.real # compute with noise @@ -215,21 +256,26 @@ def test_measurement_error_mitigation_qaoa(self): read_err = noise.errors.readout_error.ReadoutError([[0.9, 0.1], [0.25, 0.75]]) noise_model.add_all_qubit_readout_error(read_err) - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - noise_model=noise_model, - measurement_error_mitigation_cls=CompleteMeasFitter, - shots=10000, - ) - - qaoa = QAOA( - optimizer=COBYLA(maxiter=3), - quantum_instance=quantum_instance, - initial_point=initial_point, - ) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + noise_model=noise_model, + measurement_error_mitigation_cls=CompleteMeasFitter, + shots=10000, + ) + qaoa = QAOA( + optimizer=COBYLA(maxiter=3), + quantum_instance=quantum_instance, + initial_point=initial_point, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, ref_eigenvalue, delta=0.05) @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @@ -248,15 +294,21 @@ def test_measurement_error_mitigation_with_diff_qubit_order_ignis(self, fitter_s CompleteMeasFitter_IG if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter_IG ) backend = Aer.get_backend("aer_simulator") - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=1679, - seed_transpiler=167, - shots=1000, - noise_model=noise_model, - measurement_error_mitigation_cls=fitter_cls, - cals_matrix_refresh_period=0, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + seed_simulator=1679, + seed_transpiler=167, + shots=1000, + noise_model=noise_model, + measurement_error_mitigation_cls=fitter_cls, + cals_matrix_refresh_period=0, + ) + self.assertTrue(len(caught_warnings) > 0) # circuit qc1 = QuantumCircuit(2, 2) qc1.h(0) @@ -311,14 +363,20 @@ def test_measurement_error_mitigation_with_vqe_ignis(self, config): CompleteMeasFitter_IG if fitter_str == "CompleteMeasFitter" else TensoredMeasFitter_IG ) backend = Aer.get_backend("aer_simulator") - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=167, - seed_transpiler=167, - noise_model=noise_model, - measurement_error_mitigation_cls=fitter_cls, - mit_pattern=mit_pattern, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=backend, + seed_simulator=167, + seed_transpiler=167, + noise_model=noise_model, + measurement_error_mitigation_cls=fitter_cls, + mit_pattern=mit_pattern, + ) + self.assertTrue(len(caught_warnings) > 0) h2_hamiltonian = ( -1.052373245772859 * (I ^ I) @@ -352,24 +410,30 @@ def test_calibration_results(self): counts_array = [None, None] for idx, is_use_mitigation in enumerate([True, False]): - if is_use_mitigation: - quantum_instance = QuantumInstance( - backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - shots=1024, - measurement_error_mitigation_cls=CompleteMeasFitter_IG, + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, ) - with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): + if is_use_mitigation: + quantum_instance = QuantumInstance( + backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + shots=1024, + measurement_error_mitigation_cls=CompleteMeasFitter_IG, + ) + with self.assertWarnsRegex(DeprecationWarning, r".*ignis.*"): + counts_array[idx] = quantum_instance.execute(qc_meas).get_counts() + else: + quantum_instance = QuantumInstance( + backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + shots=1024, + ) counts_array[idx] = quantum_instance.execute(qc_meas).get_counts() - else: - quantum_instance = QuantumInstance( - backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - shots=1024, - ) - counts_array[idx] = quantum_instance.execute(qc_meas).get_counts() + self.assertTrue(len(caught_warnings) > 0) self.assertEqual( counts_array[0], counts_array[1], msg="Counts different with/without fitter." ) @@ -385,19 +449,30 @@ def test_circuit_modified(self): circuit.x(0) circuit.measure_all() - qi = QuantumInstance( - Aer.get_backend("aer_simulator"), - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - shots=1024, - measurement_error_mitigation_cls=CompleteMeasFitter, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = QuantumInstance( + Aer.get_backend("aer_simulator"), + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + shots=1024, + measurement_error_mitigation_cls=CompleteMeasFitter, + ) + self.assertTrue(len(caught_warnings) > 0) # The error happens on transpiled circuits since "execute" was changing the input array # Non transpiled circuits didn't have a problem because a new transpiled array was created # internally. circuits_ref = qi.transpile(circuit) # always returns a new array circuits_input = circuits_ref.copy() - _ = qi.execute(circuits_input, had_transpiled=True) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + _ = qi.execute(circuits_input, had_transpiled=True) self.assertEqual(circuits_ref, circuits_input, msg="Transpiled circuit array modified.") @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required for this test") @@ -419,22 +494,34 @@ def test_tensor_subset_fitter(self): mit_pattern = [[idx] for idx in range(3)] backend = Aer.get_backend("aer_simulator") backend.set_options(seed_simulator=123) - mit_circuits = build_measurement_error_mitigation_circuits( - [0, 1, 2], - TensoredMeasFitter, - backend, - backend_config={}, - compile_config={}, - mit_pattern=mit_pattern, - ) - result = execute(mit_circuits[0], backend, noise_model=noise_model).result() - fitter = TensoredMeasFitter(result, mit_pattern=mit_pattern) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + mit_circuits = build_measurement_error_mitigation_circuits( + [0, 1, 2], + TensoredMeasFitter, + backend, + backend_config={}, + compile_config={}, + mit_pattern=mit_pattern, + ) + result = execute(mit_circuits[0], backend, noise_model=noise_model).result() + fitter = TensoredMeasFitter(result, mit_pattern=mit_pattern) + self.assertTrue(len(caught_warnings) > 0) cal_matrices = fitter.cal_matrices # Check that permutations and permuted subsets match. for subset in [[1, 0], [1, 2], [0, 2], [2, 0, 1]]: with self.subTest(subset=subset): - new_fitter = fitter.subset_fitter(subset) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + new_fitter = fitter.subset_fitter(subset) + self.assertTrue(len(caught_warnings) > 0) for idx, qubit in enumerate(subset): self.assertTrue(np.allclose(new_fitter.cal_matrices[idx], cal_matrices[qubit])) @@ -455,7 +542,14 @@ def test_tensor_subset_fitter(self): result = execute( circuit, backend, noise_model=noise_model, shots=1000, seed_simulator=0 ).result() - new_result = fitter.subset_fitter([1, 2, 0]).filter.apply(result) + with self.subTest(subset=subset): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + new_result = fitter.subset_fitter([1, 2, 0]).filter.apply(result) + self.assertTrue(len(caught_warnings) > 0) # The noisy result should have a poor 111 state, the mit. result should be good. self.assertTrue(result.get_counts()["111"] < 800) diff --git a/test/python/algorithms/test_numpy_eigen_solver.py b/test/python/algorithms/test_numpy_eigen_solver.py index d2a918a8acff..0679eabaf5ad 100644 --- a/test/python/algorithms/test_numpy_eigen_solver.py +++ b/test/python/algorithms/test_numpy_eigen_solver.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test NumPy Eigen solver """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np @@ -28,20 +29,32 @@ class TestNumPyEigensolver(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - self.qubit_op = PauliSumOp.from_list( - [ - ("II", -1.052373245772859), - ("ZI", 0.39793742484318045), - ("IZ", -0.39793742484318045), - ("ZZ", -0.01128010425623538), - ("XX", 0.18093119978423156), - ] - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.qubit_op = PauliSumOp.from_list( + [ + ("II", -1.052373245772859), + ("ZI", 0.39793742484318045), + ("IZ", -0.39793742484318045), + ("ZZ", -0.01128010425623538), + ("XX", 0.18093119978423156), + ] + ) + self.assertTrue(len(caught_warnings) > 0) def test_ce(self): """Test basics""" algo = NumPyEigensolver() - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 1) self.assertEqual(len(result.eigenstates), 1) self.assertEqual(result.eigenvalues.dtype, np.float64) @@ -50,7 +63,13 @@ def test_ce(self): def test_ce_k4(self): """Test for k=4 eigenvalues""" algo = NumPyEigensolver(k=4) - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 4) self.assertEqual(len(result.eigenstates), 4) self.assertEqual(result.eigenvalues.dtype, np.float64) @@ -67,7 +86,13 @@ def criterion(x, v, a_v): return v >= -1 algo = NumPyEigensolver(k=4, filter_criterion=criterion) - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 2) self.assertEqual(len(result.eigenstates), 2) self.assertEqual(result.eigenvalues.dtype, np.float64) @@ -82,7 +107,13 @@ def criterion(x, v, a_v): return False algo = NumPyEigensolver(k=4, filter_criterion=criterion) - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=[]) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 0) self.assertEqual(len(result.eigenstates), 0) @@ -90,23 +121,41 @@ def criterion(x, v, a_v): def test_ce_k1_1q(self, op): """Test for 1 qubit operator""" algo = NumPyEigensolver(k=1) - result = algo.compute_eigenvalues(operator=op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(result.eigenvalues, [-1]) @data(X, Y, Z) def test_ce_k2_1q(self, op): """Test for 1 qubit operator""" algo = NumPyEigensolver(k=2) - result = algo.compute_eigenvalues(operator=op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(result.eigenvalues, [-1, 1]) def test_aux_operators_list(self): """Test list-based aux_operators.""" - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - algo = NumPyEigensolver() - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + algo = NumPyEigensolver() + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 1) self.assertEqual(len(result.eigenstates), 1) self.assertEqual(result.eigenvalues.dtype, np.float64) @@ -122,7 +171,13 @@ def test_aux_operators_list(self): # Go again with additional None and zero operators extra_ops = [*aux_ops, None, 0] - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 1) self.assertEqual(len(result.eigenstates), 1) self.assertEqual(result.eigenvalues.dtype, np.float64) @@ -141,11 +196,17 @@ def test_aux_operators_list(self): def test_aux_operators_dict(self): """Test dict-based aux_operators.""" - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} - algo = NumPyEigensolver() - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} + algo = NumPyEigensolver() + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 1) self.assertEqual(len(result.eigenstates), 1) self.assertEqual(result.eigenvalues.dtype, np.float64) @@ -161,7 +222,13 @@ def test_aux_operators_dict(self): # Go again with additional None and zero operators extra_ops = {**aux_ops, "None_operator": None, "zero_operator": 0} - result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_eigenvalues(operator=self.qubit_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 1) self.assertEqual(len(result.eigenstates), 1) self.assertEqual(result.eigenvalues.dtype, np.float64) diff --git a/test/python/algorithms/test_numpy_minimum_eigen_solver.py b/test/python/algorithms/test_numpy_minimum_eigen_solver.py index 6523e3d10e75..043de78b5d53 100644 --- a/test/python/algorithms/test_numpy_minimum_eigen_solver.py +++ b/test/python/algorithms/test_numpy_minimum_eigen_solver.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020, 2021. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test NumPy Minimum Eigensolver """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np @@ -28,27 +29,39 @@ class TestNumPyMinimumEigensolver(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - self.qubit_op = PauliSumOp.from_list( - [ - ("II", -1.052373245772859), - ("ZI", 0.39793742484318045), - ("IZ", -0.39793742484318045), - ("ZZ", -0.01128010425623538), - ("XX", 0.18093119978423156), - ] - ) - - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.qubit_op = PauliSumOp.from_list( + [ + ("II", -1.052373245772859), + ("ZI", 0.39793742484318045), + ("IZ", -0.39793742484318045), + ("ZZ", -0.01128010425623538), + ("XX", 0.18093119978423156), + ] + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + self.assertTrue(len(caught_warnings) > 0) + self.aux_ops_list = [aux_op1, aux_op2] self.aux_ops_dict = {"aux_op1": aux_op1, "aux_op2": aux_op2} def test_cme(self): """Basic test""" algo = NumPyMinimumEigensolver() - result = algo.compute_minimum_eigenvalue( - operator=self.qubit_op, aux_operators=self.aux_ops_list - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=self.aux_ops_list + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 2) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues[0], [2, 0]) @@ -58,37 +71,69 @@ def test_cme_reuse(self): """Test reuse""" # Start with no operator or aux_operators, give via compute method algo = NumPyMinimumEigensolver() - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue(operator=self.qubit_op) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(result.eigenvalue.dtype, np.float64) self.assertAlmostEqual(result.eigenvalue, -1.85727503) self.assertIsNone(result.aux_operator_eigenvalues) # Add aux_operators and go again - result = algo.compute_minimum_eigenvalue( - operator=self.qubit_op, aux_operators=self.aux_ops_list - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=self.aux_ops_list + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 2) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues[0], [2, 0]) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues[1], [0, 0]) # "Remove" aux_operators and go again - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=[]) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(result.eigenvalue.dtype, np.float64) self.assertAlmostEqual(result.eigenvalue, -1.85727503) self.assertIsNone(result.aux_operator_eigenvalues) # Set aux_operators and go again - result = algo.compute_minimum_eigenvalue( - operator=self.qubit_op, aux_operators=self.aux_ops_list - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=self.aux_ops_list + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 2) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues[0], [2, 0]) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues[1], [0, 0]) # Finally just set one of aux_operators and main operator, remove aux_operators - result = algo.compute_minimum_eigenvalue(operator=self.aux_ops_list[0], aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.aux_ops_list[0], aux_operators=[] + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, 2 + 0j) self.assertIsNone(result.aux_operator_eigenvalues) @@ -101,9 +146,15 @@ def criterion(x, v, a_v): return v >= -0.5 algo = NumPyMinimumEigensolver(filter_criterion=criterion) - result = algo.compute_minimum_eigenvalue( - operator=self.qubit_op, aux_operators=self.aux_ops_list - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=self.aux_ops_list + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -0.22491125 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 2) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues[0], [2, 0]) @@ -118,9 +169,15 @@ def criterion(x, v, a_v): return False algo = NumPyMinimumEigensolver(filter_criterion=criterion) - result = algo.compute_minimum_eigenvalue( - operator=self.qubit_op, aux_operators=self.aux_ops_list - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=self.aux_ops_list + ) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(result.eigenvalue, None) self.assertEqual(result.eigenstate, None) self.assertEqual(result.aux_operator_eigenvalues, None) @@ -129,21 +186,39 @@ def criterion(x, v, a_v): def test_cme_1q(self, op): """Test for 1 qubit operator""" algo = NumPyMinimumEigensolver() - result = algo.compute_minimum_eigenvalue(operator=op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue(operator=op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1) def test_cme_aux_ops_dict(self): """Test dictionary compatibility of aux_operators""" # Start with an empty dictionary algo = NumPyMinimumEigensolver() - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators={}) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators={}) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertIsNone(result.aux_operator_eigenvalues) # Add aux_operators dictionary and go again - result = algo.compute_minimum_eigenvalue( - operator=self.qubit_op, aux_operators=self.aux_ops_dict - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=self.aux_ops_dict + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 2) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues["aux_op1"], [2, 0]) @@ -151,7 +226,15 @@ def test_cme_aux_ops_dict(self): # Add None and zero operators and go again extra_ops = {"None_op": None, "zero_op": 0, **self.aux_ops_dict} - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=extra_ops + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 3) np.testing.assert_array_almost_equal(result.aux_operator_eigenvalues["aux_op1"], [2, 0]) @@ -160,11 +243,17 @@ def test_cme_aux_ops_dict(self): def test_aux_operators_list(self): """Test list-based aux_operators.""" - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - algo = NumPyMinimumEigensolver() - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + algo = NumPyMinimumEigensolver() + result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values @@ -176,7 +265,15 @@ def test_aux_operators_list(self): # Go again with additional None and zero operators extra_ops = [*aux_ops, None, 0] - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=extra_ops + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 4) # expectation values @@ -191,11 +288,17 @@ def test_aux_operators_list(self): def test_aux_operators_dict(self): """Test dict-based aux_operators.""" - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} - algo = NumPyMinimumEigensolver() - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} + algo = NumPyMinimumEigensolver() + result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values @@ -207,7 +310,15 @@ def test_aux_operators_dict(self): # Go again with additional None and zero operators extra_ops = {**aux_ops, "None_operator": None, "zero_operator": 0} - result = algo.compute_minimum_eigenvalue(operator=self.qubit_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = algo.compute_minimum_eigenvalue( + operator=self.qubit_op, aux_operators=extra_ops + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue, -1.85727503 + 0j) self.assertEqual(len(result.aux_operator_eigenvalues), 3) # expectation values diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 9db5f02b312d..f454f3de1702 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -14,6 +14,7 @@ from __future__ import annotations import unittest +import warnings from typing import Tuple from test.python.algorithms import QiskitAlgorithmsTestCase @@ -72,7 +73,14 @@ def _run_test( observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): - result = estimate_observables(estimator, quantum_state, observables, None, self.threshold) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = estimate_observables( + estimator, quantum_state, observables, None, self.threshold + ) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) @@ -144,7 +152,13 @@ def test_estimate_observables_zero_op(self): state = bound_ansatz estimator = Estimator() observables = [SparsePauliOp(["XX", "YY"]), 0] - result = estimate_observables(estimator, state, observables, None, self.threshold) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = estimate_observables(estimator, state, observables, None, self.threshold) + self.assertTrue(len(caught_warnings) > 0) expected_result = [(0.015607318055509564, {}), (0.0, {})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] @@ -165,8 +179,14 @@ def test_estimate_observables_shots(self): bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator(options={"shots": 2048}) - observables = [PauliSumOp.from_list([("ZZ", 2.0)])] - result = estimate_observables(estimator, state, observables, None, self.threshold) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + observables = [PauliSumOp.from_list([("ZZ", 2.0)])] + result = estimate_observables(estimator, state, observables, None, self.threshold) + self.assertTrue(len(caught_warnings) > 0) exact_result = self.get_exact_expectation(bound_ansatz, observables) expected_result = [(exact_result[0][0], {"variance": 1.0898, "shots": 2048})] diff --git a/test/python/algorithms/test_phase_estimator.py b/test/python/algorithms/test_phase_estimator.py index d4f33620170e..63df5271ed02 100644 --- a/test/python/algorithms/test_phase_estimator.py +++ b/test/python/algorithms/test_phase_estimator.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2022. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -13,7 +13,7 @@ """Test phase estimation""" import unittest - +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np @@ -48,23 +48,35 @@ def hamiltonian_pe( """Run HamiltonianPhaseEstimation and return result with all phases.""" if backend is None: backend = qiskit.BasicAer.get_backend("statevector_simulator") - quantum_instance = qiskit.utils.QuantumInstance(backend=backend, shots=10000) - phase_est = HamiltonianPhaseEstimation( - num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance - ) - result = phase_est.estimate( - hamiltonian=hamiltonian, - state_preparation=state_preparation, - evolution=evolution, - bound=bound, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = qiskit.utils.QuantumInstance(backend=backend, shots=10000) + phase_est = HamiltonianPhaseEstimation( + num_evaluation_qubits=num_evaluation_qubits, quantum_instance=quantum_instance + ) + result = phase_est.estimate( + hamiltonian=hamiltonian, + state_preparation=state_preparation, + evolution=evolution, + bound=bound, + ) + self.assertTrue(len(caught_warnings) > 0) return result @data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 4)) def test_pauli_sum_1(self, evolution): """Two eigenvalues from Pauli sum with X, Z""" - hamiltonian = 0.5 * X + Z - state_preparation = StateFn(H.to_circuit()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = 0.5 * X + Z + state_preparation = StateFn(H.to_circuit()) + self.assertTrue(len(caught_warnings) > 0) result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution) phase_dict = result.filter_phases(0.162, as_float=True) @@ -77,7 +89,13 @@ def test_pauli_sum_1(self, evolution): @data(MatrixEvolution(), PauliTrotterEvolution("suzuki", 3)) def test_pauli_sum_2(self, evolution): """Two eigenvalues from Pauli sum with X, Y, Z""" - hamiltonian = 0.5 * X + Y + Z + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = 0.5 * X + Y + Z + self.assertTrue(len(caught_warnings) > 0) state_preparation = None result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evolution) @@ -92,13 +110,18 @@ def test_single_pauli_op(self): """Two eigenvalues from Pauli sum with X, Y, Z""" hamiltonian = Z state_preparation = None - result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=None) eigv = result.most_likely_eigenvalue with self.subTest("First eigenvalue"): self.assertAlmostEqual(eigv, 1.0, delta=0.001) - state_preparation = StateFn(X.to_circuit()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + state_preparation = StateFn(X.to_circuit()) + self.assertTrue(len(caught_warnings) > 0) result = self.hamiltonian_pe(hamiltonian, state_preparation, bound=1.05) eigv = result.most_likely_eigenvalue @@ -108,15 +131,21 @@ def test_single_pauli_op(self): @slow_test def test_H2_hamiltonian(self): """Test H2 hamiltonian""" - hamiltonian = ( - (-1.0523732457728587 * (I ^ I)) - + (0.3979374248431802 * (I ^ Z)) - + (-0.3979374248431802 * (Z ^ I)) - + (-0.011280104256235324 * (Z ^ Z)) - + (0.18093119978423147 * (X ^ X)) - ) - state_preparation = StateFn((I ^ H).to_circuit()) - evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=4) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = ( + (-1.0523732457728587 * (I ^ I)) + + (0.3979374248431802 * (I ^ Z)) + + (-0.3979374248431802 * (Z ^ I)) + + (-0.011280104256235324 * (Z ^ Z)) + + (0.18093119978423147 * (X ^ X)) + ) + state_preparation = StateFn((I ^ H).to_circuit()) + evo = PauliTrotterEvolution(trotter_mode="suzuki", reps=4) + self.assertTrue(len(caught_warnings) > 0) result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=evo) with self.subTest("Most likely eigenvalues"): @@ -132,23 +161,43 @@ def test_H2_hamiltonian(self): def test_matrix_evolution(self): """1Q Hamiltonian with MatrixEvolution""" - hamiltonian = (0.5 * X) + (0.6 * Y) + (0.7 * I) - state_preparation = None - result = self.hamiltonian_pe(hamiltonian, state_preparation, evolution=MatrixEvolution()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = (0.5 * X) + (0.6 * Y) + (0.7 * I) + state_preparation = None + result = self.hamiltonian_pe( + hamiltonian, state_preparation, evolution=MatrixEvolution() + ) + self.assertTrue(len(caught_warnings) > 0) phase_dict = result.filter_phases(0.2, as_float=True) phases = list(phase_dict.keys()) self.assertAlmostEqual(phases[0], 1.490, delta=0.001) self.assertAlmostEqual(phases[1], -0.090, delta=0.001) def _setup_from_bound(self, evolution, op_class): - hamiltonian = 0.5 * X + Y + Z + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = 0.5 * X + Y + Z + self.assertTrue(len(caught_warnings) > 0) state_preparation = None bound = 1.2 * sum(abs(hamiltonian.coeff * coeff) for coeff in hamiltonian.coeffs) if op_class == "MatrixOp": hamiltonian = hamiltonian.to_matrix_op() backend = qiskit.BasicAer.get_backend("statevector_simulator") - qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) - phase_est = HamiltonianPhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) + phase_est = HamiltonianPhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) + self.assertTrue(len(caught_warnings) > 0) result = phase_est.estimate( hamiltonian=hamiltonian, bound=bound, @@ -159,23 +208,35 @@ def _setup_from_bound(self, evolution, op_class): def test_from_bound(self): """HamiltonianPhaseEstimation with bound""" - for op_class in ("SummedOp", "MatrixOp"): - result = self._setup_from_bound(MatrixEvolution(), op_class) - cutoff = 0.01 - phases = result.filter_phases(cutoff) - with self.subTest(f"test phases has the correct length: {op_class}"): - self.assertEqual(len(phases), 2) - with self.subTest(f"test scaled phases are correct: {op_class}"): - self.assertEqual(list(phases.keys()), [1.5, -1.5]) - phases = result.filter_phases(cutoff, scaled=False) - with self.subTest(f"test unscaled phases are correct: {op_class}"): - self.assertEqual(list(phases.keys()), [0.25, 0.75]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for op_class in ("SummedOp", "MatrixOp"): + result = self._setup_from_bound(MatrixEvolution(), op_class) + cutoff = 0.01 + phases = result.filter_phases(cutoff) + with self.subTest(f"test phases has the correct length: {op_class}"): + self.assertEqual(len(phases), 2) + with self.subTest(f"test scaled phases are correct: {op_class}"): + self.assertEqual(list(phases.keys()), [1.5, -1.5]) + phases = result.filter_phases(cutoff, scaled=False) + with self.subTest(f"test unscaled phases are correct: {op_class}"): + self.assertEqual(list(phases.keys()), [0.25, 0.75]) + self.assertTrue(len(caught_warnings) > 0) def test_trotter_from_bound(self): """HamiltonianPhaseEstimation with bound and Trotterization""" - result = self._setup_from_bound( - PauliTrotterEvolution(trotter_mode="suzuki", reps=3), op_class="SummedOp" - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = self._setup_from_bound( + PauliTrotterEvolution(trotter_mode="suzuki", reps=3), op_class="SummedOp" + ) + self.assertTrue(len(caught_warnings) > 0) phase_dict = result.filter_phases(0.1) phases = list(phase_dict.keys()) with self.subTest("test phases has the correct length"): @@ -198,18 +259,29 @@ def hamiltonian_pe_sampler( phase_est = HamiltonianPhaseEstimation( num_evaluation_qubits=num_evaluation_qubits, sampler=sampler ) - result = phase_est.estimate( - hamiltonian=hamiltonian, - state_preparation=state_preparation, - evolution=evolution, - bound=bound, - ) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = phase_est.estimate( + hamiltonian=hamiltonian, + state_preparation=state_preparation, + evolution=evolution, + bound=bound, + ) return result @data(MatrixExponential(), SuzukiTrotter(reps=4)) def test_pauli_sum_1_sampler(self, evolution): """Two eigenvalues from Pauli sum with X, Z""" - hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1)])) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1)])) + self.assertTrue(len(caught_warnings) > 0) state_preparation = QuantumCircuit(1).compose(HGate()) result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution) @@ -223,7 +295,13 @@ def test_pauli_sum_1_sampler(self, evolution): @data(MatrixExponential(), SuzukiTrotter(reps=3)) def test_pauli_sum_2_sampler(self, evolution): """Two eigenvalues from Pauli sum with X, Y, Z""" - hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1), ("Y", 1)])) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Z", 1), ("Y", 1)])) + self.assertTrue(len(caught_warnings) > 0) state_preparation = None result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evolution) @@ -258,17 +336,24 @@ def test_single_pauli_op_sampler(self): def test_H2_hamiltonian_sampler(self, state_preparation): """Test H2 hamiltonian""" - hamiltonian = PauliSumOp( - SparsePauliOp.from_list( - [ - ("II", -1.0523732457728587), - ("IZ", 0.3979374248431802), - ("ZI", -0.3979374248431802), - ("ZZ", -0.011280104256235324), - ("XX", 0.18093119978423147), - ] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, ) - ) + hamiltonian = PauliSumOp( + SparsePauliOp.from_list( + [ + ("II", -1.0523732457728587), + ("IZ", 0.3979374248431802), + ("ZI", -0.3979374248431802), + ("ZZ", -0.011280104256235324), + ("XX", 0.18093119978423147), + ] + ) + ) + self.assertTrue(len(caught_warnings) > 0) + evo = SuzukiTrotter(reps=4) result = self.hamiltonian_pe_sampler(hamiltonian, state_preparation, evolution=evo) with self.subTest("Most likely eigenvalues"): @@ -284,7 +369,13 @@ def test_H2_hamiltonian_sampler(self, state_preparation): def test_matrix_evolution_sampler(self): """1Q Hamiltonian with MatrixEvolution""" - hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Y", 0.6), ("I", 0.7)])) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = PauliSumOp(SparsePauliOp.from_list([("X", 0.5), ("Y", 0.6), ("I", 0.7)])) + self.assertTrue(len(caught_warnings) > 0) state_preparation = None result = self.hamiltonian_pe_sampler( hamiltonian, state_preparation, evolution=MatrixExponential() @@ -313,16 +404,22 @@ def one_phase( if backend_type is None: backend_type = "qasm_simulator" backend = qiskit.BasicAer.get_backend(backend_type) - qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) if phase_estimator is None: phase_estimator = IterativePhaseEstimation - if phase_estimator == IterativePhaseEstimation: - p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi) - elif phase_estimator == PhaseEstimation: - p_est = PhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) - else: - raise ValueError("Unrecognized phase_estimator") - result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) + if phase_estimator == IterativePhaseEstimation: + p_est = IterativePhaseEstimation(num_iterations=num_iterations, quantum_instance=qi) + elif phase_estimator == PhaseEstimation: + p_est = PhaseEstimation(num_evaluation_qubits=6, quantum_instance=qi) + else: + raise ValueError("Unrecognized phase_estimator") + result = p_est.estimate(unitary=unitary_circuit, state_preparation=state_preparation) + self.assertTrue(len(caught_warnings) > 0) phase = result.phase return phase @@ -338,12 +435,17 @@ def one_phase( def test_qpe_Z(self, state_preparation, expected_phase, backend_type, phase_estimator): """eigenproblem Z, |0> and |1>""" unitary_circuit = Z.to_circuit() - phase = self.one_phase( - unitary_circuit, - state_preparation, - backend_type=backend_type, - phase_estimator=phase_estimator, - ) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + phase = self.one_phase( + unitary_circuit, + state_preparation, + backend_type=backend_type, + phase_estimator=phase_estimator, + ) self.assertEqual(phase, expected_phase) @data( @@ -394,17 +496,23 @@ def phase_estimation( """ if backend is None: backend = qiskit.BasicAer.get_backend("statevector_simulator") - qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) - phase_est = PhaseEstimation( - num_evaluation_qubits=num_evaluation_qubits, quantum_instance=qi - ) - if construct_circuit: - pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation) - result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits) - else: - result = phase_est.estimate( - unitary=unitary_circuit, state_preparation=state_preparation + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) + phase_est = PhaseEstimation( + num_evaluation_qubits=num_evaluation_qubits, quantum_instance=qi ) + if construct_circuit: + pe_circuit = phase_est.construct_circuit(unitary_circuit, state_preparation) + result = phase_est.estimate_from_pe_circuit(pe_circuit, unitary_circuit.num_qubits) + else: + result = phase_est.estimate( + unitary=unitary_circuit, state_preparation=state_preparation + ) + self.assertTrue(len(caught_warnings) > 0) return result @data(True, False) diff --git a/test/python/algorithms/test_qaoa.py b/test/python/algorithms/test_qaoa.py index 2998c1f17f25..893f17c655f8 100644 --- a/test/python/algorithms/test_qaoa.py +++ b/test/python/algorithms/test_qaoa.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test QAOA """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial @@ -62,18 +63,23 @@ def setUp(self): super().setUp() self.seed = 10598 algorithm_globals.random_seed = self.seed - - self.qasm_simulator = QuantumInstance( - BasicAer.get_backend("qasm_simulator"), - shots=4096, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) - self.statevector_simulator = QuantumInstance( - BasicAer.get_backend("statevector_simulator"), - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.qasm_simulator = QuantumInstance( + BasicAer.get_backend("qasm_simulator"), + shots=4096, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.statevector_simulator = QuantumInstance( + BasicAer.get_backend("statevector_simulator"), + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.assertTrue(len(caught_warnings) > 0) @idata( [ @@ -89,12 +95,16 @@ def test_qaoa(self, w, prob, m, solutions, convert_to_matrix_op): self.log.debug("Testing %s-step QAOA with MaxCut on graph\n%s", prob, w) qubit_op, _ = self._get_operator(w) - if convert_to_matrix_op: - qubit_op = qubit_op.to_matrix_op() - - qaoa = QAOA(COBYLA(), prob, mixer=m, quantum_instance=self.statevector_simulator) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + if convert_to_matrix_op: + qubit_op = qubit_op.to_matrix_op() + qaoa = QAOA(COBYLA(), prob, mixer=m, quantum_instance=self.statevector_simulator) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @@ -119,16 +129,26 @@ def test_qaoa_qc_mixer(self, w, prob, solutions, convert_to_matrix_op): optimizer = COBYLA() qubit_op, _ = self._get_operator(w) if convert_to_matrix_op: - qubit_op = qubit_op.to_matrix_op() - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qubit_op = qubit_op.to_matrix_op() + self.assertTrue(len(caught_warnings) > 0) num_qubits = qubit_op.num_qubits mixer = QuantumCircuit(num_qubits) theta = Parameter("θ") mixer.rx(theta, range(num_qubits)) qaoa = QAOA(optimizer, prob, mixer=mixer, quantum_instance=self.statevector_simulator) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @@ -145,7 +165,13 @@ def test_qaoa_qc_mixer_many_parameters(self): mixer.rx(theta, range(num_qubits)) qaoa = QAOA(optimizer, reps=2, mixer=mixer, quantum_instance=self.statevector_simulator) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) @@ -161,7 +187,13 @@ def test_qaoa_qc_mixer_no_parameters(self): mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(COBYLA(), reps=1, mixer=mixer, quantum_instance=self.statevector_simulator) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) @@ -171,7 +203,13 @@ def test_change_operator_size(self): np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(COBYLA(), 1, quantum_instance=self.statevector_simulator) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): @@ -189,8 +227,13 @@ def test_change_operator_size(self): ] ) ) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): @@ -215,8 +258,13 @@ def cb_callback(eval_count, parameters, mean, std): callback=cb_callback, quantum_instance=self.statevector_simulator, ) - - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) @@ -246,70 +294,89 @@ def test_qaoa_initial_state(self, w, init_state): initial_state.initialize(init_state, initial_state.qubits) zero_init_state = QuantumCircuit(QuantumRegister(qubit_op.num_qubits, "q")) - qaoa_zero_init_state = QAOA( - optimizer=optimizer, - initial_state=zero_init_state, - initial_point=init_pt, - quantum_instance=self.statevector_simulator, - ) - qaoa = QAOA( - optimizer=optimizer, - initial_state=initial_state, - initial_point=init_pt, - quantum_instance=self.statevector_simulator, - ) - - zero_circuits = qaoa_zero_init_state.construct_circuit(init_pt, qubit_op) - custom_circuits = qaoa.construct_circuit(init_pt, qubit_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qaoa_zero_init_state = QAOA( + optimizer=optimizer, + initial_state=zero_init_state, + initial_point=init_pt, + quantum_instance=self.statevector_simulator, + ) + qaoa = QAOA( + optimizer=optimizer, + initial_state=initial_state, + initial_point=init_pt, + quantum_instance=self.statevector_simulator, + ) + zero_circuits = qaoa_zero_init_state.construct_circuit(init_pt, qubit_op) + custom_circuits = qaoa.construct_circuit(init_pt, qubit_op) - self.assertEqual(len(zero_circuits), len(custom_circuits)) + self.assertEqual(len(zero_circuits), len(custom_circuits)) - for zero_circ, custom_circ in zip(zero_circuits, custom_circuits): + for zero_circ, custom_circ in zip(zero_circuits, custom_circuits): - z_length = len(zero_circ.data) - c_length = len(custom_circ.data) + z_length = len(zero_circ.data) + c_length = len(custom_circ.data) - self.assertGreaterEqual(c_length, z_length) - self.assertTrue(zero_circ.data == custom_circ.data[-z_length:]) + self.assertGreaterEqual(c_length, z_length) + self.assertTrue(zero_circ.data == custom_circ.data[-z_length:]) - custom_init_qc = QuantumCircuit(custom_circ.num_qubits) - custom_init_qc.data = custom_circ.data[0 : c_length - z_length] + custom_init_qc = QuantumCircuit(custom_circ.num_qubits) + custom_init_qc.data = custom_circ.data[0 : c_length - z_length] - if initial_state is None: - original_init_qc = QuantumCircuit(qubit_op.num_qubits) - original_init_qc.h(range(qubit_op.num_qubits)) - else: - original_init_qc = initial_state + if initial_state is None: + original_init_qc = QuantumCircuit(qubit_op.num_qubits) + original_init_qc.h(range(qubit_op.num_qubits)) + else: + original_init_qc = initial_state - job_init_state = self.statevector_simulator.execute(original_init_qc) - job_qaoa_init_state = self.statevector_simulator.execute(custom_init_qc) + job_init_state = self.statevector_simulator.execute(original_init_qc) + job_qaoa_init_state = self.statevector_simulator.execute(custom_init_qc) - statevector_original = job_init_state.get_statevector(original_init_qc) - statevector_custom = job_qaoa_init_state.get_statevector(custom_init_qc) + statevector_original = job_init_state.get_statevector(original_init_qc) + statevector_custom = job_qaoa_init_state.get_statevector(custom_init_qc) - self.assertListEqual(statevector_original.tolist(), statevector_custom.tolist()) + self.assertListEqual(statevector_original.tolist(), statevector_custom.tolist()) + self.assertTrue(len(caught_warnings) > 0) def test_qaoa_random_initial_point(self): """QAOA random initial point""" w = rx.adjacency_matrix( rx.undirected_gnp_random_graph(5, 0.5, seed=algorithm_globals.random_seed) ) - qubit_op, _ = self._get_operator(w) - qaoa = QAOA(optimizer=NELDER_MEAD(disp=True), reps=1, quantum_instance=self.qasm_simulator) - result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qubit_op, _ = self._get_operator(w) + qaoa = QAOA( + optimizer=NELDER_MEAD(disp=True), reps=1, quantum_instance=self.qasm_simulator + ) + result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) + self.assertTrue(len(caught_warnings) > 0) + self.assertTrue(len(caught_warnings) > 0) self.assertLess(result.eigenvalue, -0.97) def test_qaoa_construct_circuit_update(self): """Test updating operators with QAOA construct_circuit""" - qaoa = QAOA() - ref = qaoa.construct_circuit([0, 0], I ^ Z)[0] - circ2 = qaoa.construct_circuit([0, 0], I ^ Z)[0] - self.assertEqual(circ2, ref) - circ3 = qaoa.construct_circuit([0, 0], Z ^ I)[0] - self.assertNotEqual(circ3, ref) - circ4 = qaoa.construct_circuit([0, 0], I ^ Z)[0] - self.assertEqual(circ4, ref) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qaoa = QAOA() + ref = qaoa.construct_circuit([0, 0], I ^ Z)[0] + circ2 = qaoa.construct_circuit([0, 0], I ^ Z)[0] + self.assertEqual(circ2, ref) + circ3 = qaoa.construct_circuit([0, 0], Z ^ I)[0] + self.assertNotEqual(circ3, ref) + circ4 = qaoa.construct_circuit([0, 0], I ^ Z)[0] + self.assertEqual(circ4, ref) + self.assertTrue(len(caught_warnings) > 0) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" @@ -317,7 +384,13 @@ def test_optimizer_scipy_callable(self): optimizer=partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), quantum_instance=self.statevector_simulator, ) - result = qaoa.compute_minimum_eigenvalue(Z) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = qaoa.compute_minimum_eigenvalue(Z) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(result.cost_function_evals, 4) def _get_operator(self, weight_matrix): @@ -344,7 +417,12 @@ def _get_operator(self, weight_matrix): pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] - return PauliSumOp.from_list(opflow_list), shift + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + return PauliSumOp.from_list(opflow_list), shift def _get_graph_solution(self, x: np.ndarray) -> str: """Get graph solution from binary string. diff --git a/test/python/algorithms/test_shor.py b/test/python/algorithms/test_shor.py index 8f22714cb97b..24854057c852 100644 --- a/test/python/algorithms/test_shor.py +++ b/test/python/algorithms/test_shor.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2022. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -70,22 +70,13 @@ def test_shor_factoring_5_bit_number(self, n_v, backend, factors): def _test_shor_factoring(self, backend, factors, n_v): """shor factoring test""" - from qiskit_aer import Aer - with warnings.catch_warnings(record=True) as caught_warnings: + with warnings.catch_warnings(record=True): warnings.simplefilter("always") from qiskit_aer import Aer - shor = Shor(quantum_instance=QuantumInstance(Aer.get_backend(backend), shots=1000)) - found = False - for caught_warning in caught_warnings: - if "Shor class is deprecated" in str(caught_warning.message): - found = True - break - - if not found: - self.fail("Shor class is not emitting deprecation message.") - return + with self.assertWarnsRegex(DeprecationWarning, "Shor class is deprecated"): + shor = Shor(quantum_instance=QuantumInstance(Aer.get_backend(backend), shots=1000)) result = shor.factor(N=n_v) self.assertListEqual(result.factors[0], factors) diff --git a/test/python/algorithms/test_skip_qobj_validation.py b/test/python/algorithms/test_skip_qobj_validation.py index dc7b7a0e5c19..d18906277816 100644 --- a/test/python/algorithms/test_skip_qobj_validation.py +++ b/test/python/algorithms/test_skip_qobj_validation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2020. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -13,7 +13,7 @@ """ Test Skip Qobj Validation """ import unittest - +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer @@ -63,18 +63,24 @@ def setUp(self): def test_wo_backend_options(self): """without backend options test""" - quantum_instance = QuantumInstance( - self.backend, - seed_transpiler=self.random_seed, - seed_simulator=self.random_seed, - shots=1024, - ) - # run without backend_options and without noise - res_wo_bo = quantum_instance.execute(self.qc).get_counts(self.qc) - self.assertGreaterEqual(quantum_instance.time_taken, 0.0) - quantum_instance.reset_execution_results() - quantum_instance.skip_qobj_validation = True - res_wo_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + self.backend, + seed_transpiler=self.random_seed, + seed_simulator=self.random_seed, + shots=1024, + ) + # run without backend_options and without noise + res_wo_bo = quantum_instance.execute(self.qc).get_counts(self.qc) + self.assertGreaterEqual(quantum_instance.time_taken, 0.0) + quantum_instance.reset_execution_results() + quantum_instance.skip_qobj_validation = True + res_wo_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) + self.assertTrue(len(caught_warnings) > 0) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_wo_bo, res_wo_bo_skip_validation)) @@ -82,18 +88,24 @@ def test_wo_backend_options(self): def test_w_backend_options(self): """with backend options test""" # run with backend_options - quantum_instance = QuantumInstance( - self.backend, - seed_transpiler=self.random_seed, - seed_simulator=self.random_seed, - shots=1024, - backend_options={"initial_statevector": [0.5, 0.5, 0.5, 0.5]}, - ) - res_w_bo = quantum_instance.execute(self.qc).get_counts(self.qc) - self.assertGreaterEqual(quantum_instance.time_taken, 0.0) - quantum_instance.reset_execution_results() - quantum_instance.skip_qobj_validation = True - res_w_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + self.backend, + seed_transpiler=self.random_seed, + seed_simulator=self.random_seed, + shots=1024, + backend_options={"initial_statevector": [0.5, 0.5, 0.5, 0.5]}, + ) + res_w_bo = quantum_instance.execute(self.qc).get_counts(self.qc) + self.assertGreaterEqual(quantum_instance.time_taken, 0.0) + quantum_instance.reset_execution_results() + quantum_instance.skip_qobj_validation = True + res_w_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) + self.assertTrue(len(caught_warnings) > 0) self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_w_bo, res_w_bo_skip_validation)) @@ -116,26 +128,38 @@ def test_w_noise(self): noise_model = NoiseModel() noise_model.add_readout_error([probs_given0, probs_given1], [0]) - quantum_instance = QuantumInstance( - self.backend, - seed_transpiler=self.random_seed, - seed_simulator=self.random_seed, - shots=1024, - noise_model=noise_model, - ) - res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc) - - quantum_instance.skip_qobj_validation = True - res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) - self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation)) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + self.backend, + seed_transpiler=self.random_seed, + seed_simulator=self.random_seed, + shots=1024, + noise_model=noise_model, + ) + res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc) + quantum_instance.skip_qobj_validation = True + res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) + self.assertTrue(len(caught_warnings) > 0) - # BasicAer should fail: - with self.assertRaises(QiskitError): - _ = QuantumInstance(BasicAer.get_backend("qasm_simulator"), noise_model=noise_model) + self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation)) - with self.assertRaises(QiskitError): - quantum_instance = QuantumInstance(BasicAer.get_backend("qasm_simulator")) - quantum_instance.set_config(noise_model=noise_model) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # BasicAer should fail: + with self.assertRaises(QiskitError): + _ = QuantumInstance(BasicAer.get_backend("qasm_simulator"), noise_model=noise_model) + + with self.assertRaises(QiskitError): + quantum_instance = QuantumInstance(BasicAer.get_backend("qasm_simulator")) + quantum_instance.set_config(noise_model=noise_model) + self.assertTrue(len(caught_warnings) > 0) if __name__ == "__main__": diff --git a/test/python/algorithms/test_vqd.py b/test/python/algorithms/test_vqd.py index 72d82568df9c..07fc63f58cc3 100644 --- a/test/python/algorithms/test_vqd.py +++ b/test/python/algorithms/test_vqd.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -13,6 +13,7 @@ """ Test VQD """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np @@ -55,17 +56,9 @@ def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed - self.h2_op = ( - -1.052373245772859 * (I ^ I) - + 0.39793742484318045 * (I ^ Z) - - 0.39793742484318045 * (Z ^ I) - - 0.01128010425623538 * (Z ^ Z) - + 0.18093119978423156 * (X ^ X) - ) self.h2_energy = -1.85727503 self.h2_energy_excited = [-1.85727503, -1.24458455] - self.test_op = MatrixOp(np.diagflat([3, 5, -1, 0.8, 0.2, 2, 1, -3])).to_pauli_op() self.test_results = [-3, -1] self.ryrz_wavefunction = TwoLocal( @@ -73,18 +66,32 @@ def setUp(self): ) self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") - self.qasm_simulator = QuantumInstance( - BasicAer.get_backend("qasm_simulator"), - shots=2048, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) - self.statevector_simulator = QuantumInstance( - BasicAer.get_backend("statevector_simulator"), - shots=1, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.h2_op = ( + -1.052373245772859 * (I ^ I) + + 0.39793742484318045 * (I ^ Z) + - 0.39793742484318045 * (Z ^ I) + - 0.01128010425623538 * (Z ^ Z) + + 0.18093119978423156 * (X ^ X) + ) + self.test_op = MatrixOp(np.diagflat([3, 5, -1, 0.8, 0.2, 2, 1, -3])).to_pauli_op() + self.qasm_simulator = QuantumInstance( + BasicAer.get_backend("qasm_simulator"), + shots=2048, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.statevector_simulator = QuantumInstance( + BasicAer.get_backend("statevector_simulator"), + shots=1, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.assertTrue(len(caught_warnings) > 0) @slow_test def test_basic_aer_statevector(self): @@ -102,8 +109,13 @@ def test_basic_aer_statevector(self): seed_transpiler=algorithm_globals.random_seed, ), ) - - result = vqd.compute_eigenvalues(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) with self.subTest(msg="test eigenvalue"): np.testing.assert_array_almost_equal( @@ -123,14 +135,20 @@ def test_mismatching_num_qubits(self): """Ensuring circuit and operator mismatch is caught""" wavefunction = QuantumCircuit(1) optimizer = SLSQP(maxiter=50) - vqd = VQD( - k=1, - ansatz=wavefunction, - optimizer=optimizer, - quantum_instance=self.statevector_simulator, - ) - with self.assertRaises(AlgorithmError): - _ = vqd.compute_eigenvalues(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + k=1, + ansatz=wavefunction, + optimizer=optimizer, + quantum_instance=self.statevector_simulator, + ) + with self.assertRaises(AlgorithmError): + _ = vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) @data( (MatrixExpectation(), 1), @@ -142,10 +160,15 @@ def test_construct_circuit(self, expectation, num_circuits): """Test construct circuits returns QuantumCircuits and the right number of them.""" try: wavefunction = EfficientSU2(2, reps=1) - vqd = VQD(k=2, ansatz=wavefunction, expectation=expectation) - params = [0] * wavefunction.num_parameters - circuits = vqd.construct_circuit(parameter=params, operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD(k=2, ansatz=wavefunction, expectation=expectation) + params = [0] * wavefunction.num_parameters + circuits = vqd.construct_circuit(parameter=params, operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(circuits), num_circuits) for circuit in circuits: self.assertIsInstance(circuit, QuantumCircuit) @@ -156,26 +179,43 @@ def test_construct_circuit(self, expectation, num_circuits): def test_missing_varform_params(self): """Test specifying a variational form with no parameters raises an error.""" circuit = QuantumCircuit(self.h2_op.num_qubits) - vqd = VQD( - k=1, ansatz=circuit, quantum_instance=BasicAer.get_backend("statevector_simulator") - ) - with self.assertRaises(RuntimeError): - vqd.compute_eigenvalues(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + k=1, ansatz=circuit, quantum_instance=BasicAer.get_backend("statevector_simulator") + ) + with self.assertRaises(RuntimeError): + vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) def test_basic_aer_qasm(self): """Test the VQD on BasicAer's QASM simulator.""" optimizer = COBYLA(maxiter=1000) wavefunction = self.ry_wavefunction - vqd = VQD( - ansatz=wavefunction, - optimizer=optimizer, - max_evals_grouped=1, - quantum_instance=self.qasm_simulator, - ) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + ansatz=wavefunction, + optimizer=optimizer, + max_evals_grouped=1, + quantum_instance=self.qasm_simulator, + ) + self.assertTrue(len(caught_warnings) > 0) # TODO benchmark this later. - result = vqd.compute_eigenvalues(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=1 ) @@ -187,20 +227,25 @@ def test_with_aer_statevector(self): wavefunction = self.ry_wavefunction optimizer = L_BFGS_B() - quantum_instance = QuantumInstance( - backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - vqd = VQD( - k=2, - ansatz=wavefunction, - optimizer=optimizer, - max_evals_grouped=1, - quantum_instance=quantum_instance, - ) - - result = vqd.compute_eigenvalues(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqd = VQD( + k=2, + ansatz=wavefunction, + optimizer=optimizer, + max_evals_grouped=1, + quantum_instance=quantum_instance, + ) + result = vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=2 ) @@ -212,22 +257,34 @@ def test_with_aer_qasm(self): optimizer = COBYLA(maxiter=1000) wavefunction = self.ry_wavefunction - quantum_instance = QuantumInstance( - backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - - vqd = VQD( - k=2, - ansatz=wavefunction, - optimizer=optimizer, - expectation=PauliExpectation(), - quantum_instance=quantum_instance, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqd = VQD( + k=2, + ansatz=wavefunction, + optimizer=optimizer, + expectation=PauliExpectation(), + quantum_instance=quantum_instance, + ) - result = vqd.compute_eigenvalues(operator=self.h2_op) + vqd = VQD( + k=2, + ansatz=wavefunction, + optimizer=optimizer, + expectation=PauliExpectation(), + quantum_instance=quantum_instance, + ) + result = vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=1 ) @@ -240,21 +297,26 @@ def test_with_aer_qasm_snapshot_mode(self): optimizer = COBYLA(maxiter=400) wavefunction = self.ryrz_wavefunction - quantum_instance = QuantumInstance( - backend, - shots=100, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - vqd = VQD( - k=2, - ansatz=wavefunction, - optimizer=optimizer, - expectation=AerPauliExpectation(), - quantum_instance=quantum_instance, - ) - - result = vqd.compute_eigenvalues(operator=self.test_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend, + shots=100, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqd = VQD( + k=2, + ansatz=wavefunction, + optimizer=optimizer, + expectation=AerPauliExpectation(), + quantum_instance=quantum_instance, + ) + result = vqd.compute_eigenvalues(operator=self.test_op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(result.eigenvalues.real, self.test_results, decimal=1) def test_callback(self): @@ -271,14 +333,19 @@ def store_intermediate_result(eval_count, parameters, mean, std, step): optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction - vqd = VQD( - ansatz=wavefunction, - optimizer=optimizer, - callback=store_intermediate_result, - quantum_instance=self.qasm_simulator, - ) - vqd.compute_eigenvalues(operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + ansatz=wavefunction, + optimizer=optimizer, + callback=store_intermediate_result, + quantum_instance=self.qasm_simulator, + ) + vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(std, float) for std in history["std"])) @@ -299,38 +366,73 @@ def store_intermediate_result(eval_count, parameters, mean, std, step): def test_reuse(self): """Test re-using a VQD algorithm instance.""" vqd = VQD(k=1) - with self.subTest(msg="assert running empty raises AlgorithmError"): - with self.assertRaises(AlgorithmError): - _ = vqd.compute_eigenvalues(operator=self.h2_op) - + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.subTest(msg="assert running empty raises AlgorithmError"): + with self.assertRaises(AlgorithmError): + _ = vqd.compute_eigenvalues(operator=self.h2_op) ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqd.ansatz = ansatz - with self.subTest(msg="assert missing operator raises AlgorithmError"): - with self.assertRaises(AlgorithmError): - _ = vqd.compute_eigenvalues(operator=self.h2_op) - - vqd.expectation = MatrixExpectation() - vqd.quantum_instance = self.statevector_simulator - with self.subTest(msg="assert VQE works once all info is available"): - result = vqd.compute_eigenvalues(operator=self.h2_op) - np.testing.assert_array_almost_equal(result.eigenvalues.real, self.h2_energy, decimal=2) - - operator = PrimitiveOp(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) - - with self.subTest(msg="assert minimum eigensolver interface works"): - result = vqd.compute_eigenvalues(operator=operator) - self.assertAlmostEqual(result.eigenvalues.real[0], -1.0, places=5) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.subTest(msg="assert missing operator raises AlgorithmError"): + with self.assertRaises(AlgorithmError): + _ = vqd.compute_eigenvalues(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd.expectation = MatrixExpectation() + vqd.quantum_instance = self.statevector_simulator + with self.subTest(msg="assert VQE works once all info is available"): + result = vqd.compute_eigenvalues(operator=self.h2_op) + np.testing.assert_array_almost_equal( + result.eigenvalues.real, self.h2_energy, decimal=2 + ) + self.assertTrue(len(caught_warnings) > 0) + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operator = PrimitiveOp( + np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]) + ) + with self.subTest(msg="assert minimum eigensolver interface works"): + result = vqd.compute_eigenvalues(operator=operator) + self.assertAlmostEqual(result.eigenvalues.real[0], -1.0, places=5) + self.assertTrue(len(caught_warnings) > 0) def test_vqd_optimizer(self): """Test running same VQD twice to re-use optimizer, then switch optimizer""" - vqd = VQD( - k=2, - optimizer=SLSQP(), - quantum_instance=QuantumInstance(BasicAer.get_backend("statevector_simulator")), - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + k=2, + optimizer=SLSQP(), + quantum_instance=QuantumInstance(BasicAer.get_backend("statevector_simulator")), + ) + self.assertTrue(len(caught_warnings) > 0) def run_check(): - result = vqd.compute_eigenvalues(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=3 ) @@ -347,23 +449,34 @@ def run_check(): @data(MatrixExpectation(), None) def test_backend_change(self, user_expectation): """Test that VQE works when backend changes.""" - vqd = VQD( - k=1, - ansatz=TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz"), - optimizer=SLSQP(maxiter=2), - expectation=user_expectation, - quantum_instance=BasicAer.get_backend("statevector_simulator"), - ) - result0 = vqd.compute_eigenvalues(operator=self.h2_op) - if user_expectation is not None: - with self.subTest("User expectation kept."): - self.assertEqual(vqd.expectation, user_expectation) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + k=1, + ansatz=TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz"), + optimizer=SLSQP(maxiter=2), + expectation=user_expectation, + quantum_instance=BasicAer.get_backend("statevector_simulator"), + ) + result0 = vqd.compute_eigenvalues(operator=self.h2_op) + if user_expectation is not None: + with self.subTest("User expectation kept."): + self.assertEqual(vqd.expectation, user_expectation) - vqd.quantum_instance = BasicAer.get_backend("qasm_simulator") + vqd.quantum_instance = BasicAer.get_backend("qasm_simulator") + self.assertTrue(len(caught_warnings) > 0) # works also if no expectation is set, since it will be determined automatically - result1 = vqd.compute_eigenvalues(operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result1 = vqd.compute_eigenvalues(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) if user_expectation is not None: with self.subTest("Change backend with user expectation, it is kept."): self.assertEqual(vqd.expectation, user_expectation) @@ -373,43 +486,67 @@ def test_backend_change(self, user_expectation): def test_set_ansatz_to_none(self): """Tests that setting the ansatz to None results in the default behavior""" - vqd = VQD( - k=1, - ansatz=self.ryrz_wavefunction, - optimizer=L_BFGS_B(), - quantum_instance=self.statevector_simulator, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + k=1, + ansatz=self.ryrz_wavefunction, + optimizer=L_BFGS_B(), + quantum_instance=self.statevector_simulator, + ) + self.assertTrue(len(caught_warnings) > 0) vqd.ansatz = None self.assertIsInstance(vqd.ansatz, RealAmplitudes) def test_set_optimizer_to_none(self): """Tests that setting the optimizer to None results in the default behavior""" - vqd = VQD( - k=1, - ansatz=self.ryrz_wavefunction, - optimizer=L_BFGS_B(), - quantum_instance=self.statevector_simulator, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + k=1, + ansatz=self.ryrz_wavefunction, + optimizer=L_BFGS_B(), + quantum_instance=self.statevector_simulator, + ) + self.assertTrue(len(caught_warnings) > 0) vqd.optimizer = None self.assertIsInstance(vqd.optimizer, SLSQP) def test_aux_operators_list(self): """Test list-based aux_operators.""" wavefunction = self.ry_wavefunction - vqd = VQD(k=2, ansatz=wavefunction, quantum_instance=self.statevector_simulator) # Start with an empty list - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD(k=2, ansatz=wavefunction, quantum_instance=self.statevector_simulator) + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=[]) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=2 ) self.assertIsNone(result.aux_operator_eigenvalues) # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=2 ) @@ -423,7 +560,13 @@ def test_aux_operators_list(self): # Go again with additional None and zero operators extra_ops = [*aux_ops, None, 0] - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=2 ) @@ -441,20 +584,32 @@ def test_aux_operators_list(self): def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" wavefunction = self.ry_wavefunction - vqd = VQD(ansatz=wavefunction, quantum_instance=self.statevector_simulator) # Start with an empty dictionary - result = vqd.compute_eigenvalues(self.h2_op, aux_operators={}) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD(ansatz=wavefunction, quantum_instance=self.statevector_simulator) + result = vqd.compute_eigenvalues(self.h2_op, aux_operators={}) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited, decimal=2 ) self.assertIsNone(result.aux_operator_eigenvalues) # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 2) self.assertEqual(len(result.eigenstates), 2) self.assertEqual(result.eigenvalues.dtype, np.complex128) @@ -470,7 +625,13 @@ def test_aux_operators_dict(self): # Go again with additional None and zero operators extra_ops = {**aux_ops, "None_operator": None, "zero_operator": 0} - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.eigenvalues), 2) self.assertEqual(len(result.eigenstates), 2) self.assertEqual(result.eigenvalues.dtype, np.complex128) @@ -490,28 +651,34 @@ def test_aux_operators_dict(self): def test_aux_operator_std_dev_pauli(self): """Test non-zero standard deviations of aux operators with PauliExpectation.""" wavefunction = self.ry_wavefunction - vqd = VQD( - ansatz=wavefunction, - expectation=PauliExpectation(), - initial_point=[ - 1.70256666, - -5.34843975, - -0.39542903, - 5.99477786, - -2.74374986, - -4.85284669, - 0.2442925, - -1.51638917, - ], - optimizer=COBYLA(maxiter=0), - quantum_instance=self.qasm_simulator, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + ansatz=wavefunction, + expectation=PauliExpectation(), + initial_point=[ + 1.70256666, + -5.34843975, + -0.39542903, + 5.99477786, + -2.74374986, + -4.85284669, + 0.2442925, + -1.51638917, + ], + optimizer=COBYLA(maxiter=0), + quantum_instance=self.qasm_simulator, + ) - # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + # Go again with two auxiliary operators + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][0], 2.0, places=1) @@ -526,7 +693,13 @@ def test_aux_operator_std_dev_pauli(self): # Go again with additional None and zero operators aux_ops = [*aux_ops, None, 0] - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues[0]), 4) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][0], 2.0, places=1) @@ -547,23 +720,29 @@ def test_aux_operator_std_dev_pauli(self): def test_aux_operator_std_dev_aer_pauli(self): """Test non-zero standard deviations of aux operators with AerPauliExpectation.""" wavefunction = self.ry_wavefunction - vqd = VQD( - ansatz=wavefunction, - expectation=AerPauliExpectation(), - optimizer=COBYLA(maxiter=0), - quantum_instance=QuantumInstance( - backend=Aer.get_backend("qasm_simulator"), - shots=1, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ), - ) # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqd = VQD( + ansatz=wavefunction, + expectation=AerPauliExpectation(), + optimizer=COBYLA(maxiter=0), + quantum_instance=QuantumInstance( + backend=Aer.get_backend("qasm_simulator"), + shots=1, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ), + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][0], 2.0, places=1) @@ -576,7 +755,13 @@ def test_aux_operator_std_dev_aer_pauli(self): # Go again with additional None and zero operators aux_ops = [*aux_ops, None, 0] - result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqd.compute_eigenvalues(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues[-1]), 4) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0][0], 2.0, places=6) diff --git a/test/python/algorithms/test_vqe.py b/test/python/algorithms/test_vqe.py index ae1d57824712..2068312dfedb 100644 --- a/test/python/algorithms/test_vqe.py +++ b/test/python/algorithms/test_vqe.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -14,6 +14,7 @@ import logging import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from test.python.transpiler._dummy_passes import DummyAP @@ -52,10 +53,7 @@ from qiskit.quantum_info import Statevector from qiskit.transpiler import PassManager, PassManagerConfig from qiskit.transpiler.preset_passmanagers import level_1_pass_manager -from qiskit.utils import QuantumInstance, algorithm_globals, has_aer - -if has_aer(): - from qiskit import Aer +from qiskit.utils import QuantumInstance, algorithm_globals, optionals logger = "LocalLogger" @@ -89,47 +87,58 @@ def setUp(self): super().setUp() self.seed = 50 algorithm_globals.random_seed = self.seed - self.h2_op = ( - -1.052373245772859 * (I ^ I) - + 0.39793742484318045 * (I ^ Z) - - 0.39793742484318045 * (Z ^ I) - - 0.01128010425623538 * (Z ^ Z) - + 0.18093119978423156 * (X ^ X) - ) self.h2_energy = -1.85727503 self.ryrz_wavefunction = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") self.ry_wavefunction = TwoLocal(rotation_blocks="ry", entanglement_blocks="cz") - self.qasm_simulator = QuantumInstance( - BasicAer.get_backend("qasm_simulator"), - shots=1024, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) - self.statevector_simulator = QuantumInstance( - BasicAer.get_backend("statevector_simulator"), - shots=1, - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.h2_op = ( + -1.052373245772859 * (I ^ I) + + 0.39793742484318045 * (I ^ Z) + - 0.39793742484318045 * (Z ^ I) + - 0.01128010425623538 * (Z ^ Z) + + 0.18093119978423156 * (X ^ X) + ) + self.qasm_simulator = QuantumInstance( + BasicAer.get_backend("qasm_simulator"), + shots=1024, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.statevector_simulator = QuantumInstance( + BasicAer.get_backend("statevector_simulator"), + shots=1, + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.assertTrue(len(caught_warnings) > 0) def test_basic_aer_statevector(self): """Test the VQE on BasicAer's statevector simulator.""" wavefunction = self.ryrz_wavefunction - vqe = VQE( - ansatz=wavefunction, - optimizer=L_BFGS_B(), - quantum_instance=QuantumInstance( - BasicAer.get_backend("statevector_simulator"), - basis_gates=["u1", "u2", "u3", "cx", "id"], - coupling_map=[[0, 1]], - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ), - ) - - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=L_BFGS_B(), + quantum_instance=QuantumInstance( + BasicAer.get_backend("statevector_simulator"), + basis_gates=["u1", "u2", "u3", "cx", "id"], + coupling_map=[[0, 1]], + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ), + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) with self.subTest(msg="test eigenvalue"): self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy) @@ -147,10 +156,18 @@ def test_circuit_input(self): """Test running the VQE on a plain QuantumCircuit object.""" wavefunction = QuantumCircuit(2).compose(EfficientSU2(2)) optimizer = SLSQP(maxiter=50) - vqe = VQE( - ansatz=wavefunction, optimizer=optimizer, quantum_instance=self.statevector_simulator - ) - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + quantum_instance=self.statevector_simulator, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) @data( @@ -163,9 +180,15 @@ def test_construct_circuit(self, expectation, num_circuits): """Test construct circuits returns QuantumCircuits and the right number of them.""" try: wavefunction = EfficientSU2(2, reps=1) - vqe = VQE(ansatz=wavefunction, expectation=expectation) - params = [0] * wavefunction.num_parameters - circuits = vqe.construct_circuit(parameter=params, operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE(ansatz=wavefunction, expectation=expectation) + params = [0] * wavefunction.num_parameters + circuits = vqe.construct_circuit(parameter=params, operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(circuits), num_circuits) for circuit in circuits: @@ -177,9 +200,17 @@ def test_construct_circuit(self, expectation, num_circuits): def test_missing_varform_params(self): """Test specifying a variational form with no parameters raises an error.""" circuit = QuantumCircuit(self.h2_op.num_qubits) - vqe = VQE(ansatz=circuit, quantum_instance=BasicAer.get_backend("statevector_simulator")) - with self.assertRaises(RuntimeError): - vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=circuit, quantum_instance=BasicAer.get_backend("statevector_simulator") + ) + with self.assertRaises(RuntimeError): + vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) @data( (SLSQP(maxiter=50), 5, 4), @@ -188,13 +219,19 @@ def test_missing_varform_params(self): @unpack def test_max_evals_grouped(self, optimizer, places, max_evals_grouped): """VQE Optimizers test""" - vqe = VQE( - ansatz=self.ryrz_wavefunction, - optimizer=optimizer, - max_evals_grouped=max_evals_grouped, - quantum_instance=self.statevector_simulator, - ) - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=self.ryrz_wavefunction, + optimizer=optimizer, + max_evals_grouped=max_evals_grouped, + quantum_instance=self.statevector_simulator, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=places) def test_basic_aer_qasm(self): @@ -202,97 +239,142 @@ def test_basic_aer_qasm(self): optimizer = SPSA(maxiter=300, last_avg=5) wavefunction = self.ry_wavefunction - vqe = VQE( - ansatz=wavefunction, - optimizer=optimizer, - max_evals_grouped=1, - quantum_instance=self.qasm_simulator, - ) - # TODO benchmark this later. - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + max_evals_grouped=1, + quantum_instance=self.qasm_simulator, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.86823, places=2) def test_qasm_eigenvector_normalized(self): """Test VQE with qasm_simulator returns normalized eigenvector.""" wavefunction = self.ry_wavefunction - vqe = VQE(ansatz=wavefunction, quantum_instance=self.qasm_simulator) - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE(ansatz=wavefunction, quantum_instance=self.qasm_simulator) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) amplitudes = list(result.eigenstate.values()) self.assertAlmostEqual(np.linalg.norm(amplitudes), 1.0, places=4) - @unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.") + @unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests") def test_with_aer_statevector(self): """Test VQE with Aer's statevector_simulator.""" - backend = Aer.get_backend("aer_simulator_statevector") + from qiskit_aer import AerSimulator + + backend = AerSimulator(method="statevector") wavefunction = self.ry_wavefunction optimizer = L_BFGS_B() - quantum_instance = QuantumInstance( - backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - vqe = VQE( - ansatz=wavefunction, - optimizer=optimizer, - max_evals_grouped=1, - quantum_instance=quantum_instance, - ) - - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + max_evals_grouped=1, + quantum_instance=quantum_instance, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) - @unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.") + @unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests") def test_with_aer_qasm(self): """Test VQE with Aer's qasm_simulator.""" - backend = Aer.get_backend("aer_simulator") + from qiskit_aer import AerSimulator + + backend = AerSimulator() optimizer = SPSA(maxiter=200, last_avg=5) wavefunction = self.ry_wavefunction - quantum_instance = QuantumInstance( - backend, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - - vqe = VQE( - ansatz=wavefunction, - optimizer=optimizer, - expectation=PauliExpectation(), - quantum_instance=quantum_instance, - ) - - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + expectation=PauliExpectation(), + quantum_instance=quantum_instance, + ) + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + expectation=PauliExpectation(), + quantum_instance=quantum_instance, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.86305, places=2) - @unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.") + @unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests") def test_with_aer_qasm_snapshot_mode(self): """Test the VQE using Aer's qasm_simulator snapshot mode.""" + from qiskit_aer import AerSimulator - backend = Aer.get_backend("aer_simulator") + backend = AerSimulator() optimizer = L_BFGS_B() wavefunction = self.ry_wavefunction - quantum_instance = QuantumInstance( - backend, - shots=1, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - vqe = VQE( - ansatz=wavefunction, - optimizer=optimizer, - expectation=AerPauliExpectation(), - quantum_instance=quantum_instance, - ) - - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend, + shots=1, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + expectation=AerPauliExpectation(), + quantum_instance=quantum_instance, + ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) - @unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.") + @unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests") @data( CG(maxiter=1), L_BFGS_B(maxfun=1), @@ -302,54 +384,68 @@ def test_with_aer_qasm_snapshot_mode(self): ) def test_with_gradient(self, optimizer): """Test VQE using Gradient().""" - quantum_instance = QuantumInstance( - backend=Aer.get_backend("qasm_simulator"), - shots=1, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) - vqe = VQE( - ansatz=self.ry_wavefunction, - optimizer=optimizer, - gradient=Gradient(), - expectation=AerPauliExpectation(), - quantum_instance=quantum_instance, - max_evals_grouped=1000, - ) - vqe.compute_minimum_eigenvalue(operator=self.h2_op) + from qiskit_aer import AerSimulator + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=AerSimulator(), + shots=1, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ) + vqe = VQE( + ansatz=self.ry_wavefunction, + optimizer=optimizer, + gradient=Gradient(), + expectation=AerPauliExpectation(), + quantum_instance=quantum_instance, + max_evals_grouped=1000, + ) + vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" - qubit_op = PauliSumOp.from_list( - [ - ("IIII", -0.8105479805373266), - ("IIIZ", 0.17218393261915552), - ("IIZZ", -0.22575349222402472), - ("IZZI", 0.1721839326191556), - ("ZZII", -0.22575349222402466), - ("IIZI", 0.1209126326177663), - ("IZZZ", 0.16892753870087912), - ("IXZX", -0.045232799946057854), - ("ZXIX", 0.045232799946057854), - ("IXIX", 0.045232799946057854), - ("ZXZX", -0.045232799946057854), - ("ZZIZ", 0.16614543256382414), - ("IZIZ", 0.16614543256382414), - ("ZZZZ", 0.17464343068300453), - ("ZIZI", 0.1209126326177663), - ] - ) - tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) - for simulator in [self.qasm_simulator, self.statevector_simulator]: - with self.subTest(f"Test for {simulator}."): - vqe = VQE( - self.ry_wavefunction, - SPSA(maxiter=300, last_avg=5), - quantum_instance=simulator, - ) - result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) - energy = -1.868 if simulator == self.qasm_simulator else self.h2_energy - self.assertAlmostEqual(result.eigenvalue.real, energy, places=2) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qubit_op = PauliSumOp.from_list( + [ + ("IIII", -0.8105479805373266), + ("IIIZ", 0.17218393261915552), + ("IIZZ", -0.22575349222402472), + ("IZZI", 0.1721839326191556), + ("ZZII", -0.22575349222402466), + ("IIZI", 0.1209126326177663), + ("IZZZ", 0.16892753870087912), + ("IXZX", -0.045232799946057854), + ("ZXIX", 0.045232799946057854), + ("IXIX", 0.045232799946057854), + ("ZXZX", -0.045232799946057854), + ("ZZIZ", 0.16614543256382414), + ("IZIZ", 0.16614543256382414), + ("ZZZZ", 0.17464343068300453), + ("ZIZI", 0.1209126326177663), + ] + ) + tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) + for simulator in [self.qasm_simulator, self.statevector_simulator]: + with self.subTest(f"Test for {simulator}."): + vqe = VQE( + self.ry_wavefunction, + SPSA(maxiter=300, last_avg=5), + quantum_instance=simulator, + ) + result = vqe.compute_minimum_eigenvalue(tapered_qubit_op) + energy = -1.868 if simulator == self.qasm_simulator else self.h2_energy + self.assertAlmostEqual(result.eigenvalue.real, energy, places=2) + self.assertTrue(len(caught_warnings) > 0) def test_callback(self): """Test the callback on VQE.""" @@ -364,14 +460,19 @@ def store_intermediate_result(eval_count, parameters, mean, std): optimizer = COBYLA(maxiter=3) wavefunction = self.ry_wavefunction - vqe = VQE( - ansatz=wavefunction, - optimizer=optimizer, - callback=store_intermediate_result, - quantum_instance=self.qasm_simulator, - ) - vqe.compute_minimum_eigenvalue(operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, + optimizer=optimizer, + callback=store_intermediate_result, + quantum_instance=self.qasm_simulator, + ) + vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertTrue(all(isinstance(count, int) for count in history["eval_count"])) self.assertTrue(all(isinstance(mean, float) for mean in history["mean"])) self.assertTrue(all(isinstance(std, float) for std in history["std"])) @@ -381,37 +482,71 @@ def store_intermediate_result(eval_count, parameters, mean, std): def test_reuse(self): """Test re-using a VQE algorithm instance.""" vqe = VQE() - with self.subTest(msg="assert running empty raises AlgorithmError"): - with self.assertRaises(AlgorithmError): - _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) - + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.subTest(msg="assert running empty raises AlgorithmError"): + with self.assertRaises(AlgorithmError): + _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) ansatz = TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz") vqe.ansatz = ansatz - with self.subTest(msg="assert missing operator raises AlgorithmError"): - with self.assertRaises(AlgorithmError): - _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) - - vqe.expectation = MatrixExpectation() - vqe.quantum_instance = self.statevector_simulator - with self.subTest(msg="assert VQE works once all info is available"): - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) - self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) - - operator = PrimitiveOp(np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]])) - - with self.subTest(msg="assert minimum eigensolver interface works"): - result = vqe.compute_minimum_eigenvalue(operator=operator) - self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.subTest(msg="assert missing operator raises AlgorithmError"): + with self.assertRaises(AlgorithmError): + _ = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + vqe.expectation = MatrixExpectation() + self.assertTrue(len(caught_warnings) > 0) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe.quantum_instance = self.statevector_simulator + with self.subTest(msg="assert VQE works once all info is available"): + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) + self.assertTrue(len(caught_warnings) > 0) + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operator = PrimitiveOp( + np.array([[1, 0, 0, 0], [0, -1, 0, 0], [0, 0, 2, 0], [0, 0, 0, 3]]) + ) + with self.subTest(msg="assert minimum eigensolver interface works"): + result = vqe.compute_minimum_eigenvalue(operator=operator) + self.assertAlmostEqual(result.eigenvalue.real, -1.0, places=5) + self.assertTrue(len(caught_warnings) > 0) def test_vqe_optimizer(self): """Test running same VQE twice to re-use optimizer, then switch optimizer""" - vqe = VQE( - optimizer=SLSQP(), - quantum_instance=QuantumInstance(BasicAer.get_backend("statevector_simulator")), - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + optimizer=SLSQP(), + quantum_instance=QuantumInstance(BasicAer.get_backend("statevector_simulator")), + ) + self.assertTrue(len(caught_warnings) > 0) def run_check(): - result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, -1.85727503, places=5) run_check() @@ -426,22 +561,32 @@ def run_check(): @data(MatrixExpectation(), None) def test_backend_change(self, user_expectation): """Test that VQE works when backend changes.""" - vqe = VQE( - ansatz=TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz"), - optimizer=SLSQP(maxiter=2), - expectation=user_expectation, - quantum_instance=BasicAer.get_backend("statevector_simulator"), - ) - result0 = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=TwoLocal(rotation_blocks=["ry", "rz"], entanglement_blocks="cz"), + optimizer=SLSQP(maxiter=2), + expectation=user_expectation, + quantum_instance=BasicAer.get_backend("statevector_simulator"), + ) + result0 = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) if user_expectation is not None: with self.subTest("User expectation kept."): self.assertEqual(vqe.expectation, user_expectation) - vqe.quantum_instance = BasicAer.get_backend("qasm_simulator") - # works also if no expectation is set, since it will be determined automatically - result1 = vqe.compute_minimum_eigenvalue(operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe.quantum_instance = BasicAer.get_backend("qasm_simulator") + result1 = vqe.compute_minimum_eigenvalue(operator=self.h2_op) + self.assertTrue(len(caught_warnings) > 0) if user_expectation is not None: with self.subTest("Change backend with user expectation, it is kept."): self.assertEqual(vqe.expectation, user_expectation) @@ -464,17 +609,22 @@ def wrapped_run(circuits, **kwargs): wrapped_backend.run = partial(wrapped_run, callcount=callcount) - fidelity = QNSPSA.get_fidelity(ansatz, backend=wrapped_backend) - qnspsa = QNSPSA(fidelity, maxiter=5) - - vqe = VQE( - ansatz=ansatz, - optimizer=qnspsa, - max_evals_grouped=100, - quantum_instance=wrapped_backend, - ) - _ = vqe.compute_minimum_eigenvalue(Z ^ Z) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + fidelity = QNSPSA.get_fidelity(ansatz, backend=wrapped_backend) + qnspsa = QNSPSA(fidelity, maxiter=5) + + vqe = VQE( + ansatz=ansatz, + optimizer=qnspsa, + max_evals_grouped=100, + quantum_instance=wrapped_backend, + ) + _ = vqe.compute_minimum_eigenvalue(Z ^ Z) + self.assertTrue(len(caught_warnings) > 0) # 1 calibration + 1 stddev estimation + 1 initial blocking # + 5 (1 loss + 1 fidelity + 1 blocking) + 1 return loss + 1 VQE eval expected = 1 + 1 + 1 + 5 * 3 + 1 + 1 @@ -483,57 +633,95 @@ def wrapped_run(circuits, **kwargs): def test_set_ansatz_to_none(self): """Tests that setting the ansatz to None results in the default behavior""" - vqe = VQE( - ansatz=self.ryrz_wavefunction, - optimizer=L_BFGS_B(), - quantum_instance=self.statevector_simulator, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=self.ryrz_wavefunction, + optimizer=L_BFGS_B(), + quantum_instance=self.statevector_simulator, + ) + self.assertTrue(len(caught_warnings) > 0) vqe.ansatz = None self.assertIsInstance(vqe.ansatz, RealAmplitudes) def test_set_optimizer_to_none(self): """Tests that setting the optimizer to None results in the default behavior""" - vqe = VQE( - ansatz=self.ryrz_wavefunction, - optimizer=L_BFGS_B(), - quantum_instance=self.statevector_simulator, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=self.ryrz_wavefunction, + optimizer=L_BFGS_B(), + quantum_instance=self.statevector_simulator, + ) + self.assertTrue(len(caught_warnings) > 0) vqe.optimizer = None self.assertIsInstance(vqe.optimizer, SLSQP) def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" - vqe = VQE( - optimizer=partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 2}), - quantum_instance=self.statevector_simulator, - ) - result = vqe.compute_minimum_eigenvalue(Z) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + optimizer=partial(scipy_minimize, method="L-BFGS-B", options={"maxiter": 2}), + quantum_instance=self.statevector_simulator, + ) + result = vqe.compute_minimum_eigenvalue(Z) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(result.cost_function_evals, 20) def test_optimizer_callable(self): """Test passing a optimizer directly as callable.""" ansatz = RealAmplitudes(1, reps=1) - vqe = VQE( - ansatz=ansatz, optimizer=_mock_optimizer, quantum_instance=self.statevector_simulator - ) - result = vqe.compute_minimum_eigenvalue(Z) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=ansatz, + optimizer=_mock_optimizer, + quantum_instance=self.statevector_simulator, + ) + result = vqe.compute_minimum_eigenvalue(Z) + self.assertTrue(len(caught_warnings) > 0) self.assertTrue(np.all(result.optimal_point == np.zeros(ansatz.num_parameters))) def test_aux_operators_list(self): """Test list-based aux_operators.""" wavefunction = self.ry_wavefunction - vqe = VQE(ansatz=wavefunction, quantum_instance=self.statevector_simulator) # Start with an empty list - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE(ansatz=wavefunction, quantum_instance=self.statevector_simulator) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=[]) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsNone(result.aux_operator_eigenvalues) # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values @@ -545,7 +733,13 @@ def test_aux_operators_list(self): # Go again with additional None and zero operators extra_ops = [*aux_ops, None, 0] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operator_eigenvalues), 4) # expectation values @@ -562,18 +756,30 @@ def test_aux_operators_list(self): def test_aux_operators_dict(self): """Test dictionary compatibility of aux_operators""" wavefunction = self.ry_wavefunction - vqe = VQE(ansatz=wavefunction, quantum_instance=self.statevector_simulator) # Start with an empty dictionary - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE(ansatz=wavefunction, quantum_instance=self.statevector_simulator) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators={}) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertIsNone(result.aux_operator_eigenvalues) # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values @@ -585,7 +791,13 @@ def test_aux_operators_dict(self): # Go again with additional None and zero operators extra_ops = {**aux_ops, "None_operator": None, "zero_operator": 0} - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operator_eigenvalues), 3) # expectation values @@ -601,18 +813,24 @@ def test_aux_operators_dict(self): def test_aux_operator_std_dev_pauli(self): """Test non-zero standard deviations of aux operators with PauliExpectation.""" wavefunction = self.ry_wavefunction - vqe = VQE( - ansatz=wavefunction, - expectation=PauliExpectation(), - optimizer=COBYLA(maxiter=0), - quantum_instance=self.qasm_simulator, - ) # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, + expectation=PauliExpectation(), + optimizer=COBYLA(maxiter=0), + quantum_instance=self.qasm_simulator, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0], 2.0, places=6) @@ -623,7 +841,13 @@ def test_aux_operator_std_dev_pauli(self): # Go again with additional None and zero operators aux_ops = [*aux_ops, None, 0] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues), 4) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0], 2.0, places=6) @@ -638,27 +862,40 @@ def test_aux_operator_std_dev_pauli(self): self.assertAlmostEqual(result.aux_operator_eigenvalues[2][1], 0.0) self.assertAlmostEqual(result.aux_operator_eigenvalues[3][1], 0.0) - @unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.") + @unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests") def test_aux_operator_std_dev_aer_pauli(self): """Test non-zero standard deviations of aux operators with AerPauliExpectation.""" - wavefunction = self.ry_wavefunction - vqe = VQE( - ansatz=wavefunction, - expectation=AerPauliExpectation(), - optimizer=COBYLA(maxiter=0), - quantum_instance=QuantumInstance( - backend=Aer.get_backend("qasm_simulator"), - shots=1, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ), - ) + from qiskit_aer import AerSimulator - # Go again with two auxiliary operators - aux_op1 = PauliSumOp.from_list([("II", 2.0)]) - aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) - aux_ops = [aux_op1, aux_op2] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + wavefunction = self.ry_wavefunction + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, + expectation=AerPauliExpectation(), + optimizer=COBYLA(maxiter=0), + quantum_instance=QuantumInstance( + backend=AerSimulator(), + shots=1, + seed_simulator=algorithm_globals.random_seed, + seed_transpiler=algorithm_globals.random_seed, + ), + ) + self.assertTrue(len(caught_warnings) > 0) + # Go again with two auxiliary operator + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aux_op1 = PauliSumOp.from_list([("II", 2.0)]) + aux_op2 = PauliSumOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) + aux_ops = [aux_op1, aux_op2] + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues), 2) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0], 2.0, places=6) @@ -669,7 +906,13 @@ def test_aux_operator_std_dev_aer_pauli(self): # Go again with additional None and zero operators aux_ops = [*aux_ops, None, 0] - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(len(result.aux_operator_eigenvalues), 4) # expectation values self.assertAlmostEqual(result.aux_operator_eigenvalues[0][0], 2.0, places=6) @@ -694,21 +937,24 @@ def test_2step_transpile(self): bound_counter = LogPass("bound_pass_manager") bound_pass = PassManager(bound_counter) - quantum_instance = QuantumInstance( - backend=BasicAer.get_backend("statevector_simulator"), - basis_gates=["u3", "cx"], - pass_manager=pre_pass, - bound_pass_manager=bound_pass, - ) - optimizer = SPSA(maxiter=5, learning_rate=0.01, perturbation=0.01) - - vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance) - _ = vqe.compute_minimum_eigenvalue(Z) - - with self.assertLogs(logger, level="INFO") as cm: + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + quantum_instance = QuantumInstance( + backend=BasicAer.get_backend("statevector_simulator"), + basis_gates=["u3", "cx"], + pass_manager=pre_pass, + bound_pass_manager=bound_pass, + ) + vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance) _ = vqe.compute_minimum_eigenvalue(Z) + with self.assertLogs(logger, level="INFO") as cm: + _ = vqe.compute_minimum_eigenvalue(Z) + self.assertTrue(len(caught_warnings) > 0) expected = [ "pre_passmanager", "bound_pass_manager", @@ -731,14 +977,19 @@ def test_construct_eigenstate_from_optpoint(self): """Test constructing the eigenstate from the optimal point, if the default ansatz is used.""" # use Hamiltonian yielding more than 11 parameters in the default ansatz - hamiltonian = Z ^ Z ^ Z optimizer = SPSA(maxiter=1, learning_rate=0.01, perturbation=0.01) - quantum_instance = QuantumInstance( - backend=BasicAer.get_backend("statevector_simulator"), basis_gates=["u3", "cx"] - ) - vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance) - result = vqe.compute_minimum_eigenvalue(hamiltonian) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = Z ^ Z ^ Z + quantum_instance = QuantumInstance( + backend=BasicAer.get_backend("statevector_simulator"), basis_gates=["u3", "cx"] + ) + vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance) + result = vqe.compute_minimum_eigenvalue(hamiltonian) + self.assertTrue(len(caught_warnings) > 0) optimal_circuit = vqe.ansatz.bind_parameters(result.optimal_point) self.assertTrue(Statevector(result.eigenstate).equiv(optimal_circuit)) diff --git a/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py b/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py index 52e26d559623..43c262715a1c 100644 --- a/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py +++ b/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -12,6 +12,7 @@ """Test Classical Imaginary Evolver.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack import numpy as np @@ -123,13 +124,19 @@ def test_quantum_circuit_initial_state(self): def test_paulisumop_hamiltonian(self): """Tests if the hamiltonian can be a PauliSumOp""" - hamiltonian = PauliSumOp.from_list( - [ - ("XI", 1), - ("IX", 1), - ] - ) - observable = PauliSumOp.from_list([("ZZ", 1)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = PauliSumOp.from_list( + [ + ("XI", 1), + ("IX", 1), + ] + ) + observable = PauliSumOp.from_list([("ZZ", 1)]) + self.assertTrue(len(caught_warnings) > 0) evolution_problem = TimeEvolutionProblem( hamiltonian=hamiltonian, time=1.0, diff --git a/test/python/algorithms/time_evolvers/test_pvqd.py b/test/python/algorithms/time_evolvers/test_pvqd.py index 70cb12520e84..23f0dbd228b7 100644 --- a/test/python/algorithms/time_evolvers/test_pvqd.py +++ b/test/python/algorithms/time_evolvers/test_pvqd.py @@ -12,6 +12,8 @@ """Tests for PVQD.""" import unittest +import warnings +from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial import numpy as np @@ -53,7 +55,7 @@ def inverse(self): @ddt -class TestPVQD(QiskitTestCase): +class TestPVQD(QiskitAlgorithmsTestCase): """Tests for the pVQD algorithm.""" def setUp(self): @@ -73,7 +75,13 @@ def test_pvqd(self, hamiltonian_type, gradient, num_timesteps): if hamiltonian_type == "ising": hamiltonian = self.hamiltonian elif hamiltonian_type == "pauli_sum_op": - hamiltonian = PauliSumOp(self.hamiltonian) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = PauliSumOp(self.hamiltonian) + self.assertTrue(len(caught_warnings) > 0) else: # hamiltonian_type == "pauli": hamiltonian = Pauli("XX") 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 8cc0134c2cdb..e069d18884ee 100644 --- a/test/python/algorithms/time_evolvers/test_time_evolution_problem.py +++ b/test/python/algorithms/time_evolvers/test_time_evolution_problem.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -12,6 +12,7 @@ """Test evolver problem class.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt from numpy.testing import assert_raises @@ -52,7 +53,13 @@ def test_init_default(self): def test_init_all(self, initial_state): """Tests that all fields are initialized correctly.""" t_parameter = Parameter("t") - hamiltonian = t_parameter * Z + Y + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = t_parameter * Z + Y + self.assertTrue(len(caught_warnings) > 0) time = 2 aux_operators = [X, Y] param_value_dict = {t_parameter: 3.2} @@ -66,14 +73,26 @@ def test_init_all(self, initial_state): param_value_map=param_value_dict, ) - expected_hamiltonian = Y + t_parameter * Z + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + expected_hamiltonian = Y + t_parameter * Z + self.assertTrue(len(caught_warnings) > 0) expected_time = 2 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) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(type(evo_problem.initial_state), expected_type) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) @@ -84,7 +103,13 @@ 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) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x) + self.assertTrue(len(caught_warnings) > 0) evolution_problem = TimeEvolutionProblem(hamiltonian, 2, Zero) with assert_raises(ValueError): evolution_problem.validate_params() diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 6c342bb57f60..8d93d10a7d17 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -13,6 +13,7 @@ """ Test TrotterQRTE. """ import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np @@ -53,7 +54,13 @@ 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 = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) + self.assertTrue(len(caught_warnings) > 0) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) @@ -96,7 +103,13 @@ def test_trotter_qrte_trotter(self, operator, t_param): algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps) - evolution_result = trotter_qrte.evolve(evolution_problem) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evolution_result = trotter_qrte.evolve(evolution_problem) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, @@ -169,7 +182,13 @@ 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 = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) + self.assertTrue(len(caught_warnings) > 0) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) @@ -177,17 +196,30 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) - np.testing.assert_array_almost_equal( - Statevector.from_instruction(evolution_result.evolved_state).data, expected_state.data - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + np.testing.assert_array_almost_equal( + Statevector.from_instruction(evolution_result.evolved_state).data, + expected_state.data, + ) + self.assertTrue(len(caught_warnings) > 0) @data((Parameter("t"), {}), (None, {Parameter("x"): 2}), (None, None)) @unpack 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")]) - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( + SparsePauliOp([Pauli("Z")]) + ) + self.assertTrue(len(caught_warnings) > 0) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) @@ -195,7 +227,15 @@ def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): @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")])) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( + SparsePauliOp([Pauli("Z")]) + ) + self.assertTrue(len(caught_warnings) > 0) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) diff --git a/test/python/algorithms/time_evolvers/variational/test_var_qite.py b/test/python/algorithms/time_evolvers/variational/test_var_qite.py index 067d9d3226bc..bd46100a9508 100644 --- a/test/python/algorithms/time_evolvers/variational/test_var_qite.py +++ b/test/python/algorithms/time_evolvers/variational/test_var_qite.py @@ -13,6 +13,7 @@ """Test Variational Quantum Imaginary Time Evolution algorithm.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np @@ -99,8 +100,13 @@ def test_run_d_1_with_aux_ops(self): var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - evolution_result = var_qite.evolve(evolution_problem) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evolution_result = var_qite.evolve(evolution_problem) + self.assertTrue(len(caught_warnings) > 0) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] @@ -127,8 +133,13 @@ def test_run_d_1_with_aux_ops(self): var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - evolution_result = var_qite.evolve(evolution_problem) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evolution_result = var_qite.evolve(evolution_problem) + self.assertTrue(len(caught_warnings) > 0) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] diff --git a/test/python/algorithms/time_evolvers/variational/test_var_qrte.py b/test/python/algorithms/time_evolvers/variational/test_var_qrte.py index b7dfaf59f12b..f5f5724f6d4f 100644 --- a/test/python/algorithms/time_evolvers/variational/test_var_qrte.py +++ b/test/python/algorithms/time_evolvers/variational/test_var_qrte.py @@ -13,6 +13,7 @@ """Test Variational Quantum Real Time Evolution algorithm.""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt @@ -130,8 +131,13 @@ def test_run_d_1_with_aux_ops(self): var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - evolution_result = var_qrte.evolve(evolution_problem) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evolution_result = var_qrte.evolve(evolution_problem) + self.assertTrue(len(caught_warnings) > 0) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] @@ -158,8 +164,13 @@ def test_run_d_1_with_aux_ops(self): var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - evolution_result = var_qrte.evolve(evolution_problem) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evolution_result = var_qrte.evolve(evolution_problem) + self.assertTrue(len(caught_warnings) > 0) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] diff --git a/test/python/circuit/library/test_evolution_gate.py b/test/python/circuit/library/test_evolution_gate.py index 8b5c491af088..c8e98d4a3e66 100644 --- a/test/python/circuit/library/test_evolution_gate.py +++ b/test/python/circuit/library/test_evolution_gate.py @@ -12,6 +12,7 @@ """Test the evolution gate.""" +import warnings import numpy as np import scipy from ddt import ddt, data, unpack @@ -37,7 +38,13 @@ def setUp(self): def test_matrix_decomposition(self): """Test the default decomposition.""" - op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) + self.assertTrue(len(caught_warnings) > 0) time = 0.123 matrix = op.to_matrix() @@ -49,7 +56,13 @@ def test_matrix_decomposition(self): def test_lie_trotter(self): """Test constructing the circuit with Lie Trotter decomposition.""" - op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) + self.assertTrue(len(caught_warnings) > 0) time = 0.123 reps = 4 evo_gate = PauliEvolutionGate(op, time, synthesis=LieTrotter(reps=reps)) @@ -58,29 +71,42 @@ def test_lie_trotter(self): def test_rzx_order(self): """Test ZX and XZ is mapped onto the correct qubits.""" - for op, indices in zip([X ^ Z, Z ^ X], [(0, 1), (1, 0)]): - with self.subTest(op=op, indices=indices): - evo_gate = PauliEvolutionGate(op) - decomposed = evo_gate.definition.decompose() - - # ┌───┐┌───────┐┌───┐ - # q_0: ─────┤ X ├┤ Rz(2) ├┤ X ├───── - # ┌───┐└─┬─┘└───────┘└─┬─┘┌───┐ - # q_1: ┤ H ├──■─────────────■──┤ H ├ - # └───┘ └───┘ - ref = QuantumCircuit(2) - ref.h(indices[1]) - ref.cx(indices[1], indices[0]) - ref.rz(2.0, indices[0]) - ref.cx(indices[1], indices[0]) - ref.h(indices[1]) - - # don't use circuit equality since RZX here decomposes with RZ on the bottom - self.assertTrue(Operator(decomposed).equiv(ref)) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) + for op, indices in zip([X ^ Z, Z ^ X], [(0, 1), (1, 0)]): + with self.subTest(op=op, indices=indices): + evo_gate = PauliEvolutionGate(op) + decomposed = evo_gate.definition.decompose() + + # ┌───┐┌───────┐┌───┐ + # q_0: ─────┤ X ├┤ Rz(2) ├┤ X ├───── + # ┌───┐└─┬─┘└───────┘└─┬─┘┌───┐ + # q_1: ┤ H ├──■─────────────■──┤ H ├ + # └───┘ └───┘ + ref = QuantumCircuit(2) + ref.h(indices[1]) + ref.cx(indices[1], indices[0]) + ref.rz(2.0, indices[0]) + ref.cx(indices[1], indices[0]) + ref.h(indices[1]) + + # don't use circuit equality since RZX here decomposes with RZ on the bottom + self.assertTrue(Operator(decomposed).equiv(ref)) + self.assertTrue(len(caught_warnings) > 0) def test_suzuki_trotter(self): """Test constructing the circuit with Lie Trotter decomposition.""" - op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) + self.assertTrue(len(caught_warnings) > 0) time = 0.123 reps = 4 for order in [2, 4, 6]: @@ -102,7 +128,13 @@ def test_suzuki_trotter(self): def test_suzuki_trotter_manual(self): """Test the evolution circuit of Suzuki Trotter against a manually constructed circuit.""" - op = X + Y + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = X + Y + self.assertTrue(len(caught_warnings) > 0) time = 0.1 reps = 1 evo_gate = PauliEvolutionGate(op, time, synthesis=SuzukiTrotter(order=4, reps=reps)) @@ -136,7 +168,13 @@ def test_qdrift_manual(self, op, time, reps, sampled_ops): """Test the evolution circuit of Suzuki Trotter against a manually constructed circuit.""" qdrift = QDrift(reps=reps) evo_gate = PauliEvolutionGate(op, time, synthesis=qdrift) - evo_gate.definition.decompose() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo_gate.definition.decompose() + self.assertTrue(len(caught_warnings) > 0) # manually construct expected evolution expected = QuantumCircuit(1) @@ -150,9 +188,21 @@ def test_qdrift_manual(self, op, time, reps, sampled_ops): def test_qdrift_evolution(self): """Test QDrift on an example.""" - op = 0.1 * (Z ^ Z) + (X ^ I) + (I ^ X) + 0.2 * (X ^ X) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = 0.1 * (Z ^ Z) + (X ^ I) + (I ^ X) + 0.2 * (X ^ X) + self.assertTrue(len(caught_warnings) > 0) reps = 20 - qdrift = PauliEvolutionGate(op, time=0.5 / reps, synthesis=QDrift(reps=reps)).definition + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qdrift = PauliEvolutionGate(op, time=0.5 / reps, synthesis=QDrift(reps=reps)).definition + self.assertTrue(len(caught_warnings) > 0) exact = scipy.linalg.expm(-0.5j * op.to_matrix()).dot(np.eye(4)[0, :]) def energy(evo): @@ -162,7 +212,13 @@ def energy(evo): def test_passing_grouped_paulis(self): """Test passing a list of already grouped Paulis.""" - grouped_ops = [(X ^ Y) + (Y ^ X), (Z ^ I) + (Z ^ Z) + (I ^ Z), (X ^ X)] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + grouped_ops = [(X ^ Y) + (Y ^ X), (Z ^ I) + (Z ^ Z) + (I ^ Z), (X ^ X)] + self.assertTrue(len(caught_warnings) > 0) evo_gate = PauliEvolutionGate(grouped_ops, time=0.12, synthesis=LieTrotter()) decomposed = evo_gate.definition.decompose() self.assertEqual(decomposed.count_ops()["rz"], 4) @@ -171,7 +227,13 @@ def test_passing_grouped_paulis(self): def test_list_from_grouped_paulis(self): """Test getting a string representation from grouped Paulis.""" - grouped_ops = [(X ^ Y) + (Y ^ X), (Z ^ I) + (Z ^ Z) + (I ^ Z), (X ^ X)] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + grouped_ops = [(X ^ Y) + (Y ^ X), (Z ^ I) + (Z ^ Z) + (I ^ Z), (X ^ X)] + self.assertTrue(len(caught_warnings) > 0) evo_gate = PauliEvolutionGate(grouped_ops, time=0.12, synthesis=LieTrotter()) pauli_strings = [] @@ -191,7 +253,13 @@ def test_list_from_grouped_paulis(self): def test_dag_conversion(self): """Test constructing a circuit with evolutions yields a DAG with evolution blocks.""" time = Parameter("t") - evo = PauliEvolutionGate((Z ^ 2) + (X ^ 2), time=time) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate((Z ^ 2) + (X ^ 2), time=time) + self.assertTrue(len(caught_warnings) > 0) circuit = QuantumCircuit(2) circuit.h(circuit.qubits) @@ -209,7 +277,13 @@ def test_dag_conversion(self): def test_cnot_chain_options(self, option): """Test selecting different kinds of CNOT chains.""" - op = Z ^ Z ^ Z + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = Z ^ Z ^ Z + self.assertTrue(len(caught_warnings) > 0) synthesis = LieTrotter(reps=1, cx_structure=option) evo = PauliEvolutionGate(op, synthesis=synthesis) @@ -253,14 +327,26 @@ def test_different_input_types(self, op): def test_pauliop_coefficients_respected(self): """Test that global ``PauliOp`` coefficients are being taken care of.""" - evo = PauliEvolutionGate(5 * (Z ^ I), time=1, synthesis=LieTrotter()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate(5 * (Z ^ I), time=1, synthesis=LieTrotter()) + self.assertTrue(len(caught_warnings) > 0) circuit = evo.definition.decompose() rz_angle = circuit.data[0].operation.params[0] self.assertEqual(rz_angle, 10) def test_paulisumop_coefficients_respected(self): """Test that global ``PauliSumOp`` coefficients are being taken care of.""" - evo = PauliEvolutionGate(5 * (2 * X + 3 * Y - Z), time=1, synthesis=LieTrotter()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate(5 * (2 * X + 3 * Y - Z), time=1, synthesis=LieTrotter()) + self.assertTrue(len(caught_warnings) > 0) circuit = evo.definition.decompose() rz_angles = [ circuit.data[0].operation.params[0], # X @@ -274,7 +360,13 @@ def test_lie_trotter_two_qubit_correct_order(self): Regression test of Qiskit/qiskit-terra#7544. """ - operator = I ^ Z ^ Z + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operator = I ^ Z ^ Z + self.assertTrue(len(caught_warnings) > 0) time = 0.5 exact = scipy.linalg.expm(-1j * time * operator.to_matrix()) lie_trotter = PauliEvolutionGate(operator, time, synthesis=LieTrotter()) @@ -294,7 +386,13 @@ def test_paramtrized_op_raises(self): @data(LieTrotter, MatrixExponential) def test_inverse(self, synth_cls): """Test calculating the inverse is correct.""" - evo = PauliEvolutionGate(X + Y, time=0.12, synthesis=synth_cls()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate(X + Y, time=0.12, synthesis=synth_cls()) + self.assertTrue(len(caught_warnings) > 0) circuit = QuantumCircuit(1) circuit.append(evo, circuit.qubits) @@ -304,7 +402,13 @@ def test_inverse(self, synth_cls): def test_labels_and_name(self): """Test the name and labels are correct.""" - operators = [X, (X + Y), ((I ^ Z) + (Z ^ I) - 0.2 * (X ^ X))] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + operators = [X, (X + Y), ((I ^ Z) + (Z ^ I) - 0.2 * (X ^ X))] + self.assertTrue(len(caught_warnings) > 0) # note: the labels do not show coefficients! expected_labels = ["X", "(X + Y)", "(IZ + ZI + XX)"] diff --git a/test/python/circuit/library/test_evolved_op_ansatz.py b/test/python/circuit/library/test_evolved_op_ansatz.py index 93b489c7dc82..d58b329ef3b4 100644 --- a/test/python/circuit/library/test_evolved_op_ansatz.py +++ b/test/python/circuit/library/test_evolved_op_ansatz.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -12,7 +12,7 @@ """Test the evolved operator ansatz.""" - +import warnings from qiskit.circuit import QuantumCircuit from qiskit.opflow import X, Y, Z, I, MatrixEvolution @@ -26,14 +26,18 @@ class TestEvolvedOperatorAnsatz(QiskitTestCase): def test_evolved_op_ansatz(self): """Test the default evolution.""" num_qubits = 3 + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + ops = [Z ^ num_qubits, Y ^ num_qubits, X ^ num_qubits] + strings = ["z" * num_qubits, "y" * num_qubits, "x" * num_qubits] * 2 + evo = EvolvedOperatorAnsatz(ops, 2) + reference = QuantumCircuit(num_qubits) + parameters = evo.parameters + self.assertTrue(len(caught_warnings) > 0) - ops = [Z ^ num_qubits, Y ^ num_qubits, X ^ num_qubits] - strings = ["z" * num_qubits, "y" * num_qubits, "x" * num_qubits] * 2 - - evo = EvolvedOperatorAnsatz(ops, 2) - - reference = QuantumCircuit(num_qubits) - parameters = evo.parameters for string, time in zip(strings, parameters): reference.compose(evolve(string, time), inplace=True) @@ -42,11 +46,17 @@ def test_evolved_op_ansatz(self): def test_custom_evolution(self): """Test using another evolution than the default (e.g. matrix evolution).""" - op = X ^ I ^ Z - matrix = op.to_matrix() - evo = EvolvedOperatorAnsatz(op, evolution=MatrixEvolution()) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = X ^ I ^ Z + matrix = op.to_matrix() + evo = EvolvedOperatorAnsatz(op, evolution=MatrixEvolution()) + parameters = evo.parameters + self.assertTrue(len(caught_warnings) > 0) - parameters = evo.parameters reference = QuantumCircuit(3) reference.hamiltonian(matrix, parameters[0], [0, 1, 2]) @@ -56,10 +66,16 @@ def test_changing_operators(self): """Test rebuilding after the operators changed.""" ops = [X, Y, Z] - evo = EvolvedOperatorAnsatz(ops) - evo.operators = [X, Y] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = EvolvedOperatorAnsatz(ops) + evo.operators = [X, Y] + parameters = evo.parameters + self.assertTrue(len(caught_warnings) > 0) - parameters = evo.parameters reference = QuantumCircuit(1) reference.rx(2 * parameters[0], 0) reference.ry(2 * parameters[1], 0) @@ -68,22 +84,46 @@ def test_changing_operators(self): def test_invalid_reps(self): """Test setting an invalid number of reps.""" - with self.assertRaises(ValueError): - _ = EvolvedOperatorAnsatz(X, reps=-1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.assertRaises(ValueError): + _ = EvolvedOperatorAnsatz(X, reps=-1) + self.assertTrue(len(caught_warnings) > 0) def test_insert_barriers(self): """Test using insert_barriers.""" - evo = EvolvedOperatorAnsatz(Z, reps=4, insert_barriers=True) - ref = QuantumCircuit(1) - for parameter in evo.parameters: - ref.rz(2.0 * parameter, 0) - ref.barrier() - - self.assertEqual(evo.decompose(), ref) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = EvolvedOperatorAnsatz(Z, reps=4, insert_barriers=True) + ref = QuantumCircuit(1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for parameter in evo.parameters: + ref.rz(2.0 * parameter, 0) + ref.barrier() + self.assertTrue(len(caught_warnings) > 0) + + self.assertEqual(evo.decompose(), ref) + self.assertTrue(len(caught_warnings) > 0) def test_empty_build_fails(self): """Test setting no operators to evolve raises the appropriate error.""" - evo = EvolvedOperatorAnsatz() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = EvolvedOperatorAnsatz() + self.assertTrue(len(caught_warnings) > 0) with self.assertRaises(ValueError): _ = evo.draw() diff --git a/test/python/circuit/library/test_qaoa_ansatz.py b/test/python/circuit/library/test_qaoa_ansatz.py index 1bde60570bdb..774ae37081d7 100644 --- a/test/python/circuit/library/test_qaoa_ansatz.py +++ b/test/python/circuit/library/test_qaoa_ansatz.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -12,6 +12,7 @@ """Test QAOA ansatz from the library.""" +import warnings import numpy as np from ddt import ddt, data @@ -28,9 +29,14 @@ class TestQAOAAnsatz(QiskitTestCase): def test_default_qaoa(self): """Test construction of the default circuit.""" - circuit = QAOAAnsatz(I, 1) - - parameters = circuit.parameters + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(I, 1) + parameters = circuit.parameters + self.assertTrue(len(caught_warnings) > 0) circuit = circuit.decompose() self.assertEqual(1, len(parameters)) @@ -41,9 +47,14 @@ def test_custom_initial_state(self): """Test circuit with a custom initial state.""" initial_state = QuantumCircuit(1) initial_state.y(0) - circuit = QAOAAnsatz(initial_state=initial_state, cost_operator=I, reps=1) - - parameters = circuit.parameters + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(initial_state=initial_state, cost_operator=I, reps=1) + parameters = circuit.parameters + self.assertTrue(len(caught_warnings) > 0) circuit = circuit.decompose() self.assertEqual(1, len(parameters)) self.assertIsInstance(circuit.data[0].operation, YGate) @@ -51,22 +62,40 @@ def test_custom_initial_state(self): def test_invalid_reps(self): """Test negative reps.""" - with self.assertRaises(ValueError): - _ = QAOAAnsatz(I, reps=-1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.assertRaises(ValueError): + _ = QAOAAnsatz(I, reps=-1) + self.assertTrue(len(caught_warnings) > 0) def test_zero_reps(self): """Test zero reps.""" - circuit = QAOAAnsatz(I ^ 4, reps=0) - reference = QuantumCircuit(4) - reference.h(range(4)) - - self.assertEqual(circuit.decompose(), reference) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(I ^ 4, reps=0) + reference = QuantumCircuit(4) + reference.h(range(4)) + + self.assertEqual(circuit.decompose(), reference) + self.assertTrue(len(caught_warnings) > 0) def test_custom_circuit_mixer(self): """Test circuit with a custom mixer as a circuit""" mixer = QuantumCircuit(1) mixer.ry(1, 0) - circuit = QAOAAnsatz(cost_operator=I, reps=1, mixer_operator=mixer) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(cost_operator=I, reps=1, mixer_operator=mixer) + self.assertTrue(len(caught_warnings) > 0) parameters = circuit.parameters circuit = circuit.decompose() @@ -77,9 +106,14 @@ def test_custom_circuit_mixer(self): def test_custom_operator_mixer(self): """Test circuit with a custom mixer as an operator.""" mixer = Y - circuit = QAOAAnsatz(cost_operator=I, reps=1, mixer_operator=mixer) - - parameters = circuit.parameters + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(cost_operator=I, reps=1, mixer_operator=mixer) + parameters = circuit.parameters + self.assertTrue(len(caught_warnings) > 0) circuit = circuit.decompose() self.assertEqual(1, len(parameters)) self.assertIsInstance(circuit.data[0].operation, HGate) @@ -87,8 +121,14 @@ def test_custom_operator_mixer(self): def test_parameter_bounds(self): """Test the parameter bounds.""" - circuit = QAOAAnsatz(Z, reps=2) - bounds = circuit.parameter_bounds + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(Z, reps=2) + bounds = circuit.parameter_bounds + self.assertTrue(len(caught_warnings) > 0) for lower, upper in bounds[:2]: self.assertAlmostEqual(lower, 0) @@ -104,11 +144,17 @@ def test_all_custom_parameters(self): initial_state.y(0) mixer = Z - circuit = QAOAAnsatz( - cost_operator=I, reps=2, initial_state=initial_state, mixer_operator=mixer - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz( + cost_operator=I, reps=2, initial_state=initial_state, mixer_operator=mixer + ) + parameters = circuit.parameters + self.assertTrue(len(caught_warnings) > 0) - parameters = circuit.parameters circuit = circuit.decompose() self.assertEqual(2, len(parameters)) self.assertIsInstance(circuit.data[0].operation, YGate) @@ -118,21 +164,33 @@ def test_all_custom_parameters(self): def test_configuration(self): """Test configuration checks.""" mixer = QuantumCircuit(2) - circuit = QAOAAnsatz(cost_operator=I, reps=1, mixer_operator=mixer) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(cost_operator=I, reps=1, mixer_operator=mixer) + self.assertTrue(len(caught_warnings) > 0) self.assertRaises(ValueError, lambda: circuit.parameters) def test_rebuild(self): """Test how a circuit can be rebuilt.""" - circuit = QAOAAnsatz(cost_operator=Z ^ I) # circuit with 2 qubits - # force circuit to be built - _ = circuit.parameters - - circuit.cost_operator = Z # now it only has 1 qubit - circuit.reps = 5 # and now 5 repetitions - # rebuild the circuit - self.assertEqual(1, circuit.num_qubits) - self.assertEqual(10, circuit.num_parameters) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(cost_operator=Z ^ I) # circuit with 2 qubits + # force circuit to be built + _ = circuit.parameters + + circuit.cost_operator = Z # now it only has 1 qubit + circuit.reps = 5 # and now 5 repetitions + # rebuild the circuit + self.assertEqual(1, circuit.num_qubits) + self.assertEqual(10, circuit.num_parameters) + self.assertTrue(len(caught_warnings) > 0) def test_circuit_mixer(self): """Test using a parameterized circuit as mixer.""" @@ -142,12 +200,24 @@ def test_circuit_mixer(self): mixer.ry(x2, 1) reps = 4 - circuit = QAOAAnsatz(cost_operator=Z ^ Z, mixer_operator=mixer, reps=reps) - self.assertEqual(circuit.num_parameters, 3 * reps) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(cost_operator=Z ^ Z, mixer_operator=mixer, reps=reps) + self.assertEqual(circuit.num_parameters, 3 * reps) + self.assertTrue(len(caught_warnings) > 0) def test_empty_op(self): """Test construction without cost operator""" - circuit = QAOAAnsatz(reps=1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(reps=1) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(circuit.num_qubits, 0) with self.assertRaises(ValueError): circuit.decompose() @@ -156,18 +226,30 @@ def test_empty_op(self): def test_num_qubits(self, num_qubits): """Test num_qubits with {num_qubits} qubits""" - circuit = QAOAAnsatz(cost_operator=I ^ num_qubits, reps=5) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circuit = QAOAAnsatz(cost_operator=I ^ num_qubits, reps=5) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(circuit.num_qubits, num_qubits) def test_identity(self): """Test construction with identity""" reps = 4 num_qubits = 3 - pauli_sum_op = PauliSumOp.from_list([("I" * num_qubits, 1)]) - pauli_op = I ^ num_qubits - for cost in [pauli_op, pauli_sum_op]: - for mixer in [None, pauli_op, pauli_sum_op]: - with self.subTest(f"cost: {type(cost)}, mixer:{type(mixer)}"): - circuit = QAOAAnsatz(cost_operator=cost, mixer_operator=mixer, reps=reps) - target = reps if mixer is None else 0 - self.assertEqual(circuit.num_parameters, target) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + pauli_sum_op = PauliSumOp.from_list([("I" * num_qubits, 1)]) + pauli_op = I ^ num_qubits + for cost in [pauli_op, pauli_sum_op]: + for mixer in [None, pauli_op, pauli_sum_op]: + with self.subTest(f"cost: {type(cost)}, mixer:{type(mixer)}"): + circuit = QAOAAnsatz(cost_operator=cost, mixer_operator=mixer, reps=reps) + target = reps if mixer is None else 0 + self.assertEqual(circuit.num_parameters, target) + self.assertTrue(len(caught_warnings) > 0) diff --git a/test/python/circuit/test_circuit_load_from_qpy.py b/test/python/circuit/test_circuit_load_from_qpy.py index 349bca64f3f1..f5102dcf20bb 100644 --- a/test/python/circuit/test_circuit_load_from_qpy.py +++ b/test/python/circuit/test_circuit_load_from_qpy.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2020. +# (C) Copyright IBM 2020, 2023. # # 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 @@ -13,6 +13,7 @@ """Test cases for the circuit qasm_file and qasm_string method.""" +import warnings import io import json import random @@ -273,7 +274,13 @@ def test_parameter_expression(self): def test_string_parameter(self): """Test a PauliGate instruction that has string parameters.""" - circ = (X ^ Y ^ Z).to_circuit_op().to_circuit() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + circ = (X ^ Y ^ Z).to_circuit_op().to_circuit() + self.assertTrue(len(caught_warnings) > 0) qpy_file = io.BytesIO() dump(circ, qpy_file) qpy_file.seek(0) @@ -598,10 +605,22 @@ def test_single_bit_teleportation(self): def test_qaoa(self): """Test loading a QAOA circuit works.""" - cost_operator = Z ^ I ^ I ^ Z - qaoa = QAOAAnsatz(cost_operator, reps=2) - qpy_file = io.BytesIO() - dump(qaoa, qpy_file) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + cost_operator = Z ^ I ^ I ^ Z + self.assertTrue(len(caught_warnings) > 0) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qaoa = QAOAAnsatz(cost_operator, reps=2) + qpy_file = io.BytesIO() + dump(qaoa, qpy_file) + self.assertTrue(len(caught_warnings) > 0) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qaoa, new_circ) @@ -612,7 +631,13 @@ def test_qaoa(self): def test_evolutiongate(self): """Test loading a circuit with evolution gate works.""" synthesis = LieTrotter(reps=2) - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=2, synthesis=synthesis) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=2, synthesis=synthesis) + self.assertTrue(len(caught_warnings) > 0) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -632,7 +657,13 @@ def test_evolutiongate_param_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time, synthesis=synthesis) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time, synthesis=synthesis) + self.assertTrue(len(caught_warnings) > 0) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -652,7 +683,13 @@ def test_evolutiongate_param_expr_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time * time, synthesis=synthesis) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time * time, synthesis=synthesis) + self.assertTrue(len(caught_warnings) > 0) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -672,7 +709,13 @@ def test_evolutiongate_param_vec_time(self): """Test loading a an evolution gate that has a param vector element for time.""" synthesis = LieTrotter(reps=2) time = ParameterVector("TimeVec", 1) - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time[0], synthesis=synthesis) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time[0], synthesis=synthesis) + self.assertTrue(len(caught_warnings) > 0) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -690,7 +733,13 @@ def test_evolutiongate_param_vec_time(self): def test_op_list_evolutiongate(self): """Test loading a circuit with evolution gate works.""" - evo = PauliEvolutionGate([(Z ^ I) + (I ^ Z)] * 5, time=0.2, synthesis=None) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate([(Z ^ I) + (I ^ Z)] * 5, time=0.2, synthesis=None) + self.assertTrue(len(caught_warnings) > 0) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -709,7 +758,13 @@ def test_op_list_evolutiongate(self): def test_op_evolution_gate_suzuki_trotter(self): """Test qpy path with a suzuki trotter synthesis method on an evolution gate.""" synthesis = SuzukiTrotter() - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=0.2, synthesis=synthesis) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=0.2, synthesis=synthesis) + self.assertTrue(len(caught_warnings) > 0) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() diff --git a/test/python/opflow/opflow_test_case.py b/test/python/opflow/opflow_test_case.py index 4a4e1781b485..a481b5187c2d 100644 --- a/test/python/opflow/opflow_test_case.py +++ b/test/python/opflow/opflow_test_case.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2020. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -12,10 +12,19 @@ """ Opflow Test Case """ +import warnings from qiskit.test import QiskitTestCase class QiskitOpflowTestCase(QiskitTestCase): """Opflow test Case""" - pass + def setUp(self): + super().setUp() + # ignore opflow msgs + warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*opflow.*") + + def tearDown(self): + super().tearDown() + # restore opflow msgs + warnings.filterwarnings("error", category=DeprecationWarning, message=r".*opflow.*") diff --git a/test/python/opflow/test_aer_pauli_expectation.py b/test/python/opflow/test_aer_pauli_expectation.py index 3f5d64f42658..0d1f188089e6 100644 --- a/test/python/opflow/test_aer_pauli_expectation.py +++ b/test/python/opflow/test_aer_pauli_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -15,7 +15,7 @@ import itertools import unittest from test.python.opflow import QiskitOpflowTestCase - +import warnings import numpy as np from qiskit.circuit.library import RealAmplitudes @@ -40,27 +40,30 @@ Zero, MatrixOp, ) -from qiskit.utils import QuantumInstance +from qiskit.utils import QuantumInstance, optionals class TestAerPauliExpectation(QiskitOpflowTestCase): """Pauli Change of Basis Expectation tests.""" + @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def setUp(self) -> None: super().setUp() - try: - from qiskit_aer import Aer - - self.seed = 97 - self.backend = Aer.get_backend("aer_simulator") + from qiskit_aer import AerSimulator + + self.seed = 97 + self.backend = AerSimulator() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) q_instance = QuantumInstance( self.backend, seed_simulator=self.seed, seed_transpiler=self.seed ) - self.sampler = CircuitSampler(q_instance, attach_results=True) - self.expect = AerPauliExpectation() - except Exception as ex: # pylint: disable=broad-except - self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") - return + self.assertTrue(len(caught_warnings) > 0) + self.sampler = CircuitSampler(q_instance, attach_results=True) + self.expect = AerPauliExpectation() def test_pauli_expect_pair(self): """pauli expect pair test""" @@ -69,18 +72,30 @@ def test_pauli_expect_pair(self): wvf = CX @ (H ^ I) @ Zero converted_meas = self.expect.convert(~StateFn(op) @ wvf) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" paulis = [Z, X, Y, I] states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - for pauli, state in itertools.product(paulis, states): - converted_meas = self.expect.convert(~StateFn(pauli) @ state) - matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() - sampled = self.sampler.convert(converted_meas) - self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for pauli, state in itertools.product(paulis, states): + converted_meas = self.expect.convert(~StateFn(pauli) @ state) + matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() + sampled = self.sampler.convert(converted_meas) + self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + self.assertTrue(len(caught_warnings) > 0) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" @@ -88,20 +103,27 @@ def test_pauli_expect_op_vector(self): converted_meas = self.expect.convert(~StateFn(paulis_op)) plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) - np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_plus = self.sampler.convert(plus_mean) + np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) + + minus_mean = converted_meas @ Minus + sampled_minus = self.sampler.convert(minus_mean) + np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) - minus_mean = converted_meas @ Minus - sampled_minus = self.sampler.convert(minus_mean) - np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) + zero_mean = converted_meas @ Zero + sampled_zero = self.sampler.convert(zero_mean) + np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) - zero_mean = converted_meas @ Zero - sampled_zero = self.sampler.convert(zero_mean) - np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) + sum_zero = (Plus + Minus) * (0.5**0.5) + sum_zero_mean = converted_meas @ sum_zero + sampled_zero_mean = self.sampler.convert(sum_zero_mean) + self.assertTrue(len(caught_warnings) > 0) - sum_zero = (Plus + Minus) * (0.5**0.5) - sum_zero_mean = converted_meas @ sum_zero - sampled_zero_mean = self.sampler.convert(sum_zero_mean) # !!NOTE!!: Depolarizing channel (Sampling) means interference # does not happen between circuits in sum, so expectation does # not equal expectation for Zero!! @@ -113,7 +135,13 @@ def test_pauli_expect_state_vector(self): paulis_op = X converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) # Small test to see if execution results are accessible for composed_op in sampled: @@ -129,7 +157,13 @@ def test_pauli_expect_non_hermitian_matrixop(self): op = MatrixOp(op_mat) converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), [3, 0, 3, 0], decimal=1) @@ -140,7 +174,13 @@ def test_pauli_expect_non_hermitian_pauliop(self): op = 1j * X converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1j, -1j], decimal=1) @@ -156,7 +196,13 @@ def test_pauli_expect_op_vector_state_vector(self): [+1, 1, 1, 1], ] converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_multi_representation_ops(self): @@ -165,7 +211,13 @@ def test_multi_representation_ops(self): converted_meas = self.expect.convert(~StateFn(mixed_ops)) plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_plus = self.sampler.convert(plus_mean) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 ) @@ -201,8 +253,14 @@ def generate_parameters(num): return param_bindings def validate_sampler(ideal, sut, param_bindings): - expect_sampled = ideal.convert(expect_op, params=param_bindings).eval() - actual_sampled = sut.convert(expect_op, params=param_bindings).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + expect_sampled = ideal.convert(expect_op, params=param_bindings).eval() + actual_sampled = sut.convert(expect_op, params=param_bindings).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertTrue( np.allclose(actual_sampled, expect_sampled), f"{actual_sampled} != {expect_sampled}", @@ -236,9 +294,15 @@ def validate_aer_templates_reused(prev_templates, cur_templates): def test_pauli_expectation_param_qobj(self): """Test PauliExpectation with param_qobj""" - q_instance = QuantumInstance( - self.backend, seed_simulator=self.seed, seed_transpiler=self.seed, shots=10000 - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + self.backend, seed_simulator=self.seed, seed_transpiler=self.seed, shots=10000 + ) + self.assertTrue(len(caught_warnings) > 0) qubit_op = (0.1 * I ^ I) + (0.2 * I ^ Z) + (0.3 * Z ^ I) + (0.4 * Z ^ Z) + (0.5 * X ^ X) ansatz = RealAmplitudes(qubit_op.num_qubits) ansatz_circuit_op = CircuitStateFn(ansatz) @@ -250,15 +314,21 @@ def test_pauli_expectation_param_qobj(self): params1[param] = [0] params2[param] = [0, 0] - sampler1 = CircuitSampler(backend=q_instance, param_qobj=False) - samples1 = sampler1.convert(expect_op, params=params1) - val1 = np.real(samples1.eval())[0] - samples2 = sampler1.convert(expect_op, params=params2) - val2 = np.real(samples2.eval()) - sampler2 = CircuitSampler(backend=q_instance, param_qobj=True) - samples3 = sampler2.convert(expect_op, params=params1) - val3 = np.real(samples3.eval()) - samples4 = sampler2.convert(expect_op, params=params2) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampler1 = CircuitSampler(backend=q_instance, param_qobj=False) + samples1 = sampler1.convert(expect_op, params=params1) + val1 = np.real(samples1.eval())[0] + samples2 = sampler1.convert(expect_op, params=params2) + val2 = np.real(samples2.eval()) + sampler2 = CircuitSampler(backend=q_instance, param_qobj=True) + samples3 = sampler2.convert(expect_op, params=params1) + val3 = np.real(samples3.eval()) + samples4 = sampler2.convert(expect_op, params=params2) + self.assertTrue(len(caught_warnings) > 0) val4 = np.real(samples4.eval()) np.testing.assert_array_almost_equal([val1] * 2, val2, decimal=2) @@ -277,12 +347,24 @@ def test_expectation_with_coeff(self): """Test AerPauliExpectation with coefficients.""" with self.subTest("integer coefficients"): exp = 3 * ~StateFn(X) @ (2 * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + target = self.sampler.convert(self.expect.convert(exp)).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(target, -12) with self.subTest("complex coefficients"): exp = 3j * ~StateFn(X) @ (2j * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + target = self.sampler.convert(self.expect.convert(exp)).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(target, -12j) diff --git a/test/python/opflow/test_expectation_factory.py b/test/python/opflow/test_expectation_factory.py index 47c9302e8c54..83cee6a0bcbb 100644 --- a/test/python/opflow/test_expectation_factory.py +++ b/test/python/opflow/test_expectation_factory.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -16,20 +16,18 @@ from test.python.opflow import QiskitOpflowTestCase from qiskit.opflow import PauliExpectation, AerPauliExpectation, ExpectationFactory, Z, I, X -from qiskit.utils import has_aer - - -if has_aer(): - from qiskit import Aer +from qiskit.utils import optionals class TestExpectationFactory(QiskitOpflowTestCase): """Tests for the expectation factory.""" - @unittest.skipUnless(has_aer(), "qiskit-aer doesn't appear to be installed.") + @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_aer_simulator_pauli_sum(self): """Test expectation selection with Aer's qasm_simulator.""" - backend = Aer.get_backend("aer_simulator") + from qiskit_aer import AerSimulator + + backend = AerSimulator() op = 0.2 * (X ^ X) + 0.1 * (Z ^ I) with self.subTest("Defaults"): diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index f66d1cbd9971..078282642fa0 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2021. +# (C) Copyright IBM 2019, 2023. # # 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 @@ -15,6 +15,7 @@ import unittest from test.python.opflow import QiskitOpflowTestCase +import warnings from itertools import product import numpy as np from ddt import ddt, data, idata, unpack @@ -998,13 +999,27 @@ def test_circuit_sampler(self, method): ] backend = BasicAer.get_backend("qasm_simulator") - q_instance = QuantumInstance(backend=backend, shots=shots) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance(backend=backend, shots=shots) + self.assertTrue(len(caught_warnings) > 0) - for i, value_dict in enumerate(values_dict): - sampler = CircuitSampler(backend=q_instance).convert( - state_grad, params={k: [v] for k, v in value_dict.items()} + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, ) - np.testing.assert_array_almost_equal(sampler.eval()[0], correct_values[i], decimal=1) + for i, value_dict in enumerate(values_dict): + sampler = CircuitSampler(backend=q_instance).convert( + state_grad, params={k: [v] for k, v in value_dict.items()} + ) + np.testing.assert_array_almost_equal( + sampler.eval()[0], correct_values[i], decimal=1 + ) + self.assertTrue(len(caught_warnings) > 0) @data("lin_comb", "param_shift", "fin_diff") def test_circuit_sampler2(self, method): @@ -1048,13 +1063,25 @@ def test_circuit_sampler2(self, method): ] backend = BasicAer.get_backend("qasm_simulator") - q_instance = QuantumInstance(backend=backend, shots=shots) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance(backend=backend, shots=shots) + self.assertTrue(len(caught_warnings) > 0) - for i, value_dict in enumerate(values_dict): - sampler = CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict) - result = sampler.eval()[0] - self.assertTrue(np.allclose(result[0].toarray(), correct_values[i][0], atol=0.1)) - self.assertTrue(np.allclose(result[1].toarray(), correct_values[i][1], atol=0.1)) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for i, value_dict in enumerate(values_dict): + sampler = CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict) + result = sampler.eval()[0] + self.assertTrue(np.allclose(result[0].toarray(), correct_values[i][0], atol=0.1)) + self.assertTrue(np.allclose(result[1].toarray(), correct_values[i][1], atol=0.1)) + self.assertTrue(len(caught_warnings) > 0) @idata(["statevector_simulator", "qasm_simulator"]) def test_gradient_wrapper(self, backend_type): @@ -1079,9 +1106,15 @@ def test_gradient_wrapper(self, backend_type): shots = 8000 backend = BasicAer.get_backend(backend_type) - q_instance = QuantumInstance( - backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 + ) + self.assertTrue(len(caught_warnings) > 0) if method == "fin_diff": np.random.seed(8) prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( @@ -1097,13 +1130,19 @@ def test_gradient_wrapper(self, backend_type): [[1 / 4, -1 / 4], [1 / 4, -1 / 4]], [[0, 0], [-1 / 2, 1 / 2]], ] - for i, value in enumerate(values): - result = prob_grad(value) - if backend_type == "qasm_simulator": # sparse result - result = [result[0].toarray(), result[1].toarray()] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for i, value in enumerate(values): + result = prob_grad(value) + if backend_type == "qasm_simulator": # sparse result + result = [result[0].toarray(), result[1].toarray()] - self.assertTrue(np.allclose(result[0], correct_values[i][0], atol=0.1)) - self.assertTrue(np.allclose(result[1], correct_values[i][1], atol=0.1)) + self.assertTrue(np.allclose(result[0], correct_values[i][0], atol=0.1)) + self.assertTrue(np.allclose(result[1], correct_values[i][1], atol=0.1)) + self.assertTrue(len(caught_warnings) > 0) @data(("statevector_simulator", 1e-7), ("qasm_simulator", 2e-1)) @unpack @@ -1137,16 +1176,28 @@ def test_gradient_wrapper2(self, backend_type, atol): values = [[0, np.pi / 2], [np.pi / 4, np.pi / 4], [np.pi / 3, np.pi / 9]] correct_values = [[-4.0, 0], [-2.0, -4.82842712], [-0.68404029, -7.01396121]] - for i, value in enumerate(values): - backend = BasicAer.get_backend(backend_type) - q_instance = QuantumInstance( - backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 - ) - grad = NaturalGradient(grad_method=method).gradient_wrapper( - operator=op, bind_params=params, backend=q_instance + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, ) - result = grad(value) - self.assertTrue(np.allclose(result, correct_values[i], atol=atol)) + for i, value in enumerate(values): + backend = BasicAer.get_backend(backend_type) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 + ) + self.assertTrue(len(caught_warnings) > 0) + grad = NaturalGradient(grad_method=method).gradient_wrapper( + operator=op, bind_params=params, backend=q_instance + ) + result = grad(value) + self.assertTrue(np.allclose(result, correct_values[i], atol=atol)) + self.assertTrue(len(caught_warnings) > 0) @slow_test def test_vqe(self): @@ -1154,9 +1205,15 @@ def test_vqe(self): method = "lin_comb" backend = "qasm_simulator" - q_instance = QuantumInstance( - BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2 - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2 + ) + self.assertTrue(len(caught_warnings) > 0) # Define the Hamiltonian h2_hamiltonian = ( -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) @@ -1183,11 +1240,16 @@ def test_vqe(self): grad = Gradient(grad_method=method) # Gradient callable - vqe = VQE( - ansatz=wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=q_instance - ) - - result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + vqe = VQE( + ansatz=wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=q_instance + ) + result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_almost_equal(result.optimal_value, h2_energy, decimal=0) def test_qfi_overlap_works_with_bound_parameters(self): @@ -1497,22 +1559,33 @@ def test_aux_meas_op(self, aux_meas_op): ], ] - for backend_type in ["qasm_simulator", "statevector_simulator"]: - - for j, value_dict in enumerate(value_dicts): - - q_instance = QuantumInstance( - backend=BasicAer.get_backend(backend_type), shots=shots - ) - result = ( - CircuitSampler(backend=q_instance) - .convert(prob_grad, params=value_dict) - .eval()[0] - ) - if backend_type == "qasm_simulator": # sparse result - result = [result[0].toarray()[0], result[1].toarray()[0]] - for i, item in enumerate(result): - np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for backend_type in ["qasm_simulator", "statevector_simulator"]: + + for j, value_dict in enumerate(value_dicts): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + backend=BasicAer.get_backend(backend_type), shots=shots + ) + self.assertTrue(len(caught_warnings) > 0) + result = ( + CircuitSampler(backend=q_instance) + .convert(prob_grad, params=value_dict) + .eval()[0] + ) + if backend_type == "qasm_simulator": # sparse result + result = [result[0].toarray()[0], result[1].toarray()[0]] + for i, item in enumerate(result): + np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1) + self.assertTrue(len(caught_warnings) > 0) def test_unsupported_aux_meas_op(self): """Test error for unsupported auxiliary measurement operator in LinComb Gradient. @@ -1544,7 +1617,13 @@ def test_unsupported_aux_meas_op(self): value_dict = {a: [np.pi / 4], b: [0]} backend = BasicAer.get_backend("qasm_simulator") - q_instance = QuantumInstance(backend=backend, shots=shots) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance(backend=backend, shots=shots) + self.assertTrue(len(caught_warnings) > 0) CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() def test_nat_grad_error(self): @@ -1577,14 +1656,26 @@ def test_nat_grad_error(self): value = [0, np.pi / 2] backend = BasicAer.get_backend(backend_type) - q_instance = QuantumInstance( - backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 + ) + self.assertTrue(len(caught_warnings) > 0) grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) - with self.assertRaises(ValueError): - grad(value) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.assertRaises(ValueError): + grad(value) + self.assertTrue(len(caught_warnings) > 0) if __name__ == "__main__": diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index 06fb28efce78..c3f78ebafa84 100644 --- a/test/python/opflow/test_matrix_expectation.py +++ b/test/python/opflow/test_matrix_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2020. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -10,10 +10,11 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -" Test MatrixExpectation" +"""Test MatrixExpectation""" import unittest from test.python.opflow import QiskitOpflowTestCase +import warnings import itertools import numpy as np @@ -45,7 +46,15 @@ def setUp(self) -> None: super().setUp() self.seed = 97 backend = BasicAer.get_backend("statevector_simulator") - q_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + backend, seed_simulator=self.seed, seed_transpiler=self.seed + ) + self.assertTrue(len(caught_warnings) > 0) self.sampler = CircuitSampler(q_instance, attach_results=True) self.expect = MatrixExpectation() @@ -57,45 +66,64 @@ def test_pauli_expect_pair(self): converted_meas = self.expect.convert(~StateFn(op) @ wf) self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" paulis = [Z, X, Y, I] states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - for pauli, state in itertools.product(paulis, states): - converted_meas = self.expect.convert(~StateFn(pauli) @ state) - matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() - self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for pauli, state in itertools.product(paulis, states): + converted_meas = self.expect.convert(~StateFn(pauli) @ state) + matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() + self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) - sampled = self.sampler.convert(converted_meas) - self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + sampled = self.sampler.convert(converted_meas) + self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + self.assertTrue(len(caught_warnings) > 0) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" paulis_op = ListOp([X, Y, Z, I]) converted_meas = self.expect.convert(~StateFn(paulis_op)) - plus_mean = converted_meas @ Plus - np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) - sampled_plus = self.sampler.convert(plus_mean) - np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) - - minus_mean = converted_meas @ Minus - np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1) - sampled_minus = self.sampler.convert(minus_mean) - np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) - - zero_mean = converted_meas @ Zero - np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1) - sampled_zero = self.sampler.convert(zero_mean) - np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) - - sum_zero = (Plus + Minus) * (0.5**0.5) - sum_zero_mean = converted_meas @ sum_zero - np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1) - sampled_zero = self.sampler.convert(sum_zero) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + plus_mean = converted_meas @ Plus + np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) + sampled_plus = self.sampler.convert(plus_mean) + np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) + + minus_mean = converted_meas @ Minus + np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1) + sampled_minus = self.sampler.convert(minus_mean) + np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) + + zero_mean = converted_meas @ Zero + np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1) + sampled_zero = self.sampler.convert(zero_mean) + np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) + + sum_zero = (Plus + Minus) * (0.5**0.5) + sum_zero_mean = converted_meas @ sum_zero + np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1) + sampled_zero = self.sampler.convert(sum_zero) + self.assertTrue(len(caught_warnings) > 0) + np.testing.assert_array_almost_equal( (converted_meas @ sampled_zero).eval(), [0, 0, 1, 1], decimal=1 ) @@ -126,7 +154,13 @@ def test_pauli_expect_state_vector(self): converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) # Small test to see if execution results are accessible @@ -142,7 +176,13 @@ def test_pauli_expect_op_vector_state_vector(self): converted_meas = self.expect.convert(~StateFn(paulis_op)) np.testing.assert_array_almost_equal((converted_meas @ states_op).eval(), valids, decimal=1) - sampled = self.sampler.convert(states_op) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(states_op) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal((converted_meas @ sampled).eval(), valids, decimal=1) def test_multi_representation_ops(self): @@ -151,7 +191,13 @@ def test_multi_representation_ops(self): converted_meas = self.expect.convert(~StateFn(mixed_ops)) plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_plus = self.sampler.convert(plus_mean) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 ) diff --git a/test/python/opflow/test_pauli_expectation.py b/test/python/opflow/test_pauli_expectation.py index a70ae06da9d0..e1202eb0ba80 100644 --- a/test/python/opflow/test_pauli_expectation.py +++ b/test/python/opflow/test_pauli_expectation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -15,6 +15,7 @@ import itertools import unittest from test.python.opflow import QiskitOpflowTestCase +import warnings import numpy as np @@ -50,7 +51,15 @@ def setUp(self) -> None: super().setUp() self.seed = 97 backend = BasicAer.get_backend("qasm_simulator") - q_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + backend, seed_simulator=self.seed, seed_transpiler=self.seed + ) + self.assertTrue(len(caught_warnings) > 0) self.sampler = CircuitSampler(q_instance, attach_results=True) self.expect = PauliExpectation() @@ -62,7 +71,13 @@ def test_pauli_expect_pair(self): converted_meas = self.expect.convert(~StateFn(op) @ wf) self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): @@ -74,7 +89,13 @@ def test_pauli_expect_single(self): matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) def test_pauli_expect_op_vector(self): @@ -84,23 +105,47 @@ def test_pauli_expect_op_vector(self): plus_mean = converted_meas @ Plus np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) - sampled_plus = self.sampler.convert(plus_mean) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_plus = self.sampler.convert(plus_mean) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) minus_mean = converted_meas @ Minus np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1) - sampled_minus = self.sampler.convert(minus_mean) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_minus = self.sampler.convert(minus_mean) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) zero_mean = converted_meas @ Zero np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1) - sampled_zero = self.sampler.convert(zero_mean) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_zero = self.sampler.convert(zero_mean) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) sum_zero = (Plus + Minus) * (0.5**0.5) sum_zero_mean = converted_meas @ sum_zero np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1) - sampled_zero_mean = self.sampler.convert(sum_zero_mean) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_zero_mean = self.sampler.convert(sum_zero_mean) + self.assertTrue(len(caught_warnings) > 0) # !!NOTE!!: Depolarizing channel (Sampling) means interference # does not happen between circuits in sum, so expectation does # not equal expectation for Zero!! @@ -131,8 +176,13 @@ def test_pauli_expect_state_vector(self): paulis_op = X converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) - - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) # Small test to see if execution results are accessible @@ -147,8 +197,13 @@ def test_pauli_expect_op_vector_state_vector(self): valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1) - - sampled = self.sampler.convert(converted_meas) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = self.sampler.convert(converted_meas) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_to_matrix_called(self): @@ -203,11 +258,17 @@ def test_grouped_pauli_expectation(self): self.assertEqual(num_circuits_ungrouped, 5) expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf) - q_instance = QuantumInstance( - BasicAer.get_backend("statevector_simulator"), - seed_simulator=self.seed, - seed_transpiler=self.seed, - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + BasicAer.get_backend("statevector_simulator"), + seed_simulator=self.seed, + seed_transpiler=self.seed, + ) + self.assertTrue(len(caught_warnings) > 0) sampler = CircuitSampler(q_instance) sampler._extract_circuitstatefns(expect_op_grouped) num_circuits_grouped = len(sampler._circuit_ops_cache) @@ -220,8 +281,15 @@ def test_ibmq_grouped_pauli_expectation(self): p = IBMQ.load_account() backend = p.get_backend("ibmq_qasm_simulator") - q_instance = QuantumInstance(backend, seed_simulator=self.seed, seed_transpiler=self.seed) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance( + backend, seed_simulator=self.seed, seed_transpiler=self.seed + ) + self.assertTrue(len(caught_warnings) > 0) paulis_op = ListOp([X, Y, Z, I]) states_op = ListOp([One, Zero, Plus, Minus]) @@ -236,7 +304,13 @@ def test_multi_representation_ops(self): converted_meas = self.expect.convert(~StateFn(mixed_ops)) plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled_plus = self.sampler.convert(plus_mean) + self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 ) @@ -258,12 +332,24 @@ def test_expectation_with_coeff(self): """Test PauliExpectation with coefficients.""" with self.subTest("integer coefficients"): exp = 3 * ~StateFn(X) @ (2 * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + target = self.sampler.convert(self.expect.convert(exp)).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(target, -12) with self.subTest("complex coefficients"): exp = 3j * ~StateFn(X) @ (2j * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + target = self.sampler.convert(self.expect.convert(exp)).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(target, -12j) diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index c39da2f359f2..3beba1fb8aae 100644 --- a/test/python/opflow/test_state_op_meas_evals.py +++ b/test/python/opflow/test_state_op_meas_evals.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2021. +# (C) Copyright IBM 2018, 2023. # # 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 @@ -17,6 +17,7 @@ import unittest from test.python.opflow import QiskitOpflowTestCase +import warnings from ddt import ddt, data import numpy @@ -76,16 +77,34 @@ def test_coefficients_correctly_propagated(self): self.assertEqual((~StateFn(op) @ state).eval(), 0j) backend = Aer.get_backend("aer_simulator") - q_instance = QuantumInstance(backend, seed_simulator=97, seed_transpiler=97) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance(backend, seed_simulator=97, seed_transpiler=97) + self.assertTrue(len(caught_warnings) > 0) op = I with self.subTest("zero coeff in summed StateFn and CircuitSampler"): state = 0 * (Plus + Minus) - sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state) + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(sampler.eval(), 0j) with self.subTest("coeff gets squared in CircuitSampler shot-based readout"): state = (Plus + Minus) / numpy.sqrt(2) - sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(sampler.eval(), 1 + 0j) def test_is_measurement_correctly_propagated(self): @@ -96,9 +115,21 @@ def test_is_measurement_correctly_propagated(self): self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") return backend = Aer.get_backend("aer_simulator") - q_instance = QuantumInstance(backend) # no seeds needed since no values are compared + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + q_instance = QuantumInstance(backend) # no seeds needed since no values are compared + self.assertTrue(len(caught_warnings) > 0) state = Plus - sampler = CircuitSampler(q_instance).convert(~state @ state) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampler = CircuitSampler(q_instance).convert(~state @ state) + self.assertTrue(len(caught_warnings) > 0) self.assertTrue(sampler.oplist[0].is_measurement) def test_parameter_binding_on_listop(self): @@ -121,7 +152,13 @@ def test_parameter_binding_on_listop(self): listop = ListOp([StateFn(circuit) for circuit in [circuit1, circuit2, circuit3]]) sampler = CircuitSampler(Aer.get_backend("aer_simulator")) - sampled = sampler.convert(listop, params=bindings) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampled = sampler.convert(listop, params=bindings) + self.assertTrue(len(caught_warnings) > 0) self.assertTrue(all(len(op.parameters) == 0 for op in sampled.oplist)) @@ -150,8 +187,13 @@ def test_single_parameter_binds(self): expr = ~StateFn(H) @ StateFn(circuit) sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector")) - - res = sampler.convert(expr, params={x: 0}).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = sampler.convert(expr, params={x: 0}).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertIsInstance(res, complex) @@ -172,10 +214,16 @@ def test_circuit_sampler_caching(self, caching): sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector"), caching=caching) - res1 = sampler.convert(expr1, params={x: 0}).eval() - res2 = sampler.convert(expr2, params={x: 0}).eval() - res3 = sampler.convert(expr1, params={x: 0}).eval() - res4 = sampler.convert(expr2, params={x: 0}).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res1 = sampler.convert(expr1, params={x: 0}).eval() + res2 = sampler.convert(expr2, params={x: 0}).eval() + res3 = sampler.convert(expr1, params={x: 0}).eval() + res4 = sampler.convert(expr2, params={x: 0}).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res1, res3) self.assertEqual(res2, res4) @@ -215,7 +263,13 @@ def test_quantum_instance_with_backend_shots(self): backend = AerSimulator(shots=10) sampler = CircuitSampler(backend) - res = sampler.convert(~Plus @ Plus).eval() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = sampler.convert(~Plus @ Plus).eval() + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(res, 1 + 0j, places=2) def test_adjoint_vector_to_circuit_fn(self): diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index 4a79627995ef..16dbdbb207bc 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -13,7 +13,7 @@ """Tests for Estimator.""" import unittest - +import warnings import numpy as np from ddt import data, ddt, unpack @@ -62,7 +62,13 @@ def test_estimator(self): """test for a simple use case""" lst = [("XX", 1), ("YY", 2), ("ZZ", 3)] with self.subTest("PauliSumOp"): - observable = PauliSumOp.from_list(lst) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + observable = PauliSumOp.from_list(lst) + self.assertTrue(len(caught_warnings) > 0) ansatz = RealAmplitudes(num_qubits=2, reps=2) with self.assertWarns(DeprecationWarning): est = Estimator([ansatz], [observable]) @@ -81,7 +87,13 @@ def test_estimator(self): def test_estimator_param_reverse(self): """test for the reverse parameter""" - observable = PauliSumOp.from_list([("XX", 1), ("YY", 2), ("ZZ", 3)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + observable = PauliSumOp.from_list([("XX", 1), ("YY", 2), ("ZZ", 3)]) + self.assertTrue(len(caught_warnings) > 0) ansatz = RealAmplitudes(num_qubits=2, reps=2) with self.assertWarns(DeprecationWarning): est = Estimator([ansatz], [observable], [ansatz.parameters[::-1]]) diff --git a/test/python/result/test_sampled_expval.py b/test/python/result/test_sampled_expval.py index 65ebc3dd966f..8cac9042b406 100644 --- a/test/python/result/test_sampled_expval.py +++ b/test/python/result/test_sampled_expval.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2017, 2018. +# (C) Copyright IBM 2017, 2023. # # 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 @@ -13,7 +13,7 @@ """Tests for qiskit.quantum_info.analysis""" import unittest - +import warnings from qiskit.result import Counts, QuasiDistribution, ProbDistribution, sampled_expectation_value from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.opflow import PauliOp, PauliSumOp @@ -83,11 +83,23 @@ def test_same(self): exp2 = sampled_expectation_value(counts, Pauli(oper)) self.assertAlmostEqual(exp2, ans) - exp3 = sampled_expectation_value(counts, PauliOp(Pauli(oper))) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + exp3 = sampled_expectation_value(counts, PauliOp(Pauli(oper))) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(exp3, ans) spo = SparsePauliOp([oper], coeffs=[1]) - exp4 = sampled_expectation_value(counts, PauliSumOp(spo, coeff=2)) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + exp4 = sampled_expectation_value(counts, PauliSumOp(spo, coeff=2)) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(exp4, 2 * ans) exp5 = sampled_expectation_value(counts, SparsePauliOp.from_list([[oper, 1]])) diff --git a/test/python/transpiler/test_swap_strategy_router.py b/test/python/transpiler/test_swap_strategy_router.py index fe94206d497e..74667d505e0e 100644 --- a/test/python/transpiler/test_swap_strategy_router.py +++ b/test/python/transpiler/test_swap_strategy_router.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022. +# (C) Copyright IBM 2022, 2023. # # 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 @@ -12,6 +12,7 @@ """Tests for swap strategy routers.""" +import warnings from ddt import ddt, data from qiskit.circuit import QuantumCircuit, Qubit, QuantumRegister @@ -77,7 +78,13 @@ def test_basic_zz(self): """ - op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) @@ -113,7 +120,13 @@ def test_basic_xx(self): └─────────────────┘ └────────────────┘ """ - op = PauliSumOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) + self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 3), range(4)) @@ -150,7 +163,13 @@ def test_idle_qubit(self): q_3: ───────────────────────────────────────── """ - op = PauliSumOp.from_list([("IIXX", 1), ("IXIX", 2)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("IIXX", 1), ("IXIX", 2)]) + self.assertTrue(len(caught_warnings) > 0) cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (2, 3)]) swap_strat = SwapStrategy(cmap, swap_layers=(((0, 1),),)) @@ -191,7 +210,13 @@ def test_basic_xx_with_measure(self): 0 1 2 3 """ - op = PauliSumOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) + self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4, 4) circ.append(PauliEvolutionGate(op, 3), range(4)) @@ -258,10 +283,16 @@ def test_qaoa(self): for idx in range(4): mixer.ry(-idx, idx) - op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) - circ = QAOAAnsatz(op, reps=2, mixer_operator=mixer) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + circ = QAOAAnsatz(op, reps=2, mixer_operator=mixer) + swapped = self.pm_.run(circ.decompose()) + self.assertTrue(len(caught_warnings) > 0) - swapped = self.pm_.run(circ.decompose()) param_dict = {p: idx + 1 for idx, p in enumerate(swapped.parameters)} swapped.assign_parameters(param_dict, inplace=True) @@ -303,7 +334,13 @@ def test_enlarge_with_ancilla(self): """This pass tests that idle qubits after an embedding are left idle.""" # Create a four qubit problem. - op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) @@ -380,7 +417,13 @@ def test_ccx(self): Commuting2qGateRouter(swap_strat), ] ) - op = PauliSumOp.from_list([("IZZ", 1), ("ZIZ", 2)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("IZZ", 1), ("ZIZ", 2)]) + self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(3)) circ.ccx(0, 2, 1) @@ -424,21 +467,27 @@ def test_t_device(self): swap_strat = SwapStrategy(cmap, swaps) - # A dense Pauli op. - op = PauliSumOp.from_list( - [ - ("IIIZZ", 1), - ("IIZIZ", 2), - ("IZIIZ", 3), - ("ZIIIZ", 4), - ("IIZZI", 5), - ("IZIZI", 6), - ("ZIIZI", 7), - ("IZZII", 8), - ("ZIZII", 9), - ("ZZIII", 10), - ] - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # A dense Pauli op. + op = PauliSumOp.from_list( + [ + ("IIIZZ", 1), + ("IIZIZ", 2), + ("IZIIZ", 3), + ("ZIIIZ", 4), + ("IIZZI", 5), + ("IZIZI", 6), + ("ZIIZI", 7), + ("IZZII", 8), + ("ZIZII", 9), + ("ZZIII", 10), + ] + ) + self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(5) circ.append(PauliEvolutionGate(op, 1), range(5)) @@ -495,7 +544,13 @@ def inst_info(op, qargs, qreg): def test_single_qubit_circuit(self): """Test that a circuit with only single qubit gates is left unchanged.""" - op = PauliSumOp.from_list([("IIIX", 1), ("IIXI", 2), ("IZII", 3), ("XIII", 4)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("IIIX", 1), ("IIXI", 2), ("IZII", 3), ("XIII", 4)]) + self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) @@ -508,7 +563,13 @@ def test_single_qubit_circuit(self): ) def test_edge_coloring(self, edge_coloring): """Test that the edge coloring works.""" - op = PauliSumOp.from_list([("IIZZ", 1), ("IZZI", 2), ("ZZII", 3), ("ZIZI", 4)]) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list([("IIZZ", 1), ("IZZI", 2), ("ZZII", 3), ("ZIZI", 4)]) + self.assertTrue(len(caught_warnings) > 0) swaps = (((1, 2),),) cmap = CouplingMap([[0, 1], [1, 2], [2, 3]]) @@ -572,9 +633,15 @@ def setUp(self): super().setUp() # A fully connected problem. - op = PauliSumOp.from_list( - [("IIZZ", 1), ("IZIZ", 1), ("ZIIZ", 1), ("IZZI", 1), ("ZIZI", 1), ("ZZII", 1)] - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = PauliSumOp.from_list( + [("IIZZ", 1), ("IZIZ", 1), ("ZIIZ", 1), ("IZZI", 1), ("ZIZI", 1), ("ZZII", 1)] + ) + self.assertTrue(len(caught_warnings) > 0) self.circ = QuantumCircuit(4) self.circ.append(PauliEvolutionGate(op, 1), range(4)) diff --git a/test/python/utils/mitigation/test_meas.py b/test/python/utils/mitigation/test_meas.py index 21c6322b09bd..e10f47ea77f9 100644 --- a/test/python/utils/mitigation/test_meas.py +++ b/test/python/utils/mitigation/test_meas.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2021. +# (C) Copyright IBM 2021, 2023. # # 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 @@ -28,6 +28,7 @@ """ import unittest +import warnings import numpy as np import qiskit @@ -46,9 +47,9 @@ if optionals.HAS_AER: # pylint: disable=no-name-in-module - from qiskit.providers.aer import Aer - from qiskit.providers.aer.noise import NoiseModel - from qiskit.providers.aer.noise.errors.standard_errors import pauli_error + from qiskit_aer import AerSimulator + from qiskit_aer.noise import NoiseModel + from qiskit_aer.noise.errors.standard_errors import pauli_error # fixed seed for tests - for both simulator and transpiler SEED = 42 @@ -156,7 +157,7 @@ def meas_calibration_circ_execution(shots: int, seed: int): noise_model.add_all_qubit_quantum_error(error_meas, "measure") # run the circuits multiple times - backend = qiskit.Aer.get_backend("qasm_simulator") + backend = AerSimulator() cal_results = qiskit.execute( meas_calibs, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed ).result() @@ -193,7 +194,7 @@ def tensored_calib_circ_execution(shots: int, seed: int): noise_model.add_all_qubit_quantum_error(error_meas, "measure") # run the circuits multiple times - backend = qiskit.Aer.get_backend("qasm_simulator") + backend = AerSimulator() cal_results = qiskit.execute( meas_calibs, backend=backend, shots=shots, noise_model=noise_model, seed_simulator=seed ).result() @@ -278,16 +279,30 @@ def test_ideal_meas_cal(self): # Generate the quantum register according to the pattern qubits, weight = self.choose_calibration(nq, pattern_type) - # Generate the calibration circuits - meas_calibs, state_labels = complete_meas_cal(qubit_list=qubits, circlabel="test") + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Generate the calibration circuits + meas_calibs, state_labels = complete_meas_cal( + qubit_list=qubits, circlabel="test" + ) + self.assertTrue(len(caught_warnings) > 0) # Perform an ideal execution on the generated circuits - backend = Aer.get_backend("qasm_simulator") + backend = AerSimulator() job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots) cal_results = job.result() - # Make a calibration matrix - meas_cal = CompleteMeasFitter(cal_results, state_labels, circlabel="test") + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Make a calibration matrix + meas_cal = CompleteMeasFitter(cal_results, state_labels, circlabel="test") + self.assertTrue(len(caught_warnings) > 0) # Assert that the calibration matrix is equal to identity IdentityMatrix = np.identity(2**weight) @@ -307,8 +322,14 @@ def test_ideal_meas_cal(self): # Generate ideal (equally distributed) results results_dict, results_list = self.generate_ideal_results(state_labels, weight) - # Output the filter - meas_filter = meas_cal.filter + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Output the filter + meas_filter = meas_cal.filter + self.assertTrue(len(caught_warnings) > 0) # Apply the calibration matrix to results # in list and dict forms using different methods @@ -329,10 +350,16 @@ def test_ideal_meas_cal(self): def test_meas_cal_on_circuit(self): """Test an execution on a circuit.""" # Generate the calibration circuits - meas_calibs, state_labels, ghz = meas_calib_circ_creation() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + meas_calibs, state_labels, ghz = meas_calib_circ_creation() + self.assertTrue(len(caught_warnings) > 0) # Run the calibration circuits - backend = Aer.get_backend("qasm_simulator") + backend = AerSimulator() job = qiskit.execute( meas_calibs, backend=backend, @@ -342,8 +369,14 @@ def test_meas_cal_on_circuit(self): ) cal_results = job.result() - # Make a calibration matrix - meas_cal = CompleteMeasFitter(cal_results, state_labels) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Make a calibration matrix + meas_cal = CompleteMeasFitter(cal_results, state_labels) + self.assertTrue(len(caught_warnings) > 0) # Calculate the fidelity fidelity = meas_cal.readout_fidelity() @@ -355,7 +388,13 @@ def test_meas_cal_on_circuit(self): # Predicted equally distributed results predicted_results = {"000": 0.5, "111": 0.5} - meas_filter = meas_cal.filter + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + meas_filter = meas_cal.filter + self.assertTrue(len(caught_warnings) > 0) # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( @@ -390,14 +429,26 @@ def test_ideal_tensored_meas_cal(self): meas_layout = [1, 2, 3, 4, 5, 6] # Generate the calibration circuits - meas_calibs, _ = tensored_meas_cal(mit_pattern=mit_pattern) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + meas_calibs, _ = tensored_meas_cal(mit_pattern=mit_pattern) + self.assertTrue(len(caught_warnings) > 0) # Perform an ideal execution on the generated circuits - backend = Aer.get_backend("qasm_simulator") + backend = AerSimulator() cal_results = qiskit.execute(meas_calibs, backend=backend, shots=self.shots).result() - # Make calibration matrices - meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Make calibration matrices + meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) + self.assertTrue(len(caught_warnings) > 0) # Assert that the calibration matrices are equal to identity cal_matrices = meas_cal.cal_matrices @@ -419,20 +470,24 @@ def test_ideal_tensored_meas_cal(self): "Error: the average fidelity is not equal to 1", ) - # Generate ideal (equally distributed) results - results_dict, _ = self.generate_ideal_results(count_keys(6), 6) - - # Output the filter - meas_filter = meas_cal.filter - - # Apply the calibration matrix to results - # in list and dict forms using different methods - results_dict_1 = meas_filter.apply( - results_dict, method="least_squares", meas_layout=meas_layout - ) - results_dict_0 = meas_filter.apply( - results_dict, method="pseudo_inverse", meas_layout=meas_layout - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Generate ideal (equally distributed) results + results_dict, _ = self.generate_ideal_results(count_keys(6), 6) + # Output the filter + meas_filter = meas_cal.filter + # Apply the calibration matrix to results + # in list and dict forms using different methods + results_dict_1 = meas_filter.apply( + results_dict, method="least_squares", meas_layout=meas_layout + ) + results_dict_0 = meas_filter.apply( + results_dict, method="pseudo_inverse", meas_layout=meas_layout + ) + self.assertTrue(len(caught_warnings) > 0) # Assert that the results are equally distributed self.assertDictEqual(results_dict, results_dict_0) @@ -444,11 +499,17 @@ def test_ideal_tensored_meas_cal(self): def test_tensored_meas_cal_on_circuit(self): """Test an execution on a circuit.""" - # Generate the calibration circuits - meas_calibs, mit_pattern, ghz, meas_layout = tensored_calib_circ_creation() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Generate the calibration circuits + meas_calibs, mit_pattern, ghz, meas_layout = tensored_calib_circ_creation() + self.assertTrue(len(caught_warnings) > 0) # Run the calibration circuits - backend = Aer.get_backend("qasm_simulator") + backend = AerSimulator() cal_results = qiskit.execute( meas_calibs, backend=backend, @@ -457,8 +518,14 @@ def test_tensored_meas_cal_on_circuit(self): seed_transpiler=SEED, ).result() - # Make a calibration matrix - meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + # Make a calibration matrix + meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) + self.assertTrue(len(caught_warnings) > 0) # Calculate the fidelity fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1) @@ -469,15 +536,20 @@ def test_tensored_meas_cal_on_circuit(self): # Predicted equally distributed results predicted_results = {"000": 0.5, "111": 0.5} - meas_filter = meas_cal.filter - - # Calculate the results after mitigation - output_results_pseudo_inverse = meas_filter.apply( - results, method="pseudo_inverse", meas_layout=meas_layout - ).get_counts(0) - output_results_least_square = meas_filter.apply( - results, method="least_squares", meas_layout=meas_layout - ).get_counts(0) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + meas_filter = meas_cal.filter + # Calculate the results after mitigation + output_results_pseudo_inverse = meas_filter.apply( + results, method="pseudo_inverse", meas_layout=meas_layout + ).get_counts(0) + output_results_least_square = meas_filter.apply( + results, method="least_squares", meas_layout=meas_layout + ).get_counts(0) + self.assertTrue(len(caught_warnings) > 0) # Compare with expected fidelity and expected results self.assertAlmostEqual(fidelity, 1.0) @@ -501,89 +573,99 @@ def test_meas_fitter_with_noise(self): """Test the MeasurementFitter with noise.""" tests = [] runs = 3 - for run in range(runs): - cal_results, state_labels, circuit_results = meas_calibration_circ_execution( - 1000, SEED + run - ) - - meas_cal = CompleteMeasFitter(cal_results, state_labels) - meas_filter = MeasurementFilter(meas_cal.cal_matrix, state_labels) - - # Calculate the results after mitigation - results_pseudo_inverse = meas_filter.apply(circuit_results, method="pseudo_inverse") - results_least_square = meas_filter.apply(circuit_results, method="least_squares") - tests.append( - { - "cal_matrix": convert_ndarray_to_list_in_data(meas_cal.cal_matrix), - "fidelity": meas_cal.readout_fidelity(), - "results": circuit_results, - "results_pseudo_inverse": results_pseudo_inverse, - "results_least_square": results_least_square, - } + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, ) + for run in range(runs): + cal_results, state_labels, circuit_results = meas_calibration_circ_execution( + 1000, SEED + run + ) - # Set the state labels - state_labels = ["000", "001", "010", "011", "100", "101", "110", "111"] - meas_cal = CompleteMeasFitter(None, state_labels, circlabel="test") + meas_cal = CompleteMeasFitter(cal_results, state_labels) + meas_filter = MeasurementFilter(meas_cal.cal_matrix, state_labels) + + # Calculate the results after mitigation + results_pseudo_inverse = meas_filter.apply(circuit_results, method="pseudo_inverse") + results_least_square = meas_filter.apply(circuit_results, method="least_squares") + tests.append( + { + "cal_matrix": convert_ndarray_to_list_in_data(meas_cal.cal_matrix), + "fidelity": meas_cal.readout_fidelity(), + "results": circuit_results, + "results_pseudo_inverse": results_pseudo_inverse, + "results_least_square": results_least_square, + } + ) + # Set the state labels + state_labels = ["000", "001", "010", "011", "100", "101", "110", "111"] + meas_cal = CompleteMeasFitter(None, state_labels, circlabel="test") - for tst_index, _ in enumerate(tests): - # Set the calibration matrix - meas_cal.cal_matrix = tests[tst_index]["cal_matrix"] - # Calculate the fidelity - fidelity = meas_cal.readout_fidelity() + for tst_index, _ in enumerate(tests): + # Set the calibration matrix + meas_cal.cal_matrix = tests[tst_index]["cal_matrix"] + # Calculate the fidelity + fidelity = meas_cal.readout_fidelity() - meas_filter = MeasurementFilter(tests[tst_index]["cal_matrix"], state_labels) + meas_filter = MeasurementFilter(tests[tst_index]["cal_matrix"], state_labels) - # Calculate the results after mitigation - output_results_pseudo_inverse = meas_filter.apply( - tests[tst_index]["results"], method="pseudo_inverse" - ) - output_results_least_square = meas_filter.apply( - tests[tst_index]["results"], method="least_squares" - ) + # Calculate the results after mitigation + output_results_pseudo_inverse = meas_filter.apply( + tests[tst_index]["results"], method="pseudo_inverse" + ) + output_results_least_square = meas_filter.apply( + tests[tst_index]["results"], method="least_squares" + ) - # Compare with expected fidelity and expected results - self.assertAlmostEqual(fidelity, tests[tst_index]["fidelity"], places=0) - self.assertAlmostEqual( - output_results_pseudo_inverse["000"], - tests[tst_index]["results_pseudo_inverse"]["000"], - places=0, - ) + # Compare with expected fidelity and expected results + self.assertAlmostEqual(fidelity, tests[tst_index]["fidelity"], places=0) + self.assertAlmostEqual( + output_results_pseudo_inverse["000"], + tests[tst_index]["results_pseudo_inverse"]["000"], + places=0, + ) - self.assertAlmostEqual( - output_results_least_square["000"], - tests[tst_index]["results_least_square"]["000"], - places=0, - ) + self.assertAlmostEqual( + output_results_least_square["000"], + tests[tst_index]["results_least_square"]["000"], + places=0, + ) - self.assertAlmostEqual( - output_results_pseudo_inverse["111"], - tests[tst_index]["results_pseudo_inverse"]["111"], - places=0, - ) + self.assertAlmostEqual( + output_results_pseudo_inverse["111"], + tests[tst_index]["results_pseudo_inverse"]["111"], + places=0, + ) - self.assertAlmostEqual( - output_results_least_square["111"], - tests[tst_index]["results_least_square"]["111"], - places=0, - ) + self.assertAlmostEqual( + output_results_least_square["111"], + tests[tst_index]["results_least_square"]["111"], + places=0, + ) + self.assertTrue(len(caught_warnings) > 0) def test_tensored_meas_fitter_with_noise(self): """Test the TensoredFitter with noise.""" - cal_results, mit_pattern, circuit_results, meas_layout = tensored_calib_circ_execution( - 1000, SEED - ) - - meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) - meas_filter = meas_cal.filter + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + cal_results, mit_pattern, circuit_results, meas_layout = tensored_calib_circ_execution( + 1000, SEED + ) + meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) + meas_filter = meas_cal.filter + # Calculate the results after mitigation + results_pseudo_inverse = meas_filter.apply( + circuit_results.get_counts(), method="pseudo_inverse", meas_layout=meas_layout + ) + results_least_square = meas_filter.apply( + circuit_results.get_counts(), method="least_squares", meas_layout=meas_layout + ) + self.assertTrue(len(caught_warnings) > 0) - # Calculate the results after mitigation - results_pseudo_inverse = meas_filter.apply( - circuit_results.get_counts(), method="pseudo_inverse", meas_layout=meas_layout - ) - results_least_square = meas_filter.apply( - circuit_results.get_counts(), method="least_squares", meas_layout=meas_layout - ) saved_info = { "cal_results": cal_results.to_dict(), "results": circuit_results.to_dict(), @@ -597,26 +679,37 @@ def test_tensored_meas_fitter_with_noise(self): saved_info["cal_results"] = Result.from_dict(saved_info["cal_results"]) saved_info["results"] = Result.from_dict(saved_info["results"]) - meas_cal = TensoredMeasFitter( - saved_info["cal_results"], mit_pattern=saved_info["mit_pattern"] - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + meas_cal = TensoredMeasFitter( + saved_info["cal_results"], mit_pattern=saved_info["mit_pattern"] + ) + self.assertTrue(len(caught_warnings) > 0) # Calculate the fidelity fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1) # Compare with expected fidelity and expected results self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0) - meas_filter = meas_cal.filter - - # Calculate the results after mitigation - output_results_pseudo_inverse = meas_filter.apply( - saved_info["results"].get_counts(0), - method="pseudo_inverse", - meas_layout=saved_info["meas_layout"], - ) - output_results_least_square = meas_filter.apply( - saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"] - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + meas_filter = meas_cal.filter + # Calculate the results after mitigation + output_results_pseudo_inverse = meas_filter.apply( + saved_info["results"].get_counts(0), + method="pseudo_inverse", + meas_layout=saved_info["meas_layout"], + ) + output_results_least_square = meas_filter.apply( + saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"] + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual( output_results_pseudo_inverse["000"], @@ -643,30 +736,40 @@ def test_tensored_meas_fitter_with_noise(self): ) substates_list = [] - for qubit_list in saved_info["mit_pattern"]: - substates_list.append(count_keys(len(qubit_list))[::-1]) - - fitter_other_order = TensoredMeasFitter( - saved_info["cal_results"], - substate_labels_list=substates_list, - mit_pattern=saved_info["mit_pattern"], - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + for qubit_list in saved_info["mit_pattern"]: + substates_list.append(count_keys(len(qubit_list))[::-1]) + fitter_other_order = TensoredMeasFitter( + saved_info["cal_results"], + substate_labels_list=substates_list, + mit_pattern=saved_info["mit_pattern"], + ) + self.assertTrue(len(caught_warnings) > 0) fidelity = fitter_other_order.readout_fidelity(0) * meas_cal.readout_fidelity(1) self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0) - meas_filter = fitter_other_order.filter - - # Calculate the results after mitigation - output_results_pseudo_inverse = meas_filter.apply( - saved_info["results"].get_counts(0), - method="pseudo_inverse", - meas_layout=saved_info["meas_layout"], - ) - output_results_least_square = meas_filter.apply( - saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"] - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + meas_filter = fitter_other_order.filter + # Calculate the results after mitigation + output_results_pseudo_inverse = meas_filter.apply( + saved_info["results"].get_counts(0), + method="pseudo_inverse", + meas_layout=saved_info["meas_layout"], + ) + output_results_least_square = meas_filter.apply( + saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"] + ) + self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual( output_results_pseudo_inverse["000"], From 24dc67874ff5711ebefc69fb51347d25ce188744 Mon Sep 17 00:00:00 2001 From: Manoel Marques Date: Wed, 8 Feb 2023 12:15:55 -0500 Subject: [PATCH 03/47] Add link to url guide --- qiskit/opflow/converters/abelian_grouper.py | 10 +- qiskit/opflow/converters/circuit_sampler.py | 10 +- qiskit/opflow/converters/converter_base.py | 10 +- .../opflow/converters/dict_to_circuit_sum.py | 10 +- .../opflow/converters/pauli_basis_change.py | 10 +- .../opflow/converters/two_qubit_reduction.py | 10 +- qiskit/opflow/evolutions/evolution_base.py | 10 +- qiskit/opflow/evolutions/evolution_factory.py | 11 +- qiskit/opflow/evolutions/evolved_op.py | 10 +- qiskit/opflow/evolutions/matrix_evolution.py | 10 +- .../evolutions/pauli_trotter_evolution.py | 10 +- .../evolutions/trotterizations/qdrift.py | 10 +- .../evolutions/trotterizations/suzuki.py | 10 +- .../evolutions/trotterizations/trotter.py | 10 +- .../trotterizations/trotterization_base.py | 10 +- .../trotterizations/trotterization_factory.py | 11 +- qiskit/opflow/exceptions.py | 10 +- .../expectations/aer_pauli_expectation.py | 10 +- .../opflow/expectations/cvar_expectation.py | 10 +- .../opflow/expectations/expectation_base.py | 10 +- .../expectations/expectation_factory.py | 11 +- .../opflow/expectations/matrix_expectation.py | 10 +- .../opflow/expectations/pauli_expectation.py | 10 +- .../circuit_gradients/circuit_gradient.py | 10 +- .../gradients/circuit_gradients/lin_comb.py | 10 +- .../circuit_gradients/param_shift.py | 10 +- .../gradients/circuit_qfis/circuit_qfi.py | 10 +- .../gradients/circuit_qfis/lin_comb_full.py | 10 +- .../circuit_qfis/overlap_block_diag.py | 10 +- .../gradients/circuit_qfis/overlap_diag.py | 10 +- qiskit/opflow/gradients/derivative_base.py | 10 +- qiskit/opflow/gradients/gradient.py | 10 +- qiskit/opflow/gradients/gradient_base.py | 10 +- qiskit/opflow/gradients/hessian.py | 10 +- qiskit/opflow/gradients/hessian_base.py | 10 +- qiskit/opflow/gradients/natural_gradient.py | 10 +- qiskit/opflow/gradients/qfi.py | 10 +- qiskit/opflow/gradients/qfi_base.py | 10 +- qiskit/opflow/list_ops/composed_op.py | 10 +- qiskit/opflow/list_ops/list_op.py | 10 +- qiskit/opflow/list_ops/summed_op.py | 10 +- qiskit/opflow/list_ops/tensored_op.py | 10 +- qiskit/opflow/mixins/star_algebra.py | 10 +- qiskit/opflow/mixins/tensor.py | 10 +- qiskit/opflow/operator_base.py | 10 +- qiskit/opflow/operator_globals.py | 11 +- qiskit/opflow/primitive_ops/circuit_op.py | 10 +- qiskit/opflow/primitive_ops/matrix_op.py | 10 +- qiskit/opflow/primitive_ops/pauli_op.py | 10 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 10 +- qiskit/opflow/primitive_ops/primitive_op.py | 10 +- .../primitive_ops/tapered_pauli_sum_op.py | 10 +- qiskit/opflow/state_fns/circuit_state_fn.py | 10 +- qiskit/opflow/state_fns/cvar_measurement.py | 10 +- qiskit/opflow/state_fns/dict_state_fn.py | 10 +- qiskit/opflow/state_fns/operator_state_fn.py | 10 +- .../state_fns/sparse_vector_state_fn.py | 10 +- qiskit/opflow/state_fns/state_fn.py | 10 +- qiskit/opflow/state_fns/vector_state_fn.py | 10 +- qiskit/opflow/utils.py | 29 +++-- qiskit/utils/backend_utils.py | 101 ++++++++++++------ qiskit/utils/deprecation.py | 96 ++++++++++++++++- qiskit/utils/measurement_error_mitigation.py | 38 ++++--- qiskit/utils/mitigation/_filters.py | 18 ++-- qiskit/utils/mitigation/circuits.py | 29 +++-- qiskit/utils/mitigation/fitters.py | 18 ++-- qiskit/utils/quantum_instance.py | 10 +- qiskit/utils/run_circuits.py | 20 ++-- .../deprecate-opflow-qi-32f7e27884deea3f.yaml | 2 + 69 files changed, 625 insertions(+), 330 deletions(-) diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index 6eaf0e57e323..43a18081b4d7 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class AbelianGrouper(ConverterBase): @@ -42,9 +42,11 @@ class AbelianGrouper(ConverterBase): diagonalized together. """ - @deprecate_function( - "The AbelianGrouper opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="AbelianGrouper", + url="https://qisk.it/opflow_migration", ) def __init__(self, traverse: bool = True) -> None: """ diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index aab8a8af855e..3750c6b3b6c7 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -33,7 +33,7 @@ from qiskit.providers import Backend from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend from qiskit.utils.quantum_instance import QuantumInstance -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -53,9 +53,11 @@ class CircuitSampler(ConverterBase): you are better off using a different CircuitSampler for each Operator to avoid cache thrashing. """ - @deprecate_function( - "The CircuitSampler opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="CircuitSampler", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index f4eed24b44e8..5d115834fa2f 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -15,7 +15,7 @@ from abc import ABC, abstractmethod from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class ConverterBase(ABC): @@ -30,9 +30,11 @@ class ConverterBase(ABC): in the number of qubits unless a clever trick is known (such as the use of sparse matrices).""" - @deprecate_function( - "The ConverterBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="ConverterBase", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index 7eb042b2d549..e30e4fa04631 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -18,7 +18,7 @@ from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class DictToCircuitSum(ConverterBase): @@ -29,9 +29,11 @@ class DictToCircuitSum(ConverterBase): or ``VectorStateFns``, rather than both. """ - @deprecate_function( - "The DictToCircuitSum opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="DictToCircuitSum", + url="https://qisk.it/opflow_migration", ) def __init__( self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index fe621bbdfa42..8d39853bc3f3 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -30,7 +30,7 @@ from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Pauli -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class PauliBasisChange(ConverterBase): @@ -56,9 +56,11 @@ class PauliBasisChange(ConverterBase): this method, such as the placement of the CNOT chains. """ - @deprecate_function( - "The PauliBasisChange opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="PauliBasisChange", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index 939185639a8c..cc4b518e00ed 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -20,7 +20,7 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.tapered_pauli_sum_op import Z2Symmetries from qiskit.quantum_info import Pauli -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -36,9 +36,11 @@ class TwoQubitReduction(ConverterBase): sectors, (block spin order) according to the number of particles in the system. """ - @deprecate_function( - "The TwoQubitReduction opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="TwoQubitReduction", + url="https://qisk.it/opflow_migration", ) def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): """ diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index 30aae7f5afe9..488f8e9bf63d 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -16,7 +16,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.converters.converter_base import ConverterBase -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class EvolutionBase(ConverterBase, ABC): @@ -30,9 +30,11 @@ class EvolutionBase(ConverterBase, ABC): """ - @deprecate_function( - "The EvolutionBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="EvolutionBase", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index b98600796fd9..8c2ac0afa8b5 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -16,7 +16,7 @@ from qiskit.opflow.evolutions.evolution_base import EvolutionBase from qiskit.opflow.evolutions.pauli_trotter_evolution import PauliTrotterEvolution from qiskit.opflow.evolutions.matrix_evolution import MatrixEvolution -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class EvolutionFactory: @@ -25,9 +25,12 @@ class EvolutionFactory: """ @staticmethod - @deprecate_function( - "The EvolutionFactory.build opflow method is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="EvolutionFactory.build", + old_type="method", + url="https://qisk.it/opflow_migration", ) def build(operator: OperatorBase = None) -> EvolutionBase: r""" diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index 836eceb905dc..673110c15b5f 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class EvolvedOp(PrimitiveOp): @@ -40,9 +40,11 @@ class EvolvedOp(PrimitiveOp): but would have ended up copying and pasting a lot of code from PrimitiveOp.""" primitive: PrimitiveOp - @deprecate_function( - "The EvolvedOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="EvolvedOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, primitive: OperatorBase, coeff: Union[complex, ParameterExpression] = 1.0 diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index e1bf5a60edca..3857f5008515 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -20,7 +20,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.pauli_op import PauliOp -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -31,9 +31,11 @@ class MatrixEvolution(EvolutionBase): ``UnitaryGates`` or ``HamiltonianGates`` containing the exponentiation of the Operator. """ - @deprecate_function( - "The MatrixEvolution opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="MatrixEvolution", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index a4859ec2b0ab..38117e97cffd 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -32,7 +32,7 @@ from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg # TODO uncomment when we implement Abelian grouped evolution. # from qiskit.opflow.converters.abelian_grouper import AbelianGrouper @@ -51,9 +51,11 @@ class PauliTrotterEvolution(EvolutionBase): evolution circuits are composed together by Trotterization scheme. """ - @deprecate_function( - "The PauliTrotterEvolution opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="PauliTrotterEvolution", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 036d38f6ef12..1b0e6c797065 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -26,7 +26,7 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg # pylint: disable=invalid-name @@ -37,9 +37,11 @@ class QDrift(TrotterizationBase): of Earl Campbell in https://arxiv.org/abs/1811.08017. """ - @deprecate_function( - "The QDrift opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="QDrift", + url="https://qisk.it/opflow_migration", ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index 68fce87d85aa..38374e707a8d 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -23,7 +23,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class Suzuki(TrotterizationBase): @@ -35,9 +35,11 @@ class Suzuki(TrotterizationBase): Detailed in https://arxiv.org/pdf/quant-ph/0508139.pdf. """ - @deprecate_function( - "The Suzuki opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="Suzuki", + url="https://qisk.it/opflow_migration", ) def __init__(self, reps: int = 1, order: int = 2) -> None: """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index f139185a608d..27dfc4becabe 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -13,7 +13,7 @@ """ Trotter Class """ from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class Trotter(Suzuki): @@ -22,9 +22,11 @@ class Trotter(Suzuki): together ``reps`` times and dividing the evolution time of each by ``reps``. """ - @deprecate_function( - "The Trotter opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="Trotter", + url="https://qisk.it/opflow_migration", ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 2bcd474109e8..2c5c878ccc2e 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -16,7 +16,7 @@ from qiskit.opflow.evolutions.evolution_base import EvolutionBase from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg # TODO centralize handling of commuting groups @@ -26,9 +26,11 @@ class TrotterizationBase(EvolutionBase): operator sums by compositions of exponentiations. """ - @deprecate_function( - "The TrotterizationBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="TrotterizationBase", + url="https://qisk.it/opflow_migration", ) def __init__(self, reps: int = 1) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index c6e4f5e5da9d..73fb3137a560 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -16,16 +16,19 @@ from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki from qiskit.opflow.evolutions.trotterizations.trotter import Trotter from qiskit.opflow.evolutions.trotterizations.trotterization_base import TrotterizationBase -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class TrotterizationFactory: """Deprecation: A factory for conveniently creating TrotterizationBase instances.""" @staticmethod - @deprecate_function( - "The TrotterizationFactory.build opflow method is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="TrotterizationFactory.build", + old_type="method", + url="https://qisk.it/opflow_migration", ) def build(mode: str = "trotter", reps: int = 1) -> TrotterizationBase: """A factory for conveniently creating TrotterizationBase instances. diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index aba2a3098433..b9fa70778e48 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -13,15 +13,17 @@ """Exception for errors raised by Opflow module.""" from qiskit.exceptions import QiskitError -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class OpflowError(QiskitError): """Deprecation: For Opflow specific errors.""" - @deprecate_function( - "The OpflowError opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="OpflowError", + url="https://qisk.it/opflow_migration", ) def __init__(self, *message): """Set the error message.""" diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index b004c95d8bc8..edbc437652e0 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -28,7 +28,7 @@ from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.quantum_info import SparsePauliOp -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -39,9 +39,11 @@ class AerPauliExpectation(ExpectationBase): """ - @deprecate_function( - "The AerPauliExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="AerPauliExpectation", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 18ea1a6bcec3..34f7fcd2c786 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -20,7 +20,7 @@ from qiskit.opflow.list_ops import ComposedOp, ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns import CVaRMeasurement, OperatorStateFn -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class CVaRExpectation(ExpectationBase): @@ -55,9 +55,11 @@ class CVaRExpectation(ExpectationBase): """ - @deprecate_function( - "The CVaRExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="CVaRExpectation", + url="https://qisk.it/opflow_migration", ) def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) -> None: """ diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index e016f9ada6be..807273c129ca 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -19,7 +19,7 @@ from qiskit.opflow.converters import ConverterBase from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class ExpectationBase(ConverterBase): @@ -38,9 +38,11 @@ class ExpectationBase(ConverterBase): """ - @deprecate_function( - "The ExpectationBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="ExpectationBase", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index f1fa0c7514d1..2fc297df3f73 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -25,7 +25,7 @@ from qiskit.providers import Backend from qiskit.utils.backend_utils import is_aer_qasm, is_statevector_backend from qiskit.utils import QuantumInstance, optionals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -36,9 +36,12 @@ class ExpectationFactory: """ @staticmethod - @deprecate_function( - "The ExpectationFactory.build opflow method is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="ExpectationFactory.build", + old_type="method", + url="https://qisk.it/opflow_migration", ) def build( operator: OperatorBase, diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index de061eb2207e..7eaa13cd08f9 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -18,16 +18,18 @@ from qiskit.opflow.list_ops import ComposedOp, ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class MatrixExpectation(ExpectationBase): """Deprecation: An Expectation converter which converts Operator measurements to be matrix-based so they can be evaluated by matrix multiplication.""" - @deprecate_function( - "The MatrixExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="MatrixExpectation", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index 8cd9b3be1428..9fecca23b050 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -42,9 +42,11 @@ class PauliExpectation(ExpectationBase): """ - @deprecate_function( - "The PauliExpectation opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="PauliExpectation", + url="https://qisk.it/opflow_migration", ) def __init__(self, group_paulis: bool = True) -> None: """ diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index ecab623370a2..2be07768595f 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -17,7 +17,7 @@ from qiskit import QuantumCircuit, QiskitError, transpile from qiskit.circuit import ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ...converters.converter_base import ConverterBase from ...operator_base import OperatorBase @@ -36,9 +36,11 @@ class CircuitGradient(ConverterBase): DerivativeBase - uses classical techniques to differentiate operator flow data structures """ - @deprecate_function( - "The CircuitGradient opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="CircuitGradient", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 1786c347312c..4823e88bba6d 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -50,7 +50,7 @@ ZGate, ) from qiskit.quantum_info import partial_trace -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ...operator_base import OperatorBase from ...list_ops.list_op import ListOp from ...list_ops.composed_op import ComposedOp @@ -101,9 +101,11 @@ class LinComb(CircuitGradient): } # pylint: disable=signature-differs, arguments-differ - @deprecate_function( - "The LinComb opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="LinComb", + url="https://qisk.it/opflow_migration", ) def __init__(self, aux_meas_op: OperatorBase = Z): """ diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index 0ddcc3381a12..be430d75848f 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -22,7 +22,7 @@ from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from .circuit_gradient import CircuitGradient from ...operator_base import OperatorBase from ...state_fns.state_fn import StateFn @@ -47,9 +47,11 @@ class ParamShift(CircuitGradient): SUPPORTED_GATES = {"x", "y", "z", "h", "rx", "ry", "rz", "p", "u", "cx", "cy", "cz"} - @deprecate_function( - "The ParamShift opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="ParamShift", + url="https://qisk.it/opflow_migration", ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): r""" diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 898e1bb8fd20..86b7cc27d591 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -16,7 +16,7 @@ from typing import List, Union from qiskit.circuit import ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ...converters.converter_base import ConverterBase from ...operator_base import OperatorBase @@ -36,9 +36,11 @@ class CircuitQFI(ConverterBase): DerivativeBase - uses classical techniques to differentiate opflow data structures """ - @deprecate_function( - "The CircuitQFI opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="CircuitQFI", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 5a0c9874fca5..ce7cbfad71d1 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -17,7 +17,7 @@ import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ParameterVector, ParameterExpression from qiskit.utils.arithmetic import triu_to_dense -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ...operator_base import OperatorBase from ...list_ops.list_op import ListOp @@ -37,9 +37,11 @@ class LinCombFull(CircuitQFI): """ # pylint: disable=signature-differs, arguments-differ - @deprecate_function( - "The LinCombFull opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="LinCombFull", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index 827d14cf9007..3d584a2c9e9f 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -18,7 +18,7 @@ from scipy.linalg import block_diag from qiskit.circuit import Parameter, ParameterVector, ParameterExpression from qiskit.utils.arithmetic import triu_to_dense -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ...list_ops.list_op import ListOp from ...primitive_ops.circuit_op import CircuitOp from ...expectations.pauli_expectation import PauliExpectation @@ -39,9 +39,11 @@ class OverlapBlockDiag(CircuitQFI): See also :class:`~qiskit.opflow.QFI`. """ - @deprecate_function( - "The OverlapBlockDiag opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="OverlapBlockDiag", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index cc88dc6808cb..1f86877b9912 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -19,7 +19,7 @@ from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.circuit.library import RZGate, RXGate, RYGate from qiskit.converters import dag_to_circuit, circuit_to_dag -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ...list_ops.list_op import ListOp from ...primitive_ops.circuit_op import CircuitOp from ...expectations.pauli_expectation import PauliExpectation @@ -38,9 +38,11 @@ class OverlapDiag(CircuitQFI): See also :class:`~qiskit.opflow.QFI`. """ - @deprecate_function( - "The OverlapDiag opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="OverlapDiag", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 711083581b49..d0ce99e6ddde 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -20,7 +20,7 @@ from qiskit.utils.quantum_instance import QuantumInstance from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.providers import Backend -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ..converters.converter_base import ConverterBase from ..expectations import ExpectationBase, PauliExpectation @@ -49,9 +49,11 @@ class DerivativeBase(ConverterBase): DerivativeBase - uses classical techniques to differentiate opflow data structures """ - @deprecate_function( - "The DerivativeBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="DerivativeBase", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index 60c289613cec..b1d4f7a9b77e 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -19,7 +19,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.utils import optionals as _optionals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from .circuit_gradients.circuit_gradient import CircuitGradient from ..expectations.pauli_expectation import PauliExpectation from .gradient_base import GradientBase @@ -37,9 +37,11 @@ class Gradient(GradientBase): """Deprecation: Convert an operator expression to the first-order gradient.""" - @deprecate_function( - "The Gradient opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="Gradient", + url="https://qisk.it/opflow_migration", ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(grad_method=grad_method, **kwargs) diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index 7fda662c4ed1..6c0cb601cba8 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -14,7 +14,7 @@ from typing import Union -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from .circuit_gradients.circuit_gradient import CircuitGradient from .derivative_base import DerivativeBase @@ -25,9 +25,11 @@ class GradientBase(DerivativeBase): Convert an operator expression to the first-order gradient. """ - @deprecate_function( - "The GradientBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="GradientBase", + url="https://qisk.it/opflow_migration", ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index c76fa491103f..6de153e1636f 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -19,7 +19,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.utils import optionals as _optionals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ..operator_globals import Zero, One from ..state_fns.circuit_state_fn import CircuitStateFn from ..state_fns.state_fn import StateFn @@ -40,9 +40,11 @@ class Hessian(HessianBase): """Deprecation: Compute the Hessian of an expected value.""" - @deprecate_function( - "The Hessian opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="Hessian", + url="https://qisk.it/opflow_migration", ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(hess_method=hess_method, **kwargs) diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 82c3d0cd50be..838a11bde8e2 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -14,7 +14,7 @@ from typing import Union -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from .circuit_gradients.circuit_gradient import CircuitGradient from .derivative_base import DerivativeBase @@ -22,9 +22,11 @@ class HessianBase(DerivativeBase): """Deprecation: Base class for the Hessian of an expected value.""" - @deprecate_function( - "The HessianBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="HessianBase", + url="https://qisk.it/opflow_migration", ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index fd0569014c63..6e974d20bb21 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -20,7 +20,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.utils import optionals as _optionals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ..operator_base import OperatorBase from ..list_ops.list_op import ListOp from ..list_ops.composed_op import ComposedOp @@ -52,9 +52,11 @@ class NaturalGradient(GradientBase): where R(x) represents the penalization term. """ - @deprecate_function( - "The NaturalGradient opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="NaturalGradient", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index 7ad0dd4190ba..a52f23aaa759 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -17,7 +17,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ..list_ops.list_op import ListOp from ..expectations.pauli_expectation import PauliExpectation from ..state_fns.circuit_state_fn import CircuitStateFn @@ -37,9 +37,11 @@ class QFI(QFIBase): """ - @deprecate_function( - "The QFI opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="QFI", + url="https://qisk.it/opflow_migration", ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): super().__init__(qfi_method=qfi_method) diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index 63e39df96917..ab30032098be 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -14,7 +14,7 @@ from typing import Union -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from .derivative_base import DerivativeBase from .circuit_qfis import CircuitQFI @@ -30,9 +30,11 @@ class QFIBase(DerivativeBase): [QFI]kl= Re[〈∂kψ|∂lψ〉−〈∂kψ|ψ〉〈ψ|∂lψ〉] * 4. """ - @deprecate_function( - "The QFIBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="QFIBase", + url="https://qisk.it/opflow_migration", ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): r""" diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index 3e01f8fb3366..88f098d56d86 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -24,7 +24,7 @@ from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class ComposedOp(ListOp): @@ -34,9 +34,11 @@ class ComposedOp(ListOp): be composed, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits or matrices, they can be reduced by composition.""" - @deprecate_function( - "The ComposedOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="ComposedOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index 4bdd0c75b38c..c521c93b8a2d 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -23,7 +23,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.utils import arithmetic -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class ListOp(OperatorBase): @@ -53,9 +53,11 @@ class ListOp(OperatorBase): multiple dimensional lists. """ - @deprecate_function( - "The ListOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="ListOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index c558497068f4..fb8c958fafd1 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -21,7 +21,7 @@ from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class SummedOp(ListOp): @@ -31,9 +31,11 @@ class SummedOp(ListOp): be added together, and therefore if they reach a point in which they can be, such as after evaluation or conversion to matrices, they can be reduced by addition.""" - @deprecate_function( - "The SummedOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="SummedOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index 7adfac90d938..021e9689ed60 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -22,7 +22,7 @@ from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class TensoredOp(ListOp): @@ -32,9 +32,11 @@ class TensoredOp(ListOp): be tensored together, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits, they can be reduced by tensor product.""" - @deprecate_function( - "The TensoredOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="TensoredOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index 433186d6204b..a62b130a2364 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -16,7 +16,7 @@ from numbers import Integral from qiskit.quantum_info.operators.mixins import MultiplyMixin -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class StarAlgebraMixin(MultiplyMixin, ABC): @@ -40,9 +40,11 @@ class StarAlgebraMixin(MultiplyMixin, ABC): - :meth:`adjoint(self)` """ - @deprecate_function( - "The StarAlgebraMixin opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="StarAlgebraMixin", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index fff1202bfa9a..f8b0dba5bd28 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -14,7 +14,7 @@ from abc import ABC, abstractmethod from numbers import Integral -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class TensorMixin(ABC): @@ -28,9 +28,11 @@ class TensorMixin(ABC): - :meth:``tensorpower(self, other: int)`` """ - @deprecate_function( - "The TensorMixin opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="TensorMixin", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index a931765dd0a6..8b304fa0037e 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -25,7 +25,7 @@ from qiskit.opflow.mixins import StarAlgebraMixin, TensorMixin from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): @@ -45,9 +45,11 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): _count = itertools.count() - @deprecate_function( - "The OperatorBase opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="OperatorBase", + url="https://qisk.it/opflow_migration", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/operator_globals.py b/qiskit/opflow/operator_globals.py index 23ab364e1794..5025c0ebeb85 100644 --- a/qiskit/opflow/operator_globals.py +++ b/qiskit/opflow/operator_globals.py @@ -20,7 +20,7 @@ from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.state_fns.dict_state_fn import DictStateFn -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg # Digits of precision when returning values from eval functions. Without rounding, 1e-17 or 1e-32 # values often show up in place of 0, etc. @@ -33,9 +33,12 @@ # Immutable convenience objects -@deprecate_function( - "The make_immutable opflow function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="make_immutable", + old_type="function", + url="https://qisk.it/opflow_migration", ) def make_immutable(obj): r"""Deprecate\: Delete the __setattr__ property to make the object mostly immutable.""" diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 9d224821aec7..255274103033 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -23,7 +23,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class CircuitOp(PrimitiveOp): @@ -31,9 +31,11 @@ class CircuitOp(PrimitiveOp): primitive: QuantumCircuit - @deprecate_function( - "The CircuitOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="CircuitOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index bc18780af58f..5525ae16c148 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Operator, Statevector from qiskit.utils import arithmetic -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class MatrixOp(PrimitiveOp): @@ -36,9 +36,11 @@ class MatrixOp(PrimitiveOp): primitive: Operator - @deprecate_function( - "The MatrixOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="MatrixOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 05b57fcee97f..a7cf7f2f8c5a 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -27,7 +27,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class PauliOp(PrimitiveOp): @@ -35,9 +35,11 @@ class PauliOp(PrimitiveOp): primitive: Pauli - @deprecate_function( - "The PauliOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="PauliOp", + url="https://qisk.it/opflow_migration", ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index d79f0a53f0a9..7fb28e877d80 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -26,7 +26,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.quantum_info.operators.custom_iterator import CustomIterator -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class PauliSumOp(PrimitiveOp): @@ -34,9 +34,11 @@ class PauliSumOp(PrimitiveOp): primitive: SparsePauliOp - @deprecate_function( - "The PauliSumOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="PauliSumOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index 5d14a7808b67..0e0dc7c076aa 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -22,7 +22,7 @@ from qiskit.circuit import Instruction, ParameterExpression from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class PrimitiveOp(OperatorBase): @@ -93,9 +93,11 @@ def __new__( "factory constructor".format(type(primitive)) ) - @deprecate_function( - "The PrimitiveOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="PrimitiveOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index b46fa61b5a82..f099eac9230e 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.utils import commutator from qiskit.quantum_info import Pauli, SparsePauliOp -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -35,9 +35,11 @@ class TaperedPauliSumOp(PauliSumOp): """Deprecation: Class for PauliSumOp after tapering""" - @deprecate_function( - "The TaperedPauliSumOp opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="TaperedPauliSumOp", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index 277b210a40e5..f301ab116d12 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -33,7 +33,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class CircuitStateFn(StateFn): @@ -44,9 +44,11 @@ class CircuitStateFn(StateFn): primitive: QuantumCircuit # TODO allow normalization somehow? - @deprecate_function( - "The CircuitStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="CircuitStateFn", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index 19396a7abd8d..ec0f0e669537 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -28,7 +28,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class CVaRMeasurement(OperatorStateFn): @@ -41,9 +41,11 @@ class CVaRMeasurement(OperatorStateFn): primitive: OperatorBase # TODO allow normalization somehow? - @deprecate_function( - "The CVaRMeasurement opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="CVaRMeasurement", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index aca74e48ca62..69376aa3d253 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -27,7 +27,7 @@ from qiskit.quantum_info import Statevector from qiskit.result import Result from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class DictStateFn(StateFn): @@ -38,9 +38,11 @@ class DictStateFn(StateFn): primitive: Dict[str, complex] # TODO allow normalization somehow? - @deprecate_function( - "The DictStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="DictStateFn", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index 3ecec4421be5..39c5cdfcbcc1 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -26,7 +26,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class OperatorStateFn(StateFn): @@ -37,9 +37,11 @@ class OperatorStateFn(StateFn): primitive: OperatorBase # TODO allow normalization somehow? - @deprecate_function( - "The OperatorStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="OperatorStateFn", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index 983a8533a1fa..66ab79c84c13 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -26,7 +26,7 @@ from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class SparseVectorStateFn(StateFn): @@ -38,9 +38,11 @@ class SparseVectorStateFn(StateFn): primitive: scipy.sparse.spmatrix # TODO allow normalization somehow? - @deprecate_function( - "The SparseVectorStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="SparseVectorStateFn", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 9fc9008e62bf..d2b9d1cee32f 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -21,7 +21,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.result import Result -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class StateFn(OperatorBase): @@ -113,9 +113,11 @@ def __new__( ) # TODO allow normalization somehow? - @deprecate_function( - "The StateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="StateFn", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index 00534ce85e67..3dae50ff3fb9 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -26,7 +26,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals, arithmetic -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class VectorStateFn(StateFn): @@ -37,9 +37,11 @@ class VectorStateFn(StateFn): primitive: Statevector # TODO allow normalization somehow? - @deprecate_function( - "The VectorStateFn opflow class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="VectorStateFn", + url="https://qisk.it/opflow_migration", ) def __init__( self, diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index c4b252af3409..224b7131c335 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -13,12 +13,15 @@ """ Utility functions for OperatorFlow """ from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg -@deprecate_function( - "The commutator opflow function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="commutator", + old_type="function", + url="https://qisk.it/opflow_migration", ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" @@ -37,9 +40,12 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: return (op_a @ op_b - op_b @ op_a).reduce() -@deprecate_function( - "The anti_commutator opflow function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="anti_commutator", + old_type="function", + url="https://qisk.it/opflow_migration", ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" @@ -58,9 +64,12 @@ def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: return (op_a @ op_b + op_b @ op_a).reduce() -@deprecate_function( - "The double_commutator opflow function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="opflow", + old_name="double_commutator", + old_type="function", + url="https://qisk.it/opflow_migration", ) def double_commutator( op_a: OperatorBase, diff --git a/qiskit/utils/backend_utils.py b/qiskit/utils/backend_utils.py index 2bc77534cc82..83820b079fdc 100644 --- a/qiskit/utils/backend_utils.py +++ b/qiskit/utils/backend_utils.py @@ -13,7 +13,7 @@ """ backend utility functions """ import logging -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -50,9 +50,12 @@ def _get_backend_provider(backend): return provider -@deprecate_function( - "The has_ibmq function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="has_ibmq", + old_type="function", + url="https://qisk.it/qi_migration", ) def has_ibmq(): """Check if IBMQ is installed""" @@ -71,9 +74,12 @@ def has_ibmq(): return _PROVIDER_CHECK.has_ibmq -@deprecate_function( - "The has_aer function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="has_aer", + old_type="function", + url="https://qisk.it/qi_migration", ) def has_aer(): """check if Aer is installed""" @@ -91,9 +97,12 @@ def has_aer(): return _PROVIDER_CHECK.has_aer -@deprecate_function( - "The is_aer_provider function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_aer_provider", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_aer_provider(backend): """Detect whether or not backend is from Aer provider. @@ -115,9 +124,12 @@ def is_aer_provider(backend): return False -@deprecate_function( - "The is_basicaer_provider function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_basicaer_provider", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_basicaer_provider(backend): """Detect whether or not backend is from BasicAer provider. @@ -132,9 +144,12 @@ def is_basicaer_provider(backend): return isinstance(_get_backend_provider(backend), BasicAerProvider) -@deprecate_function( - "The is_ibmq_provider function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_ibmq_provider", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_ibmq_provider(backend): """Detect whether or not backend is from IBMQ provider. @@ -152,9 +167,12 @@ def is_ibmq_provider(backend): return False -@deprecate_function( - "The is_aer_statevector_backend function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_aer_statevector_backend", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_aer_statevector_backend(backend): """ @@ -168,9 +186,12 @@ def is_aer_statevector_backend(backend): return is_statevector_backend(backend) and is_aer_provider(backend) -@deprecate_function( - "The is_statevector_backend function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_statevector_backend", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_statevector_backend(backend): """ @@ -197,9 +218,12 @@ def is_statevector_backend(backend): return backend.name.startswith("statevector") -@deprecate_function( - "The is_simulator_backend function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_simulator_backend", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_simulator_backend(backend): """ @@ -216,9 +240,12 @@ def is_simulator_backend(backend): return False -@deprecate_function( - "The is_local_backend function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_local_backend", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_local_backend(backend): """ @@ -235,9 +262,12 @@ def is_local_backend(backend): return False -@deprecate_function( - "The is_aer_qasm function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="is_aer_qasm", + old_type="function", + url="https://qisk.it/qi_migration", ) def is_aer_qasm(backend): """ @@ -255,9 +285,12 @@ def is_aer_qasm(backend): return ret -@deprecate_function( - "The support_backend_options function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="support_backend_options", + old_type="function", + url="https://qisk.it/qi_migration", ) def support_backend_options(backend): """ diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 633c2472288d..bd28a44adcd3 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2017, 2022. +# (C) Copyright IBM 2017, 2023. # # 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 @@ -14,7 +14,99 @@ import functools import warnings -from typing import Type +from typing import Type, Optional + + +def deprecate_string_msg( + version: str, + old_module: str, + old_name: str, + old_type: Optional[str] = "class", + project_name: Optional[str] = "Qiskit Terra", + new_module: Optional[str] = None, + new_name: Optional[str] = None, + new_type: Optional[str] = None, + url: Optional[str] = None, + additional_msg: Optional[str] = None, +): + """Builds deprecated message. + + Args: + version: Version to be used + old_module: Old module to be used + old_name: Old name to be used + old_type: Old type to be used, defaults to class + project_name: project name to use, defaults to Qiskit Terra. + new_module: New module to be used, if None, old_module is used instead. + new_name: New name to be used + new_type: New type to be used, if None, old_type is used instead. + url: link to further explanations, tutorials + additional_msg: any additional message + + Returns: + Message: The build message + """ + msg = ( + f"The {old_module} {old_name} {old_type} is deprecated as of {project_name} {version} " + "and will be removed no sooner than 3 months after the release date. " + ) + if new_name is not None: + module_str = new_module if new_module is not None else old_module + type_str = new_type if new_type is not None else old_type + msg += f"Instead use the {module_str} {new_name} {type_str}. " + if url is not None: + msg += f"More details at {url}. " + if additional_msg is not None: + msg += f" {additional_msg}" + return msg + + +def deprecate_function_msg( + version: str, + old_module: str, + old_name: str, + old_type: Optional[str] = "class", + project_name: Optional[str] = "Qiskit Terra", + new_module: Optional[str] = None, + new_name: Optional[str] = None, + new_type: Optional[str] = None, + url: Optional[str] = None, + additional_msg: Optional[str] = None, + stacklevel: int = 2, + category: Type[Warning] = DeprecationWarning, +): + """Emit a warning prior to calling decorated function. + + Args: + version: Version to be used + old_module: Old module to be used + old_name: Old name to be used + old_type: Old type to be used, defaults to class + project_name: project name to use, defaults to Qiskit Terra. + new_module: New module to be used, if None, old_module is used instead. + new_name: New name to be used + new_type: New type to be used, if None, old_type is used instead. + url: link to further explanations, tutorials + additional_msg: any additional message + stacklevel: The warning stackevel to use, defaults to 2. + category: warning category, defaults to DeprecationWarning + + Returns: + Callable: The decorated, deprecated callable. + """ + msg = deprecate_string_msg( + version=version, + old_module=old_module, + old_name=old_name, + old_type=old_type, + project_name=project_name, + new_module=new_module, + new_name=new_name, + new_type=new_type, + url=url, + additional_msg=additional_msg, + ) + return deprecate_function(msg, stacklevel, category) def deprecate_arguments(kwarg_map, category: Type[Warning] = DeprecationWarning): diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index 09f69c5cdabc..71bfc1ac2e66 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -27,14 +27,17 @@ CompleteMeasFitter, TensoredMeasFitter, ) -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg # pylint: disable=invalid-name -@deprecate_function( - "The get_measured_qubits function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="get_measured_qubits", + old_type="function", + url="https://qisk.it/qi_migration", ) def get_measured_qubits( transpiled_circuits: List[QuantumCircuit], @@ -80,9 +83,12 @@ def get_measured_qubits( return sorted(qubit_index), qubit_mappings -@deprecate_function( - "The get_measured_qubits_from_qobj function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="get_measured_qubits_from_qobj", + old_type="function", + url="https://qisk.it/qi_migration", ) def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, List[int]]]: """ @@ -125,9 +131,12 @@ def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, return sorted(qubit_index), qubit_mappings -@deprecate_function( - "The build_measurement_error_mitigation_circuits function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="build_measurement_error_mitigation_circuits", + old_type="function", + url="https://qisk.it/qi_migration", ) def build_measurement_error_mitigation_circuits( qubit_list: List[int], @@ -204,9 +213,12 @@ def build_measurement_error_mitigation_circuits( return t_meas_calibs_circuits, state_labels, circlabel -@deprecate_function( - "The build_measurement_error_mitigation_qobj function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="build_measurement_error_mitigation_qobj", + old_type="function", + url="https://qisk.it/qi_migration", ) def build_measurement_error_mitigation_qobj( qubit_list: List[int], diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 69cc1e7d87c0..e681993584cc 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -31,7 +31,7 @@ from qiskit import QiskitError from qiskit.tools import parallel_map from qiskit.utils.mitigation.circuits import count_keys -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class MeasurementFilter: @@ -43,9 +43,11 @@ class MeasurementFilter: """ - @deprecate_function( - "The MeasurementFilter class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="MeasurementFilter", + url="https://qisk.it/qi_migration", ) def __init__(self, cal_matrix: np.matrix, state_labels: list): """ @@ -225,9 +227,11 @@ class TensoredFilter: to data. """ - @deprecate_function( - "The TensoredFilter class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="TensoredFilter", + url="https://qisk.it/qi_migration", ) def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): """ diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index 1139aa47834e..471df42f48a8 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -19,12 +19,15 @@ use the fitters to produce a filter. """ from typing import List, Tuple, Union -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg -@deprecate_function( - "The count_keys function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="count_keys", + old_type="function", + url="https://qisk.it/qi_migration", ) def count_keys(num_qubits: int) -> List[str]: """Deprecation: Return ordered count keys. @@ -40,9 +43,12 @@ def count_keys(num_qubits: int) -> List[str]: return [bin(j)[2:].zfill(num_qubits) for j in range(2**num_qubits)] -@deprecate_function( - "The complete_meas_cal function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="complete_meas_cal", + old_type="function", + url="https://qisk.it/qi_migration", ) def complete_meas_cal( qubit_list: List[int] = None, @@ -121,9 +127,12 @@ def complete_meas_cal( return cal_circuits, state_labels -@deprecate_function( - "The tensored_meas_cal function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="tensored_meas_cal", + old_type="function", + url="https://qisk.it/qi_migration", ) def tensored_meas_cal( mit_pattern: List[List[int]] = None, diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index e527d240f337..339746e38a63 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -27,7 +27,7 @@ from qiskit import QiskitError from qiskit.utils.mitigation.circuits import count_keys from qiskit.utils.mitigation._filters import MeasurementFilter, TensoredFilter -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg class CompleteMeasFitter: @@ -35,9 +35,11 @@ class CompleteMeasFitter: Deprecation: Measurement correction fitter for a full calibration """ - @deprecate_function( - "The CompleteMeasFitter class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="CompleteMeasFitter", + url="https://qisk.it/qi_migration", ) def __init__( self, @@ -219,9 +221,11 @@ class TensoredMeasFitter: Deprecation: Measurement correction fitter for a tensored calibration. """ - @deprecate_function( - "The TensoredMeasFitter class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="TensoredMeasFitter", + url="https://qisk.it/qi_migration", ) def __init__( self, diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index fb0c2c3f1332..7354fa2e1765 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -38,7 +38,7 @@ CompleteMeasFitter, TensoredMeasFitter, ) -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg logger = logging.getLogger(__name__) @@ -144,9 +144,11 @@ class QuantumInstance: "statevector_hpc_gate_opt", ] + _BACKEND_OPTIONS_QASM_ONLY - @deprecate_function( - "The QuantumInstance class is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " + @deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="QuantumInstance", + url="https://qisk.it/qi_migration", ) def __init__( self, diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index 4ed23ac6389d..ba79e96b91b0 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -23,7 +23,7 @@ from qiskit.providers import Backend, JobStatus, JobError, Job from qiskit.providers.jobstatus import JOB_FINAL_STATES from qiskit.result import Result -from qiskit.utils.deprecation import deprecate_function +from qiskit.utils.deprecation import deprecate_function_msg from ..exceptions import QiskitError, MissingOptionalLibraryError from .backend_utils import ( is_aer_provider, @@ -40,9 +40,12 @@ logger = logging.getLogger(__name__) -@deprecate_function( - "The find_regs_by_name function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="find_regs_by_name", + old_type="function", + url="https://qisk.it/qi_migration", ) def find_regs_by_name( circuit: QuantumCircuit, name: str, qreg: bool = True @@ -106,9 +109,12 @@ def _safe_get_job_status(job: Job, job_id: str, max_job_retries: int, wait: floa return job_status -@deprecate_function( - "The run_circuits function is deprecated as of Qiskit Terra 0.24.0 " - "and will be removed no sooner than 3 months after the release date. " +@deprecate_function_msg( + version="0.24.0", + old_module="utils", + old_name="run_circuits", + old_type="function", + url="https://qisk.it/qi_migration", ) def run_circuits( circuits: Union[QuantumCircuit, List[QuantumCircuit]], diff --git a/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml b/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml index c2152839d16e..4e55ffccf0d9 100644 --- a/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml +++ b/releasenotes/notes/deprecate-opflow-qi-32f7e27884deea3f.yaml @@ -10,3 +10,5 @@ deprecations: have been deprecated and will be removed in a future release. Using :class:`~qiskit.utils.QuantumInstance` is superseded by :class:`~qiskit.primitives.BaseSampler`. + See `Opflow Migration `__. + See `QuantumInstance Migration `__. From 62160e7196c57f981935f37c8ee687c3edde09bb Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 20 Mar 2023 17:32:31 +0100 Subject: [PATCH 04/47] Remove internal use of opflow --- qiskit/synthesis/evolution/qdrift.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/qiskit/synthesis/evolution/qdrift.py b/qiskit/synthesis/evolution/qdrift.py index 009548653988..6707fa2ec411 100644 --- a/qiskit/synthesis/evolution/qdrift.py +++ b/qiskit/synthesis/evolution/qdrift.py @@ -85,14 +85,13 @@ def synthesize(self, evolution): # pylint: disable=cyclic-import from qiskit.circuit.library.pauli_evolution import PauliEvolutionGate - from qiskit.opflow import PauliOp # Build the evolution circuit using the LieTrotter synthesis with the sampled operators lie_trotter = LieTrotter( insert_barriers=self.insert_barriers, atomic_evolution=self.atomic_evolution ) evolution_circuit = PauliEvolutionGate( - sum(PauliOp(op) for op, coeff in self.sampled_ops), + sum(SparsePauliOp(op) for op, coeff in self.sampled_ops), time=evolution_time, synthesis=lie_trotter, ).definition From c3dde51ac72b8699a5b68f636b646d1ea406cbaf Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 20 Mar 2023 17:35:26 +0100 Subject: [PATCH 05/47] Fix black --- qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py | 1 - qiskit/opflow/gradients/circuit_gradients/lin_comb.py | 2 -- qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py | 2 -- qiskit/opflow/gradients/derivative_base.py | 1 - qiskit/opflow/gradients/qfi_base.py | 1 - qiskit/utils/deprecation.py | 1 + 6 files changed, 1 insertion(+), 7 deletions(-) diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index d877d85b51df..cab2cd7a64b7 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -42,7 +42,6 @@ class CircuitGradient(ConverterBase): old_name="CircuitGradient", url="https://qisk.it/opflow_migration", ) - def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 41bb6b9baa09..4823e88bba6d 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -100,7 +100,6 @@ class LinComb(CircuitGradient): "z", } - # pylint: disable=signature-differs, arguments-differ @deprecate_function_msg( version="0.24.0", @@ -108,7 +107,6 @@ class LinComb(CircuitGradient): old_name="LinComb", url="https://qisk.it/opflow_migration", ) - def __init__(self, aux_meas_op: OperatorBase = Z): """ Args: diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 0b41d59d3f67..ce7cbfad71d1 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -36,7 +36,6 @@ class LinCombFull(CircuitQFI): See also :class:`~qiskit.opflow.QFI`. """ - # pylint: disable=signature-differs, arguments-differ @deprecate_function_msg( version="0.24.0", @@ -44,7 +43,6 @@ class LinCombFull(CircuitQFI): old_name="LinCombFull", url="https://qisk.it/opflow_migration", ) - def __init__( self, aux_meas_op: OperatorBase = Z, diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index f70f8b2fec4e..748293a62363 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -55,7 +55,6 @@ class DerivativeBase(ConverterBase): old_name="DerivativeBase", url="https://qisk.it/opflow_migration", ) - def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index 19cc6d56f895..ab30032098be 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -36,7 +36,6 @@ class QFIBase(DerivativeBase): old_name="QFIBase", url="https://qisk.it/opflow_migration", ) - def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): r""" Args: diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index c73860dc8be4..904f6a3fa33f 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -108,6 +108,7 @@ def deprecate_function_msg( ) return deprecate_function(msg, stacklevel, category) + def deprecate_arguments( kwarg_map: Dict[str, Optional[str]], category: Type[Warning] = DeprecationWarning, From b41b304f04c34d18be554fab60d2e341eef8751f Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 20 Mar 2023 18:03:41 +0100 Subject: [PATCH 06/47] Discard old changes in deprecation.py --- qiskit/utils/deprecation.py | 96 +------------------------------------ 1 file changed, 2 insertions(+), 94 deletions(-) diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 03f3e95e962d..6e91657e91ab 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2017, 2023. +# (C) Copyright IBM 2017, 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 @@ -14,99 +14,7 @@ import functools import warnings -from typing import Type, Optional - - -def deprecate_string_msg( - version: str, - old_module: str, - old_name: str, - old_type: Optional[str] = "class", - project_name: Optional[str] = "Qiskit Terra", - new_module: Optional[str] = None, - new_name: Optional[str] = None, - new_type: Optional[str] = None, - url: Optional[str] = None, - additional_msg: Optional[str] = None, -): - """Builds deprecated message. - - Args: - version: Version to be used - old_module: Old module to be used - old_name: Old name to be used - old_type: Old type to be used, defaults to class - project_name: project name to use, defaults to Qiskit Terra. - new_module: New module to be used, if None, old_module is used instead. - new_name: New name to be used - new_type: New type to be used, if None, old_type is used instead. - url: link to further explanations, tutorials - additional_msg: any additional message - - Returns: - Message: The build message - """ - msg = ( - f"The {old_module} {old_name} {old_type} is deprecated as of {project_name} {version} " - "and will be removed no sooner than 3 months after the release date. " - ) - if new_name is not None: - module_str = new_module if new_module is not None else old_module - type_str = new_type if new_type is not None else old_type - msg += f"Instead use the {module_str} {new_name} {type_str}. " - if url is not None: - msg += f"More details at {url}. " - if additional_msg is not None: - msg += f" {additional_msg}" - return msg - - -def deprecate_function_msg( - version: str, - old_module: str, - old_name: str, - old_type: Optional[str] = "class", - project_name: Optional[str] = "Qiskit Terra", - new_module: Optional[str] = None, - new_name: Optional[str] = None, - new_type: Optional[str] = None, - url: Optional[str] = None, - additional_msg: Optional[str] = None, - stacklevel: int = 2, - category: Type[Warning] = DeprecationWarning, -): - """Emit a warning prior to calling decorated function. - - Args: - version: Version to be used - old_module: Old module to be used - old_name: Old name to be used - old_type: Old type to be used, defaults to class - project_name: project name to use, defaults to Qiskit Terra. - new_module: New module to be used, if None, old_module is used instead. - new_name: New name to be used - new_type: New type to be used, if None, old_type is used instead. - url: link to further explanations, tutorials - additional_msg: any additional message - stacklevel: The warning stackevel to use, defaults to 2. - category: warning category, defaults to DeprecationWarning - - Returns: - Callable: The decorated, deprecated callable. - """ - msg = deprecate_string_msg( - version=version, - old_module=old_module, - old_name=old_name, - old_type=old_type, - project_name=project_name, - new_module=new_module, - new_name=new_name, - new_type=new_type, - url=url, - additional_msg=additional_msg, - ) - return deprecate_function(msg, stacklevel, category) +from typing import Any, Callable, Dict, Optional, Type def deprecate_arguments( From 974654dbd85556fda9a8cae3dc492807156aa79a Mon Sep 17 00:00:00 2001 From: ElePT Date: Wed, 29 Mar 2023 11:51:30 +0200 Subject: [PATCH 07/47] Update decorators --- qiskit/opflow/converters/abelian_grouper.py | 10 +- qiskit/opflow/converters/circuit_sampler.py | 11 +- qiskit/opflow/converters/converter_base.py | 11 +- .../opflow/converters/dict_to_circuit_sum.py | 11 +- .../opflow/converters/pauli_basis_change.py | 11 +- .../opflow/converters/two_qubit_reduction.py | 11 +- qiskit/opflow/evolutions/evolution_base.py | 11 +- qiskit/opflow/evolutions/evolution_factory.py | 12 +-- qiskit/opflow/evolutions/evolved_op.py | 11 +- qiskit/opflow/evolutions/matrix_evolution.py | 11 +- .../evolutions/pauli_trotter_evolution.py | 11 +- .../evolutions/trotterizations/qdrift.py | 11 +- .../evolutions/trotterizations/suzuki.py | 11 +- .../evolutions/trotterizations/trotter.py | 11 +- .../trotterizations/trotterization_base.py | 11 +- .../trotterizations/trotterization_factory.py | 12 +-- qiskit/opflow/exceptions.py | 10 +- .../expectations/aer_pauli_expectation.py | 11 +- .../opflow/expectations/cvar_expectation.py | 11 +- .../opflow/expectations/expectation_base.py | 11 +- .../expectations/expectation_factory.py | 12 +-- .../opflow/expectations/matrix_expectation.py | 11 +- .../opflow/expectations/pauli_expectation.py | 11 +- .../circuit_gradients/circuit_gradient.py | 10 +- .../gradients/circuit_gradients/lin_comb.py | 10 +- .../circuit_gradients/param_shift.py | 10 +- .../gradients/circuit_qfis/circuit_qfi.py | 10 +- .../gradients/circuit_qfis/lin_comb_full.py | 11 +- .../circuit_qfis/overlap_block_diag.py | 10 +- .../gradients/circuit_qfis/overlap_diag.py | 10 +- qiskit/opflow/gradients/derivative_base.py | 11 +- qiskit/opflow/gradients/gradient.py | 10 +- qiskit/opflow/gradients/gradient_base.py | 10 +- qiskit/opflow/gradients/hessian.py | 10 +- qiskit/opflow/gradients/hessian_base.py | 10 +- qiskit/opflow/gradients/natural_gradient.py | 10 +- qiskit/opflow/gradients/qfi.py | 10 +- qiskit/opflow/gradients/qfi_base.py | 10 +- qiskit/opflow/list_ops/composed_op.py | 10 +- qiskit/opflow/list_ops/list_op.py | 10 +- qiskit/opflow/list_ops/summed_op.py | 10 +- qiskit/opflow/list_ops/tensored_op.py | 10 +- qiskit/opflow/mixins/star_algebra.py | 10 +- qiskit/opflow/mixins/tensor.py | 10 +- qiskit/opflow/operator_base.py | 10 +- qiskit/opflow/operator_globals.py | 12 +-- qiskit/opflow/primitive_ops/circuit_op.py | 10 +- qiskit/opflow/primitive_ops/matrix_op.py | 10 +- qiskit/opflow/primitive_ops/pauli_op.py | 10 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 10 +- qiskit/opflow/primitive_ops/primitive_op.py | 10 +- .../primitive_ops/tapered_pauli_sum_op.py | 10 +- qiskit/opflow/state_fns/circuit_state_fn.py | 11 +- qiskit/opflow/state_fns/cvar_measurement.py | 11 +- qiskit/opflow/state_fns/dict_state_fn.py | 11 +- qiskit/opflow/state_fns/operator_state_fn.py | 11 +- .../state_fns/sparse_vector_state_fn.py | 11 +- qiskit/opflow/state_fns/state_fn.py | 10 +- qiskit/opflow/state_fns/vector_state_fn.py | 11 +- qiskit/opflow/utils.py | 35 +++--- qiskit/utils/backend_utils.py | 101 ++++++------------ qiskit/utils/measurement_error_mitigation.py | 3 +- qiskit/utils/mitigation/_filters.py | 18 ++-- qiskit/utils/mitigation/circuits.py | 30 ++---- qiskit/utils/mitigation/fitters.py | 18 ++-- qiskit/utils/quantum_instance.py | 10 +- qiskit/utils/run_circuits.py | 3 +- 67 files changed, 313 insertions(+), 529 deletions(-) diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index 43a18081b4d7..50cb4c954141 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class AbelianGrouper(ConverterBase): @@ -42,11 +42,9 @@ class AbelianGrouper(ConverterBase): diagonalized together. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="AbelianGrouper", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, traverse: bool = True) -> None: """ diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index e029ca2387de..0e90c0c2263a 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -33,8 +33,7 @@ from qiskit.providers import Backend from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend from qiskit.utils.quantum_instance import QuantumInstance -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -53,11 +52,9 @@ class CircuitSampler(ConverterBase): you are better off using a different CircuitSampler for each Operator to avoid cache thrashing. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="CircuitSampler", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index 5ea241051d67..4f503b83a8bd 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -15,8 +15,7 @@ from abc import ABC, abstractmethod from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class ConverterBase(ABC): r""" @@ -30,11 +29,9 @@ class ConverterBase(ABC): in the number of qubits unless a clever trick is known (such as the use of sparse matrices).""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="ConverterBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index 6bbf4baa87fa..d519ddbc843f 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -18,8 +18,7 @@ from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class DictToCircuitSum(ConverterBase): r""" @@ -29,11 +28,9 @@ class DictToCircuitSum(ConverterBase): or ``VectorStateFns``, rather than both. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="DictToCircuitSum", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index b506dbd6797c..4c1120a92e2e 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -30,8 +30,7 @@ from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Pauli -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class PauliBasisChange(ConverterBase): r""" @@ -56,11 +55,9 @@ class PauliBasisChange(ConverterBase): this method, such as the placement of the CNOT chains. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="PauliBasisChange", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index c25a87e96a85..aced893e2996 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -20,8 +20,7 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.tapered_pauli_sum_op import Z2Symmetries from qiskit.quantum_info import Pauli -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -36,11 +35,9 @@ class TwoQubitReduction(ConverterBase): sectors, (block spin order) according to the number of particles in the system. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="TwoQubitReduction", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): """ diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index aea08e02eaee..8326bcefd4aa 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -16,8 +16,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.converters.converter_base import ConverterBase -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class EvolutionBase(ConverterBase, ABC): r""" @@ -30,11 +29,9 @@ class EvolutionBase(ConverterBase, ABC): """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="EvolutionBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index 78847eaa25a3..8ae0919e3ec6 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -16,8 +16,7 @@ from qiskit.opflow.evolutions.evolution_base import EvolutionBase from qiskit.opflow.evolutions.pauli_trotter_evolution import PauliTrotterEvolution from qiskit.opflow.evolutions.matrix_evolution import MatrixEvolution -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class EvolutionFactory: """Deprecation: A factory class for convenient automatic selection of an @@ -25,12 +24,9 @@ class EvolutionFactory: """ @staticmethod - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="EvolutionFactory.build", - old_type="method", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def build(operator: OperatorBase = None) -> EvolutionBase: r""" diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index 05e295b602ad..bcdbd04b1bfa 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -27,8 +27,7 @@ from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class EvolvedOp(PrimitiveOp): r""" @@ -40,11 +39,9 @@ class EvolvedOp(PrimitiveOp): but would have ended up copying and pasting a lot of code from PrimitiveOp.""" primitive: PrimitiveOp - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="EvolvedOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, primitive: OperatorBase, coeff: Union[complex, ParameterExpression] = 1.0 diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index 554f9e9622f1..fad0ae7123b4 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -20,8 +20,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.pauli_op import PauliOp -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -31,11 +30,9 @@ class MatrixEvolution(EvolutionBase): ``UnitaryGates`` or ``HamiltonianGates`` containing the exponentiation of the Operator. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="MatrixEvolution", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 4b8dc2b3992d..6901a7cbab0e 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -32,8 +32,7 @@ from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func # TODO uncomment when we implement Abelian grouped evolution. # from qiskit.opflow.converters.abelian_grouper import AbelianGrouper @@ -51,11 +50,9 @@ class PauliTrotterEvolution(EvolutionBase): evolution circuits are composed together by Trotterization scheme. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="PauliTrotterEvolution", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 1b0e6c797065..46cca0c99193 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -26,8 +26,7 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func # pylint: disable=invalid-name @@ -37,11 +36,9 @@ class QDrift(TrotterizationBase): of Earl Campbell in https://arxiv.org/abs/1811.08017. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="QDrift", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index 5b1cda448d9a..1e37e3ce96fa 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -23,8 +23,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class Suzuki(TrotterizationBase): r""" @@ -35,11 +34,9 @@ class Suzuki(TrotterizationBase): Detailed in https://arxiv.org/pdf/quant-ph/0508139.pdf. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="Suzuki", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1, order: int = 2) -> None: """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index 366c7d8490e6..f101adb5b12b 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -13,8 +13,7 @@ """Trotter Class""" from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class Trotter(Suzuki): r""" @@ -22,11 +21,9 @@ class Trotter(Suzuki): together ``reps`` times and dividing the evolution time of each by ``reps``. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="Trotter", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 689d645b6a27..e9409cd9e112 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -16,8 +16,7 @@ from qiskit.opflow.evolutions.evolution_base import EvolutionBase from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func # TODO centralize handling of commuting groups @@ -26,11 +25,9 @@ class TrotterizationBase(EvolutionBase): operator sums by compositions of exponentiations. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="TrotterizationBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index a2210cf34aec..b926ea1f9c24 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -16,19 +16,15 @@ from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki from qiskit.opflow.evolutions.trotterizations.trotter import Trotter from qiskit.opflow.evolutions.trotterizations.trotterization_base import TrotterizationBase -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class TrotterizationFactory: """Deprecation: A factory for conveniently creating TrotterizationBase instances.""" @staticmethod - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="TrotterizationFactory.build", - old_type="method", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def build(mode: str = "trotter", reps: int = 1) -> TrotterizationBase: """A factory for conveniently creating TrotterizationBase instances. diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index b9fa70778e48..3950e5bedc95 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -13,17 +13,15 @@ """Exception for errors raised by Opflow module.""" from qiskit.exceptions import QiskitError -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class OpflowError(QiskitError): """Deprecation: For Opflow specific errors.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="OpflowError", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, *message): """Set the error message.""" diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index a5738cd8f9be..ca7829fcd19e 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -28,8 +28,7 @@ from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.quantum_info import SparsePauliOp -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -39,11 +38,9 @@ class AerPauliExpectation(ExpectationBase): """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="AerPauliExpectation", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 34f7fcd2c786..d55dbdc243b1 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -20,8 +20,7 @@ from qiskit.opflow.list_ops import ComposedOp, ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns import CVaRMeasurement, OperatorStateFn -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class CVaRExpectation(ExpectationBase): r"""Deprecation: Compute the Conditional Value at Risk (CVaR) expectation value. @@ -55,11 +54,9 @@ class CVaRExpectation(ExpectationBase): """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="CVaRExpectation", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) -> None: """ diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index 832d9c23203b..678dc7697a74 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -19,8 +19,7 @@ from qiskit.opflow.converters import ConverterBase from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class ExpectationBase(ConverterBase): r""" @@ -38,11 +37,9 @@ class ExpectationBase(ConverterBase): """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="ExpectationBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index bcfc3c2af8c5..8059e638da46 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -25,8 +25,7 @@ from qiskit.providers import Backend from qiskit.utils.backend_utils import is_aer_qasm, is_statevector_backend from qiskit.utils import QuantumInstance, optionals -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -36,12 +35,9 @@ class ExpectationFactory: """ @staticmethod - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="ExpectationFactory.build", - old_type="method", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def build( operator: OperatorBase, diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index f1d2632f1770..23dc72eb6b77 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -18,18 +18,15 @@ from qiskit.opflow.list_ops import ComposedOp, ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class MatrixExpectation(ExpectationBase): """Deprecation: An Expectation converter which converts Operator measurements to be matrix-based so they can be evaluated by matrix multiplication.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="MatrixExpectation", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index dca2520a3e70..4c3793e864e5 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -27,8 +27,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -42,11 +41,9 @@ class PauliExpectation(ExpectationBase): """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="PauliExpectation", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, group_paulis: bool = True) -> None: """ diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index cab2cd7a64b7..4e109096859a 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -17,7 +17,7 @@ from qiskit import QuantumCircuit, QiskitError, transpile from qiskit.circuit import ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ...converters.converter_base import ConverterBase from ...operator_base import OperatorBase @@ -36,11 +36,9 @@ class CircuitGradient(ConverterBase): DerivativeBase - uses classical techniques to differentiate operator flow data structures """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="CircuitGradient", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 4823e88bba6d..6d7db18b531c 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -50,7 +50,7 @@ ZGate, ) from qiskit.quantum_info import partial_trace -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ...operator_base import OperatorBase from ...list_ops.list_op import ListOp from ...list_ops.composed_op import ComposedOp @@ -101,11 +101,9 @@ class LinComb(CircuitGradient): } # pylint: disable=signature-differs, arguments-differ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="LinComb", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, aux_meas_op: OperatorBase = Z): """ diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index be430d75848f..d7105041444e 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -22,7 +22,7 @@ from qiskit import QuantumCircuit from qiskit.circuit import Parameter, ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from .circuit_gradient import CircuitGradient from ...operator_base import OperatorBase from ...state_fns.state_fn import StateFn @@ -47,11 +47,9 @@ class ParamShift(CircuitGradient): SUPPORTED_GATES = {"x", "y", "z", "h", "rx", "ry", "rz", "p", "u", "cx", "cy", "cz"} - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="ParamShift", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): r""" diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 67f834312bad..61875f8c8020 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -16,7 +16,7 @@ from typing import List, Union from qiskit.circuit import ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ...converters.converter_base import ConverterBase from ...operator_base import OperatorBase @@ -36,11 +36,9 @@ class CircuitQFI(ConverterBase): DerivativeBase - uses classical techniques to differentiate opflow data structures """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="CircuitQFI", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index ce7cbfad71d1..48d548f34e35 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -17,8 +17,7 @@ import numpy as np from qiskit.circuit import QuantumCircuit, QuantumRegister, ParameterVector, ParameterExpression from qiskit.utils.arithmetic import triu_to_dense -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func from ...operator_base import OperatorBase from ...list_ops.list_op import ListOp from ...list_ops.summed_op import SummedOp @@ -37,11 +36,9 @@ class LinCombFull(CircuitQFI): """ # pylint: disable=signature-differs, arguments-differ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="LinCombFull", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index 3d584a2c9e9f..81a871904fde 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -18,7 +18,7 @@ from scipy.linalg import block_diag from qiskit.circuit import Parameter, ParameterVector, ParameterExpression from qiskit.utils.arithmetic import triu_to_dense -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ...list_ops.list_op import ListOp from ...primitive_ops.circuit_op import CircuitOp from ...expectations.pauli_expectation import PauliExpectation @@ -39,11 +39,9 @@ class OverlapBlockDiag(CircuitQFI): See also :class:`~qiskit.opflow.QFI`. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="OverlapBlockDiag", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 1f86877b9912..fc85ac3f4b67 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -19,7 +19,7 @@ from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.circuit.library import RZGate, RXGate, RYGate from qiskit.converters import dag_to_circuit, circuit_to_dag -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ...list_ops.list_op import ListOp from ...primitive_ops.circuit_op import CircuitOp from ...expectations.pauli_expectation import PauliExpectation @@ -38,11 +38,9 @@ class OverlapDiag(CircuitQFI): See also :class:`~qiskit.opflow.QFI`. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="OverlapDiag", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 748293a62363..dfadcf2db002 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -20,8 +20,7 @@ from qiskit.utils.quantum_instance import QuantumInstance from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.providers import Backend -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func from ..converters.converter_base import ConverterBase from ..expectations import ExpectationBase, PauliExpectation from ..list_ops.composed_op import ComposedOp @@ -49,11 +48,9 @@ class DerivativeBase(ConverterBase): DerivativeBase - uses classical techniques to differentiate opflow data structures """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="DerivativeBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index b1d4f7a9b77e..de3948bc2280 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -19,7 +19,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.utils import optionals as _optionals -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from .circuit_gradients.circuit_gradient import CircuitGradient from ..expectations.pauli_expectation import PauliExpectation from .gradient_base import GradientBase @@ -37,11 +37,9 @@ class Gradient(GradientBase): """Deprecation: Convert an operator expression to the first-order gradient.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="Gradient", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(grad_method=grad_method, **kwargs) diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index 6c0cb601cba8..8618023e25c6 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -14,7 +14,7 @@ from typing import Union -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from .circuit_gradients.circuit_gradient import CircuitGradient from .derivative_base import DerivativeBase @@ -25,11 +25,9 @@ class GradientBase(DerivativeBase): Convert an operator expression to the first-order gradient. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="GradientBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 6de153e1636f..e71412e38f38 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -19,7 +19,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.utils import optionals as _optionals -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ..operator_globals import Zero, One from ..state_fns.circuit_state_fn import CircuitStateFn from ..state_fns.state_fn import StateFn @@ -40,11 +40,9 @@ class Hessian(HessianBase): """Deprecation: Compute the Hessian of an expected value.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="Hessian", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(hess_method=hess_method, **kwargs) diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 838a11bde8e2..ea3e8aa0550f 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -14,7 +14,7 @@ from typing import Union -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from .circuit_gradients.circuit_gradient import CircuitGradient from .derivative_base import DerivativeBase @@ -22,11 +22,9 @@ class HessianBase(DerivativeBase): """Deprecation: Base class for the Hessian of an expected value.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="HessianBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index 62e81a609808..a0e703f016ff 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -20,7 +20,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterVector, ParameterExpression from qiskit.utils import optionals as _optionals -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ..operator_base import OperatorBase from ..list_ops.list_op import ListOp from ..list_ops.composed_op import ComposedOp @@ -52,11 +52,9 @@ class NaturalGradient(GradientBase): where R(x) represents the penalization term. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="NaturalGradient", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index a52f23aaa759..56ad342e32de 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -17,7 +17,7 @@ from qiskit.circuit.quantumcircuit import _compare_parameters from qiskit.circuit import ParameterExpression, ParameterVector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from ..list_ops.list_op import ListOp from ..expectations.pauli_expectation import PauliExpectation from ..state_fns.circuit_state_fn import CircuitStateFn @@ -37,11 +37,9 @@ class QFI(QFIBase): """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="QFI", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): super().__init__(qfi_method=qfi_method) diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index ab30032098be..deb2e722a6fe 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -14,7 +14,7 @@ from typing import Union -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func from .derivative_base import DerivativeBase from .circuit_qfis import CircuitQFI @@ -30,11 +30,9 @@ class QFIBase(DerivativeBase): [QFI]kl= Re[〈∂kψ|∂lψ〉−〈∂kψ|ψ〉〈ψ|∂lψ〉] * 4. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="QFIBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): r""" diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index 266f2026e99e..89fe194f5270 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -24,7 +24,7 @@ from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class ComposedOp(ListOp): @@ -34,11 +34,9 @@ class ComposedOp(ListOp): be composed, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits or matrices, they can be reduced by composition.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="ComposedOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index 76722a9fbf5c..ae95a3972d3b 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -23,7 +23,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.utils import arithmetic -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class ListOp(OperatorBase): @@ -53,11 +53,9 @@ class ListOp(OperatorBase): multiple dimensional lists. """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="ListOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index 1c461072567b..a0191f2b5e2d 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -21,7 +21,7 @@ from qiskit.opflow.exceptions import OpflowError from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class SummedOp(ListOp): @@ -31,11 +31,9 @@ class SummedOp(ListOp): be added together, and therefore if they reach a point in which they can be, such as after evaluation or conversion to matrices, they can be reduced by addition.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="SummedOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index c1898e662fea..efe7e0685c9b 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -22,7 +22,7 @@ from qiskit.opflow.list_ops.list_op import ListOp from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class TensoredOp(ListOp): @@ -32,11 +32,9 @@ class TensoredOp(ListOp): be tensored together, and therefore if they reach a point in which they can be, such as after conversion to QuantumCircuits, they can be reduced by tensor product.""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="TensoredOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index a62b130a2364..b4a7e5c142c9 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -16,7 +16,7 @@ from numbers import Integral from qiskit.quantum_info.operators.mixins import MultiplyMixin -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class StarAlgebraMixin(MultiplyMixin, ABC): @@ -40,11 +40,9 @@ class StarAlgebraMixin(MultiplyMixin, ABC): - :meth:`adjoint(self)` """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="StarAlgebraMixin", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index f8b0dba5bd28..5c8fd5c75078 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -14,7 +14,7 @@ from abc import ABC, abstractmethod from numbers import Integral -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class TensorMixin(ABC): @@ -28,11 +28,9 @@ class TensorMixin(ABC): - :meth:``tensorpower(self, other: int)`` """ - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="TensorMixin", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index 17e4b307fee7..f2c94d4db04f 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -25,7 +25,7 @@ from qiskit.opflow.mixins import StarAlgebraMixin, TensorMixin from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): @@ -45,11 +45,9 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): _count = itertools.count() - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="OperatorBase", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/operator_globals.py b/qiskit/opflow/operator_globals.py index 5025c0ebeb85..eee0d1bb3680 100644 --- a/qiskit/opflow/operator_globals.py +++ b/qiskit/opflow/operator_globals.py @@ -20,8 +20,7 @@ from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.state_fns.dict_state_fn import DictStateFn -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func # Digits of precision when returning values from eval functions. Without rounding, 1e-17 or 1e-32 # values often show up in place of 0, etc. # Note: care needs to be taken in rounding otherwise some behavior may not be as expected. E.g @@ -33,12 +32,9 @@ # Immutable convenience objects -@deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="make_immutable", - old_type="function", - url="https://qisk.it/opflow_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def make_immutable(obj): r"""Deprecate\: Delete the __setattr__ property to make the object mostly immutable.""" diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 64752aafcd88..69209689fe11 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -23,7 +23,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class CircuitOp(PrimitiveOp): @@ -31,11 +31,9 @@ class CircuitOp(PrimitiveOp): primitive: QuantumCircuit - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="CircuitOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index 8bee66ebb8a3..752d61d6d3f8 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Operator, Statevector from qiskit.utils import arithmetic -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class MatrixOp(PrimitiveOp): @@ -36,11 +36,9 @@ class MatrixOp(PrimitiveOp): primitive: Operator - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="MatrixOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 54e727ff10f7..3a0c1440ad75 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -27,7 +27,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class PauliOp(PrimitiveOp): @@ -35,11 +35,9 @@ class PauliOp(PrimitiveOp): primitive: Pauli - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="PauliOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index e0cc8783dff8..3578382aef72 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -26,7 +26,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.quantum_info import Pauli, SparsePauliOp, Statevector from qiskit.quantum_info.operators.custom_iterator import CustomIterator -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class PauliSumOp(PrimitiveOp): @@ -34,11 +34,9 @@ class PauliSumOp(PrimitiveOp): primitive: SparsePauliOp - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="PauliSumOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index ad41740e6333..2277dc6d2ff9 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -22,7 +22,7 @@ from qiskit.circuit import Instruction, ParameterExpression from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class PrimitiveOp(OperatorBase): @@ -93,11 +93,9 @@ def __new__( "factory constructor".format(type(primitive)) ) - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="PrimitiveOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index 830286dc3e9f..c3183cff2b3f 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -27,7 +27,7 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.utils import commutator from qiskit.quantum_info import Pauli, SparsePauliOp -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -35,11 +35,9 @@ class TaperedPauliSumOp(PauliSumOp): """Deprecation: Class for PauliSumOp after tapering""" - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="TaperedPauliSumOp", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index 011361b6db64..ac5e8fd7b7d7 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -33,8 +33,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class CircuitStateFn(StateFn): r""" @@ -44,11 +43,9 @@ class CircuitStateFn(StateFn): primitive: QuantumCircuit # TODO allow normalization somehow? - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="CircuitStateFn", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index ec0f0e669537..236cbfe0c9be 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -28,8 +28,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class CVaRMeasurement(OperatorStateFn): r"""Deprecation: A specialized measurement class to compute CVaR expectation values. @@ -41,11 +40,9 @@ class CVaRMeasurement(OperatorStateFn): primitive: OperatorBase # TODO allow normalization somehow? - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="CVaRMeasurement", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index 63dacf87511f..7b574645641a 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -27,8 +27,7 @@ from qiskit.quantum_info import Statevector from qiskit.result import Result from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class DictStateFn(StateFn): """Deprecation: A class for state functions and measurements which are defined by a lookup table, @@ -38,11 +37,9 @@ class DictStateFn(StateFn): primitive: Dict[str, complex] # TODO allow normalization somehow? - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="DictStateFn", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index c15102cbc486..dead517be5dd 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -26,8 +26,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn from qiskit.quantum_info import Statevector -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class OperatorStateFn(StateFn): r""" @@ -37,11 +36,9 @@ class OperatorStateFn(StateFn): primitive: OperatorBase # TODO allow normalization somehow? - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="OperatorStateFn", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index 66ab79c84c13..d5a4f28c4bb4 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -26,8 +26,7 @@ from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class SparseVectorStateFn(StateFn): """Deprecation: A class for sparse state functions and measurements in vector representation. @@ -38,11 +37,9 @@ class SparseVectorStateFn(StateFn): primitive: scipy.sparse.spmatrix # TODO allow normalization somehow? - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="SparseVectorStateFn", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 84558affee99..06ec935375f6 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -21,7 +21,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.quantum_info import Statevector from qiskit.result import Result -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class StateFn(OperatorBase): @@ -113,11 +113,9 @@ def __new__( ) # TODO allow normalization somehow? - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="StateFn", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index ef35b185fc4d..2e3936aa2257 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -26,8 +26,7 @@ from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.quantum_info import Statevector from qiskit.utils import algorithm_globals, arithmetic -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func class VectorStateFn(StateFn): """Deprecation: A class for state functions and measurements which are defined in vector @@ -37,11 +36,9 @@ class VectorStateFn(StateFn): primitive: Statevector # TODO allow normalization somehow? - @deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="VectorStateFn", - url="https://qisk.it/opflow_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index a86d895f838c..6010890b0b8c 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -13,16 +13,13 @@ """Utility functions for OperatorFlow""" from qiskit.opflow.operator_base import OperatorBase -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func -@deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="commutator", - old_type="function", - url="https://qisk.it/opflow_migration", -) +@deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" Deprecation: Compute commutator of `op_a` and `op_b`. @@ -40,13 +37,10 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: return (op_a @ op_b - op_b @ op_a).reduce() -@deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="anti_commutator", - old_type="function", - url="https://qisk.it/opflow_migration", -) +@deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" Deprecation: Compute anti-commutator of `op_a` and `op_b`. @@ -64,13 +58,10 @@ def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: return (op_a @ op_b + op_b @ op_a).reduce() -@deprecate_function_msg( - version="0.24.0", - old_module="opflow", - old_name="double_commutator", - old_type="function", - url="https://qisk.it/opflow_migration", -) +@deprecate_func( + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + ) def double_commutator( op_a: OperatorBase, op_b: OperatorBase, diff --git a/qiskit/utils/backend_utils.py b/qiskit/utils/backend_utils.py index 9ff9c14e8439..e867a7ea6302 100644 --- a/qiskit/utils/backend_utils.py +++ b/qiskit/utils/backend_utils.py @@ -13,7 +13,7 @@ """backend utility functions""" import logging -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -50,12 +50,9 @@ def _get_backend_provider(backend): return provider -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="has_ibmq", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def has_ibmq(): """Check if IBMQ is installed.""" @@ -74,12 +71,9 @@ def has_ibmq(): return _PROVIDER_CHECK.has_ibmq -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="has_aer", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def has_aer(): """Check if Aer is installed.""" @@ -97,12 +91,9 @@ def has_aer(): return _PROVIDER_CHECK.has_aer -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_aer_provider", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_aer_provider(backend): """Detect whether or not backend is from Aer provider. @@ -124,12 +115,9 @@ def is_aer_provider(backend): return False -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_basicaer_provider", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_basicaer_provider(backend): """Detect whether or not backend is from BasicAer provider. @@ -144,12 +132,9 @@ def is_basicaer_provider(backend): return isinstance(_get_backend_provider(backend), BasicAerProvider) -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_ibmq_provider", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_ibmq_provider(backend): """Detect whether or not backend is from IBMQ provider. @@ -167,12 +152,9 @@ def is_ibmq_provider(backend): return False -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_aer_statevector_backend", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_aer_statevector_backend(backend): """ @@ -186,12 +168,9 @@ def is_aer_statevector_backend(backend): return is_statevector_backend(backend) and is_aer_provider(backend) -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_statevector_backend", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_statevector_backend(backend): """ @@ -218,12 +197,9 @@ def is_statevector_backend(backend): return backend.name.startswith("statevector") -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_simulator_backend", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_simulator_backend(backend): """ @@ -240,12 +216,9 @@ def is_simulator_backend(backend): return False -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_local_backend", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_local_backend(backend): """ @@ -262,12 +235,9 @@ def is_local_backend(backend): return False -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="is_aer_qasm", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def is_aer_qasm(backend): """ @@ -285,12 +255,9 @@ def is_aer_qasm(backend): return ret -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="support_backend_options", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def support_backend_options(backend): """ diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index 96c5c732f8e9..d70f9936472b 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -27,8 +27,7 @@ CompleteMeasFitter, TensoredMeasFitter, ) -from qiskit.utils.deprecation import deprecate_function_msg - +from qiskit.utils.deprecation import deprecate_func @deprecate_function_msg( version="0.24.0", diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index e681993584cc..09fdb9f99774 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -31,7 +31,7 @@ from qiskit import QiskitError from qiskit.tools import parallel_map from qiskit.utils.mitigation.circuits import count_keys -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class MeasurementFilter: @@ -43,11 +43,9 @@ class MeasurementFilter: """ - @deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="MeasurementFilter", - url="https://qisk.it/qi_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def __init__(self, cal_matrix: np.matrix, state_labels: list): """ @@ -227,11 +225,9 @@ class TensoredFilter: to data. """ - @deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="TensoredFilter", - url="https://qisk.it/qi_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): """ diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index 471df42f48a8..08c092c93089 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -19,15 +19,11 @@ use the fitters to produce a filter. """ from typing import List, Tuple, Union -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func - -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="count_keys", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def count_keys(num_qubits: int) -> List[str]: """Deprecation: Return ordered count keys. @@ -43,12 +39,9 @@ def count_keys(num_qubits: int) -> List[str]: return [bin(j)[2:].zfill(num_qubits) for j in range(2**num_qubits)] -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="complete_meas_cal", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def complete_meas_cal( qubit_list: List[int] = None, @@ -127,12 +120,9 @@ def complete_meas_cal( return cal_circuits, state_labels -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="tensored_meas_cal", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def tensored_meas_cal( mit_pattern: List[List[int]] = None, diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index 11192e4a538f..4402f41dcbb6 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -27,7 +27,7 @@ from qiskit import QiskitError from qiskit.utils.mitigation.circuits import count_keys from qiskit.utils.mitigation._filters import MeasurementFilter, TensoredFilter -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func class CompleteMeasFitter: @@ -35,11 +35,9 @@ class CompleteMeasFitter: Deprecation: Measurement correction fitter for a full calibration """ - @deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="CompleteMeasFitter", - url="https://qisk.it/qi_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def __init__( self, @@ -221,11 +219,9 @@ class TensoredMeasFitter: Deprecation: Measurement correction fitter for a tensored calibration. """ - @deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="TensoredMeasFitter", - url="https://qisk.it/qi_migration", + @deprecate_func( + since="0.24.0", + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." ) def __init__( self, diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index 7a06ff19e642..e8adc558e650 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -38,7 +38,7 @@ CompleteMeasFitter, TensoredMeasFitter, ) -from qiskit.utils.deprecation import deprecate_function_msg +from qiskit.utils.deprecation import deprecate_func logger = logging.getLogger(__name__) @@ -144,11 +144,9 @@ class QuantumInstance: "statevector_hpc_gate_opt", ] + _BACKEND_OPTIONS_QASM_ONLY - @deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="QuantumInstance", - url="https://qisk.it/qi_migration", + @deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration." ) def __init__( self, diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index 8f01d76c1686..f5f6e3d5e620 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -23,8 +23,7 @@ from qiskit.providers import Backend, JobStatus, JobError, Job from qiskit.providers.jobstatus import JOB_FINAL_STATES from qiskit.result import Result -from qiskit.utils.deprecation import deprecate_function_msg -from ..exceptions import QiskitError, MissingOptionalLibraryError +from qiskit.utils.deprecation import deprecate_funcfrom ..exceptions import QiskitError, MissingOptionalLibraryError from .backend_utils import ( is_aer_provider, is_basicaer_provider, From 50e5954ecd4a729e7101e8ea4bf493240ae8b59e Mon Sep 17 00:00:00 2001 From: ElePT Date: Wed, 29 Mar 2023 12:18:03 +0200 Subject: [PATCH 08/47] Remove from docstring --- qiskit/opflow/converters/abelian_grouper.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 2 +- qiskit/opflow/converters/converter_base.py | 2 +- qiskit/opflow/converters/dict_to_circuit_sum.py | 2 +- qiskit/opflow/converters/pauli_basis_change.py | 2 +- qiskit/opflow/converters/two_qubit_reduction.py | 2 +- qiskit/opflow/evolutions/evolution_base.py | 2 +- qiskit/opflow/evolutions/evolution_factory.py | 2 +- qiskit/opflow/evolutions/evolved_op.py | 2 +- qiskit/opflow/evolutions/matrix_evolution.py | 2 +- qiskit/opflow/evolutions/pauli_trotter_evolution.py | 2 +- qiskit/opflow/evolutions/trotterizations/qdrift.py | 2 +- qiskit/opflow/evolutions/trotterizations/suzuki.py | 2 +- qiskit/opflow/evolutions/trotterizations/trotter.py | 2 +- .../evolutions/trotterizations/trotterization_base.py | 2 +- .../evolutions/trotterizations/trotterization_factory.py | 2 +- qiskit/opflow/exceptions.py | 2 +- qiskit/opflow/expectations/aer_pauli_expectation.py | 2 +- qiskit/opflow/expectations/cvar_expectation.py | 2 +- qiskit/opflow/expectations/expectation_base.py | 2 +- qiskit/opflow/expectations/expectation_factory.py | 2 +- qiskit/opflow/expectations/matrix_expectation.py | 2 +- qiskit/opflow/expectations/pauli_expectation.py | 2 +- .../opflow/gradients/circuit_gradients/circuit_gradient.py | 2 +- qiskit/opflow/gradients/circuit_gradients/lin_comb.py | 2 +- qiskit/opflow/gradients/circuit_gradients/param_shift.py | 2 +- qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py | 2 +- qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_diag.py | 2 +- qiskit/opflow/gradients/derivative_base.py | 2 +- qiskit/opflow/gradients/gradient.py | 2 +- qiskit/opflow/gradients/gradient_base.py | 2 +- qiskit/opflow/gradients/hessian.py | 2 +- qiskit/opflow/gradients/hessian_base.py | 2 +- qiskit/opflow/gradients/natural_gradient.py | 2 +- qiskit/opflow/gradients/qfi.py | 2 +- qiskit/opflow/gradients/qfi_base.py | 2 +- qiskit/opflow/list_ops/composed_op.py | 2 +- qiskit/opflow/list_ops/list_op.py | 2 +- qiskit/opflow/list_ops/summed_op.py | 2 +- qiskit/opflow/list_ops/tensored_op.py | 2 +- qiskit/opflow/mixins/star_algebra.py | 2 +- qiskit/opflow/mixins/tensor.py | 2 +- qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/primitive_ops/circuit_op.py | 2 +- qiskit/opflow/primitive_ops/matrix_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 +- qiskit/opflow/primitive_ops/primitive_op.py | 2 +- qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py | 2 +- qiskit/opflow/state_fns/circuit_state_fn.py | 2 +- qiskit/opflow/state_fns/cvar_measurement.py | 2 +- qiskit/opflow/state_fns/dict_state_fn.py | 2 +- qiskit/opflow/state_fns/operator_state_fn.py | 2 +- qiskit/opflow/state_fns/sparse_vector_state_fn.py | 2 +- qiskit/opflow/state_fns/state_fn.py | 2 +- qiskit/opflow/state_fns/vector_state_fn.py | 2 +- qiskit/opflow/utils.py | 6 +++--- 59 files changed, 61 insertions(+), 61 deletions(-) diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index 50cb4c954141..fb7cf5aeb5db 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -31,7 +31,7 @@ class AbelianGrouper(ConverterBase): - """Deprecation: The AbelianGrouper converts SummedOps into a sum of Abelian sums. + """The AbelianGrouper converts SummedOps into a sum of Abelian sums. Meaning, it will traverse the Operator, and when it finds a SummedOp, it will evaluate which of the summed sub-Operators commute with one another. It will then convert each of the groups of diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index 0e90c0c2263a..c3d6d96b4ab1 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -39,7 +39,7 @@ class CircuitSampler(ConverterBase): """ - Deprecation: The CircuitSampler traverses an Operator and converts any CircuitStateFns into + The CircuitSampler traverses an Operator and converts any CircuitStateFns into approximations of the state function by a DictStateFn or VectorStateFn using a quantum backend. Note that in order to approximate the value of the CircuitStateFn, it must 1) send state function through a depolarizing channel, which will destroy all phase information and diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index 4f503b83a8bd..9883eee01e47 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -19,7 +19,7 @@ class ConverterBase(ABC): r""" - Deprecation: Converters take an Operator and return a new Operator, generally isomorphic + Converters take an Operator and return a new Operator, generally isomorphic in some way with the first, but with certain desired properties. For example, a converter may accept ``CircuitOp`` and return a ``SummedOp`` of ``PauliOps`` representing the circuit unitary. Converters may not diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index d519ddbc843f..71689b3f2e44 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -22,7 +22,7 @@ class DictToCircuitSum(ConverterBase): r""" - Deprecation: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` + Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` on an Operator, but with the added control of choosing whether to convert only ``DictStateFns`` or ``VectorStateFns``, rather than both. diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index 4c1120a92e2e..98462250b9ab 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -34,7 +34,7 @@ class PauliBasisChange(ConverterBase): r""" - Deprecation: Converter for changing Paulis into other bases. By default, the diagonal basis + Converter for changing Paulis into other bases. By default, the diagonal basis composed only of Pauli {Z, I}^n is used as the destination basis to which to convert. Meaning, if a Pauli containing X or Y terms is passed in, which cannot be sampled or evolved natively on some Quantum hardware, the Pauli can be replaced by a diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index aced893e2996..c1c1a19859fa 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -26,7 +26,7 @@ class TwoQubitReduction(ConverterBase): """ - Deprecation: Two qubit reduction converter which eliminates the central and last + Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index 8326bcefd4aa..afd7eff2f534 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -20,7 +20,7 @@ class EvolutionBase(ConverterBase, ABC): r""" - Deprecation: A base for Evolution converters. + A base for Evolution converters. Evolutions are converters which traverse an Operator tree, replacing any ``EvolvedOp`` `e` with a Schrodinger equation-style evolution ``CircuitOp`` equalling or approximating the matrix exponential of -i * the Operator contained inside (`e.primitive`). The Evolutions are diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index 8ae0919e3ec6..8c0e3db8f464 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -19,7 +19,7 @@ from qiskit.utils.deprecation import deprecate_func class EvolutionFactory: - """Deprecation: A factory class for convenient automatic selection of an + """A factory class for convenient automatic selection of an Evolution algorithm based on the Operator to be converted. """ diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index bcdbd04b1bfa..e36b27fbd83c 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -31,7 +31,7 @@ class EvolvedOp(PrimitiveOp): r""" - Deprecation: Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase + Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase method later, essentially acting as a placeholder. Note that EvolvedOp is a weird case of PrimitiveOp. It happens to be that it fits into the PrimitiveOp interface nearly perfectly, and it essentially represents a placeholder for a PrimitiveOp later, even though it doesn't diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index fad0ae7123b4..d27b26dd538a 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -26,7 +26,7 @@ class MatrixEvolution(EvolutionBase): r""" - Deprecation: Performs Evolution by classical matrix exponentiation, constructing a circuit with + Performs Evolution by classical matrix exponentiation, constructing a circuit with ``UnitaryGates`` or ``HamiltonianGates`` containing the exponentiation of the Operator. """ diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 6901a7cbab0e..37ddf4ebe84e 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -41,7 +41,7 @@ class PauliTrotterEvolution(EvolutionBase): r""" - Deprecation: An Evolution algorithm replacing exponentiated sums of Paulis by changing + An Evolution algorithm replacing exponentiated sums of Paulis by changing them each to the Z basis, rotating with an rZ, changing back, and Trotterizing. More specifically, we compute basis change circuits for each Pauli into a single-qubit Z, diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 46cca0c99193..6a01196c6149 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -31,7 +31,7 @@ class QDrift(TrotterizationBase): - """Deprecation: The QDrift Trotterization method, which selects each each term in the + """The QDrift Trotterization method, which selects each each term in the Trotterization randomly, with a probability proportional to its weight. Based on the work of Earl Campbell in https://arxiv.org/abs/1811.08017. """ diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index 1e37e3ce96fa..d959f142149c 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -27,7 +27,7 @@ class Suzuki(TrotterizationBase): r""" - Deprecation: Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum + Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum together by a recursive "bookends" strategy, repeating the whole composed circuit ``reps`` times. diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index f101adb5b12b..ba28adfc24db 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -17,7 +17,7 @@ class Trotter(Suzuki): r""" - Deprecation: Simple Trotter expansion, composing the evolution circuits of each Operator in the sum + Simple Trotter expansion, composing the evolution circuits of each Operator in the sum together ``reps`` times and dividing the evolution time of each by ``reps``. """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index e9409cd9e112..5270c5063548 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -21,7 +21,7 @@ class TrotterizationBase(EvolutionBase): - """Deprecation: A base for Trotterization methods, algorithms for approximating exponentiations of + """A base for Trotterization methods, algorithms for approximating exponentiations of operator sums by compositions of exponentiations. """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index b926ea1f9c24..81907c3c1a29 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -19,7 +19,7 @@ from qiskit.utils.deprecation import deprecate_func class TrotterizationFactory: - """Deprecation: A factory for conveniently creating TrotterizationBase instances.""" + """A factory for conveniently creating TrotterizationBase instances.""" @staticmethod @deprecate_func( diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index 3950e5bedc95..f7f30d1b4f84 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -17,7 +17,7 @@ class OpflowError(QiskitError): - """Deprecation: For Opflow specific errors.""" + """For Opflow specific errors.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index ca7829fcd19e..b1e49516a5f7 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -33,7 +33,7 @@ class AerPauliExpectation(ExpectationBase): - r"""Deprecation: An Expectation converter for using Aer's operator snapshot to + r"""An Expectation converter for using Aer's operator snapshot to take expectations of quantum state circuits over Pauli observables. """ diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index d55dbdc243b1..14d427dacf0d 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -23,7 +23,7 @@ from qiskit.utils.deprecation import deprecate_func class CVaRExpectation(ExpectationBase): - r"""Deprecation: Compute the Conditional Value at Risk (CVaR) expectation value. + r"""Compute the Conditional Value at Risk (CVaR) expectation value. The standard approach to calculating the expectation value of a Hamiltonian w.r.t. a state is to take the sample mean of the measurement outcomes. This corresponds to an estimator diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index 678dc7697a74..585b89b5ce73 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -23,7 +23,7 @@ class ExpectationBase(ConverterBase): r""" - Deprecation: A base for Expectation value converters. Expectations are converters which enable the + A base for Expectation value converters. Expectations are converters which enable the computation of the expectation value of an Observable with respect to some state function. They traverse an Operator tree, replacing OperatorStateFn measurements with equivalent measurements which are more amenable to computation on quantum or classical hardware. For diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 8059e638da46..dfcb1fc25304 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -30,7 +30,7 @@ class ExpectationFactory: - """Deprecation: factory class for convenient automatic selection of an Expectation based on the + """ factory class for convenient automatic selection of an Expectation based on the Operator to be converted and backend used to sample the expectation value. """ diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index 23dc72eb6b77..ca4ab485f840 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -21,7 +21,7 @@ from qiskit.utils.deprecation import deprecate_func class MatrixExpectation(ExpectationBase): - """Deprecation: An Expectation converter which converts Operator measurements to + """An Expectation converter which converts Operator measurements to be matrix-based so they can be evaluated by matrix multiplication.""" @deprecate_func( diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index 4c3793e864e5..c9558bc72317 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -33,7 +33,7 @@ class PauliExpectation(ExpectationBase): r""" - Deprecation: An Expectation converter for Pauli-basis observables by changing Pauli measurements to a + An Expectation converter for Pauli-basis observables by changing Pauli measurements to a diagonal ({Z, I}^n) basis and appending circuit post-rotations to the measured state function. Optionally groups the Paulis with the same post-rotations (those that commute with one another, or form Abelian groups) into single measurements to reduce circuit execution diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index 4e109096859a..d6b5aae0cbd1 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -23,7 +23,7 @@ class CircuitGradient(ConverterBase): - r"""Deprecation: Circuit to gradient operator converter. + r"""Circuit to gradient operator converter. Converter for changing parameterized circuits into operators whose evaluation yields the gradient with respect to the circuit parameters. diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 6d7db18b531c..49065312d86c 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -68,7 +68,7 @@ class LinComb(CircuitGradient): - """Deprecation: Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the + """Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω. This method employs a linear combination of unitaries, diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index d7105041444e..bfe6f1ebcf42 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -40,7 +40,7 @@ class ParamShift(CircuitGradient): - """Deprecation: Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling + """Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω with the parameter shift method. """ diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 61875f8c8020..0a48236a26cc 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -22,7 +22,7 @@ class CircuitQFI(ConverterBase): - r"""Deprecation: Circuit to Quantum Fisher Information operator converter. + r"""Circuit to Quantum Fisher Information operator converter. Converter for changing parameterized circuits into operators whose evaluation yields Quantum Fisher Information metric tensor diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 48d548f34e35..069aa5275cf2 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -29,7 +29,7 @@ class LinCombFull(CircuitQFI): - r"""Deprecation: Compute the full Quantum Fisher Information (QFI). + r"""Compute the full Quantum Fisher Information (QFI). Given a pure, parameterized quantum state this class uses the linear combination of unitaries See also :class:`~qiskit.opflow.QFI`. diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index 81a871904fde..c4d76894cf50 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -33,7 +33,7 @@ class OverlapBlockDiag(CircuitQFI): - r"""Deprecation: Compute the block-diagonal of the QFI given a pure, parameterized quantum state. + r"""Compute the block-diagonal of the QFI given a pure, parameterized quantum state. The blocks are given by all parameterized gates in quantum circuit layer. See also :class:`~qiskit.opflow.QFI`. diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index fc85ac3f4b67..45be6670c220 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -33,7 +33,7 @@ class OverlapDiag(CircuitQFI): - r"""Deprecation: Compute the diagonal of the QFI given a pure, parameterized quantum state. + r"""Compute the diagonal of the QFI given a pure, parameterized quantum state. See also :class:`~qiskit.opflow.QFI`. """ diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index dfadcf2db002..46f1d97406a8 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -34,7 +34,7 @@ class DerivativeBase(ConverterBase): - r"""Deprecation: Base class for differentiating opflow objects. + r"""Base class for differentiating opflow objects. Converter for differentiating opflow objects and handling things like properly differentiating combo_fn's and enforcing product rules diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index de3948bc2280..52fb3166f832 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -35,7 +35,7 @@ class Gradient(GradientBase): - """Deprecation: Convert an operator expression to the first-order gradient.""" + """Convert an operator expression to the first-order gradient.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index 8618023e25c6..6775daaffeac 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -20,7 +20,7 @@ class GradientBase(DerivativeBase): - """Deprecation: Base class for first-order operator gradient. + """Base class for first-order operator gradient. Convert an operator expression to the first-order gradient. """ diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index e71412e38f38..50a0e3a47af2 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -38,7 +38,7 @@ class Hessian(HessianBase): - """Deprecation: Compute the Hessian of an expected value.""" + """Compute the Hessian of an expected value.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index ea3e8aa0550f..02a209137613 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -20,7 +20,7 @@ class HessianBase(DerivativeBase): - """Deprecation: Base class for the Hessian of an expected value.""" + """Base class for the Hessian of an expected value.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index a0e703f016ff..e8159f8ed568 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -38,7 +38,7 @@ class NaturalGradient(GradientBase): - r"""Deprecation: Convert an operator expression to the first-order gradient. + r"""Convert an operator expression to the first-order gradient. Given an ill-posed inverse problem diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index 56ad342e32de..75f1cdbaa621 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -26,7 +26,7 @@ class QFI(QFIBase): - r"""Deprecation: Compute the Quantum Fisher Information (QFI). + r"""Compute the Quantum Fisher Information (QFI). Computes the QFI given a pure, parameterized quantum state, where QFI is: diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index deb2e722a6fe..55500b87276e 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -21,7 +21,7 @@ class QFIBase(DerivativeBase): - r"""Deprecation: Base class for Quantum Fisher Information (QFI). + r"""Base class for Quantum Fisher Information (QFI). Compute the Quantum Fisher Information (QFI) given a pure, parameterized quantum state. diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index 89fe194f5270..b25a37e36930 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -28,7 +28,7 @@ class ComposedOp(ListOp): - """Deprecation: A class for lazily representing compositions of Operators. Often Operators cannot be + """A class for lazily representing compositions of Operators. Often Operators cannot be efficiently composed with one another, but may be manipulated further so that they can be composed later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be composed, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index ae95a3972d3b..49d5ae47ea78 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -28,7 +28,7 @@ class ListOp(OperatorBase): """ - Deprecation: A Class for manipulating List Operators, and parent class to ``SummedOp``, + A Class for manipulating List Operators, and parent class to ``SummedOp``, ``ComposedOp`` and ``TensoredOp``. List Operators are classes for storing and manipulating lists of Operators, State functions, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index a0191f2b5e2d..acf3298ff564 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -25,7 +25,7 @@ class SummedOp(ListOp): - """Deprecation: A class for lazily representing sums of Operators. Often Operators cannot be + """A class for lazily representing sums of Operators. Often Operators cannot be efficiently added to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be added together, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index efe7e0685c9b..6aa72d1b9ff3 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -26,7 +26,7 @@ class TensoredOp(ListOp): - """Deprecation: A class for lazily representing tensor products of Operators. Often Operators + """A class for lazily representing tensor products of Operators. Often Operators cannot be efficiently tensored to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be tensored together, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index b4a7e5c142c9..08352272ec9c 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -20,7 +20,7 @@ class StarAlgebraMixin(MultiplyMixin, ABC): - """Deprecation: The star algebra mixin class. + """The star algebra mixin class. Star algebra is an algebra with an adjoint. This class overrides: diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index 5c8fd5c75078..6b6a56bcf183 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -18,7 +18,7 @@ class TensorMixin(ABC): - """Deprecation: The mixin class for tensor operations. + """The mixin class for tensor operations. This class overrides: - ``^``, ``__xor__``, `__rxor__` -> :meth:`tensor` between two operators and diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index f2c94d4db04f..37c384bdbae5 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -29,7 +29,7 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): - """Deprecation: A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are + """A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are defined as functions which take one complex binary function to another. These complex binary functions are represented by StateFns, which are themselves a special class of Operators taking only the ``Zero`` StateFn to the complex binary function they represent. diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 69209689fe11..86ed5448d560 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -27,7 +27,7 @@ class CircuitOp(PrimitiveOp): - """Deprecation: Class for Operators backed by Terra's ``QuantumCircuit`` module.""" + """Class for Operators backed by Terra's ``QuantumCircuit`` module.""" primitive: QuantumCircuit diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index 752d61d6d3f8..fc4ab49dd1d6 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -31,7 +31,7 @@ class MatrixOp(PrimitiveOp): - """Deprecation: Class for Operators represented by matrices, + """Class for Operators represented by matrices, backed by Terra's ``Operator`` module.""" primitive: Operator diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 3a0c1440ad75..bf8fe3ddb5e1 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -31,7 +31,7 @@ class PauliOp(PrimitiveOp): - """Deprecation: Class for Operators backed by Terra's ``Pauli`` module.""" + """Class for Operators backed by Terra's ``Pauli`` module.""" primitive: Pauli diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index 3578382aef72..08f928ec6631 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -30,7 +30,7 @@ class PauliSumOp(PrimitiveOp): - """Deprecation: Class for Operators backed by Terra's ``SparsePauliOp`` class.""" + """Class for Operators backed by Terra's ``SparsePauliOp`` class.""" primitive: SparsePauliOp diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index 2277dc6d2ff9..d2f067474da3 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -27,7 +27,7 @@ class PrimitiveOp(OperatorBase): r""" - Deprecation: A class for representing basic Operators, backed by Operator primitives from + A class for representing basic Operators, backed by Operator primitives from Terra. This class (and inheritors) primarily serves to allow the underlying primitives to "flow" - i.e. interoperability and adherence to the Operator formalism - while the core computational logic mostly remains in the underlying primitives. diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index c3183cff2b3f..ba7711217398 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -33,7 +33,7 @@ class TaperedPauliSumOp(PauliSumOp): - """Deprecation: Class for PauliSumOp after tapering""" + """Class for PauliSumOp after tapering""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index ac5e8fd7b7d7..4477edd7795c 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -37,7 +37,7 @@ class CircuitStateFn(StateFn): r""" - Deprecation: A class for state functions and measurements which are defined by the action of a + A class for state functions and measurements which are defined by the action of a QuantumCircuit starting from \|0⟩, and stored using Terra's ``QuantumCircuit`` class. """ primitive: QuantumCircuit diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index 236cbfe0c9be..84df068d3f5f 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -31,7 +31,7 @@ from qiskit.utils.deprecation import deprecate_func class CVaRMeasurement(OperatorStateFn): - r"""Deprecation: A specialized measurement class to compute CVaR expectation values. + r"""A specialized measurement class to compute CVaR expectation values. See https://arxiv.org/pdf/1907.04769.pdf for further details. Used in :class:`~qiskit.opflow.CVaRExpectation`, see there for more details. diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index 7b574645641a..9ad2929f914a 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -30,7 +30,7 @@ from qiskit.utils.deprecation import deprecate_func class DictStateFn(StateFn): - """Deprecation: A class for state functions and measurements which are defined by a lookup table, + """A class for state functions and measurements which are defined by a lookup table, stored in a dict. """ diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index dead517be5dd..bf4a5c88b3ec 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -30,7 +30,7 @@ class OperatorStateFn(StateFn): r""" - Deprecation: A class for state functions and measurements which are defined by a density Operator, + A class for state functions and measurements which are defined by a density Operator, stored using an ``OperatorBase``. """ primitive: OperatorBase diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index d5a4f28c4bb4..f67aca5b600f 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -29,7 +29,7 @@ from qiskit.utils.deprecation import deprecate_func class SparseVectorStateFn(StateFn): - """Deprecation: A class for sparse state functions and measurements in vector representation. + """A class for sparse state functions and measurements in vector representation. This class uses ``scipy.sparse.spmatrix`` for the internal representation. """ diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 06ec935375f6..7fe009f59fbe 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -26,7 +26,7 @@ class StateFn(OperatorBase): r""" - Deprecation: A class for representing state functions and measurements. + A class for representing state functions and measurements. State functions are defined to be complex functions over a single binary string (as compared to an operator, which is defined as a function over two binary strings, or a diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index 2e3936aa2257..a92a14fb6ad6 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -29,7 +29,7 @@ from qiskit.utils.deprecation import deprecate_func class VectorStateFn(StateFn): - """Deprecation: A class for state functions and measurements which are defined in vector + """A class for state functions and measurements which are defined in vector representation, and stored using Terra's ``Statevector`` class. """ diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index 6010890b0b8c..f76c04c204a0 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -22,7 +22,7 @@ ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Deprecation: Compute commutator of `op_a` and `op_b`. + Compute commutator of `op_a` and `op_b`. .. math:: @@ -43,7 +43,7 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Deprecation: Compute anti-commutator of `op_a` and `op_b`. + Compute anti-commutator of `op_a` and `op_b`. .. math:: @@ -69,7 +69,7 @@ def double_commutator( sign: bool = False, ) -> OperatorBase: r""" - Deprecation: Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. + Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. See McWeeny chapter 13.6 Equation of motion methods (page 479) If `sign` is `False`, it returns From 11e74bd34c2725db9350e4e6fd17d89bf5b2b476 Mon Sep 17 00:00:00 2001 From: ElePT Date: Wed, 29 Mar 2023 17:32:10 +0200 Subject: [PATCH 09/47] Update sphinx deprecations, fix lint, fix tests --- qiskit/opflow/__init__.py | 6 +- qiskit/opflow/converters/__init__.py | 33 +- qiskit/opflow/converters/abelian_grouper.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 3 +- qiskit/opflow/converters/converter_base.py | 3 +- .../opflow/converters/dict_to_circuit_sum.py | 5 +- .../opflow/converters/pauli_basis_change.py | 3 +- .../opflow/converters/two_qubit_reduction.py | 3 +- qiskit/opflow/evolutions/__init__.py | 29 +- qiskit/opflow/evolutions/evolution_base.py | 3 +- qiskit/opflow/evolutions/evolution_factory.py | 3 +- qiskit/opflow/evolutions/evolved_op.py | 3 +- qiskit/opflow/evolutions/matrix_evolution.py | 3 +- .../evolutions/pauli_trotter_evolution.py | 3 +- .../evolutions/trotterizations/__init__.py | 6 +- .../evolutions/trotterizations/qdrift.py | 3 +- .../evolutions/trotterizations/suzuki.py | 3 +- .../evolutions/trotterizations/trotter.py | 3 +- .../trotterizations/trotterization_base.py | 3 +- .../trotterizations/trotterization_factory.py | 3 +- qiskit/opflow/exceptions.py | 2 +- qiskit/opflow/expectations/__init__.py | 27 +- .../expectations/aer_pauli_expectation.py | 3 +- .../opflow/expectations/cvar_expectation.py | 3 +- .../opflow/expectations/expectation_base.py | 3 +- .../expectations/expectation_factory.py | 5 +- .../opflow/expectations/matrix_expectation.py | 3 +- .../opflow/expectations/pauli_expectation.py | 3 +- qiskit/opflow/gradients/__init__.py | 10 +- .../gradients/circuit_gradients/__init__.py | 5 +- .../circuit_gradients/circuit_gradient.py | 2 +- .../gradients/circuit_gradients/lin_comb.py | 2 +- .../circuit_gradients/param_shift.py | 2 +- .../gradients/circuit_qfis/circuit_qfi.py | 2 +- .../gradients/circuit_qfis/lin_comb_full.py | 2 +- .../circuit_qfis/overlap_block_diag.py | 2 +- .../gradients/circuit_qfis/overlap_diag.py | 2 +- qiskit/opflow/gradients/derivative_base.py | 2 +- qiskit/opflow/gradients/gradient.py | 2 +- qiskit/opflow/gradients/gradient_base.py | 2 +- qiskit/opflow/gradients/hessian.py | 2 +- qiskit/opflow/gradients/hessian_base.py | 2 +- qiskit/opflow/gradients/natural_gradient.py | 2 +- qiskit/opflow/gradients/qfi.py | 2 +- qiskit/opflow/gradients/qfi_base.py | 2 +- qiskit/opflow/list_ops/__init__.py | 33 +- qiskit/opflow/list_ops/composed_op.py | 2 +- qiskit/opflow/list_ops/list_op.py | 2 +- qiskit/opflow/list_ops/summed_op.py | 2 +- qiskit/opflow/list_ops/tensored_op.py | 2 +- qiskit/opflow/mixins/star_algebra.py | 2 +- qiskit/opflow/mixins/tensor.py | 2 +- qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/operator_globals.py | 3 +- qiskit/opflow/primitive_ops/__init__.py | 6 +- qiskit/opflow/primitive_ops/circuit_op.py | 2 +- qiskit/opflow/primitive_ops/matrix_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 +- qiskit/opflow/primitive_ops/primitive_op.py | 2 +- .../primitive_ops/tapered_pauli_sum_op.py | 2 +- qiskit/opflow/state_fns/__init__.py | 12 +- qiskit/opflow/state_fns/circuit_state_fn.py | 3 +- qiskit/opflow/state_fns/cvar_measurement.py | 3 +- qiskit/opflow/state_fns/dict_state_fn.py | 3 +- qiskit/opflow/state_fns/operator_state_fn.py | 3 +- .../state_fns/sparse_vector_state_fn.py | 3 +- qiskit/opflow/state_fns/state_fn.py | 2 +- qiskit/opflow/state_fns/vector_state_fn.py | 3 +- qiskit/opflow/utils.py | 18 +- qiskit/utils/backend_utils.py | 22 +- qiskit/utils/measurement_error_mitigation.py | 10 +- qiskit/utils/mitigation/__init__.py | 3 +- qiskit/utils/mitigation/_filters.py | 4 +- qiskit/utils/mitigation/circuits.py | 7 +- qiskit/utils/mitigation/fitters.py | 4 +- qiskit/utils/quantum_instance.py | 2 +- qiskit/utils/run_circuits.py | 21 +- .../python/algorithms/optimizers/test_spsa.py | 1 - test/python/algorithms/test_linear_solvers.py | 382 ------------------ test/python/algorithms/test_shor.py | 205 ---------- 81 files changed, 233 insertions(+), 763 deletions(-) delete mode 100644 test/python/algorithms/test_linear_solvers.py delete mode 100644 test/python/algorithms/test_shor.py diff --git a/qiskit/opflow/__init__.py b/qiskit/opflow/__init__.py index 4fb9595244e6..14af64bd9849 100644 --- a/qiskit/opflow/__init__.py +++ b/qiskit/opflow/__init__.py @@ -18,8 +18,12 @@ .. currentmodule:: qiskit.opflow .. deprecated:: 0.24.0 - Operators and State functions are the building blocks of Quantum Algorithms. + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +Operators and State functions are the building blocks of Quantum Algorithms. A library for Quantum Algorithms & Applications is more than a collection of algorithms wrapped in Python functions. It needs to provide tools to make writing diff --git a/qiskit/opflow/converters/__init__.py b/qiskit/opflow/converters/__init__.py index 794d5275dcec..b830e4206530 100644 --- a/qiskit/opflow/converters/__init__.py +++ b/qiskit/opflow/converters/__init__.py @@ -17,20 +17,25 @@ .. currentmodule:: qiskit.opflow.converters .. deprecated:: 0.24.0 - Converters are objects which manipulate Operators, usually traversing an Operator to - change certain sub-Operators into a desired representation. Often the converted Operator is - isomorphic or approximate to the original Operator in some way, but not always. For example, - a converter may accept :class:`~qiskit.opflow.primitive_ops.CircuitOp` and return a - :class:`~qiskit.opflow.list_ops.SummedOp` of - :class:`~qiskit.opflow.primitive_ops.PauliOp`'s representing the - circuit unitary. Converters may not have polynomial space or time scaling in their operations. - On the contrary, many converters, such as a - :class:`~qiskit.opflow.expectations.MatrixExpectation` or - :class:`~qiskit.opflow.evolutions.MatrixEvolution`, - which convert :class:`~qiskit.opflow.primitive_ops.PauliOp`'s to - :class:`~qiskit.opflow.primitive_ops.MatrixOp`'s internally, will require time or space - exponential in the number of qubits unless a clever trick is known - (such as the use of sparse matrices). + + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +Converters are objects which manipulate Operators, usually traversing an Operator to +change certain sub-Operators into a desired representation. Often the converted Operator is +isomorphic or approximate to the original Operator in some way, but not always. For example, +a converter may accept :class:`~qiskit.opflow.primitive_ops.CircuitOp` and return a +:class:`~qiskit.opflow.list_ops.SummedOp` of +:class:`~qiskit.opflow.primitive_ops.PauliOp`'s representing the +circuit unitary. Converters may not have polynomial space or time scaling in their operations. +On the contrary, many converters, such as a +:class:`~qiskit.opflow.expectations.MatrixExpectation` or +:class:`~qiskit.opflow.evolutions.MatrixEvolution`, +which convert :class:`~qiskit.opflow.primitive_ops.PauliOp`'s to +:class:`~qiskit.opflow.primitive_ops.MatrixOp`'s internally, will require time or space +exponential in the number of qubits unless a clever trick is known +(such as the use of sparse matrices). Note: diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index fb7cf5aeb5db..b2e2c946a2ab 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -44,7 +44,7 @@ class AbelianGrouper(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, traverse: bool = True) -> None: """ diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index c3d6d96b4ab1..4a1e2bf1454d 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -34,6 +34,7 @@ from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend from qiskit.utils.quantum_instance import QuantumInstance from qiskit.utils.deprecation import deprecate_func + logger = logging.getLogger(__name__) @@ -54,7 +55,7 @@ class CircuitSampler(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index 9883eee01e47..64a1edce616f 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -17,6 +17,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.utils.deprecation import deprecate_func + class ConverterBase(ABC): r""" Converters take an Operator and return a new Operator, generally isomorphic @@ -31,7 +32,7 @@ class ConverterBase(ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index 71689b3f2e44..4d8e10ed157f 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -20,9 +20,10 @@ from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn from qiskit.utils.deprecation import deprecate_func + class DictToCircuitSum(ConverterBase): r""" - Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` + Deprecation: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` on an Operator, but with the added control of choosing whether to convert only ``DictStateFns`` or ``VectorStateFns``, rather than both. @@ -30,7 +31,7 @@ class DictToCircuitSum(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index 98462250b9ab..98af89f90786 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -32,6 +32,7 @@ from qiskit.quantum_info import Pauli from qiskit.utils.deprecation import deprecate_func + class PauliBasisChange(ConverterBase): r""" Converter for changing Paulis into other bases. By default, the diagonal basis @@ -57,7 +58,7 @@ class PauliBasisChange(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index c1c1a19859fa..99db05f6e860 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -21,6 +21,7 @@ from qiskit.opflow.primitive_ops.tapered_pauli_sum_op import Z2Symmetries from qiskit.quantum_info import Pauli from qiskit.utils.deprecation import deprecate_func + logger = logging.getLogger(__name__) @@ -37,7 +38,7 @@ class TwoQubitReduction(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): """ diff --git a/qiskit/opflow/evolutions/__init__.py b/qiskit/opflow/evolutions/__init__.py index f136c7fe6b6e..abe3ae0a96d2 100644 --- a/qiskit/opflow/evolutions/__init__.py +++ b/qiskit/opflow/evolutions/__init__.py @@ -17,18 +17,23 @@ .. currentmodule:: qiskit.opflow.evolutions .. deprecated:: 0.24.0 - Evolutions are converters which traverse an Operator tree, replacing - any :class:`EvolvedOp` `e` with a Schrodinger equation-style evolution - :class:`~qiskit.opflow.primitive_ops.CircuitOp` - equalling or approximating the matrix exponential of -i * the Operator contained inside - (`e.primitive`). The Evolutions are essentially implementations of Hamiltonian Simulation - algorithms, including various methods for Trotterization. - - The :class:`EvolvedOp` is simply a placeholder signifying that the Operator inside it should be - converted to its exponential by the Evolution converter. All Operators - (not :mod:`~qiskit.opflow.state_fns`) have - ``.exp_i()`` methods which either return the exponential of the Operator directly, - or an :class:`EvolvedOp` containing the Operator. + + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +Evolutions are converters which traverse an Operator tree, replacing +any :class:`EvolvedOp` `e` with a Schrodinger equation-style evolution +:class:`~qiskit.opflow.primitive_ops.CircuitOp` +equalling or approximating the matrix exponential of -i * the Operator contained inside +(`e.primitive`). The Evolutions are essentially implementations of Hamiltonian Simulation +algorithms, including various methods for Trotterization. + +The :class:`EvolvedOp` is simply a placeholder signifying that the Operator inside it should be +converted to its exponential by the Evolution converter. All Operators +(not :mod:`~qiskit.opflow.state_fns`) have +``.exp_i()`` methods which either return the exponential of the Operator directly, +or an :class:`EvolvedOp` containing the Operator. Note: diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index afd7eff2f534..8831b78e8943 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -18,6 +18,7 @@ from qiskit.opflow.converters.converter_base import ConverterBase from qiskit.utils.deprecation import deprecate_func + class EvolutionBase(ConverterBase, ABC): r""" A base for Evolution converters. @@ -31,7 +32,7 @@ class EvolutionBase(ConverterBase, ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index 8c0e3db8f464..2a99a17f4019 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -18,6 +18,7 @@ from qiskit.opflow.evolutions.matrix_evolution import MatrixEvolution from qiskit.utils.deprecation import deprecate_func + class EvolutionFactory: """A factory class for convenient automatic selection of an Evolution algorithm based on the Operator to be converted. @@ -26,7 +27,7 @@ class EvolutionFactory: @staticmethod @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def build(operator: OperatorBase = None) -> EvolutionBase: r""" diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index e36b27fbd83c..94247d8fe0fa 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -29,6 +29,7 @@ from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func + class EvolvedOp(PrimitiveOp): r""" Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase @@ -41,7 +42,7 @@ class EvolvedOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: OperatorBase, coeff: Union[complex, ParameterExpression] = 1.0 diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index d27b26dd538a..a5fab9f96a3a 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -21,6 +21,7 @@ from qiskit.opflow.primitive_ops.matrix_op import MatrixOp from qiskit.opflow.primitive_ops.pauli_op import PauliOp from qiskit.utils.deprecation import deprecate_func + logger = logging.getLogger(__name__) @@ -32,7 +33,7 @@ class MatrixEvolution(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 37ddf4ebe84e..9c8f69f75d84 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -33,6 +33,7 @@ from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.utils.deprecation import deprecate_func + # TODO uncomment when we implement Abelian grouped evolution. # from qiskit.opflow.converters.abelian_grouper import AbelianGrouper @@ -52,7 +53,7 @@ class PauliTrotterEvolution(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/evolutions/trotterizations/__init__.py b/qiskit/opflow/evolutions/trotterizations/__init__.py index 17ddd830fa31..a721bec2fee4 100644 --- a/qiskit/opflow/evolutions/trotterizations/__init__.py +++ b/qiskit/opflow/evolutions/trotterizations/__init__.py @@ -11,10 +11,8 @@ # that they have been altered from the originals. """ -.. deprecated:: 0.24.0 - Trotterization methods - Algorithms for - approximating Exponentials of Operator Sums. - +Trotterization methods - Algorithms for +approximating Exponentials of Operator Sums. """ from .trotterization_base import TrotterizationBase diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 6a01196c6149..6f37d398fad8 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -27,6 +27,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.utils import algorithm_globals from qiskit.utils.deprecation import deprecate_func + # pylint: disable=invalid-name @@ -38,7 +39,7 @@ class QDrift(TrotterizationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index d959f142149c..480380dbb31b 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -25,6 +25,7 @@ from qiskit.opflow.primitive_ops.primitive_op import PrimitiveOp from qiskit.utils.deprecation import deprecate_func + class Suzuki(TrotterizationBase): r""" Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum @@ -36,7 +37,7 @@ class Suzuki(TrotterizationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1, order: int = 2) -> None: """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index ba28adfc24db..2312dd8d1b65 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -15,6 +15,7 @@ from qiskit.opflow.evolutions.trotterizations.suzuki import Suzuki from qiskit.utils.deprecation import deprecate_func + class Trotter(Suzuki): r""" Simple Trotter expansion, composing the evolution circuits of each Operator in the sum @@ -23,7 +24,7 @@ class Trotter(Suzuki): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 5270c5063548..2a817bf3c345 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -17,6 +17,7 @@ from qiskit.opflow.evolutions.evolution_base import EvolutionBase from qiskit.opflow.operator_base import OperatorBase from qiskit.utils.deprecation import deprecate_func + # TODO centralize handling of commuting groups @@ -27,7 +28,7 @@ class TrotterizationBase(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index 81907c3c1a29..15c8b2d5a8c6 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -18,13 +18,14 @@ from qiskit.opflow.evolutions.trotterizations.trotterization_base import TrotterizationBase from qiskit.utils.deprecation import deprecate_func + class TrotterizationFactory: """A factory for conveniently creating TrotterizationBase instances.""" @staticmethod @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def build(mode: str = "trotter", reps: int = 1) -> TrotterizationBase: """A factory for conveniently creating TrotterizationBase instances. diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index f7f30d1b4f84..09919a5d63f1 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -21,7 +21,7 @@ class OpflowError(QiskitError): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, *message): """Set the error message.""" diff --git a/qiskit/opflow/expectations/__init__.py b/qiskit/opflow/expectations/__init__.py index 5eacf3c04a2f..f12b3efd0328 100644 --- a/qiskit/opflow/expectations/__init__.py +++ b/qiskit/opflow/expectations/__init__.py @@ -17,17 +17,22 @@ .. currentmodule:: qiskit.opflow.expectations .. deprecated:: 0.24.0 - Expectations are converters which enable the computation of the expectation - value of an Observable with respect to some state function. They traverse an Operator tree, - replacing :class:`~qiskit.opflow.state_fns.OperatorStateFn` measurements with equivalent - measurements which are more amenable to computation on quantum or classical hardware. - For example, if one would like to measure the - expectation value of an Operator ``o`` expressed as a sum of Paulis with respect to some state - function, but only has access to diagonal measurements on Quantum hardware, we can create a - measurement ~StateFn(o), use a :class:`PauliExpectation` to convert it to a diagonal measurement - and circuit pre-rotations to append to the state, and sample this circuit on Quantum hardware with - a :class:`~qiskit.opflow.converters.CircuitSampler`. All in all, this would be: - ``my_sampler.convert(my_expect.convert(~StateFn(o)) @ my_state).eval()``. + + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +Expectations are converters which enable the computation of the expectation +value of an Observable with respect to some state function. They traverse an Operator tree, +replacing :class:`~qiskit.opflow.state_fns.OperatorStateFn` measurements with equivalent +measurements which are more amenable to computation on quantum or classical hardware. +For example, if one would like to measure the +expectation value of an Operator ``o`` expressed as a sum of Paulis with respect to some state +function, but only has access to diagonal measurements on Quantum hardware, we can create a +measurement ~StateFn(o), use a :class:`PauliExpectation` to convert it to a diagonal measurement +and circuit pre-rotations to append to the state, and sample this circuit on Quantum hardware with +a :class:`~qiskit.opflow.converters.CircuitSampler`. All in all, this would be: +``my_sampler.convert(my_expect.convert(~StateFn(o)) @ my_state).eval()``. Expectation Base Class diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index b1e49516a5f7..6c6651de32f1 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -29,6 +29,7 @@ from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.quantum_info import SparsePauliOp from qiskit.utils.deprecation import deprecate_func + logger = logging.getLogger(__name__) @@ -40,7 +41,7 @@ class AerPauliExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 14d427dacf0d..9bc4db2a03af 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -22,6 +22,7 @@ from qiskit.opflow.state_fns import CVaRMeasurement, OperatorStateFn from qiskit.utils.deprecation import deprecate_func + class CVaRExpectation(ExpectationBase): r"""Compute the Conditional Value at Risk (CVaR) expectation value. @@ -56,7 +57,7 @@ class CVaRExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) -> None: """ diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index 585b89b5ce73..fce88cf098d3 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -21,6 +21,7 @@ from qiskit.opflow.operator_base import OperatorBase from qiskit.utils.deprecation import deprecate_func + class ExpectationBase(ConverterBase): r""" A base for Expectation value converters. Expectations are converters which enable the @@ -39,7 +40,7 @@ class ExpectationBase(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index dfcb1fc25304..9e9241695e9c 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -26,18 +26,19 @@ from qiskit.utils.backend_utils import is_aer_qasm, is_statevector_backend from qiskit.utils import QuantumInstance, optionals from qiskit.utils.deprecation import deprecate_func + logger = logging.getLogger(__name__) class ExpectationFactory: - """ factory class for convenient automatic selection of an Expectation based on the + """factory class for convenient automatic selection of an Expectation based on the Operator to be converted and backend used to sample the expectation value. """ @staticmethod @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def build( operator: OperatorBase, diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index ca4ab485f840..43f09c9a5a64 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -20,13 +20,14 @@ from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.utils.deprecation import deprecate_func + class MatrixExpectation(ExpectationBase): """An Expectation converter which converts Operator measurements to be matrix-based so they can be evaluated by matrix multiplication.""" @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index c9558bc72317..1825ad82643d 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -28,6 +28,7 @@ from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn from qiskit.opflow.state_fns.state_fn import StateFn from qiskit.utils.deprecation import deprecate_func + logger = logging.getLogger(__name__) @@ -43,7 +44,7 @@ class PauliExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, group_paulis: bool = True) -> None: """ diff --git a/qiskit/opflow/gradients/__init__.py b/qiskit/opflow/gradients/__init__.py index 7c6f5babd3ca..f1642caa0c86 100644 --- a/qiskit/opflow/gradients/__init__.py +++ b/qiskit/opflow/gradients/__init__.py @@ -15,10 +15,14 @@ ========================================== .. deprecated:: 0.24.0 - Given an operator that represents either a quantum state resp. an expectation value, - the gradient framework enables the evaluation of gradients, natural gradients, - Hessians, as well as the Quantum Fisher Information. + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +Given an operator that represents either a quantum state resp. an expectation value, +the gradient framework enables the evaluation of gradients, natural gradients, +Hessians, as well as the Quantum Fisher Information. Suppose a parameterized quantum state `|ψ(θ)〉 = V(θ)|ψ〉` with input state `|ψ〉` and parameterized Ansatz `V(θ)`, and an Operator `O(ω)`. diff --git a/qiskit/opflow/gradients/circuit_gradients/__init__.py b/qiskit/opflow/gradients/circuit_gradients/__init__.py index eae08898049a..16953b57ff21 100644 --- a/qiskit/opflow/gradients/circuit_gradients/__init__.py +++ b/qiskit/opflow/gradients/circuit_gradients/__init__.py @@ -10,8 +10,9 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -"""The module for Aqua's first order derivatives.""" - +""" +The module for first order derivatives. +""" from .circuit_gradient import CircuitGradient from .lin_comb import LinComb from .param_shift import ParamShift diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index d6b5aae0cbd1..b02d9610debd 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -38,7 +38,7 @@ class CircuitGradient(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 49065312d86c..72be1f90c3a2 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -103,7 +103,7 @@ class LinComb(CircuitGradient): # pylint: disable=signature-differs, arguments-differ @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, aux_meas_op: OperatorBase = Z): """ diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index bfe6f1ebcf42..7fd40550e6a5 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -49,7 +49,7 @@ class ParamShift(CircuitGradient): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): r""" diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 0a48236a26cc..57c136b257d0 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -38,7 +38,7 @@ class CircuitQFI(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 069aa5275cf2..478508238535 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -38,7 +38,7 @@ class LinCombFull(CircuitQFI): # pylint: disable=signature-differs, arguments-differ @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index c4d76894cf50..41c70b37ed34 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -41,7 +41,7 @@ class OverlapBlockDiag(CircuitQFI): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 45be6670c220..0124a316abf6 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -40,7 +40,7 @@ class OverlapDiag(CircuitQFI): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 46f1d97406a8..c54878934193 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -50,7 +50,7 @@ class DerivativeBase(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index 52fb3166f832..85d80eed988b 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -39,7 +39,7 @@ class Gradient(GradientBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(grad_method=grad_method, **kwargs) diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index 6775daaffeac..6869b1bccdb3 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -27,7 +27,7 @@ class GradientBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 50a0e3a47af2..85ca9ae2dcba 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -42,7 +42,7 @@ class Hessian(HessianBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(hess_method=hess_method, **kwargs) diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 02a209137613..3f72a28d0c8c 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -24,7 +24,7 @@ class HessianBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index e8159f8ed568..d578c2024207 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -54,7 +54,7 @@ class NaturalGradient(GradientBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index 75f1cdbaa621..8285dea8baf2 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -39,7 +39,7 @@ class QFI(QFIBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): super().__init__(qfi_method=qfi_method) diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index 55500b87276e..da847e26cf9b 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -32,7 +32,7 @@ class QFIBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): r""" diff --git a/qiskit/opflow/list_ops/__init__.py b/qiskit/opflow/list_ops/__init__.py index 196d73bdc308..700ff46ce774 100644 --- a/qiskit/opflow/list_ops/__init__.py +++ b/qiskit/opflow/list_ops/__init__.py @@ -17,20 +17,25 @@ .. currentmodule:: qiskit.opflow.list_ops .. deprecated:: 0.24.0 - List Operators are classes for storing and manipulating lists of Operators, State functions, - or Measurements, and include some rule or ``combo_fn`` defining how the Operator functions of the - list constituents should be combined to form to cumulative Operator function of the - :class:`ListOp`. For example, a :class:`SummedOp` has an addition-based ``combo_fn``, so once - the Operators in its list are evaluated against some bitstring to produce a list of results, - we know to add up those results to produce the final result of the :class:`SummedOp`'s evaluation. - In theory, this ``combo_fn`` can be any function over classical complex values, but for convenience - we've chosen for them to be defined over NumPy arrays and values. This way, large numbers of - evaluations, such as after calling :meth:`~ListOp.to_matrix` on the list constituents, - can be efficiently combined. While the combination function is defined over classical values, - it should be understood as the operation by which each Operators' underlying function is - combined to form the underlying Operator function of the :class:`ListOp`. In this way, the - :mod:`.list_ops` are the basis for constructing large and sophisticated Operators, - State Functions, and Measurements. + + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +List Operators are classes for storing and manipulating lists of Operators, State functions, +or Measurements, and include some rule or ``combo_fn`` defining how the Operator functions of the +list constituents should be combined to form to cumulative Operator function of the +:class:`ListOp`. For example, a :class:`SummedOp` has an addition-based ``combo_fn``, so once +the Operators in its list are evaluated against some bitstring to produce a list of results, +we know to add up those results to produce the final result of the :class:`SummedOp`'s evaluation. +In theory, this ``combo_fn`` can be any function over classical complex values, but for convenience +we've chosen for them to be defined over NumPy arrays and values. This way, large numbers of +evaluations, such as after calling :meth:`~ListOp.to_matrix` on the list constituents, +can be efficiently combined. While the combination function is defined over classical values, +it should be understood as the operation by which each Operators' underlying function is +combined to form the underlying Operator function of the :class:`ListOp`. In this way, the +:mod:`.list_ops` are the basis for constructing large and sophisticated Operators, +State Functions, and Measurements. The base :class:`ListOp` class is particularly interesting, as its ``combo_fn`` is "the identity diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index b25a37e36930..aab1cf5e2243 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -36,7 +36,7 @@ class ComposedOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index 49d5ae47ea78..e131a28ceb95 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -55,7 +55,7 @@ class ListOp(OperatorBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index acf3298ff564..960b42ff38b9 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -33,7 +33,7 @@ class SummedOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index 6aa72d1b9ff3..76a894888c33 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -34,7 +34,7 @@ class TensoredOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index 08352272ec9c..8a0be5a93fd2 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -42,7 +42,7 @@ class StarAlgebraMixin(MultiplyMixin, ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index 6b6a56bcf183..20925be5121d 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -30,7 +30,7 @@ class TensorMixin(ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index 37c384bdbae5..f67219b6c34f 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -47,7 +47,7 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/operator_globals.py b/qiskit/opflow/operator_globals.py index eee0d1bb3680..9c05a61b8d32 100644 --- a/qiskit/opflow/operator_globals.py +++ b/qiskit/opflow/operator_globals.py @@ -21,6 +21,7 @@ from qiskit.opflow.primitive_ops.circuit_op import CircuitOp from qiskit.opflow.state_fns.dict_state_fn import DictStateFn from qiskit.utils.deprecation import deprecate_func + # Digits of precision when returning values from eval functions. Without rounding, 1e-17 or 1e-32 # values often show up in place of 0, etc. # Note: care needs to be taken in rounding otherwise some behavior may not be as expected. E.g @@ -34,7 +35,7 @@ @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def make_immutable(obj): r"""Deprecate\: Delete the __setattr__ property to make the object mostly immutable.""" diff --git a/qiskit/opflow/primitive_ops/__init__.py b/qiskit/opflow/primitive_ops/__init__.py index f4a7ef1ee223..20c5fa5946cd 100644 --- a/qiskit/opflow/primitive_ops/__init__.py +++ b/qiskit/opflow/primitive_ops/__init__.py @@ -17,8 +17,12 @@ .. currentmodule:: qiskit.opflow.primitive_ops .. deprecated:: 0.24.0 - Operators are defined to be functions which take State functions to State functions. + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +Operators are defined to be functions which take State functions to State functions. PrimitiveOps are the classes for representing basic Operators, backed by computational Operator primitives from Terra. These classes (and inheritors) primarily serve to allow the diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 86ed5448d560..095f77783ec2 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -33,7 +33,7 @@ class CircuitOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index fc4ab49dd1d6..1c849fa67289 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -38,7 +38,7 @@ class MatrixOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index bf8fe3ddb5e1..10d892ce72fe 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -37,7 +37,7 @@ class PauliOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index 08f928ec6631..919900b84afd 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -36,7 +36,7 @@ class PauliSumOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index d2f067474da3..60a13759b912 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -95,7 +95,7 @@ def __new__( @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index ba7711217398..8a665a2b1b22 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -37,7 +37,7 @@ class TaperedPauliSumOp(PauliSumOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/__init__.py b/qiskit/opflow/state_fns/__init__.py index dc019c5485f4..0b2a53edcbe8 100644 --- a/qiskit/opflow/state_fns/__init__.py +++ b/qiskit/opflow/state_fns/__init__.py @@ -15,11 +15,15 @@ ================================================ .. deprecated:: 0.24.0 - State functions are defined to be complex functions over a single binary - string (as compared to an operator, which is defined as a function over two binary strings, - or a function taking a binary function to another binary function). This function may be - called by the eval() method. + The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + than 3 months after the release date. For code migration guidelines, + visit https://qisk.it/opflow_migration. + +State functions are defined to be complex functions over a single binary +string (as compared to an operator, which is defined as a function over two binary strings, +or a function taking a binary function to another binary function). This function may be +called by the eval() method. Measurements are defined to be functionals over StateFns, taking them to real values. Generally, this real value is interpreted to represent the probability of some classical diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index 4477edd7795c..f5b39635b1eb 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -35,6 +35,7 @@ from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func + class CircuitStateFn(StateFn): r""" A class for state functions and measurements which are defined by the action of a @@ -45,7 +46,7 @@ class CircuitStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index 84df068d3f5f..c7ee04b1a2d3 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -30,6 +30,7 @@ from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func + class CVaRMeasurement(OperatorStateFn): r"""A specialized measurement class to compute CVaR expectation values. See https://arxiv.org/pdf/1907.04769.pdf for further details. @@ -42,7 +43,7 @@ class CVaRMeasurement(OperatorStateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index 9ad2929f914a..e71aac807302 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -29,6 +29,7 @@ from qiskit.utils import algorithm_globals from qiskit.utils.deprecation import deprecate_func + class DictStateFn(StateFn): """A class for state functions and measurements which are defined by a lookup table, stored in a dict. @@ -39,7 +40,7 @@ class DictStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index bf4a5c88b3ec..d462746ccb73 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -28,6 +28,7 @@ from qiskit.quantum_info import Statevector from qiskit.utils.deprecation import deprecate_func + class OperatorStateFn(StateFn): r""" A class for state functions and measurements which are defined by a density Operator, @@ -38,7 +39,7 @@ class OperatorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index f67aca5b600f..e7f7cdee99fe 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -28,6 +28,7 @@ from qiskit.utils import algorithm_globals from qiskit.utils.deprecation import deprecate_func + class SparseVectorStateFn(StateFn): """A class for sparse state functions and measurements in vector representation. @@ -39,7 +40,7 @@ class SparseVectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 7fe009f59fbe..7d711169536a 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -115,7 +115,7 @@ def __new__( # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index a92a14fb6ad6..e1a1b2ecdb0c 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -28,6 +28,7 @@ from qiskit.utils import algorithm_globals, arithmetic from qiskit.utils.deprecation import deprecate_func + class VectorStateFn(StateFn): """A class for state functions and measurements which are defined in vector representation, and stored using Terra's ``Statevector`` class. @@ -38,7 +39,7 @@ class VectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index f76c04c204a0..d432b4e4fa6f 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -17,9 +17,9 @@ @deprecate_func( - since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." - ) + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", +) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" Compute commutator of `op_a` and `op_b`. @@ -38,9 +38,9 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_func( - since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." - ) + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", +) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" Compute anti-commutator of `op_a` and `op_b`. @@ -59,9 +59,9 @@ def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_func( - since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration." - ) + since="0.24.0", + additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", +) def double_commutator( op_a: OperatorBase, op_b: OperatorBase, diff --git a/qiskit/utils/backend_utils.py b/qiskit/utils/backend_utils.py index e867a7ea6302..8067a13828bb 100644 --- a/qiskit/utils/backend_utils.py +++ b/qiskit/utils/backend_utils.py @@ -52,7 +52,7 @@ def _get_backend_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def has_ibmq(): """Check if IBMQ is installed.""" @@ -73,7 +73,7 @@ def has_ibmq(): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def has_aer(): """Check if Aer is installed.""" @@ -93,7 +93,7 @@ def has_aer(): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_aer_provider(backend): """Detect whether or not backend is from Aer provider. @@ -117,7 +117,7 @@ def is_aer_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_basicaer_provider(backend): """Detect whether or not backend is from BasicAer provider. @@ -134,7 +134,7 @@ def is_basicaer_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_ibmq_provider(backend): """Detect whether or not backend is from IBMQ provider. @@ -154,7 +154,7 @@ def is_ibmq_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_aer_statevector_backend(backend): """ @@ -170,7 +170,7 @@ def is_aer_statevector_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_statevector_backend(backend): """ @@ -199,7 +199,7 @@ def is_statevector_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_simulator_backend(backend): """ @@ -218,7 +218,7 @@ def is_simulator_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_local_backend(backend): """ @@ -237,7 +237,7 @@ def is_local_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_aer_qasm(backend): """ @@ -257,7 +257,7 @@ def is_aer_qasm(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def support_backend_options(backend): """ diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index d70f9936472b..f719ac5d1fc7 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -29,12 +29,10 @@ ) from qiskit.utils.deprecation import deprecate_func -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="get_measured_qubits", - old_type="function", - url="https://qisk.it/qi_migration", + +@deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def get_measured_qubits( transpiled_circuits: List[QuantumCircuit], diff --git a/qiskit/utils/mitigation/__init__.py b/qiskit/utils/mitigation/__init__.py index f4e96f76a2d4..c79b107cdc0f 100644 --- a/qiskit/utils/mitigation/__init__.py +++ b/qiskit/utils/mitigation/__init__.py @@ -23,7 +23,8 @@ .. deprecated:: 0.24.0 This module is deprecated and will be removed no sooner than 3 months - after the release date. + after the release date. For code migration guidelines, + visit https://qisk.it/qi_migration. .. warning:: diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 09fdb9f99774..529aa9ec431a 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -45,7 +45,7 @@ class MeasurementFilter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__(self, cal_matrix: np.matrix, state_labels: list): """ @@ -227,7 +227,7 @@ class TensoredFilter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): """ diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index 08c092c93089..a50d6d207f0a 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -21,9 +21,10 @@ from typing import List, Tuple, Union from qiskit.utils.deprecation import deprecate_func + @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def count_keys(num_qubits: int) -> List[str]: """Deprecation: Return ordered count keys. @@ -41,7 +42,7 @@ def count_keys(num_qubits: int) -> List[str]: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def complete_meas_cal( qubit_list: List[int] = None, @@ -122,7 +123,7 @@ def complete_meas_cal( @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def tensored_meas_cal( mit_pattern: List[List[int]] = None, diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index 4402f41dcbb6..b92fca5a6478 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -37,7 +37,7 @@ class CompleteMeasFitter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__( self, @@ -221,7 +221,7 @@ class TensoredMeasFitter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__( self, diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index e8adc558e650..657f6d4403f5 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -146,7 +146,7 @@ class QuantumInstance: @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__( self, diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index f5f6e3d5e620..d117bada5cef 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -23,7 +23,8 @@ from qiskit.providers import Backend, JobStatus, JobError, Job from qiskit.providers.jobstatus import JOB_FINAL_STATES from qiskit.result import Result -from qiskit.utils.deprecation import deprecate_funcfrom ..exceptions import QiskitError, MissingOptionalLibraryError +from qiskit.utils.deprecation import deprecate_func +from ..exceptions import QiskitError, MissingOptionalLibraryError from .backend_utils import ( is_aer_provider, is_basicaer_provider, @@ -39,12 +40,9 @@ logger = logging.getLogger(__name__) -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="find_regs_by_name", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def find_regs_by_name( circuit: QuantumCircuit, name: str, qreg: bool = True @@ -107,12 +105,9 @@ def _safe_get_job_status(job: Job, job_id: str, max_job_retries: int, wait: floa return job_status -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="run_circuits", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def run_circuits( circuits: Union[QuantumCircuit, List[QuantumCircuit]], diff --git a/test/python/algorithms/optimizers/test_spsa.py b/test/python/algorithms/optimizers/test_spsa.py index 935d4bdfe525..78dd08c97304 100644 --- a/test/python/algorithms/optimizers/test_spsa.py +++ b/test/python/algorithms/optimizers/test_spsa.py @@ -216,7 +216,6 @@ def test_qnspsa_fidelity_deprecation(self): # No warning when used correctly. QNSPSA.get_fidelity(ansatz) - def test_qnspsa_fidelity_primitives(self): """Test the primitives can be used in get_fidelity.""" ansatz = PauliTwoDesign(2, reps=1, seed=2) diff --git a/test/python/algorithms/test_linear_solvers.py b/test/python/algorithms/test_linear_solvers.py deleted file mode 100644 index 40c70bfcbb54..000000000000 --- a/test/python/algorithms/test_linear_solvers.py +++ /dev/null @@ -1,382 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2020, 2023. -# -# 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 the quantum linear system solver algorithm.""" - -import unittest -import warnings -from test.python.algorithms import QiskitAlgorithmsTestCase -from scipy.linalg import expm -import numpy as np -from ddt import ddt, idata, unpack -from qiskit import BasicAer, QuantumCircuit -from qiskit.algorithms.linear_solvers.hhl import HHL -from qiskit.algorithms.linear_solvers.matrices.tridiagonal_toeplitz import TridiagonalToeplitz -from qiskit.algorithms.linear_solvers.matrices.numpy_matrix import NumPyMatrix -from qiskit.algorithms.linear_solvers.observables.absolute_average import AbsoluteAverage -from qiskit.algorithms.linear_solvers.observables.matrix_functional import MatrixFunctional -from qiskit.circuit.library.arithmetic.exact_reciprocal import ExactReciprocal -from qiskit.quantum_info import Operator, partial_trace -from qiskit.opflow import I, Z, StateFn -from qiskit.utils import QuantumInstance -from qiskit import quantum_info -from qiskit.test import slow_test - - -def _factory_tridiagonal_toeplitz( - num_state_qubits: int, main_diag: float, off_diag: float, trotter_steps: int = 1 -): - with warnings.catch_warnings(record=True): - warnings.simplefilter("ignore") - return TridiagonalToeplitz( - num_state_qubits, main_diag, off_diag, trotter_steps=trotter_steps - ) - - -def _factory_numpy_matrix(matrix: np.ndarray): - with warnings.catch_warnings(record=True): - warnings.simplefilter("ignore") - return NumPyMatrix(matrix) - - -@ddt -class TestMatrices(QiskitAlgorithmsTestCase): - """Tests based on the matrices classes. - - This class tests - * the constructed circuits - """ - - @idata( - [ - [_factory_tridiagonal_toeplitz(2, 1, -1 / 3)], - [_factory_tridiagonal_toeplitz(3, 2, 1), 1.1, 3], - [ - _factory_numpy_matrix( - np.array( - [ - [1 / 2, 1 / 6, 0, 0], - [1 / 6, 1 / 2, 1 / 6, 0], - [0, 1 / 6, 1 / 2, 1 / 6], - [0, 0, 1 / 6, 1 / 2], - ] - ) - ) - ], - ] - ) - @unpack - def test_matrices(self, matrix, time=1.0, power=1): - """Test the different matrix classes.""" - matrix.evolution_time = time - - num_qubits = matrix.num_state_qubits - pow_circ = matrix.power(power).control() - circ_qubits = pow_circ.num_qubits - qc = QuantumCircuit(circ_qubits) - qc.append(matrix.power(power).control(), list(range(circ_qubits))) - # extract the parts of the circuit matrix corresponding to TridiagonalToeplitz - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - zero_op = (I + Z) / 2 - one_op = (I - Z) / 2 - proj = Operator((zero_op ^ pow_circ.num_ancillas) ^ (I ^ num_qubits) ^ one_op).data - self.assertTrue(len(caught_warnings) > 0) - circ_matrix = Operator(qc).data - approx_exp = partial_trace( - np.dot(proj, circ_matrix), [0] + list(range(num_qubits + 1, circ_qubits)) - ).data - - exact_exp = expm(1j * matrix.evolution_time * power * matrix.matrix) - np.testing.assert_array_almost_equal(approx_exp, exact_exp, decimal=2) - - @idata( - [ - [_factory_tridiagonal_toeplitz(2, 1.5, 2.5)], - [_factory_tridiagonal_toeplitz(4, -1, 1.6)], - ] - ) - @unpack - def test_eigs_bounds(self, matrix): - """Test the capability of TridiagonalToeplitz matrix class - to find accurate absolute eigenvalues bounds.""" - - matrix_lambda_min, matrix_lambda_max = matrix.eigs_bounds() - - numpy_matrix = matrix.matrix - eigenvalues, _ = np.linalg.eig(numpy_matrix) - abs_eigenvalues = np.abs(eigenvalues) - exact_lambda_min = np.min(abs_eigenvalues) - exact_lambda_max = np.max(abs_eigenvalues) - - np.testing.assert_almost_equal(matrix_lambda_min, exact_lambda_min, decimal=6) - np.testing.assert_almost_equal(matrix_lambda_max, exact_lambda_max, decimal=6) - - -def _factory_absolute_average(): - with warnings.catch_warnings(record=True): - warnings.simplefilter("ignore") - return AbsoluteAverage() - - -def _factory_matrix_functional(main_diag: float, off_diag: int): - with warnings.catch_warnings(record=True): - warnings.simplefilter("ignore") - return MatrixFunctional(main_diag, off_diag) - - -@ddt -class TestObservables(QiskitAlgorithmsTestCase): - """Tests based on the observables classes. - - This class tests - * the constructed circuits - """ - - @idata( - [ - [_factory_absolute_average(), [1.0, -2.1, 3.2, -4.3]], - [_factory_absolute_average(), [-9 / 4, -0.3, 8 / 7, 10, -5, 11.1, 13 / 11, -27 / 12]], - ] - ) - @unpack - def test_absolute_average(self, observable, vector): - """Test the absolute average observable.""" - init_state = vector / np.linalg.norm(vector) - num_qubits = int(np.log2(len(vector))) - - qc = QuantumCircuit(num_qubits) - qc.isometry(init_state, list(range(num_qubits)), None) - qc.append(observable.observable_circuit(num_qubits), list(range(num_qubits))) - - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - # Observable operator - observable_op = observable.observable(num_qubits) - state_vec = (~StateFn(observable_op) @ StateFn(qc)).eval() - self.assertTrue(len(caught_warnings) > 0) - - # Obtain result - result = observable.post_processing(state_vec, num_qubits) - - # Obtain analytical evaluation - exact = observable.evaluate_classically(init_state) - - np.testing.assert_almost_equal(result, exact, decimal=2) - - @idata( - [ - [_factory_matrix_functional(1, -1 / 3), [1.0, -2.1, 3.2, -4.3]], - [ - _factory_matrix_functional(2 / 3, 11 / 7), - [-9 / 4, -0.3, 8 / 7, 10, -5, 11.1, 13 / 11, -27 / 12], - ], - ] - ) - @unpack - def test_matrix_functional(self, observable, vector): - """Test the matrix functional class.""" - from qiskit.transpiler.passes import RemoveResetInZeroState - - tpass = RemoveResetInZeroState() - - init_state = vector / np.linalg.norm(vector) - num_qubits = int(np.log2(len(vector))) - - # Get observable circuits - obs_circuits = observable.observable_circuit(num_qubits) - qcs = [] - for obs_circ in obs_circuits: - qc = QuantumCircuit(num_qubits) - qc.isometry(init_state, list(range(num_qubits)), None) - qc.append(obs_circ, list(range(num_qubits))) - qcs.append(tpass(qc.decompose())) - - # Get observables - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - observable_ops = observable.observable(num_qubits) - state_vecs = [] - # First is the norm - state_vecs.append((~StateFn(observable_ops[0]) @ StateFn(qcs[0])).eval()) - for i in range(1, len(observable_ops), 2): - state_vecs += [ - (~StateFn(observable_ops[i]) @ StateFn(qcs[i])).eval(), - (~StateFn(observable_ops[i + 1]) @ StateFn(qcs[i + 1])).eval(), - ] - self.assertTrue(len(caught_warnings) > 0) - - # Obtain result - result = observable.post_processing(state_vecs, num_qubits) - - # Obtain analytical evaluation - exact = observable.evaluate_classically(init_state) - - np.testing.assert_almost_equal(result, exact, decimal=2) - - -@ddt -class TestReciprocal(QiskitAlgorithmsTestCase): - """Tests based on the reciprocal classes. - - This class tests - * the constructed circuits - """ - - @idata([[2, 0.1, False], [3, 1 / 9, True]]) - @unpack - def test_exact_reciprocal(self, num_qubits, scaling, neg_vals): - """Test the ExactReciprocal class.""" - reciprocal = ExactReciprocal(num_qubits + neg_vals, scaling, neg_vals) - - qc = QuantumCircuit(num_qubits + 1 + neg_vals) - qc.h(list(range(num_qubits))) - # If negative eigenvalues, set the sign qubit to 1 - if neg_vals: - qc.x(num_qubits) - qc.append(reciprocal, list(range(num_qubits + 1 + neg_vals))) - - # Create the operator 0 - state_vec = quantum_info.Statevector.from_instruction(qc).data[-(2**num_qubits) :] - - # Remove the factor from the hadamards - state_vec *= np.sqrt(2) ** num_qubits - - # Analytic value - exact = [] - for i in range(0, 2**num_qubits): - if i == 0: - exact.append(0) - else: - if neg_vals: - exact.append(-scaling / (1 - i / (2**num_qubits))) - else: - exact.append(scaling * (2**num_qubits) / i) - - np.testing.assert_array_almost_equal(state_vec, exact, decimal=2) - - -@ddt -class TestLinearSolver(QiskitAlgorithmsTestCase): - """Tests based on the linear solvers classes. - - This class tests - * the constructed circuits - """ - - @slow_test - @idata( - [ - [ - _factory_tridiagonal_toeplitz(2, 1, 1 / 3, trotter_steps=2), - [1.0, -2.1, 3.2, -4.3], - _factory_matrix_functional(1, 1 / 2), - ], - [ - np.array( - [[0, 0, 1.585, 0], [0, 0, -0.585, 1], [1.585, -0.585, 0, 0], [0, 1, 0, 0]] - ), - [1.0, 0, 0, 0], - _factory_matrix_functional(1, 1 / 2), - ], - [ - [ - [1 / 2, 1 / 6, 0, 0], - [1 / 6, 1 / 2, 1 / 6, 0], - [0, 1 / 6, 1 / 2, 1 / 6], - [0, 0, 1 / 6, 1 / 2], - ], - [1.0, -2.1, 3.2, -4.3], - _factory_matrix_functional(1, 1 / 2), - ], - [ - np.array([[82, 34], [34, 58]]), - np.array([[1], [0]]), - _factory_absolute_average(), - 3, - ], - [ - _factory_tridiagonal_toeplitz(3, 1, -1 / 2, trotter_steps=2), - [-9 / 4, -0.3, 8 / 7, 10, -5, 11.1, 13 / 11, -27 / 12], - _factory_absolute_average(), - ], - ] - ) - @unpack - def test_hhl(self, matrix, right_hand_side, observable, decimal=1): - """Test the HHL class.""" - if isinstance(matrix, QuantumCircuit): - num_qubits = matrix.num_state_qubits - elif isinstance(matrix, (np.ndarray)): - num_qubits = int(np.log2(matrix.shape[0])) - elif isinstance(matrix, list): - num_qubits = int(np.log2(len(matrix))) - - rhs = right_hand_side / np.linalg.norm(right_hand_side) - - # Initial state circuit - qc = QuantumCircuit(num_qubits) - qc.isometry(rhs, list(range(num_qubits)), None) - - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.simplefilter("always") - hhl = HHL() - self.assertTrue("HHL class is deprecated" in str(caught_warnings[0].message)) - solution = hhl.solve(matrix, qc, observable) - approx_result = solution.observable - - # Calculate analytical value - if isinstance(matrix, QuantumCircuit): - exact_x = np.dot(np.linalg.inv(matrix.matrix), rhs) - elif isinstance(matrix, (list, np.ndarray)): - if isinstance(matrix, list): - matrix = np.array(matrix) - exact_x = np.dot(np.linalg.inv(matrix), rhs) - exact_result = observable.evaluate_classically(exact_x) - - np.testing.assert_almost_equal(approx_result, exact_result, decimal=decimal) - - def test_hhl_qi(self): - """Test the HHL quantum instance getter and setter.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.simplefilter("always") - hhl = HHL() - self.assertTrue("HHL class is deprecated" in str(caught_warnings[0].message)) - self.assertIsNone(hhl.quantum_instance) # Defaults to None - - # First set a valid quantum instance and check via getter - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - qinst = QuantumInstance(backend=BasicAer.get_backend("qasm_simulator")) - hhl.quantum_instance = qinst - self.assertTrue(len(caught_warnings) > 0) - self.assertEqual(hhl.quantum_instance, qinst) - - # Now set quantum instance back to None and check via getter - hhl.quantum_instance = None - self.assertIsNone(hhl.quantum_instance) - - -if __name__ == "__main__": - unittest.main() diff --git a/test/python/algorithms/test_shor.py b/test/python/algorithms/test_shor.py deleted file mode 100644 index b21a462ee408..000000000000 --- a/test/python/algorithms/test_shor.py +++ /dev/null @@ -1,205 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2018, 2023. -# -# 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 Shor""" - -import unittest -import warnings -import math -from test.python.algorithms import QiskitAlgorithmsTestCase -from ddt import ddt, data, idata, unpack - -from qiskit import ClassicalRegister -from qiskit.utils import QuantumInstance, optionals -from qiskit.algorithms import Shor -from qiskit.test import slow_test - - -@ddt -class TestShor(QiskitAlgorithmsTestCase): - """test Shor's algorithm""" - - @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") - def setUp(self): - super().setUp() - from qiskit_aer import Aer - - backend = Aer.get_backend("aer_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - self.instance = Shor(quantum_instance=QuantumInstance(backend, shots=1000)) - for caught_warning in caught_warnings: - if "Shor class is deprecated" in str(caught_warning.message): - return - - self.fail("Shor class is not emitting deprecation message.") - - @slow_test - @idata( - [ - [15, "aer_simulator", [3, 5]], - ] - ) - @unpack - def test_shor_factoring(self, n_v, backend, factors): - """shor factoring test for n = log(N) = 4""" - self._test_shor_factoring(backend, factors, n_v) - - @slow_test - @idata( - [ - [21, "aer_simulator", [3, 7]], - ] - ) - @unpack - def test_shor_factoring_5_bit_number(self, n_v, backend, factors): - """shor factoring test for n = log(N) = 5""" - self._test_shor_factoring(backend, factors, n_v) - - def _test_shor_factoring(self, backend, factors, n_v): - """shor factoring test""" - - with warnings.catch_warnings(record=True): - warnings.simplefilter("always") - from qiskit_aer import Aer - - with self.assertWarnsRegex(DeprecationWarning, "Shor class is deprecated"): - shor = Shor(quantum_instance=QuantumInstance(Aer.get_backend(backend), shots=1000)) - - result = shor.factor(N=n_v) - self.assertListEqual(result.factors[0], factors) - self.assertTrue(result.total_counts >= result.successful_counts) - - @slow_test - @data(5, 7) - def test_shor_no_factors(self, n_v): - """shor no factors test""" - shor = self.instance - result = shor.factor(N=n_v) - self.assertTrue(result.factors == []) - self.assertTrue(result.successful_counts == 0) - - @idata( - [ - [3, 5], - [5, 3], - ] - ) - @unpack - def test_shor_input_being_power(self, base, power): - """shor input being power test""" - n_v = int(math.pow(base, power)) - shor = self.instance - result = shor.factor(N=n_v) - self.assertTrue(result.factors == [base]) - self.assertTrue(result.total_counts >= result.successful_counts) - - @idata( - [[N, 2] for N in [-1, 0, 1, 2, 4, 16]] + [[15, a] for a in [-1, 0, 1, 3, 5, 15, 16]], - ) - @unpack - def test_shor_bad_input(self, n_v, a_v): - """shor factor bad input test""" - shor = self.instance - with self.assertRaises(ValueError): - _ = shor.factor(N=n_v, a=a_v) - - @slow_test - @idata( - [ - [15, 4, 2], - [15, 7, 4], - ] - ) - @unpack - def test_shor_quantum_result(self, n_v, a_v, order): - """shor quantum result test (for order being power of 2)""" - self._test_quantum_result(a_v, n_v, order) - - @slow_test - @idata( - [ - [17, 8, 8], - [21, 13, 2], - ] - ) - @unpack - def test_shor_quantum_result_for_5_bit_number(self, n_v, a_v, order): - """shor quantum result test (for order being power of 2 and n = log(N) = 5)""" - self._test_quantum_result(a_v, n_v, order) - - def _test_quantum_result(self, a_v, n_v, order): - shor = self.instance - circuit = shor.construct_circuit(N=n_v, a=a_v, measurement=True) - - result = shor.quantum_instance.execute(circuit) - measurements = [int(key, base=2) for key in result.get_counts(circuit).keys()] - - # calculate values that could be measured - values = [i << (2 * n_v.bit_length() - order.bit_length() + 1) for i in range(order)] - - for measurement in measurements: - self.assertTrue(measurement in values) - - @slow_test - @idata( - [ - [15, 4, [1, 4]], - [15, 7, [1, 4, 7, 13]], - ] - ) - @unpack - def test_shor_exponentiation_result(self, n_v, a_v, values): - """shor exponentiation result test (for n = log(N) = 4)""" - self._test_exponentiation_result(a_v, n_v, values) - - @slow_test - @idata( - [ - [5, 21, [1, 4, 5, 16, 17, 20]], - [4, 25, [1, 4, 6, 9, 11, 14, 16, 19, 21, 24]], - ] - ) - @unpack - def test_shor_exponentiation_result_for_5_bit_number(self, a_v, n_v, values): - """shor exponentiation result test (for n = log(N) = 5)""" - self._test_exponentiation_result(a_v, n_v, values) - - def _test_exponentiation_result(self, a_v, n_v, values): - shor = self.instance - - circuit = shor.construct_circuit(N=n_v, a=a_v, measurement=False) - # modify circuit to measure output (down) register - down_qreg = circuit.qregs[1] - down_creg = ClassicalRegister(len(down_qreg), name="m") - circuit.add_register(down_creg) - circuit.measure(down_qreg, down_creg) - - result = shor.quantum_instance.execute(circuit) - measurements = [int(key, base=2) for key in result.get_counts(circuit).keys()] - - for measurement in measurements: - self.assertTrue(measurement in values) - - @idata([[2, 15, 8], [4, 15, 4]]) - @unpack - def test_shor_modinv(self, a_v, m_v, expected): - """shor modular inverse test""" - modinv = Shor.modinv(a_v, m_v) - self.assertTrue(modinv == expected) - - -if __name__ == "__main__": - unittest.main() From cfb04f50e6a30a33955b57be4ab5bbdb9035923c Mon Sep 17 00:00:00 2001 From: ElePT Date: Wed, 29 Mar 2023 17:39:51 +0200 Subject: [PATCH 10/47] Remove hanging Deprecated in docstring --- qiskit/opflow/converters/dict_to_circuit_sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index 4d8e10ed157f..c2b150b9ed17 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -23,7 +23,7 @@ class DictToCircuitSum(ConverterBase): r""" - Deprecation: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` + Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` on an Operator, but with the added control of choosing whether to convert only ``DictStateFns`` or ``VectorStateFns``, rather than both. From 69c01198d58918742137c2a936c8ef105b0e802d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elena=20Pe=C3=B1a=20Tapia?= <57907331+ElePT@users.noreply.github.com> Date: Wed, 29 Mar 2023 17:47:23 +0200 Subject: [PATCH 11/47] Remove old Deprecation messages --- qiskit/utils/measurement_error_mitigation.py | 6 +++--- qiskit/utils/mitigation/_filters.py | 4 ++-- qiskit/utils/mitigation/circuits.py | 6 +++--- qiskit/utils/mitigation/fitters.py | 2 +- qiskit/utils/quantum_instance.py | 2 +- qiskit/utils/run_circuits.py | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index f719ac5d1fc7..629044b6b343 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -38,7 +38,7 @@ def get_measured_qubits( transpiled_circuits: List[QuantumCircuit], ) -> Tuple[List[int], Dict[str, List[int]]]: """ - Deprecation: Retrieve the measured qubits from transpiled circuits. + Retrieve the measured qubits from transpiled circuits. Args: transpiled_circuits: a list of transpiled circuits @@ -87,7 +87,7 @@ def get_measured_qubits( ) def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, List[int]]]: """ - Deprecation: Retrieve the measured qubits from transpiled circuits. + Retrieve the measured qubits from transpiled circuits. Args: qobj: qobj @@ -141,7 +141,7 @@ def build_measurement_error_mitigation_circuits( compile_config: Optional[Dict] = None, mit_pattern: Optional[List[List[int]]] = None, ) -> Tuple[QuantumCircuit, List[str], List[str]]: - """Deprecation: Build measurement error mitigation circuits + """Build measurement error mitigation circuits Args: qubit_list: list of ordered qubits used in the algorithm fitter_cls: CompleteMeasFitter or TensoredMeasFitter diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 529aa9ec431a..91f611946fb0 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -36,7 +36,7 @@ class MeasurementFilter: """ - Deprecation: Measurement error mitigation filter. + Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. @@ -219,7 +219,7 @@ def _apply_correction(self, resultidx, raw_data, method): class TensoredFilter: """ - Deprecation: Tensored measurement error mitigation filter. + Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index a50d6d207f0a..ba1bdd191776 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -27,7 +27,7 @@ additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def count_keys(num_qubits: int) -> List[str]: - """Deprecation: Return ordered count keys. + """Return ordered count keys. Args: num_qubits: The number of qubits in the generated list. @@ -51,7 +51,7 @@ def complete_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[str]]: """ - Deprecation: Return a list of measurement calibration circuits for the full + Return a list of measurement calibration circuits for the full Hilbert space. If the circuit contains :math:`n` qubits, then :math:`2^n` calibration circuits @@ -132,7 +132,7 @@ def tensored_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[List[int]]]: """ - Deprecation: Return a list of calibration circuits + Return a list of calibration circuits Args: mit_pattern: Qubits on which to perform the diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index b92fca5a6478..343e5af50f7e 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -216,7 +216,7 @@ def readout_fidelity(self, label_list=None): class TensoredMeasFitter: """ - Deprecation: Measurement correction fitter for a tensored calibration. + Measurement correction fitter for a tensored calibration. """ @deprecate_func( diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index 657f6d4403f5..f9c03f78310d 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -125,7 +125,7 @@ def type_from_instance(meas_instance): class QuantumInstance: - """Deprecation: Quantum Backend including execution setting.""" + """Quantum Backend including execution setting.""" _BACKEND_CONFIG = ["basis_gates", "coupling_map"] _COMPILE_CONFIG = ["initial_layout", "seed_transpiler", "optimization_level"] diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index d117bada5cef..7ebd536805e1 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -47,7 +47,7 @@ def find_regs_by_name( circuit: QuantumCircuit, name: str, qreg: bool = True ) -> Optional[Union[QuantumRegister, ClassicalRegister]]: - """Deprecation: Find the registers in the circuits. + """Find the registers in the circuits. Args: circuit: the quantum circuit. @@ -120,7 +120,7 @@ def run_circuits( max_job_retries: int = 50, ) -> Result: """ - Deprecation: An execution wrapper with Qiskit-Terra, with job auto recover capability. + An execution wrapper with Qiskit-Terra, with job auto recover capability. The auto-recovery feature is only applied for non-simulator backend. This wrapper will try to get the result no matter how long it takes. From f7835e386dc59eddbbb4995ce87faf882c283095 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:00:58 +0200 Subject: [PATCH 12/47] Revert "Remove old Deprecation messages" This reverts commit 6924130e12ffdfde971ff1e25434ee84bf983482. --- qiskit/utils/measurement_error_mitigation.py | 6 +++--- qiskit/utils/mitigation/_filters.py | 4 ++-- qiskit/utils/mitigation/circuits.py | 6 +++--- qiskit/utils/mitigation/fitters.py | 2 +- qiskit/utils/quantum_instance.py | 2 +- qiskit/utils/run_circuits.py | 4 ++-- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index 629044b6b343..f719ac5d1fc7 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -38,7 +38,7 @@ def get_measured_qubits( transpiled_circuits: List[QuantumCircuit], ) -> Tuple[List[int], Dict[str, List[int]]]: """ - Retrieve the measured qubits from transpiled circuits. + Deprecation: Retrieve the measured qubits from transpiled circuits. Args: transpiled_circuits: a list of transpiled circuits @@ -87,7 +87,7 @@ def get_measured_qubits( ) def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, List[int]]]: """ - Retrieve the measured qubits from transpiled circuits. + Deprecation: Retrieve the measured qubits from transpiled circuits. Args: qobj: qobj @@ -141,7 +141,7 @@ def build_measurement_error_mitigation_circuits( compile_config: Optional[Dict] = None, mit_pattern: Optional[List[List[int]]] = None, ) -> Tuple[QuantumCircuit, List[str], List[str]]: - """Build measurement error mitigation circuits + """Deprecation: Build measurement error mitigation circuits Args: qubit_list: list of ordered qubits used in the algorithm fitter_cls: CompleteMeasFitter or TensoredMeasFitter diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 91f611946fb0..529aa9ec431a 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -36,7 +36,7 @@ class MeasurementFilter: """ - Measurement error mitigation filter. + Deprecation: Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. @@ -219,7 +219,7 @@ def _apply_correction(self, resultidx, raw_data, method): class TensoredFilter: """ - Tensored measurement error mitigation filter. + Deprecation: Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index ba1bdd191776..a50d6d207f0a 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -27,7 +27,7 @@ additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def count_keys(num_qubits: int) -> List[str]: - """Return ordered count keys. + """Deprecation: Return ordered count keys. Args: num_qubits: The number of qubits in the generated list. @@ -51,7 +51,7 @@ def complete_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[str]]: """ - Return a list of measurement calibration circuits for the full + Deprecation: Return a list of measurement calibration circuits for the full Hilbert space. If the circuit contains :math:`n` qubits, then :math:`2^n` calibration circuits @@ -132,7 +132,7 @@ def tensored_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[List[int]]]: """ - Return a list of calibration circuits + Deprecation: Return a list of calibration circuits Args: mit_pattern: Qubits on which to perform the diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index 343e5af50f7e..b92fca5a6478 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -216,7 +216,7 @@ def readout_fidelity(self, label_list=None): class TensoredMeasFitter: """ - Measurement correction fitter for a tensored calibration. + Deprecation: Measurement correction fitter for a tensored calibration. """ @deprecate_func( diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index f9c03f78310d..657f6d4403f5 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -125,7 +125,7 @@ def type_from_instance(meas_instance): class QuantumInstance: - """Quantum Backend including execution setting.""" + """Deprecation: Quantum Backend including execution setting.""" _BACKEND_CONFIG = ["basis_gates", "coupling_map"] _COMPILE_CONFIG = ["initial_layout", "seed_transpiler", "optimization_level"] diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index 7ebd536805e1..d117bada5cef 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -47,7 +47,7 @@ def find_regs_by_name( circuit: QuantumCircuit, name: str, qreg: bool = True ) -> Optional[Union[QuantumRegister, ClassicalRegister]]: - """Find the registers in the circuits. + """Deprecation: Find the registers in the circuits. Args: circuit: the quantum circuit. @@ -120,7 +120,7 @@ def run_circuits( max_job_retries: int = 50, ) -> Result: """ - An execution wrapper with Qiskit-Terra, with job auto recover capability. + Deprecation: An execution wrapper with Qiskit-Terra, with job auto recover capability. The auto-recovery feature is only applied for non-simulator backend. This wrapper will try to get the result no matter how long it takes. From fbd04389f636df11aa34315d78bf8438c4273c96 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:01:45 +0200 Subject: [PATCH 13/47] Revert "Remove hanging Deprecated in docstring" This reverts commit cfb04f50e6a30a33955b57be4ab5bbdb9035923c. --- qiskit/opflow/converters/dict_to_circuit_sum.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index c2b150b9ed17..4d8e10ed157f 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -23,7 +23,7 @@ class DictToCircuitSum(ConverterBase): r""" - Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` + Deprecation: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` on an Operator, but with the added control of choosing whether to convert only ``DictStateFns`` or ``VectorStateFns``, rather than both. From 96ccbd2bd76882fd95e09656df0398445d582eca Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:05:12 +0200 Subject: [PATCH 14/47] Revert "Remove from docstring" This reverts commit 50e5954ecd4a729e7101e8ea4bf493240ae8b59e. --- qiskit/opflow/converters/abelian_grouper.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 2 +- qiskit/opflow/converters/converter_base.py | 2 +- qiskit/opflow/converters/pauli_basis_change.py | 2 +- qiskit/opflow/converters/two_qubit_reduction.py | 2 +- qiskit/opflow/evolutions/evolution_base.py | 2 +- qiskit/opflow/evolutions/evolution_factory.py | 2 +- qiskit/opflow/evolutions/evolved_op.py | 2 +- qiskit/opflow/evolutions/matrix_evolution.py | 2 +- qiskit/opflow/evolutions/pauli_trotter_evolution.py | 2 +- qiskit/opflow/evolutions/trotterizations/qdrift.py | 2 +- qiskit/opflow/evolutions/trotterizations/suzuki.py | 2 +- qiskit/opflow/evolutions/trotterizations/trotter.py | 2 +- .../evolutions/trotterizations/trotterization_base.py | 2 +- .../evolutions/trotterizations/trotterization_factory.py | 2 +- qiskit/opflow/exceptions.py | 2 +- qiskit/opflow/expectations/aer_pauli_expectation.py | 2 +- qiskit/opflow/expectations/cvar_expectation.py | 2 +- qiskit/opflow/expectations/expectation_base.py | 2 +- qiskit/opflow/expectations/expectation_factory.py | 3 ++- qiskit/opflow/expectations/matrix_expectation.py | 2 +- qiskit/opflow/expectations/pauli_expectation.py | 2 +- .../opflow/gradients/circuit_gradients/circuit_gradient.py | 2 +- qiskit/opflow/gradients/circuit_gradients/lin_comb.py | 2 +- qiskit/opflow/gradients/circuit_gradients/param_shift.py | 2 +- qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py | 2 +- qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_diag.py | 2 +- qiskit/opflow/gradients/derivative_base.py | 2 +- qiskit/opflow/gradients/gradient.py | 2 +- qiskit/opflow/gradients/gradient_base.py | 2 +- qiskit/opflow/gradients/hessian.py | 2 +- qiskit/opflow/gradients/hessian_base.py | 2 +- qiskit/opflow/gradients/natural_gradient.py | 2 +- qiskit/opflow/gradients/qfi.py | 2 +- qiskit/opflow/gradients/qfi_base.py | 2 +- qiskit/opflow/list_ops/composed_op.py | 2 +- qiskit/opflow/list_ops/list_op.py | 2 +- qiskit/opflow/list_ops/summed_op.py | 2 +- qiskit/opflow/list_ops/tensored_op.py | 2 +- qiskit/opflow/mixins/star_algebra.py | 2 +- qiskit/opflow/mixins/tensor.py | 2 +- qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/primitive_ops/circuit_op.py | 2 +- qiskit/opflow/primitive_ops/matrix_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 +- qiskit/opflow/primitive_ops/primitive_op.py | 2 +- qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py | 2 +- qiskit/opflow/state_fns/circuit_state_fn.py | 2 +- qiskit/opflow/state_fns/cvar_measurement.py | 2 +- qiskit/opflow/state_fns/dict_state_fn.py | 2 +- qiskit/opflow/state_fns/operator_state_fn.py | 2 +- qiskit/opflow/state_fns/sparse_vector_state_fn.py | 2 +- qiskit/opflow/state_fns/state_fn.py | 2 +- qiskit/opflow/state_fns/vector_state_fn.py | 2 +- qiskit/opflow/utils.py | 6 +++--- 58 files changed, 61 insertions(+), 60 deletions(-) diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index b2e2c946a2ab..0e0aad99687a 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -31,7 +31,7 @@ class AbelianGrouper(ConverterBase): - """The AbelianGrouper converts SummedOps into a sum of Abelian sums. + """Deprecation: The AbelianGrouper converts SummedOps into a sum of Abelian sums. Meaning, it will traverse the Operator, and when it finds a SummedOp, it will evaluate which of the summed sub-Operators commute with one another. It will then convert each of the groups of diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index 4a1e2bf1454d..abaf0adeea8d 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -40,7 +40,7 @@ class CircuitSampler(ConverterBase): """ - The CircuitSampler traverses an Operator and converts any CircuitStateFns into + Deprecation: The CircuitSampler traverses an Operator and converts any CircuitStateFns into approximations of the state function by a DictStateFn or VectorStateFn using a quantum backend. Note that in order to approximate the value of the CircuitStateFn, it must 1) send state function through a depolarizing channel, which will destroy all phase information and diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index 64a1edce616f..36b706437b32 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -20,7 +20,7 @@ class ConverterBase(ABC): r""" - Converters take an Operator and return a new Operator, generally isomorphic + Deprecation: Converters take an Operator and return a new Operator, generally isomorphic in some way with the first, but with certain desired properties. For example, a converter may accept ``CircuitOp`` and return a ``SummedOp`` of ``PauliOps`` representing the circuit unitary. Converters may not diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index 98af89f90786..77ce29346fab 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -35,7 +35,7 @@ class PauliBasisChange(ConverterBase): r""" - Converter for changing Paulis into other bases. By default, the diagonal basis + Deprecation: Converter for changing Paulis into other bases. By default, the diagonal basis composed only of Pauli {Z, I}^n is used as the destination basis to which to convert. Meaning, if a Pauli containing X or Y terms is passed in, which cannot be sampled or evolved natively on some Quantum hardware, the Pauli can be replaced by a diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index 99db05f6e860..d658b579d901 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -27,7 +27,7 @@ class TwoQubitReduction(ConverterBase): """ - Two qubit reduction converter which eliminates the central and last + Deprecation: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index 8831b78e8943..1908820b3f30 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -21,7 +21,7 @@ class EvolutionBase(ConverterBase, ABC): r""" - A base for Evolution converters. + Deprecation: A base for Evolution converters. Evolutions are converters which traverse an Operator tree, replacing any ``EvolvedOp`` `e` with a Schrodinger equation-style evolution ``CircuitOp`` equalling or approximating the matrix exponential of -i * the Operator contained inside (`e.primitive`). The Evolutions are diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index 2a99a17f4019..b9ba933429ae 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -20,7 +20,7 @@ class EvolutionFactory: - """A factory class for convenient automatic selection of an + """Deprecation: A factory class for convenient automatic selection of an Evolution algorithm based on the Operator to be converted. """ diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index 94247d8fe0fa..ab1e3ad4e93f 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -32,7 +32,7 @@ class EvolvedOp(PrimitiveOp): r""" - Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase + Deprecation: Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase method later, essentially acting as a placeholder. Note that EvolvedOp is a weird case of PrimitiveOp. It happens to be that it fits into the PrimitiveOp interface nearly perfectly, and it essentially represents a placeholder for a PrimitiveOp later, even though it doesn't diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index a5fab9f96a3a..b0d88f59c38f 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -27,7 +27,7 @@ class MatrixEvolution(EvolutionBase): r""" - Performs Evolution by classical matrix exponentiation, constructing a circuit with + Deprecation: Performs Evolution by classical matrix exponentiation, constructing a circuit with ``UnitaryGates`` or ``HamiltonianGates`` containing the exponentiation of the Operator. """ diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 9c8f69f75d84..f65f5e0142e7 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -42,7 +42,7 @@ class PauliTrotterEvolution(EvolutionBase): r""" - An Evolution algorithm replacing exponentiated sums of Paulis by changing + Deprecation: An Evolution algorithm replacing exponentiated sums of Paulis by changing them each to the Z basis, rotating with an rZ, changing back, and Trotterizing. More specifically, we compute basis change circuits for each Pauli into a single-qubit Z, diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 6f37d398fad8..14d34c0cba73 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -32,7 +32,7 @@ class QDrift(TrotterizationBase): - """The QDrift Trotterization method, which selects each each term in the + """Deprecation: The QDrift Trotterization method, which selects each each term in the Trotterization randomly, with a probability proportional to its weight. Based on the work of Earl Campbell in https://arxiv.org/abs/1811.08017. """ diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index 480380dbb31b..caf528591d17 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -28,7 +28,7 @@ class Suzuki(TrotterizationBase): r""" - Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum + Deprecation: Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum together by a recursive "bookends" strategy, repeating the whole composed circuit ``reps`` times. diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index 2312dd8d1b65..d3b766d64a3b 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -18,7 +18,7 @@ class Trotter(Suzuki): r""" - Simple Trotter expansion, composing the evolution circuits of each Operator in the sum + Deprecation: Simple Trotter expansion, composing the evolution circuits of each Operator in the sum together ``reps`` times and dividing the evolution time of each by ``reps``. """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 2a817bf3c345..78578f24af90 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -22,7 +22,7 @@ class TrotterizationBase(EvolutionBase): - """A base for Trotterization methods, algorithms for approximating exponentiations of + """Deprecation: A base for Trotterization methods, algorithms for approximating exponentiations of operator sums by compositions of exponentiations. """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index 15c8b2d5a8c6..3fb5108c44ec 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -20,7 +20,7 @@ class TrotterizationFactory: - """A factory for conveniently creating TrotterizationBase instances.""" + """Deprecation: A factory for conveniently creating TrotterizationBase instances.""" @staticmethod @deprecate_func( diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index 09919a5d63f1..5d91263e41d9 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -17,7 +17,7 @@ class OpflowError(QiskitError): - """For Opflow specific errors.""" + """Deprecation: For Opflow specific errors.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index 6c6651de32f1..ea7b72fde286 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -34,7 +34,7 @@ class AerPauliExpectation(ExpectationBase): - r"""An Expectation converter for using Aer's operator snapshot to + r"""Deprecation: An Expectation converter for using Aer's operator snapshot to take expectations of quantum state circuits over Pauli observables. """ diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 9bc4db2a03af..891a64696fc0 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -24,7 +24,7 @@ class CVaRExpectation(ExpectationBase): - r"""Compute the Conditional Value at Risk (CVaR) expectation value. + r"""Deprecation: Compute the Conditional Value at Risk (CVaR) expectation value. The standard approach to calculating the expectation value of a Hamiltonian w.r.t. a state is to take the sample mean of the measurement outcomes. This corresponds to an estimator diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index fce88cf098d3..6c6342e4765d 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -24,7 +24,7 @@ class ExpectationBase(ConverterBase): r""" - A base for Expectation value converters. Expectations are converters which enable the + Deprecation: A base for Expectation value converters. Expectations are converters which enable the computation of the expectation value of an Observable with respect to some state function. They traverse an Operator tree, replacing OperatorStateFn measurements with equivalent measurements which are more amenable to computation on quantum or classical hardware. For diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 9e9241695e9c..65c8a45257b1 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -31,7 +31,8 @@ class ExpectationFactory: - """factory class for convenient automatic selection of an Expectation based on the + + """Deprecation: factory class for convenient automatic selection of an Expectation based on the Operator to be converted and backend used to sample the expectation value. """ diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index 43f09c9a5a64..234377ff7ee3 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -22,7 +22,7 @@ class MatrixExpectation(ExpectationBase): - """An Expectation converter which converts Operator measurements to + """Deprecation: An Expectation converter which converts Operator measurements to be matrix-based so they can be evaluated by matrix multiplication.""" @deprecate_func( diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index 1825ad82643d..08e6ec7cc1bb 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -34,7 +34,7 @@ class PauliExpectation(ExpectationBase): r""" - An Expectation converter for Pauli-basis observables by changing Pauli measurements to a + Deprecation: An Expectation converter for Pauli-basis observables by changing Pauli measurements to a diagonal ({Z, I}^n) basis and appending circuit post-rotations to the measured state function. Optionally groups the Paulis with the same post-rotations (those that commute with one another, or form Abelian groups) into single measurements to reduce circuit execution diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index b02d9610debd..8074ec13e162 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -23,7 +23,7 @@ class CircuitGradient(ConverterBase): - r"""Circuit to gradient operator converter. + r"""Deprecation: Circuit to gradient operator converter. Converter for changing parameterized circuits into operators whose evaluation yields the gradient with respect to the circuit parameters. diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 72be1f90c3a2..734ca98ee0e0 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -68,7 +68,7 @@ class LinComb(CircuitGradient): - """Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the + """Deprecation: Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω. This method employs a linear combination of unitaries, diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index 7fd40550e6a5..6653097bf50d 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -40,7 +40,7 @@ class ParamShift(CircuitGradient): - """Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling + """Deprecation: Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω with the parameter shift method. """ diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 57c136b257d0..af620beb1fc2 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -22,7 +22,7 @@ class CircuitQFI(ConverterBase): - r"""Circuit to Quantum Fisher Information operator converter. + r"""Deprecation: Circuit to Quantum Fisher Information operator converter. Converter for changing parameterized circuits into operators whose evaluation yields Quantum Fisher Information metric tensor diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 478508238535..c9bbb28687bc 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -29,7 +29,7 @@ class LinCombFull(CircuitQFI): - r"""Compute the full Quantum Fisher Information (QFI). + r"""Deprecation: Compute the full Quantum Fisher Information (QFI). Given a pure, parameterized quantum state this class uses the linear combination of unitaries See also :class:`~qiskit.opflow.QFI`. diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index 41c70b37ed34..38248b25d7c5 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -33,7 +33,7 @@ class OverlapBlockDiag(CircuitQFI): - r"""Compute the block-diagonal of the QFI given a pure, parameterized quantum state. + r"""Deprecation: Compute the block-diagonal of the QFI given a pure, parameterized quantum state. The blocks are given by all parameterized gates in quantum circuit layer. See also :class:`~qiskit.opflow.QFI`. diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 0124a316abf6..99e770197016 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -33,7 +33,7 @@ class OverlapDiag(CircuitQFI): - r"""Compute the diagonal of the QFI given a pure, parameterized quantum state. + r"""Deprecation: Compute the diagonal of the QFI given a pure, parameterized quantum state. See also :class:`~qiskit.opflow.QFI`. """ diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index c54878934193..27a62deb2373 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -34,7 +34,7 @@ class DerivativeBase(ConverterBase): - r"""Base class for differentiating opflow objects. + r"""Deprecation: Base class for differentiating opflow objects. Converter for differentiating opflow objects and handling things like properly differentiating combo_fn's and enforcing product rules diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index 85d80eed988b..cb50defd1ab3 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -35,7 +35,7 @@ class Gradient(GradientBase): - """Convert an operator expression to the first-order gradient.""" + """Deprecation: Convert an operator expression to the first-order gradient.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index 6869b1bccdb3..8709964882af 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -20,7 +20,7 @@ class GradientBase(DerivativeBase): - """Base class for first-order operator gradient. + """Deprecation: Base class for first-order operator gradient. Convert an operator expression to the first-order gradient. """ diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 85ca9ae2dcba..22cf39cc3689 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -38,7 +38,7 @@ class Hessian(HessianBase): - """Compute the Hessian of an expected value.""" + """Deprecation: Compute the Hessian of an expected value.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 3f72a28d0c8c..6a9a67538425 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -20,7 +20,7 @@ class HessianBase(DerivativeBase): - """Base class for the Hessian of an expected value.""" + """Deprecation: Base class for the Hessian of an expected value.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index d578c2024207..b7e261b9f4a2 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -38,7 +38,7 @@ class NaturalGradient(GradientBase): - r"""Convert an operator expression to the first-order gradient. + r"""Deprecation: Convert an operator expression to the first-order gradient. Given an ill-posed inverse problem diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index 8285dea8baf2..8ea36f6ad0e9 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -26,7 +26,7 @@ class QFI(QFIBase): - r"""Compute the Quantum Fisher Information (QFI). + r"""Deprecation: Compute the Quantum Fisher Information (QFI). Computes the QFI given a pure, parameterized quantum state, where QFI is: diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index da847e26cf9b..f6554ef4d999 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -21,7 +21,7 @@ class QFIBase(DerivativeBase): - r"""Base class for Quantum Fisher Information (QFI). + r"""Deprecation: Base class for Quantum Fisher Information (QFI). Compute the Quantum Fisher Information (QFI) given a pure, parameterized quantum state. diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index aab1cf5e2243..30f036eae6b7 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -28,7 +28,7 @@ class ComposedOp(ListOp): - """A class for lazily representing compositions of Operators. Often Operators cannot be + """Deprecation: A class for lazily representing compositions of Operators. Often Operators cannot be efficiently composed with one another, but may be manipulated further so that they can be composed later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be composed, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index e131a28ceb95..eb1417623e00 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -28,7 +28,7 @@ class ListOp(OperatorBase): """ - A Class for manipulating List Operators, and parent class to ``SummedOp``, + Deprecation: A Class for manipulating List Operators, and parent class to ``SummedOp``, ``ComposedOp`` and ``TensoredOp``. List Operators are classes for storing and manipulating lists of Operators, State functions, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index 960b42ff38b9..b0fef0aa59a9 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -25,7 +25,7 @@ class SummedOp(ListOp): - """A class for lazily representing sums of Operators. Often Operators cannot be + """Deprecation: A class for lazily representing sums of Operators. Often Operators cannot be efficiently added to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be added together, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index 76a894888c33..de139c3d24bd 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -26,7 +26,7 @@ class TensoredOp(ListOp): - """A class for lazily representing tensor products of Operators. Often Operators + """Deprecation: A class for lazily representing tensor products of Operators. Often Operators cannot be efficiently tensored to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be tensored together, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index 8a0be5a93fd2..98a9fb61a08d 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -20,7 +20,7 @@ class StarAlgebraMixin(MultiplyMixin, ABC): - """The star algebra mixin class. + """Deprecation: The star algebra mixin class. Star algebra is an algebra with an adjoint. This class overrides: diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index 20925be5121d..e7b515544f78 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -18,7 +18,7 @@ class TensorMixin(ABC): - """The mixin class for tensor operations. + """Deprecation: The mixin class for tensor operations. This class overrides: - ``^``, ``__xor__``, `__rxor__` -> :meth:`tensor` between two operators and diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index f67219b6c34f..ee85b322d6d9 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -29,7 +29,7 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): - """A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are + """Deprecation: A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are defined as functions which take one complex binary function to another. These complex binary functions are represented by StateFns, which are themselves a special class of Operators taking only the ``Zero`` StateFn to the complex binary function they represent. diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 095f77783ec2..2a67dbeae0ba 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -27,7 +27,7 @@ class CircuitOp(PrimitiveOp): - """Class for Operators backed by Terra's ``QuantumCircuit`` module.""" + """Deprecation: Class for Operators backed by Terra's ``QuantumCircuit`` module.""" primitive: QuantumCircuit diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index 1c849fa67289..e0d68489157c 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -31,7 +31,7 @@ class MatrixOp(PrimitiveOp): - """Class for Operators represented by matrices, + """Deprecation: Class for Operators represented by matrices, backed by Terra's ``Operator`` module.""" primitive: Operator diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 10d892ce72fe..accdcc0122ef 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -31,7 +31,7 @@ class PauliOp(PrimitiveOp): - """Class for Operators backed by Terra's ``Pauli`` module.""" + """Deprecation: Class for Operators backed by Terra's ``Pauli`` module.""" primitive: Pauli diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index 919900b84afd..78c30be8b918 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -30,7 +30,7 @@ class PauliSumOp(PrimitiveOp): - """Class for Operators backed by Terra's ``SparsePauliOp`` class.""" + """Deprecation: Class for Operators backed by Terra's ``SparsePauliOp`` class.""" primitive: SparsePauliOp diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index 60a13759b912..d93031c5464a 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -27,7 +27,7 @@ class PrimitiveOp(OperatorBase): r""" - A class for representing basic Operators, backed by Operator primitives from + Deprecation: A class for representing basic Operators, backed by Operator primitives from Terra. This class (and inheritors) primarily serves to allow the underlying primitives to "flow" - i.e. interoperability and adherence to the Operator formalism - while the core computational logic mostly remains in the underlying primitives. diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index 8a665a2b1b22..5bc7804bfb82 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -33,7 +33,7 @@ class TaperedPauliSumOp(PauliSumOp): - """Class for PauliSumOp after tapering""" + """Deprecation: Class for PauliSumOp after tapering""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index f5b39635b1eb..10e69bb8d982 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -38,7 +38,7 @@ class CircuitStateFn(StateFn): r""" - A class for state functions and measurements which are defined by the action of a + Deprecation: A class for state functions and measurements which are defined by the action of a QuantumCircuit starting from \|0⟩, and stored using Terra's ``QuantumCircuit`` class. """ primitive: QuantumCircuit diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index c7ee04b1a2d3..a4174b261a10 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -32,7 +32,7 @@ class CVaRMeasurement(OperatorStateFn): - r"""A specialized measurement class to compute CVaR expectation values. + r"""Deprecation: A specialized measurement class to compute CVaR expectation values. See https://arxiv.org/pdf/1907.04769.pdf for further details. Used in :class:`~qiskit.opflow.CVaRExpectation`, see there for more details. diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index e71aac807302..200ac7c99f4e 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -31,7 +31,7 @@ class DictStateFn(StateFn): - """A class for state functions and measurements which are defined by a lookup table, + """Deprecation: A class for state functions and measurements which are defined by a lookup table, stored in a dict. """ diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index d462746ccb73..79c3fdd54597 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -31,7 +31,7 @@ class OperatorStateFn(StateFn): r""" - A class for state functions and measurements which are defined by a density Operator, + Deprecation: A class for state functions and measurements which are defined by a density Operator, stored using an ``OperatorBase``. """ primitive: OperatorBase diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index e7f7cdee99fe..019932cb79b8 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -30,7 +30,7 @@ class SparseVectorStateFn(StateFn): - """A class for sparse state functions and measurements in vector representation. + """Deprecation: A class for sparse state functions and measurements in vector representation. This class uses ``scipy.sparse.spmatrix`` for the internal representation. """ diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 7d711169536a..646c8feb080e 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -26,7 +26,7 @@ class StateFn(OperatorBase): r""" - A class for representing state functions and measurements. + Deprecation: A class for representing state functions and measurements. State functions are defined to be complex functions over a single binary string (as compared to an operator, which is defined as a function over two binary strings, or a diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index e1a1b2ecdb0c..b71746a7870a 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -30,7 +30,7 @@ class VectorStateFn(StateFn): - """A class for state functions and measurements which are defined in vector + """Deprecation: A class for state functions and measurements which are defined in vector representation, and stored using Terra's ``Statevector`` class. """ diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index d432b4e4fa6f..aa38d53faeaf 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -22,7 +22,7 @@ ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Compute commutator of `op_a` and `op_b`. + Deprecation: Compute commutator of `op_a` and `op_b`. .. math:: @@ -43,7 +43,7 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Compute anti-commutator of `op_a` and `op_b`. + Deprecation: Compute anti-commutator of `op_a` and `op_b`. .. math:: @@ -69,7 +69,7 @@ def double_commutator( sign: bool = False, ) -> OperatorBase: r""" - Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. + Deprecation: Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. See McWeeny chapter 13.6 Equation of motion methods (page 479) If `sign` is `False`, it returns From ad9249efac56885484fc102232733ae0ca12d5ba Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:10:22 +0200 Subject: [PATCH 15/47] Change Deprecation to Deprecated --- qiskit/opflow/converters/abelian_grouper.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 2 +- qiskit/opflow/converters/converter_base.py | 2 +- qiskit/opflow/converters/dict_to_circuit_sum.py | 2 +- qiskit/opflow/converters/pauli_basis_change.py | 2 +- qiskit/opflow/converters/two_qubit_reduction.py | 2 +- qiskit/opflow/evolutions/evolution_base.py | 2 +- qiskit/opflow/evolutions/evolution_factory.py | 2 +- qiskit/opflow/evolutions/evolved_op.py | 2 +- qiskit/opflow/evolutions/matrix_evolution.py | 2 +- qiskit/opflow/evolutions/pauli_trotter_evolution.py | 2 +- qiskit/opflow/evolutions/trotterizations/qdrift.py | 2 +- qiskit/opflow/evolutions/trotterizations/suzuki.py | 2 +- qiskit/opflow/evolutions/trotterizations/trotter.py | 2 +- .../evolutions/trotterizations/trotterization_base.py | 2 +- .../evolutions/trotterizations/trotterization_factory.py | 2 +- qiskit/opflow/exceptions.py | 2 +- qiskit/opflow/expectations/aer_pauli_expectation.py | 2 +- qiskit/opflow/expectations/cvar_expectation.py | 2 +- qiskit/opflow/expectations/expectation_base.py | 2 +- qiskit/opflow/expectations/expectation_factory.py | 2 +- qiskit/opflow/expectations/matrix_expectation.py | 2 +- qiskit/opflow/expectations/pauli_expectation.py | 2 +- .../opflow/gradients/circuit_gradients/circuit_gradient.py | 2 +- qiskit/opflow/gradients/circuit_gradients/lin_comb.py | 2 +- qiskit/opflow/gradients/circuit_gradients/param_shift.py | 2 +- qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py | 2 +- qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_diag.py | 2 +- qiskit/opflow/gradients/derivative_base.py | 2 +- qiskit/opflow/gradients/gradient.py | 2 +- qiskit/opflow/gradients/gradient_base.py | 2 +- qiskit/opflow/gradients/hessian.py | 2 +- qiskit/opflow/gradients/hessian_base.py | 2 +- qiskit/opflow/gradients/natural_gradient.py | 2 +- qiskit/opflow/gradients/qfi.py | 2 +- qiskit/opflow/gradients/qfi_base.py | 2 +- qiskit/opflow/list_ops/composed_op.py | 2 +- qiskit/opflow/list_ops/list_op.py | 2 +- qiskit/opflow/list_ops/summed_op.py | 2 +- qiskit/opflow/list_ops/tensored_op.py | 2 +- qiskit/opflow/mixins/star_algebra.py | 2 +- qiskit/opflow/mixins/tensor.py | 2 +- qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/primitive_ops/circuit_op.py | 2 +- qiskit/opflow/primitive_ops/matrix_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 +- qiskit/opflow/primitive_ops/primitive_op.py | 2 +- qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py | 2 +- qiskit/opflow/state_fns/circuit_state_fn.py | 2 +- qiskit/opflow/state_fns/cvar_measurement.py | 2 +- qiskit/opflow/state_fns/dict_state_fn.py | 2 +- qiskit/opflow/state_fns/operator_state_fn.py | 2 +- qiskit/opflow/state_fns/sparse_vector_state_fn.py | 2 +- qiskit/opflow/state_fns/state_fn.py | 2 +- qiskit/opflow/state_fns/vector_state_fn.py | 2 +- qiskit/opflow/utils.py | 6 +++--- qiskit/utils/measurement_error_mitigation.py | 6 +++--- qiskit/utils/mitigation/_filters.py | 4 ++-- qiskit/utils/mitigation/circuits.py | 6 +++--- qiskit/utils/mitigation/fitters.py | 4 ++-- qiskit/utils/quantum_instance.py | 2 +- qiskit/utils/run_circuits.py | 4 ++-- 65 files changed, 74 insertions(+), 74 deletions(-) diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index 0e0aad99687a..0ffc583ee579 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -31,7 +31,7 @@ class AbelianGrouper(ConverterBase): - """Deprecation: The AbelianGrouper converts SummedOps into a sum of Abelian sums. + """Deprecated: The AbelianGrouper converts SummedOps into a sum of Abelian sums. Meaning, it will traverse the Operator, and when it finds a SummedOp, it will evaluate which of the summed sub-Operators commute with one another. It will then convert each of the groups of diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index abaf0adeea8d..e59f83a68bcf 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -40,7 +40,7 @@ class CircuitSampler(ConverterBase): """ - Deprecation: The CircuitSampler traverses an Operator and converts any CircuitStateFns into + Deprecated: The CircuitSampler traverses an Operator and converts any CircuitStateFns into approximations of the state function by a DictStateFn or VectorStateFn using a quantum backend. Note that in order to approximate the value of the CircuitStateFn, it must 1) send state function through a depolarizing channel, which will destroy all phase information and diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index 36b706437b32..deb3598be0f5 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -20,7 +20,7 @@ class ConverterBase(ABC): r""" - Deprecation: Converters take an Operator and return a new Operator, generally isomorphic + Deprecated: Converters take an Operator and return a new Operator, generally isomorphic in some way with the first, but with certain desired properties. For example, a converter may accept ``CircuitOp`` and return a ``SummedOp`` of ``PauliOps`` representing the circuit unitary. Converters may not diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index 4d8e10ed157f..cf11f4916e02 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -23,7 +23,7 @@ class DictToCircuitSum(ConverterBase): r""" - Deprecation: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` + Deprecated: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` on an Operator, but with the added control of choosing whether to convert only ``DictStateFns`` or ``VectorStateFns``, rather than both. diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index 77ce29346fab..5d5fba09b5bd 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -35,7 +35,7 @@ class PauliBasisChange(ConverterBase): r""" - Deprecation: Converter for changing Paulis into other bases. By default, the diagonal basis + Deprecated: Converter for changing Paulis into other bases. By default, the diagonal basis composed only of Pauli {Z, I}^n is used as the destination basis to which to convert. Meaning, if a Pauli containing X or Y terms is passed in, which cannot be sampled or evolved natively on some Quantum hardware, the Pauli can be replaced by a diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index d658b579d901..ef5ccfb429a0 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -27,7 +27,7 @@ class TwoQubitReduction(ConverterBase): """ - Deprecation: Two qubit reduction converter which eliminates the central and last + Deprecated: Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli that has diagonal operators (Z,I) at those positions. Chemistry specific method: diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index 1908820b3f30..61a8ef9da062 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -21,7 +21,7 @@ class EvolutionBase(ConverterBase, ABC): r""" - Deprecation: A base for Evolution converters. + Deprecated: A base for Evolution converters. Evolutions are converters which traverse an Operator tree, replacing any ``EvolvedOp`` `e` with a Schrodinger equation-style evolution ``CircuitOp`` equalling or approximating the matrix exponential of -i * the Operator contained inside (`e.primitive`). The Evolutions are diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index b9ba933429ae..2828619de00b 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -20,7 +20,7 @@ class EvolutionFactory: - """Deprecation: A factory class for convenient automatic selection of an + """Deprecated: A factory class for convenient automatic selection of an Evolution algorithm based on the Operator to be converted. """ diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index ab1e3ad4e93f..84154a139146 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -32,7 +32,7 @@ class EvolvedOp(PrimitiveOp): r""" - Deprecation: Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase + Deprecated: Class for wrapping Operator Evolutions for compilation (``convert``) by an EvolutionBase method later, essentially acting as a placeholder. Note that EvolvedOp is a weird case of PrimitiveOp. It happens to be that it fits into the PrimitiveOp interface nearly perfectly, and it essentially represents a placeholder for a PrimitiveOp later, even though it doesn't diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index b0d88f59c38f..19c9f812214f 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -27,7 +27,7 @@ class MatrixEvolution(EvolutionBase): r""" - Deprecation: Performs Evolution by classical matrix exponentiation, constructing a circuit with + Deprecated: Performs Evolution by classical matrix exponentiation, constructing a circuit with ``UnitaryGates`` or ``HamiltonianGates`` containing the exponentiation of the Operator. """ diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index f65f5e0142e7..6400293c50a0 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -42,7 +42,7 @@ class PauliTrotterEvolution(EvolutionBase): r""" - Deprecation: An Evolution algorithm replacing exponentiated sums of Paulis by changing + Deprecated: An Evolution algorithm replacing exponentiated sums of Paulis by changing them each to the Z basis, rotating with an rZ, changing back, and Trotterizing. More specifically, we compute basis change circuits for each Pauli into a single-qubit Z, diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 14d34c0cba73..9a000e7fd969 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -32,7 +32,7 @@ class QDrift(TrotterizationBase): - """Deprecation: The QDrift Trotterization method, which selects each each term in the + """Deprecated: The QDrift Trotterization method, which selects each each term in the Trotterization randomly, with a probability proportional to its weight. Based on the work of Earl Campbell in https://arxiv.org/abs/1811.08017. """ diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index caf528591d17..e67948d9493f 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -28,7 +28,7 @@ class Suzuki(TrotterizationBase): r""" - Deprecation: Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum + Deprecated: Suzuki Trotter expansion, composing the evolution circuits of each Operator in the sum together by a recursive "bookends" strategy, repeating the whole composed circuit ``reps`` times. diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index d3b766d64a3b..03fb05a424cd 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -18,7 +18,7 @@ class Trotter(Suzuki): r""" - Deprecation: Simple Trotter expansion, composing the evolution circuits of each Operator in the sum + Deprecated: Simple Trotter expansion, composing the evolution circuits of each Operator in the sum together ``reps`` times and dividing the evolution time of each by ``reps``. """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 78578f24af90..9d79cb0957f8 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -22,7 +22,7 @@ class TrotterizationBase(EvolutionBase): - """Deprecation: A base for Trotterization methods, algorithms for approximating exponentiations of + """Deprecated: A base for Trotterization methods, algorithms for approximating exponentiations of operator sums by compositions of exponentiations. """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index 3fb5108c44ec..7994963cf31d 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -20,7 +20,7 @@ class TrotterizationFactory: - """Deprecation: A factory for conveniently creating TrotterizationBase instances.""" + """Deprecated: A factory for conveniently creating TrotterizationBase instances.""" @staticmethod @deprecate_func( diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index 5d91263e41d9..6d32163f940d 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -17,7 +17,7 @@ class OpflowError(QiskitError): - """Deprecation: For Opflow specific errors.""" + """Deprecated: For Opflow specific errors.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index ea7b72fde286..8c71249a3114 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -34,7 +34,7 @@ class AerPauliExpectation(ExpectationBase): - r"""Deprecation: An Expectation converter for using Aer's operator snapshot to + r"""Deprecated: An Expectation converter for using Aer's operator snapshot to take expectations of quantum state circuits over Pauli observables. """ diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 891a64696fc0..c66d447faf09 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -24,7 +24,7 @@ class CVaRExpectation(ExpectationBase): - r"""Deprecation: Compute the Conditional Value at Risk (CVaR) expectation value. + r"""Deprecated: Compute the Conditional Value at Risk (CVaR) expectation value. The standard approach to calculating the expectation value of a Hamiltonian w.r.t. a state is to take the sample mean of the measurement outcomes. This corresponds to an estimator diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index 6c6342e4765d..a7b6d84313dd 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -24,7 +24,7 @@ class ExpectationBase(ConverterBase): r""" - Deprecation: A base for Expectation value converters. Expectations are converters which enable the + Deprecated: A base for Expectation value converters. Expectations are converters which enable the computation of the expectation value of an Observable with respect to some state function. They traverse an Operator tree, replacing OperatorStateFn measurements with equivalent measurements which are more amenable to computation on quantum or classical hardware. For diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 65c8a45257b1..60cb29835571 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -32,7 +32,7 @@ class ExpectationFactory: - """Deprecation: factory class for convenient automatic selection of an Expectation based on the + """Deprecated: factory class for convenient automatic selection of an Expectation based on the Operator to be converted and backend used to sample the expectation value. """ diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index 234377ff7ee3..07da63374788 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -22,7 +22,7 @@ class MatrixExpectation(ExpectationBase): - """Deprecation: An Expectation converter which converts Operator measurements to + """Deprecated: An Expectation converter which converts Operator measurements to be matrix-based so they can be evaluated by matrix multiplication.""" @deprecate_func( diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index 08e6ec7cc1bb..c0702df8d9b3 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -34,7 +34,7 @@ class PauliExpectation(ExpectationBase): r""" - Deprecation: An Expectation converter for Pauli-basis observables by changing Pauli measurements to a + Deprecated: An Expectation converter for Pauli-basis observables by changing Pauli measurements to a diagonal ({Z, I}^n) basis and appending circuit post-rotations to the measured state function. Optionally groups the Paulis with the same post-rotations (those that commute with one another, or form Abelian groups) into single measurements to reduce circuit execution diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index 8074ec13e162..ab0ba89e1fea 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -23,7 +23,7 @@ class CircuitGradient(ConverterBase): - r"""Deprecation: Circuit to gradient operator converter. + r"""Deprecated: Circuit to gradient operator converter. Converter for changing parameterized circuits into operators whose evaluation yields the gradient with respect to the circuit parameters. diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 734ca98ee0e0..ef4b7d8c9d26 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -68,7 +68,7 @@ class LinComb(CircuitGradient): - """Deprecation: Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the + """Deprecated: Compute the state gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω. This method employs a linear combination of unitaries, diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index 6653097bf50d..2ff9b6b04c24 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -40,7 +40,7 @@ class ParamShift(CircuitGradient): - """Deprecation: Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling + """Deprecated: Compute the gradient d⟨ψ(ω)|O(θ)|ψ(ω)〉/ dω respectively the gradients of the sampling probabilities of the basis states of a state |ψ(ω)〉w.r.t. ω with the parameter shift method. """ diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index af620beb1fc2..64d14e468852 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -22,7 +22,7 @@ class CircuitQFI(ConverterBase): - r"""Deprecation: Circuit to Quantum Fisher Information operator converter. + r"""Deprecated: Circuit to Quantum Fisher Information operator converter. Converter for changing parameterized circuits into operators whose evaluation yields Quantum Fisher Information metric tensor diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index c9bbb28687bc..1680c9f9a5a1 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -29,7 +29,7 @@ class LinCombFull(CircuitQFI): - r"""Deprecation: Compute the full Quantum Fisher Information (QFI). + r"""Deprecated: Compute the full Quantum Fisher Information (QFI). Given a pure, parameterized quantum state this class uses the linear combination of unitaries See also :class:`~qiskit.opflow.QFI`. diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index 38248b25d7c5..f1a3599c9002 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -33,7 +33,7 @@ class OverlapBlockDiag(CircuitQFI): - r"""Deprecation: Compute the block-diagonal of the QFI given a pure, parameterized quantum state. + r"""Deprecated: Compute the block-diagonal of the QFI given a pure, parameterized quantum state. The blocks are given by all parameterized gates in quantum circuit layer. See also :class:`~qiskit.opflow.QFI`. diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 99e770197016..356aa8efa05e 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -33,7 +33,7 @@ class OverlapDiag(CircuitQFI): - r"""Deprecation: Compute the diagonal of the QFI given a pure, parameterized quantum state. + r"""Deprecated: Compute the diagonal of the QFI given a pure, parameterized quantum state. See also :class:`~qiskit.opflow.QFI`. """ diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 27a62deb2373..c97c2b40fe8e 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -34,7 +34,7 @@ class DerivativeBase(ConverterBase): - r"""Deprecation: Base class for differentiating opflow objects. + r"""Deprecated: Base class for differentiating opflow objects. Converter for differentiating opflow objects and handling things like properly differentiating combo_fn's and enforcing product rules diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index cb50defd1ab3..b5bcd49396fe 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -35,7 +35,7 @@ class Gradient(GradientBase): - """Deprecation: Convert an operator expression to the first-order gradient.""" + """Deprecated: Convert an operator expression to the first-order gradient.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index 8709964882af..dbe1f1a8088f 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -20,7 +20,7 @@ class GradientBase(DerivativeBase): - """Deprecation: Base class for first-order operator gradient. + """Deprecated: Base class for first-order operator gradient. Convert an operator expression to the first-order gradient. """ diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 22cf39cc3689..888b65bd450a 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -38,7 +38,7 @@ class Hessian(HessianBase): - """Deprecation: Compute the Hessian of an expected value.""" + """Deprecated: Compute the Hessian of an expected value.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 6a9a67538425..8213db987068 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -20,7 +20,7 @@ class HessianBase(DerivativeBase): - """Deprecation: Base class for the Hessian of an expected value.""" + """Deprecated: Base class for the Hessian of an expected value.""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index b7e261b9f4a2..63978997a2ea 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -38,7 +38,7 @@ class NaturalGradient(GradientBase): - r"""Deprecation: Convert an operator expression to the first-order gradient. + r"""Deprecated: Convert an operator expression to the first-order gradient. Given an ill-posed inverse problem diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index 8ea36f6ad0e9..04f0dc268008 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -26,7 +26,7 @@ class QFI(QFIBase): - r"""Deprecation: Compute the Quantum Fisher Information (QFI). + r"""Deprecated: Compute the Quantum Fisher Information (QFI). Computes the QFI given a pure, parameterized quantum state, where QFI is: diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index f6554ef4d999..ad60a6b1e4ff 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -21,7 +21,7 @@ class QFIBase(DerivativeBase): - r"""Deprecation: Base class for Quantum Fisher Information (QFI). + r"""Deprecated: Base class for Quantum Fisher Information (QFI). Compute the Quantum Fisher Information (QFI) given a pure, parameterized quantum state. diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index 30f036eae6b7..bae742488666 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -28,7 +28,7 @@ class ComposedOp(ListOp): - """Deprecation: A class for lazily representing compositions of Operators. Often Operators cannot be + """Deprecated: A class for lazily representing compositions of Operators. Often Operators cannot be efficiently composed with one another, but may be manipulated further so that they can be composed later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be composed, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index eb1417623e00..546647866b73 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -28,7 +28,7 @@ class ListOp(OperatorBase): """ - Deprecation: A Class for manipulating List Operators, and parent class to ``SummedOp``, + Deprecated: A Class for manipulating List Operators, and parent class to ``SummedOp``, ``ComposedOp`` and ``TensoredOp``. List Operators are classes for storing and manipulating lists of Operators, State functions, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index b0fef0aa59a9..968648d1cfb6 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -25,7 +25,7 @@ class SummedOp(ListOp): - """Deprecation: A class for lazily representing sums of Operators. Often Operators cannot be + """Deprecated: A class for lazily representing sums of Operators. Often Operators cannot be efficiently added to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be added together, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index de139c3d24bd..0643e7698c9f 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -26,7 +26,7 @@ class TensoredOp(ListOp): - """Deprecation: A class for lazily representing tensor products of Operators. Often Operators + """Deprecated: A class for lazily representing tensor products of Operators. Often Operators cannot be efficiently tensored to one another, but may be manipulated further so that they can be later. This class holds logic to indicate that the Operators in ``oplist`` are meant to be tensored together, and therefore if they reach a point in which they can be, such as after diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index 98a9fb61a08d..8117540e1089 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -20,7 +20,7 @@ class StarAlgebraMixin(MultiplyMixin, ABC): - """Deprecation: The star algebra mixin class. + """Deprecated: The star algebra mixin class. Star algebra is an algebra with an adjoint. This class overrides: diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index e7b515544f78..86e576844ae4 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -18,7 +18,7 @@ class TensorMixin(ABC): - """Deprecation: The mixin class for tensor operations. + """Deprecated: The mixin class for tensor operations. This class overrides: - ``^``, ``__xor__``, `__rxor__` -> :meth:`tensor` between two operators and diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index ee85b322d6d9..1ed787b2f029 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -29,7 +29,7 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): - """Deprecation: A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are + """Deprecated: A base class for all Operators: PrimitiveOps, StateFns, ListOps, etc. Operators are defined as functions which take one complex binary function to another. These complex binary functions are represented by StateFns, which are themselves a special class of Operators taking only the ``Zero`` StateFn to the complex binary function they represent. diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 2a67dbeae0ba..53b653022b89 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -27,7 +27,7 @@ class CircuitOp(PrimitiveOp): - """Deprecation: Class for Operators backed by Terra's ``QuantumCircuit`` module.""" + """Deprecated: Class for Operators backed by Terra's ``QuantumCircuit`` module.""" primitive: QuantumCircuit diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index e0d68489157c..d34ce9ad42b6 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -31,7 +31,7 @@ class MatrixOp(PrimitiveOp): - """Deprecation: Class for Operators represented by matrices, + """Deprecated: Class for Operators represented by matrices, backed by Terra's ``Operator`` module.""" primitive: Operator diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index accdcc0122ef..39fc7932a52f 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -31,7 +31,7 @@ class PauliOp(PrimitiveOp): - """Deprecation: Class for Operators backed by Terra's ``Pauli`` module.""" + """Deprecated: Class for Operators backed by Terra's ``Pauli`` module.""" primitive: Pauli diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index 78c30be8b918..3faa32650214 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -30,7 +30,7 @@ class PauliSumOp(PrimitiveOp): - """Deprecation: Class for Operators backed by Terra's ``SparsePauliOp`` class.""" + """Deprecated: Class for Operators backed by Terra's ``SparsePauliOp`` class.""" primitive: SparsePauliOp diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index d93031c5464a..c05f6894c49d 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -27,7 +27,7 @@ class PrimitiveOp(OperatorBase): r""" - Deprecation: A class for representing basic Operators, backed by Operator primitives from + Deprecated: A class for representing basic Operators, backed by Operator primitives from Terra. This class (and inheritors) primarily serves to allow the underlying primitives to "flow" - i.e. interoperability and adherence to the Operator formalism - while the core computational logic mostly remains in the underlying primitives. diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index 5bc7804bfb82..fa52c37eb0c2 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -33,7 +33,7 @@ class TaperedPauliSumOp(PauliSumOp): - """Deprecation: Class for PauliSumOp after tapering""" + """Deprecated: Class for PauliSumOp after tapering""" @deprecate_func( since="0.24.0", diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index 10e69bb8d982..b2940c229041 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -38,7 +38,7 @@ class CircuitStateFn(StateFn): r""" - Deprecation: A class for state functions and measurements which are defined by the action of a + Deprecated: A class for state functions and measurements which are defined by the action of a QuantumCircuit starting from \|0⟩, and stored using Terra's ``QuantumCircuit`` class. """ primitive: QuantumCircuit diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index a4174b261a10..49d573533a69 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -32,7 +32,7 @@ class CVaRMeasurement(OperatorStateFn): - r"""Deprecation: A specialized measurement class to compute CVaR expectation values. + r"""Deprecated: A specialized measurement class to compute CVaR expectation values. See https://arxiv.org/pdf/1907.04769.pdf for further details. Used in :class:`~qiskit.opflow.CVaRExpectation`, see there for more details. diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index 200ac7c99f4e..92fa67a41850 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -31,7 +31,7 @@ class DictStateFn(StateFn): - """Deprecation: A class for state functions and measurements which are defined by a lookup table, + """Deprecated: A class for state functions and measurements which are defined by a lookup table, stored in a dict. """ diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index 79c3fdd54597..836caf70df77 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -31,7 +31,7 @@ class OperatorStateFn(StateFn): r""" - Deprecation: A class for state functions and measurements which are defined by a density Operator, + Deprecated: A class for state functions and measurements which are defined by a density Operator, stored using an ``OperatorBase``. """ primitive: OperatorBase diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index 019932cb79b8..179950bcd8cc 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -30,7 +30,7 @@ class SparseVectorStateFn(StateFn): - """Deprecation: A class for sparse state functions and measurements in vector representation. + """Deprecated: A class for sparse state functions and measurements in vector representation. This class uses ``scipy.sparse.spmatrix`` for the internal representation. """ diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 646c8feb080e..6ca015527427 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -26,7 +26,7 @@ class StateFn(OperatorBase): r""" - Deprecation: A class for representing state functions and measurements. + Deprecated: A class for representing state functions and measurements. State functions are defined to be complex functions over a single binary string (as compared to an operator, which is defined as a function over two binary strings, or a diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index b71746a7870a..4d1b78660c85 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -30,7 +30,7 @@ class VectorStateFn(StateFn): - """Deprecation: A class for state functions and measurements which are defined in vector + """Deprecated: A class for state functions and measurements which are defined in vector representation, and stored using Terra's ``Statevector`` class. """ diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index aa38d53faeaf..d112dd9b2eb7 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -22,7 +22,7 @@ ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Deprecation: Compute commutator of `op_a` and `op_b`. + Deprecated: Compute commutator of `op_a` and `op_b`. .. math:: @@ -43,7 +43,7 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" - Deprecation: Compute anti-commutator of `op_a` and `op_b`. + Deprecated: Compute anti-commutator of `op_a` and `op_b`. .. math:: @@ -69,7 +69,7 @@ def double_commutator( sign: bool = False, ) -> OperatorBase: r""" - Deprecation: Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. + Deprecated: Compute symmetric double commutator of `op_a`, `op_b` and `op_c`. See McWeeny chapter 13.6 Equation of motion methods (page 479) If `sign` is `False`, it returns diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index f719ac5d1fc7..6320e375a6f3 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -38,7 +38,7 @@ def get_measured_qubits( transpiled_circuits: List[QuantumCircuit], ) -> Tuple[List[int], Dict[str, List[int]]]: """ - Deprecation: Retrieve the measured qubits from transpiled circuits. + Deprecated: Retrieve the measured qubits from transpiled circuits. Args: transpiled_circuits: a list of transpiled circuits @@ -87,7 +87,7 @@ def get_measured_qubits( ) def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, List[int]]]: """ - Deprecation: Retrieve the measured qubits from transpiled circuits. + Deprecated: Retrieve the measured qubits from transpiled circuits. Args: qobj: qobj @@ -141,7 +141,7 @@ def build_measurement_error_mitigation_circuits( compile_config: Optional[Dict] = None, mit_pattern: Optional[List[List[int]]] = None, ) -> Tuple[QuantumCircuit, List[str], List[str]]: - """Deprecation: Build measurement error mitigation circuits + """Deprecated: Build measurement error mitigation circuits Args: qubit_list: list of ordered qubits used in the algorithm fitter_cls: CompleteMeasFitter or TensoredMeasFitter diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 529aa9ec431a..696c0a2314a2 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -36,7 +36,7 @@ class MeasurementFilter: """ - Deprecation: Measurement error mitigation filter. + Deprecated: Measurement error mitigation filter. Produced from a measurement calibration fitter and can be applied to data. @@ -219,7 +219,7 @@ def _apply_correction(self, resultidx, raw_data, method): class TensoredFilter: """ - Deprecation: Tensored measurement error mitigation filter. + Deprecated: Tensored measurement error mitigation filter. Produced from a tensored measurement calibration fitter and can be applied to data. diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index a50d6d207f0a..a19d27af2c13 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -27,7 +27,7 @@ additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", ) def count_keys(num_qubits: int) -> List[str]: - """Deprecation: Return ordered count keys. + """Deprecated: Return ordered count keys. Args: num_qubits: The number of qubits in the generated list. @@ -51,7 +51,7 @@ def complete_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[str]]: """ - Deprecation: Return a list of measurement calibration circuits for the full + Deprecated: Return a list of measurement calibration circuits for the full Hilbert space. If the circuit contains :math:`n` qubits, then :math:`2^n` calibration circuits @@ -132,7 +132,7 @@ def tensored_meas_cal( circlabel: str = "", ) -> Tuple[List["QuantumCircuit"], List[List[int]]]: """ - Deprecation: Return a list of calibration circuits + Deprecated: Return a list of calibration circuits Args: mit_pattern: Qubits on which to perform the diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index b92fca5a6478..8b8286100ae9 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -32,7 +32,7 @@ class CompleteMeasFitter: """ - Deprecation: Measurement correction fitter for a full calibration + Deprecated: Measurement correction fitter for a full calibration """ @deprecate_func( @@ -216,7 +216,7 @@ def readout_fidelity(self, label_list=None): class TensoredMeasFitter: """ - Deprecation: Measurement correction fitter for a tensored calibration. + Deprecated: Measurement correction fitter for a tensored calibration. """ @deprecate_func( diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index 657f6d4403f5..78dd76a94976 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -125,7 +125,7 @@ def type_from_instance(meas_instance): class QuantumInstance: - """Deprecation: Quantum Backend including execution setting.""" + """Deprecated: Quantum Backend including execution setting.""" _BACKEND_CONFIG = ["basis_gates", "coupling_map"] _COMPILE_CONFIG = ["initial_layout", "seed_transpiler", "optimization_level"] diff --git a/qiskit/utils/run_circuits.py b/qiskit/utils/run_circuits.py index d117bada5cef..9714234ca694 100644 --- a/qiskit/utils/run_circuits.py +++ b/qiskit/utils/run_circuits.py @@ -47,7 +47,7 @@ def find_regs_by_name( circuit: QuantumCircuit, name: str, qreg: bool = True ) -> Optional[Union[QuantumRegister, ClassicalRegister]]: - """Deprecation: Find the registers in the circuits. + """Deprecated: Find the registers in the circuits. Args: circuit: the quantum circuit. @@ -120,7 +120,7 @@ def run_circuits( max_job_retries: int = 50, ) -> Result: """ - Deprecation: An execution wrapper with Qiskit-Terra, with job auto recover capability. + Deprecated: An execution wrapper with Qiskit-Terra, with job auto recover capability. The auto-recovery feature is only applied for non-simulator backend. This wrapper will try to get the result no matter how long it takes. From 82efe0ba5e9e60757a56488807143e1bc0bf03ac Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:18:17 +0200 Subject: [PATCH 16/47] Remove catch warnings in main code --- qiskit/opflow/converters/circuit_sampler.py | 42 +++++++++---------- .../expectations/expectation_factory.py | 41 +++++++++--------- 2 files changed, 38 insertions(+), 45 deletions(-) diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index e59f83a68bcf..9147e4f4a57a 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -14,7 +14,6 @@ import logging -import warnings from functools import partial from time import time from typing import Any, Dict, List, Optional, Tuple, Union, cast @@ -83,16 +82,15 @@ def __init__( ValueError: Set statevector or param_qobj True when not supported by backend. """ super().__init__() - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - self._quantum_instance = ( - backend - if isinstance(backend, QuantumInstance) - else QuantumInstance(backend=backend) - ) - self._statevector = ( - statevector if statevector is not None else self.quantum_instance.is_statevector - ) + + self._quantum_instance = ( + backend + if isinstance(backend, QuantumInstance) + else QuantumInstance(backend=backend) + ) + self._statevector = ( + statevector if statevector is not None else self.quantum_instance.is_statevector + ) self._param_qobj = param_qobj self._attach_results = attach_results @@ -116,19 +114,17 @@ def _check_quantum_instance_and_modes_consistent(self) -> None: Raises: ValueError: statevector or param_qobj are True when not supported by backend. """ - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - if self._statevector and not is_statevector_backend(self.quantum_instance.backend): - raise ValueError( - "Statevector mode for circuit sampling requires statevector " - "backend, not {}.".format(self.quantum_instance.backend) - ) + if self._statevector and not is_statevector_backend(self.quantum_instance.backend): + raise ValueError( + "Statevector mode for circuit sampling requires statevector " + "backend, not {}.".format(self.quantum_instance.backend) + ) - if self._param_qobj and not is_aer_provider(self.quantum_instance.backend): - raise ValueError( - "Parameterized Qobj mode requires Aer " - "backend, not {}.".format(self.quantum_instance.backend) - ) + if self._param_qobj and not is_aer_provider(self.quantum_instance.backend): + raise ValueError( + "Parameterized Qobj mode requires Aer " + "backend, not {}.".format(self.quantum_instance.backend) + ) @property def quantum_instance(self) -> QuantumInstance: diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 60cb29835571..6197551d3df3 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -12,7 +12,6 @@ """ExpectationFactory Class""" -import warnings import logging from typing import Optional, Union @@ -100,27 +99,25 @@ def build( # If the user specified Aer qasm backend and is using a # Pauli operator, use the Aer fast expectation if we are including such # custom behaviors. - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - if is_aer_qasm(backend_to_check) and include_custom: - return AerPauliExpectation() - - # If the user specified a statevector backend (either Aer or BasicAer), - # use a converter to produce a - # Matrix operator and compute using matmul - elif is_statevector_backend(backend_to_check): - if operator.num_qubits >= 16: - logger.warning( - "Note: Using a statevector_simulator with %d qubits can be very expensive. " - "Consider using the Aer qasm_simulator instead to take advantage of Aer's " - "built-in fast Pauli Expectation", - operator.num_qubits, - ) - return MatrixExpectation() - - # All other backends, including IBMQ, BasicAer QASM, go here. - else: - return PauliExpectation() + if is_aer_qasm(backend_to_check) and include_custom: + return AerPauliExpectation() + + # If the user specified a statevector backend (either Aer or BasicAer), + # use a converter to produce a + # Matrix operator and compute using matmul + elif is_statevector_backend(backend_to_check): + if operator.num_qubits >= 16: + logger.warning( + "Note: Using a statevector_simulator with %d qubits can be very expensive. " + "Consider using the Aer qasm_simulator instead to take advantage of Aer's " + "built-in fast Pauli Expectation", + operator.num_qubits, + ) + return MatrixExpectation() + + # All other backends, including IBMQ, BasicAer QASM, go here. + else: + return PauliExpectation() elif primitives == {"Matrix"}: return MatrixExpectation() From 6f9e54deb9763cc831de24fda2156cedce82c358 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:22:33 +0200 Subject: [PATCH 17/47] Fix missing decorators --- qiskit/utils/measurement_error_mitigation.py | 27 +++++++------------- 1 file changed, 9 insertions(+), 18 deletions(-) diff --git a/qiskit/utils/measurement_error_mitigation.py b/qiskit/utils/measurement_error_mitigation.py index 6320e375a6f3..0ef09c997ec5 100644 --- a/qiskit/utils/measurement_error_mitigation.py +++ b/qiskit/utils/measurement_error_mitigation.py @@ -78,12 +78,9 @@ def get_measured_qubits( return sorted(qubit_index), qubit_mappings -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="get_measured_qubits_from_qobj", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, List[int]]]: """ @@ -126,12 +123,9 @@ def get_measured_qubits_from_qobj(qobj: QasmQobj) -> Tuple[List[int], Dict[str, return sorted(qubit_index), qubit_mappings -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="build_measurement_error_mitigation_circuits", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def build_measurement_error_mitigation_circuits( qubit_list: List[int], @@ -208,12 +202,9 @@ def build_measurement_error_mitigation_circuits( return t_meas_calibs_circuits, state_labels, circlabel -@deprecate_function_msg( - version="0.24.0", - old_module="utils", - old_name="build_measurement_error_mitigation_qobj", - old_type="function", - url="https://qisk.it/qi_migration", +@deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def build_measurement_error_mitigation_qobj( qubit_list: List[int], From 153b9a04da12dcf17980cfc7b00f5c90e1b7e19c Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:35:55 +0200 Subject: [PATCH 18/47] Fix tests --- test/python/algorithms/test_backendv1.py | 1 + test/python/algorithms/test_backendv2.py | 1 + 2 files changed, 2 insertions(+) diff --git a/test/python/algorithms/test_backendv1.py b/test/python/algorithms/test_backendv1.py index 93963ec4b347..7fd68ce4baae 100644 --- a/test/python/algorithms/test_backendv1.py +++ b/test/python/algorithms/test_backendv1.py @@ -13,6 +13,7 @@ """Test Providers that support BackendV1 interface""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeProvider diff --git a/test/python/algorithms/test_backendv2.py b/test/python/algorithms/test_backendv2.py index 0c71291a79cc..3115c34fde0a 100644 --- a/test/python/algorithms/test_backendv2.py +++ b/test/python/algorithms/test_backendv2.py @@ -13,6 +13,7 @@ """Test Providers that support BackendV2 interface""" import unittest +import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit from qiskit.providers.fake_provider import FakeProvider From ba9f61456e57ba81aadd4d67235965553b6a56c7 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:36:06 +0200 Subject: [PATCH 19/47] Shorten message --- qiskit/opflow/converters/abelian_grouper.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 2 +- qiskit/opflow/converters/converter_base.py | 2 +- qiskit/opflow/converters/dict_to_circuit_sum.py | 2 +- qiskit/opflow/converters/pauli_basis_change.py | 2 +- qiskit/opflow/converters/two_qubit_reduction.py | 2 +- qiskit/opflow/evolutions/evolution_base.py | 2 +- qiskit/opflow/evolutions/evolution_factory.py | 2 +- qiskit/opflow/evolutions/evolved_op.py | 2 +- qiskit/opflow/evolutions/matrix_evolution.py | 2 +- qiskit/opflow/evolutions/pauli_trotter_evolution.py | 2 +- qiskit/opflow/evolutions/trotterizations/qdrift.py | 2 +- qiskit/opflow/evolutions/trotterizations/suzuki.py | 2 +- qiskit/opflow/evolutions/trotterizations/trotter.py | 2 +- .../evolutions/trotterizations/trotterization_base.py | 2 +- .../evolutions/trotterizations/trotterization_factory.py | 2 +- qiskit/opflow/exceptions.py | 2 +- qiskit/opflow/expectations/aer_pauli_expectation.py | 2 +- qiskit/opflow/expectations/cvar_expectation.py | 2 +- qiskit/opflow/expectations/expectation_base.py | 2 +- qiskit/opflow/expectations/expectation_factory.py | 2 +- qiskit/opflow/expectations/matrix_expectation.py | 2 +- qiskit/opflow/expectations/pauli_expectation.py | 2 +- .../opflow/gradients/circuit_gradients/circuit_gradient.py | 2 +- qiskit/opflow/gradients/circuit_gradients/lin_comb.py | 2 +- qiskit/opflow/gradients/circuit_gradients/param_shift.py | 2 +- qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py | 2 +- qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_diag.py | 2 +- qiskit/opflow/gradients/derivative_base.py | 2 +- qiskit/opflow/gradients/gradient.py | 2 +- qiskit/opflow/gradients/gradient_base.py | 2 +- qiskit/opflow/gradients/hessian.py | 2 +- qiskit/opflow/gradients/hessian_base.py | 2 +- qiskit/opflow/gradients/natural_gradient.py | 2 +- qiskit/opflow/gradients/qfi.py | 2 +- qiskit/opflow/gradients/qfi_base.py | 2 +- qiskit/opflow/list_ops/composed_op.py | 2 +- qiskit/opflow/list_ops/list_op.py | 2 +- qiskit/opflow/list_ops/summed_op.py | 2 +- qiskit/opflow/list_ops/tensored_op.py | 2 +- qiskit/opflow/mixins/star_algebra.py | 2 +- qiskit/opflow/mixins/tensor.py | 2 +- qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/operator_globals.py | 2 +- qiskit/opflow/primitive_ops/circuit_op.py | 2 +- qiskit/opflow/primitive_ops/matrix_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 +- qiskit/opflow/primitive_ops/primitive_op.py | 2 +- qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py | 2 +- qiskit/opflow/state_fns/circuit_state_fn.py | 2 +- qiskit/opflow/state_fns/cvar_measurement.py | 2 +- qiskit/opflow/state_fns/dict_state_fn.py | 2 +- qiskit/opflow/state_fns/operator_state_fn.py | 2 +- qiskit/opflow/state_fns/sparse_vector_state_fn.py | 2 +- qiskit/opflow/state_fns/state_fn.py | 2 +- qiskit/opflow/state_fns/vector_state_fn.py | 2 +- qiskit/opflow/utils.py | 6 +++--- 60 files changed, 62 insertions(+), 62 deletions(-) diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index 0ffc583ee579..a7c2fecc7965 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -44,7 +44,7 @@ class AbelianGrouper(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, traverse: bool = True) -> None: """ diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index 9147e4f4a57a..0705001ffde1 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -54,7 +54,7 @@ class CircuitSampler(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index deb3598be0f5..077f3d5beece 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -32,7 +32,7 @@ class ConverterBase(ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index cf11f4916e02..a5eec7204334 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -31,7 +31,7 @@ class DictToCircuitSum(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index 5d5fba09b5bd..ecaa370d9286 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -58,7 +58,7 @@ class PauliBasisChange(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index ef5ccfb429a0..9077400837be 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -38,7 +38,7 @@ class TwoQubitReduction(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): """ diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index 61a8ef9da062..6c4898d596c4 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -32,7 +32,7 @@ class EvolutionBase(ConverterBase, ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index 2828619de00b..7f516c62ffa6 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -27,7 +27,7 @@ class EvolutionFactory: @staticmethod @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def build(operator: OperatorBase = None) -> EvolutionBase: r""" diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index 84154a139146..2438d14d9545 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -42,7 +42,7 @@ class EvolvedOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, primitive: OperatorBase, coeff: Union[complex, ParameterExpression] = 1.0 diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index 19c9f812214f..a5cae8ce6aa2 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -33,7 +33,7 @@ class MatrixEvolution(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 6400293c50a0..0ed3ca8d74e6 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -53,7 +53,7 @@ class PauliTrotterEvolution(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 9a000e7fd969..68e70a4e8456 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -39,7 +39,7 @@ class QDrift(TrotterizationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index e67948d9493f..4ea3ffb96719 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -37,7 +37,7 @@ class Suzuki(TrotterizationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1, order: int = 2) -> None: """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index 03fb05a424cd..8b1ce307f528 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -24,7 +24,7 @@ class Trotter(Suzuki): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 9d79cb0957f8..8312dd658017 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -28,7 +28,7 @@ class TrotterizationBase(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, reps: int = 1) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index 7994963cf31d..7ae1d7b34761 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -25,7 +25,7 @@ class TrotterizationFactory: @staticmethod @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def build(mode: str = "trotter", reps: int = 1) -> TrotterizationBase: """A factory for conveniently creating TrotterizationBase instances. diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index 6d32163f940d..abed5f98f52d 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -21,7 +21,7 @@ class OpflowError(QiskitError): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, *message): """Set the error message.""" diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index 8c71249a3114..dd6d3810cd33 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -41,7 +41,7 @@ class AerPauliExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index c66d447faf09..5a95e9cd0e12 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -57,7 +57,7 @@ class CVaRExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) -> None: """ diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index a7b6d84313dd..4717775832bd 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -40,7 +40,7 @@ class ExpectationBase(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 6197551d3df3..28fb981a3755 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -38,7 +38,7 @@ class ExpectationFactory: @staticmethod @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def build( operator: OperatorBase, diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index 07da63374788..282aba9bc298 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -27,7 +27,7 @@ class MatrixExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index c0702df8d9b3..e6b5711178cf 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -44,7 +44,7 @@ class PauliExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, group_paulis: bool = True) -> None: """ diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index ab0ba89e1fea..872cda44f2c5 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -38,7 +38,7 @@ class CircuitGradient(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index ef4b7d8c9d26..90858aecaccb 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -103,7 +103,7 @@ class LinComb(CircuitGradient): # pylint: disable=signature-differs, arguments-differ @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, aux_meas_op: OperatorBase = Z): """ diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index 2ff9b6b04c24..bcc459fef1b9 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -49,7 +49,7 @@ class ParamShift(CircuitGradient): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): r""" diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 64d14e468852..3b60fa6447da 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -38,7 +38,7 @@ class CircuitQFI(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 1680c9f9a5a1..742bf81d0045 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -38,7 +38,7 @@ class LinCombFull(CircuitQFI): # pylint: disable=signature-differs, arguments-differ @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index f1a3599c9002..b56c80e35041 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -41,7 +41,7 @@ class OverlapBlockDiag(CircuitQFI): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 356aa8efa05e..030cc6cc4b8c 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -40,7 +40,7 @@ class OverlapDiag(CircuitQFI): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index c97c2b40fe8e..368274fb58c0 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -50,7 +50,7 @@ class DerivativeBase(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index b5bcd49396fe..7395aa129df5 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -39,7 +39,7 @@ class Gradient(GradientBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(grad_method=grad_method, **kwargs) diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index dbe1f1a8088f..2332297301df 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -27,7 +27,7 @@ class GradientBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 888b65bd450a..37f39ee4caed 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -42,7 +42,7 @@ class Hessian(HessianBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(hess_method=hess_method, **kwargs) diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 8213db987068..353a2c90d2bc 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -24,7 +24,7 @@ class HessianBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index 63978997a2ea..7f945670f92e 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -54,7 +54,7 @@ class NaturalGradient(GradientBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index 04f0dc268008..0aa0b1399bbc 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -39,7 +39,7 @@ class QFI(QFIBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): super().__init__(qfi_method=qfi_method) diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index ad60a6b1e4ff..4bb2b6a4a24f 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -32,7 +32,7 @@ class QFIBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): r""" diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index bae742488666..667130e55f77 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -36,7 +36,7 @@ class ComposedOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index 546647866b73..43447cc15604 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -55,7 +55,7 @@ class ListOp(OperatorBase): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index 968648d1cfb6..bedf2a8ae349 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -33,7 +33,7 @@ class SummedOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index 0643e7698c9f..6b031305bb3b 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -34,7 +34,7 @@ class TensoredOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index 8117540e1089..dd0c786cd441 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -42,7 +42,7 @@ class StarAlgebraMixin(MultiplyMixin, ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index 86e576844ae4..e81c1ee08647 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -30,7 +30,7 @@ class TensorMixin(ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index 1ed787b2f029..91a70902d1a7 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -47,7 +47,7 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/operator_globals.py b/qiskit/opflow/operator_globals.py index 9c05a61b8d32..5454d384ab7a 100644 --- a/qiskit/opflow/operator_globals.py +++ b/qiskit/opflow/operator_globals.py @@ -35,7 +35,7 @@ @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def make_immutable(obj): r"""Deprecate\: Delete the __setattr__ property to make the object mostly immutable.""" diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 53b653022b89..3a3c618216e8 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -33,7 +33,7 @@ class CircuitOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index d34ce9ad42b6..ce6c0722b58f 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -38,7 +38,7 @@ class MatrixOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 39fc7932a52f..40dce497ac63 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -37,7 +37,7 @@ class PauliOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index 3faa32650214..e5c7f1790fc7 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -36,7 +36,7 @@ class PauliSumOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index c05f6894c49d..879713451a17 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -95,7 +95,7 @@ def __new__( @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index fa52c37eb0c2..68cdb2bfca9e 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -37,7 +37,7 @@ class TaperedPauliSumOp(PauliSumOp): @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index b2940c229041..e4476b8bcb1f 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -46,7 +46,7 @@ class CircuitStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index 49d573533a69..d8dc322116ab 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -43,7 +43,7 @@ class CVaRMeasurement(OperatorStateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index 92fa67a41850..4cff30a28b70 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -40,7 +40,7 @@ class DictStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index 836caf70df77..3f7dcf4c8911 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -39,7 +39,7 @@ class OperatorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index 179950bcd8cc..22464eb9b6bf 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -40,7 +40,7 @@ class SparseVectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 6ca015527427..8cbae6cb2397 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -115,7 +115,7 @@ def __new__( # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index 4d1b78660c85..f86987fb4510 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -39,7 +39,7 @@ class VectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def __init__( self, diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index d112dd9b2eb7..45f0322fd9a8 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -18,7 +18,7 @@ @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" @@ -39,7 +39,7 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" @@ -60,7 +60,7 @@ def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_func( since="0.24.0", - additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." ) def double_commutator( op_a: OperatorBase, From 6b6b2bc59f3556a1fa864d55cd0f708885dd1a70 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 11:36:50 +0200 Subject: [PATCH 20/47] Fix black --- qiskit/opflow/converters/abelian_grouper.py | 2 +- qiskit/opflow/converters/circuit_sampler.py | 6 ++---- qiskit/opflow/converters/converter_base.py | 2 +- qiskit/opflow/converters/dict_to_circuit_sum.py | 2 +- qiskit/opflow/converters/pauli_basis_change.py | 2 +- qiskit/opflow/converters/two_qubit_reduction.py | 2 +- qiskit/opflow/evolutions/evolution_base.py | 2 +- qiskit/opflow/evolutions/evolution_factory.py | 2 +- qiskit/opflow/evolutions/evolved_op.py | 2 +- qiskit/opflow/evolutions/matrix_evolution.py | 2 +- qiskit/opflow/evolutions/pauli_trotter_evolution.py | 2 +- qiskit/opflow/evolutions/trotterizations/qdrift.py | 2 +- qiskit/opflow/evolutions/trotterizations/suzuki.py | 2 +- qiskit/opflow/evolutions/trotterizations/trotter.py | 2 +- .../evolutions/trotterizations/trotterization_base.py | 2 +- .../evolutions/trotterizations/trotterization_factory.py | 2 +- qiskit/opflow/exceptions.py | 2 +- qiskit/opflow/expectations/aer_pauli_expectation.py | 2 +- qiskit/opflow/expectations/cvar_expectation.py | 2 +- qiskit/opflow/expectations/expectation_base.py | 2 +- qiskit/opflow/expectations/expectation_factory.py | 2 +- qiskit/opflow/expectations/matrix_expectation.py | 2 +- qiskit/opflow/expectations/pauli_expectation.py | 2 +- .../opflow/gradients/circuit_gradients/circuit_gradient.py | 2 +- qiskit/opflow/gradients/circuit_gradients/lin_comb.py | 2 +- qiskit/opflow/gradients/circuit_gradients/param_shift.py | 2 +- qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py | 2 +- qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py | 2 +- qiskit/opflow/gradients/circuit_qfis/overlap_diag.py | 2 +- qiskit/opflow/gradients/derivative_base.py | 2 +- qiskit/opflow/gradients/gradient.py | 2 +- qiskit/opflow/gradients/gradient_base.py | 2 +- qiskit/opflow/gradients/hessian.py | 2 +- qiskit/opflow/gradients/hessian_base.py | 2 +- qiskit/opflow/gradients/natural_gradient.py | 2 +- qiskit/opflow/gradients/qfi.py | 2 +- qiskit/opflow/gradients/qfi_base.py | 2 +- qiskit/opflow/list_ops/composed_op.py | 2 +- qiskit/opflow/list_ops/list_op.py | 2 +- qiskit/opflow/list_ops/summed_op.py | 2 +- qiskit/opflow/list_ops/tensored_op.py | 2 +- qiskit/opflow/mixins/star_algebra.py | 2 +- qiskit/opflow/mixins/tensor.py | 2 +- qiskit/opflow/operator_base.py | 2 +- qiskit/opflow/operator_globals.py | 2 +- qiskit/opflow/primitive_ops/circuit_op.py | 2 +- qiskit/opflow/primitive_ops/matrix_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_op.py | 2 +- qiskit/opflow/primitive_ops/pauli_sum_op.py | 2 +- qiskit/opflow/primitive_ops/primitive_op.py | 2 +- qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py | 2 +- qiskit/opflow/state_fns/circuit_state_fn.py | 2 +- qiskit/opflow/state_fns/cvar_measurement.py | 2 +- qiskit/opflow/state_fns/dict_state_fn.py | 2 +- qiskit/opflow/state_fns/operator_state_fn.py | 2 +- qiskit/opflow/state_fns/sparse_vector_state_fn.py | 2 +- qiskit/opflow/state_fns/state_fn.py | 2 +- qiskit/opflow/state_fns/vector_state_fn.py | 2 +- qiskit/opflow/utils.py | 6 +++--- 60 files changed, 63 insertions(+), 65 deletions(-) diff --git a/qiskit/opflow/converters/abelian_grouper.py b/qiskit/opflow/converters/abelian_grouper.py index a7c2fecc7965..fa1d1842a8ed 100644 --- a/qiskit/opflow/converters/abelian_grouper.py +++ b/qiskit/opflow/converters/abelian_grouper.py @@ -44,7 +44,7 @@ class AbelianGrouper(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, traverse: bool = True) -> None: """ diff --git a/qiskit/opflow/converters/circuit_sampler.py b/qiskit/opflow/converters/circuit_sampler.py index 0705001ffde1..e8e5938617e7 100644 --- a/qiskit/opflow/converters/circuit_sampler.py +++ b/qiskit/opflow/converters/circuit_sampler.py @@ -54,7 +54,7 @@ class CircuitSampler(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, @@ -84,9 +84,7 @@ def __init__( super().__init__() self._quantum_instance = ( - backend - if isinstance(backend, QuantumInstance) - else QuantumInstance(backend=backend) + backend if isinstance(backend, QuantumInstance) else QuantumInstance(backend=backend) ) self._statevector = ( statevector if statevector is not None else self.quantum_instance.is_statevector diff --git a/qiskit/opflow/converters/converter_base.py b/qiskit/opflow/converters/converter_base.py index 077f3d5beece..231f3f2daad7 100644 --- a/qiskit/opflow/converters/converter_base.py +++ b/qiskit/opflow/converters/converter_base.py @@ -32,7 +32,7 @@ class ConverterBase(ABC): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/converters/dict_to_circuit_sum.py b/qiskit/opflow/converters/dict_to_circuit_sum.py index a5eec7204334..b52f16f185c6 100644 --- a/qiskit/opflow/converters/dict_to_circuit_sum.py +++ b/qiskit/opflow/converters/dict_to_circuit_sum.py @@ -31,7 +31,7 @@ class DictToCircuitSum(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True diff --git a/qiskit/opflow/converters/pauli_basis_change.py b/qiskit/opflow/converters/pauli_basis_change.py index ecaa370d9286..5e432e70ffd3 100644 --- a/qiskit/opflow/converters/pauli_basis_change.py +++ b/qiskit/opflow/converters/pauli_basis_change.py @@ -58,7 +58,7 @@ class PauliBasisChange(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/converters/two_qubit_reduction.py b/qiskit/opflow/converters/two_qubit_reduction.py index 9077400837be..10f596f10494 100644 --- a/qiskit/opflow/converters/two_qubit_reduction.py +++ b/qiskit/opflow/converters/two_qubit_reduction.py @@ -38,7 +38,7 @@ class TwoQubitReduction(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]): """ diff --git a/qiskit/opflow/evolutions/evolution_base.py b/qiskit/opflow/evolutions/evolution_base.py index 6c4898d596c4..1123c36c34a7 100644 --- a/qiskit/opflow/evolutions/evolution_base.py +++ b/qiskit/opflow/evolutions/evolution_base.py @@ -32,7 +32,7 @@ class EvolutionBase(ConverterBase, ABC): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/evolution_factory.py b/qiskit/opflow/evolutions/evolution_factory.py index 7f516c62ffa6..fffad684e816 100644 --- a/qiskit/opflow/evolutions/evolution_factory.py +++ b/qiskit/opflow/evolutions/evolution_factory.py @@ -27,7 +27,7 @@ class EvolutionFactory: @staticmethod @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def build(operator: OperatorBase = None) -> EvolutionBase: r""" diff --git a/qiskit/opflow/evolutions/evolved_op.py b/qiskit/opflow/evolutions/evolved_op.py index 2438d14d9545..03771aa52fa8 100644 --- a/qiskit/opflow/evolutions/evolved_op.py +++ b/qiskit/opflow/evolutions/evolved_op.py @@ -42,7 +42,7 @@ class EvolvedOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, primitive: OperatorBase, coeff: Union[complex, ParameterExpression] = 1.0 diff --git a/qiskit/opflow/evolutions/matrix_evolution.py b/qiskit/opflow/evolutions/matrix_evolution.py index a5cae8ce6aa2..8c18a6a57728 100644 --- a/qiskit/opflow/evolutions/matrix_evolution.py +++ b/qiskit/opflow/evolutions/matrix_evolution.py @@ -33,7 +33,7 @@ class MatrixEvolution(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/pauli_trotter_evolution.py b/qiskit/opflow/evolutions/pauli_trotter_evolution.py index 0ed3ca8d74e6..414ffd5777ca 100644 --- a/qiskit/opflow/evolutions/pauli_trotter_evolution.py +++ b/qiskit/opflow/evolutions/pauli_trotter_evolution.py @@ -53,7 +53,7 @@ class PauliTrotterEvolution(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/evolutions/trotterizations/qdrift.py b/qiskit/opflow/evolutions/trotterizations/qdrift.py index 68e70a4e8456..865cbd1071ae 100644 --- a/qiskit/opflow/evolutions/trotterizations/qdrift.py +++ b/qiskit/opflow/evolutions/trotterizations/qdrift.py @@ -39,7 +39,7 @@ class QDrift(TrotterizationBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/suzuki.py b/qiskit/opflow/evolutions/trotterizations/suzuki.py index 4ea3ffb96719..cfe59acac5a8 100644 --- a/qiskit/opflow/evolutions/trotterizations/suzuki.py +++ b/qiskit/opflow/evolutions/trotterizations/suzuki.py @@ -37,7 +37,7 @@ class Suzuki(TrotterizationBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1, order: int = 2) -> None: """ diff --git a/qiskit/opflow/evolutions/trotterizations/trotter.py b/qiskit/opflow/evolutions/trotterizations/trotter.py index 8b1ce307f528..eb1c48d7e27d 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotter.py +++ b/qiskit/opflow/evolutions/trotterizations/trotter.py @@ -24,7 +24,7 @@ class Trotter(Suzuki): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1) -> None: r""" diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py index 8312dd658017..222d338dfdce 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_base.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_base.py @@ -28,7 +28,7 @@ class TrotterizationBase(EvolutionBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, reps: int = 1) -> None: super().__init__() diff --git a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py index 7ae1d7b34761..f8d119140502 100644 --- a/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py +++ b/qiskit/opflow/evolutions/trotterizations/trotterization_factory.py @@ -25,7 +25,7 @@ class TrotterizationFactory: @staticmethod @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def build(mode: str = "trotter", reps: int = 1) -> TrotterizationBase: """A factory for conveniently creating TrotterizationBase instances. diff --git a/qiskit/opflow/exceptions.py b/qiskit/opflow/exceptions.py index abed5f98f52d..27bc0f6cc14d 100644 --- a/qiskit/opflow/exceptions.py +++ b/qiskit/opflow/exceptions.py @@ -21,7 +21,7 @@ class OpflowError(QiskitError): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, *message): """Set the error message.""" diff --git a/qiskit/opflow/expectations/aer_pauli_expectation.py b/qiskit/opflow/expectations/aer_pauli_expectation.py index dd6d3810cd33..44d8f6ebcb01 100644 --- a/qiskit/opflow/expectations/aer_pauli_expectation.py +++ b/qiskit/opflow/expectations/aer_pauli_expectation.py @@ -41,7 +41,7 @@ class AerPauliExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/cvar_expectation.py b/qiskit/opflow/expectations/cvar_expectation.py index 5a95e9cd0e12..9a6711c498ae 100644 --- a/qiskit/opflow/expectations/cvar_expectation.py +++ b/qiskit/opflow/expectations/cvar_expectation.py @@ -57,7 +57,7 @@ class CVaRExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, alpha: float, expectation: Optional[ExpectationBase] = None) -> None: """ diff --git a/qiskit/opflow/expectations/expectation_base.py b/qiskit/opflow/expectations/expectation_base.py index 4717775832bd..593c43b83833 100644 --- a/qiskit/opflow/expectations/expectation_base.py +++ b/qiskit/opflow/expectations/expectation_base.py @@ -40,7 +40,7 @@ class ExpectationBase(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/expectation_factory.py b/qiskit/opflow/expectations/expectation_factory.py index 28fb981a3755..58a72ed6daca 100644 --- a/qiskit/opflow/expectations/expectation_factory.py +++ b/qiskit/opflow/expectations/expectation_factory.py @@ -38,7 +38,7 @@ class ExpectationFactory: @staticmethod @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def build( operator: OperatorBase, diff --git a/qiskit/opflow/expectations/matrix_expectation.py b/qiskit/opflow/expectations/matrix_expectation.py index 282aba9bc298..dcd2d64adb08 100644 --- a/qiskit/opflow/expectations/matrix_expectation.py +++ b/qiskit/opflow/expectations/matrix_expectation.py @@ -27,7 +27,7 @@ class MatrixExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/expectations/pauli_expectation.py b/qiskit/opflow/expectations/pauli_expectation.py index e6b5711178cf..0305fc90250a 100644 --- a/qiskit/opflow/expectations/pauli_expectation.py +++ b/qiskit/opflow/expectations/pauli_expectation.py @@ -44,7 +44,7 @@ class PauliExpectation(ExpectationBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, group_paulis: bool = True) -> None: """ diff --git a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py index 872cda44f2c5..284cd7da7eb7 100644 --- a/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py +++ b/qiskit/opflow/gradients/circuit_gradients/circuit_gradient.py @@ -38,7 +38,7 @@ class CircuitGradient(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py index 90858aecaccb..361d13112e85 100644 --- a/qiskit/opflow/gradients/circuit_gradients/lin_comb.py +++ b/qiskit/opflow/gradients/circuit_gradients/lin_comb.py @@ -103,7 +103,7 @@ class LinComb(CircuitGradient): # pylint: disable=signature-differs, arguments-differ @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, aux_meas_op: OperatorBase = Z): """ diff --git a/qiskit/opflow/gradients/circuit_gradients/param_shift.py b/qiskit/opflow/gradients/circuit_gradients/param_shift.py index bcc459fef1b9..5329cc4c14c0 100644 --- a/qiskit/opflow/gradients/circuit_gradients/param_shift.py +++ b/qiskit/opflow/gradients/circuit_gradients/param_shift.py @@ -49,7 +49,7 @@ class ParamShift(CircuitGradient): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, analytic: bool = True, epsilon: float = 1e-6): r""" diff --git a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py index 3b60fa6447da..9a11d619e6c7 100644 --- a/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py +++ b/qiskit/opflow/gradients/circuit_qfis/circuit_qfi.py @@ -38,7 +38,7 @@ class CircuitQFI(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py index 742bf81d0045..71f4eea3d8c2 100644 --- a/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py +++ b/qiskit/opflow/gradients/circuit_qfis/lin_comb_full.py @@ -38,7 +38,7 @@ class LinCombFull(CircuitQFI): # pylint: disable=signature-differs, arguments-differ @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py index b56c80e35041..86b0bd1094cf 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_block_diag.py @@ -41,7 +41,7 @@ class OverlapBlockDiag(CircuitQFI): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py index 030cc6cc4b8c..3f630fe304b9 100644 --- a/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py +++ b/qiskit/opflow/gradients/circuit_qfis/overlap_diag.py @@ -40,7 +40,7 @@ class OverlapDiag(CircuitQFI): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 368274fb58c0..9ac6f7fa0541 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -50,7 +50,7 @@ class DerivativeBase(ConverterBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/gradients/gradient.py b/qiskit/opflow/gradients/gradient.py index 7395aa129df5..b65784127a5a 100644 --- a/qiskit/opflow/gradients/gradient.py +++ b/qiskit/opflow/gradients/gradient.py @@ -39,7 +39,7 @@ class Gradient(GradientBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(grad_method=grad_method, **kwargs) diff --git a/qiskit/opflow/gradients/gradient_base.py b/qiskit/opflow/gradients/gradient_base.py index 2332297301df..f8da278acc93 100644 --- a/qiskit/opflow/gradients/gradient_base.py +++ b/qiskit/opflow/gradients/gradient_base.py @@ -27,7 +27,7 @@ class GradientBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, grad_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/hessian.py b/qiskit/opflow/gradients/hessian.py index 37f39ee4caed..d25de4ad4cae 100644 --- a/qiskit/opflow/gradients/hessian.py +++ b/qiskit/opflow/gradients/hessian.py @@ -42,7 +42,7 @@ class Hessian(HessianBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): super().__init__(hess_method=hess_method, **kwargs) diff --git a/qiskit/opflow/gradients/hessian_base.py b/qiskit/opflow/gradients/hessian_base.py index 353a2c90d2bc..2230ec28d824 100644 --- a/qiskit/opflow/gradients/hessian_base.py +++ b/qiskit/opflow/gradients/hessian_base.py @@ -24,7 +24,7 @@ class HessianBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, hess_method: Union[str, CircuitGradient] = "param_shift", **kwargs): r""" diff --git a/qiskit/opflow/gradients/natural_gradient.py b/qiskit/opflow/gradients/natural_gradient.py index 7f945670f92e..9866b79e943b 100644 --- a/qiskit/opflow/gradients/natural_gradient.py +++ b/qiskit/opflow/gradients/natural_gradient.py @@ -54,7 +54,7 @@ class NaturalGradient(GradientBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/gradients/qfi.py b/qiskit/opflow/gradients/qfi.py index 0aa0b1399bbc..64ba631455d2 100644 --- a/qiskit/opflow/gradients/qfi.py +++ b/qiskit/opflow/gradients/qfi.py @@ -39,7 +39,7 @@ class QFI(QFIBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): super().__init__(qfi_method=qfi_method) diff --git a/qiskit/opflow/gradients/qfi_base.py b/qiskit/opflow/gradients/qfi_base.py index 4bb2b6a4a24f..b09f9170dbad 100644 --- a/qiskit/opflow/gradients/qfi_base.py +++ b/qiskit/opflow/gradients/qfi_base.py @@ -32,7 +32,7 @@ class QFIBase(DerivativeBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, qfi_method: Union[str, CircuitQFI] = "lin_comb_full"): r""" diff --git a/qiskit/opflow/list_ops/composed_op.py b/qiskit/opflow/list_ops/composed_op.py index 667130e55f77..d47a81fbd796 100644 --- a/qiskit/opflow/list_ops/composed_op.py +++ b/qiskit/opflow/list_ops/composed_op.py @@ -36,7 +36,7 @@ class ComposedOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/list_op.py b/qiskit/opflow/list_ops/list_op.py index 43447cc15604..abf2d2326d0c 100644 --- a/qiskit/opflow/list_ops/list_op.py +++ b/qiskit/opflow/list_ops/list_op.py @@ -55,7 +55,7 @@ class ListOp(OperatorBase): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/summed_op.py b/qiskit/opflow/list_ops/summed_op.py index bedf2a8ae349..52f7faa15083 100644 --- a/qiskit/opflow/list_ops/summed_op.py +++ b/qiskit/opflow/list_ops/summed_op.py @@ -33,7 +33,7 @@ class SummedOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/list_ops/tensored_op.py b/qiskit/opflow/list_ops/tensored_op.py index 6b031305bb3b..e3eb30cfaa41 100644 --- a/qiskit/opflow/list_ops/tensored_op.py +++ b/qiskit/opflow/list_ops/tensored_op.py @@ -34,7 +34,7 @@ class TensoredOp(ListOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/mixins/star_algebra.py b/qiskit/opflow/mixins/star_algebra.py index dd0c786cd441..642086d5ba04 100644 --- a/qiskit/opflow/mixins/star_algebra.py +++ b/qiskit/opflow/mixins/star_algebra.py @@ -42,7 +42,7 @@ class StarAlgebraMixin(MultiplyMixin, ABC): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/mixins/tensor.py b/qiskit/opflow/mixins/tensor.py index e81c1ee08647..3535db439f09 100644 --- a/qiskit/opflow/mixins/tensor.py +++ b/qiskit/opflow/mixins/tensor.py @@ -30,7 +30,7 @@ class TensorMixin(ABC): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: pass diff --git a/qiskit/opflow/operator_base.py b/qiskit/opflow/operator_base.py index 91a70902d1a7..7c1e031d8620 100644 --- a/qiskit/opflow/operator_base.py +++ b/qiskit/opflow/operator_base.py @@ -47,7 +47,7 @@ class OperatorBase(StarAlgebraMixin, TensorMixin, ABC): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self) -> None: super().__init__() diff --git a/qiskit/opflow/operator_globals.py b/qiskit/opflow/operator_globals.py index 5454d384ab7a..a5afcd9cf08f 100644 --- a/qiskit/opflow/operator_globals.py +++ b/qiskit/opflow/operator_globals.py @@ -35,7 +35,7 @@ @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def make_immutable(obj): r"""Deprecate\: Delete the __setattr__ property to make the object mostly immutable.""" diff --git a/qiskit/opflow/primitive_ops/circuit_op.py b/qiskit/opflow/primitive_ops/circuit_op.py index 3a3c618216e8..1a6104a4cac3 100644 --- a/qiskit/opflow/primitive_ops/circuit_op.py +++ b/qiskit/opflow/primitive_ops/circuit_op.py @@ -33,7 +33,7 @@ class CircuitOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/matrix_op.py b/qiskit/opflow/primitive_ops/matrix_op.py index ce6c0722b58f..be8c8ac90eec 100644 --- a/qiskit/opflow/primitive_ops/matrix_op.py +++ b/qiskit/opflow/primitive_ops/matrix_op.py @@ -38,7 +38,7 @@ class MatrixOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/pauli_op.py b/qiskit/opflow/primitive_ops/pauli_op.py index 40dce497ac63..5720a13357df 100644 --- a/qiskit/opflow/primitive_ops/pauli_op.py +++ b/qiskit/opflow/primitive_ops/pauli_op.py @@ -37,7 +37,7 @@ class PauliOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__(self, primitive: Pauli, coeff: Union[complex, ParameterExpression] = 1.0) -> None: """ diff --git a/qiskit/opflow/primitive_ops/pauli_sum_op.py b/qiskit/opflow/primitive_ops/pauli_sum_op.py index e5c7f1790fc7..97ecd8fe23ad 100644 --- a/qiskit/opflow/primitive_ops/pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/pauli_sum_op.py @@ -36,7 +36,7 @@ class PauliSumOp(PrimitiveOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/primitive_op.py b/qiskit/opflow/primitive_ops/primitive_op.py index 879713451a17..de3ef06c3add 100644 --- a/qiskit/opflow/primitive_ops/primitive_op.py +++ b/qiskit/opflow/primitive_ops/primitive_op.py @@ -95,7 +95,7 @@ def __new__( @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index 68cdb2bfca9e..49d96547fe2b 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -37,7 +37,7 @@ class TaperedPauliSumOp(PauliSumOp): @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/circuit_state_fn.py b/qiskit/opflow/state_fns/circuit_state_fn.py index e4476b8bcb1f..3f23f89a1cee 100644 --- a/qiskit/opflow/state_fns/circuit_state_fn.py +++ b/qiskit/opflow/state_fns/circuit_state_fn.py @@ -46,7 +46,7 @@ class CircuitStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/cvar_measurement.py b/qiskit/opflow/state_fns/cvar_measurement.py index d8dc322116ab..858d3b87f671 100644 --- a/qiskit/opflow/state_fns/cvar_measurement.py +++ b/qiskit/opflow/state_fns/cvar_measurement.py @@ -43,7 +43,7 @@ class CVaRMeasurement(OperatorStateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/dict_state_fn.py b/qiskit/opflow/state_fns/dict_state_fn.py index 4cff30a28b70..77d5c32d8772 100644 --- a/qiskit/opflow/state_fns/dict_state_fn.py +++ b/qiskit/opflow/state_fns/dict_state_fn.py @@ -40,7 +40,7 @@ class DictStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/operator_state_fn.py b/qiskit/opflow/state_fns/operator_state_fn.py index 3f7dcf4c8911..a9cac679deef 100644 --- a/qiskit/opflow/state_fns/operator_state_fn.py +++ b/qiskit/opflow/state_fns/operator_state_fn.py @@ -39,7 +39,7 @@ class OperatorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/sparse_vector_state_fn.py b/qiskit/opflow/state_fns/sparse_vector_state_fn.py index 22464eb9b6bf..b26c6dff9df1 100644 --- a/qiskit/opflow/state_fns/sparse_vector_state_fn.py +++ b/qiskit/opflow/state_fns/sparse_vector_state_fn.py @@ -40,7 +40,7 @@ class SparseVectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/state_fn.py b/qiskit/opflow/state_fns/state_fn.py index 8cbae6cb2397..f24592bdaf55 100644 --- a/qiskit/opflow/state_fns/state_fn.py +++ b/qiskit/opflow/state_fns/state_fn.py @@ -115,7 +115,7 @@ def __new__( # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/state_fns/vector_state_fn.py b/qiskit/opflow/state_fns/vector_state_fn.py index f86987fb4510..8391d92a697b 100644 --- a/qiskit/opflow/state_fns/vector_state_fn.py +++ b/qiskit/opflow/state_fns/vector_state_fn.py @@ -39,7 +39,7 @@ class VectorStateFn(StateFn): # TODO allow normalization somehow? @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def __init__( self, diff --git a/qiskit/opflow/utils.py b/qiskit/opflow/utils.py index 45f0322fd9a8..0979fc0bc3e7 100644 --- a/qiskit/opflow/utils.py +++ b/qiskit/opflow/utils.py @@ -18,7 +18,7 @@ @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" @@ -39,7 +39,7 @@ def commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: r""" @@ -60,7 +60,7 @@ def anti_commutator(op_a: OperatorBase, op_b: OperatorBase) -> OperatorBase: @deprecate_func( since="0.24.0", - additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration." + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", ) def double_commutator( op_a: OperatorBase, From 585903b7105f090d6c71e665ca4584df34880c64 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 13:07:16 +0200 Subject: [PATCH 21/47] Shorten qi message --- qiskit/utils/backend_utils.py | 22 +++++++++++----------- qiskit/utils/mitigation/_filters.py | 4 ++-- qiskit/utils/mitigation/circuits.py | 6 +++--- qiskit/utils/mitigation/fitters.py | 4 ++-- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/qiskit/utils/backend_utils.py b/qiskit/utils/backend_utils.py index 8067a13828bb..7f71a7c91897 100644 --- a/qiskit/utils/backend_utils.py +++ b/qiskit/utils/backend_utils.py @@ -52,7 +52,7 @@ def _get_backend_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def has_ibmq(): """Check if IBMQ is installed.""" @@ -73,7 +73,7 @@ def has_ibmq(): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def has_aer(): """Check if Aer is installed.""" @@ -93,7 +93,7 @@ def has_aer(): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_aer_provider(backend): """Detect whether or not backend is from Aer provider. @@ -117,7 +117,7 @@ def is_aer_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_basicaer_provider(backend): """Detect whether or not backend is from BasicAer provider. @@ -134,7 +134,7 @@ def is_basicaer_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_ibmq_provider(backend): """Detect whether or not backend is from IBMQ provider. @@ -154,7 +154,7 @@ def is_ibmq_provider(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_aer_statevector_backend(backend): """ @@ -170,7 +170,7 @@ def is_aer_statevector_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_statevector_backend(backend): """ @@ -199,7 +199,7 @@ def is_statevector_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_simulator_backend(backend): """ @@ -218,7 +218,7 @@ def is_simulator_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_local_backend(backend): """ @@ -237,7 +237,7 @@ def is_local_backend(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def is_aer_qasm(backend): """ @@ -257,7 +257,7 @@ def is_aer_qasm(backend): @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def support_backend_options(backend): """ diff --git a/qiskit/utils/mitigation/_filters.py b/qiskit/utils/mitigation/_filters.py index 696c0a2314a2..5d566f625116 100644 --- a/qiskit/utils/mitigation/_filters.py +++ b/qiskit/utils/mitigation/_filters.py @@ -45,7 +45,7 @@ class MeasurementFilter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__(self, cal_matrix: np.matrix, state_labels: list): """ @@ -227,7 +227,7 @@ class TensoredFilter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__(self, cal_matrices: np.matrix, substate_labels_list: list, mit_pattern: list): """ diff --git a/qiskit/utils/mitigation/circuits.py b/qiskit/utils/mitigation/circuits.py index a19d27af2c13..2fdeaa6372a6 100644 --- a/qiskit/utils/mitigation/circuits.py +++ b/qiskit/utils/mitigation/circuits.py @@ -24,7 +24,7 @@ @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def count_keys(num_qubits: int) -> List[str]: """Deprecated: Return ordered count keys. @@ -42,7 +42,7 @@ def count_keys(num_qubits: int) -> List[str]: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def complete_meas_cal( qubit_list: List[int] = None, @@ -123,7 +123,7 @@ def complete_meas_cal( @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def tensored_meas_cal( mit_pattern: List[List[int]] = None, diff --git a/qiskit/utils/mitigation/fitters.py b/qiskit/utils/mitigation/fitters.py index 8b8286100ae9..65357d5dc5b5 100644 --- a/qiskit/utils/mitigation/fitters.py +++ b/qiskit/utils/mitigation/fitters.py @@ -37,7 +37,7 @@ class CompleteMeasFitter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__( self, @@ -221,7 +221,7 @@ class TensoredMeasFitter: @deprecate_func( since="0.24.0", - additional_msg="This function was used by the deprecated QuantumInstance class. For code migration guidelines, visit https://qisk.it/qi_migration.", + additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) def __init__( self, From 40771b715786175c6dcb28603c76023a56c5ad87 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 13:13:50 +0200 Subject: [PATCH 22/47] Remove checks for QDrift's internal use of opflow (changed in this PR) --- .../time_evolvers/test_trotter_qrte.py | 14 ++++---------- .../circuit/library/test_evolution_gate.py | 17 +++-------------- 2 files changed, 7 insertions(+), 24 deletions(-) diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index cb06a4cfb63a..727900ab7b41 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -195,16 +195,10 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): trotter_qrte = TrotterQRTE(product_formula=QDrift()) evolution_result = trotter_qrte.evolve(evolution_problem) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - np.testing.assert_array_almost_equal( - Statevector.from_instruction(evolution_result.evolved_state).data, - expected_state.data, - ) - self.assertTrue(len(caught_warnings) > 0) + 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 diff --git a/test/python/circuit/library/test_evolution_gate.py b/test/python/circuit/library/test_evolution_gate.py index c8e98d4a3e66..2e2e629874fc 100644 --- a/test/python/circuit/library/test_evolution_gate.py +++ b/test/python/circuit/library/test_evolution_gate.py @@ -168,16 +168,10 @@ def test_qdrift_manual(self, op, time, reps, sampled_ops): """Test the evolution circuit of Suzuki Trotter against a manually constructed circuit.""" qdrift = QDrift(reps=reps) evo_gate = PauliEvolutionGate(op, time, synthesis=qdrift) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo_gate.definition.decompose() - self.assertTrue(len(caught_warnings) > 0) + evo_gate.definition.decompose() # manually construct expected evolution - expected = QuantumCircuit(1) + expected = QuantumCircuit(1)∂ for pauli in sampled_ops: if pauli[0].to_label() == "X": expected.rx(2 * pauli[1], 0) @@ -196,12 +190,7 @@ def test_qdrift_evolution(self): op = 0.1 * (Z ^ Z) + (X ^ I) + (I ^ X) + 0.2 * (X ^ X) self.assertTrue(len(caught_warnings) > 0) reps = 20 - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - qdrift = PauliEvolutionGate(op, time=0.5 / reps, synthesis=QDrift(reps=reps)).definition + qdrift = PauliEvolutionGate(op, time=0.5 / reps, synthesis=QDrift(reps=reps)).definition self.assertTrue(len(caught_warnings) > 0) exact = scipy.linalg.expm(-0.5j * op.to_matrix()).dot(np.eye(4)[0, :]) From 42ae937b54143663483f51b9d25a3265ae99c8c2 Mon Sep 17 00:00:00 2001 From: ElePT Date: Thu, 30 Mar 2023 13:32:59 +0200 Subject: [PATCH 23/47] Add warning catchers to unit tests --- .../circuit/library/test_evolution_gate.py | 2 +- .../opflow/test_aer_pauli_expectation.py | 17 +++++++----- .../python/opflow/test_expectation_factory.py | 22 ++++++++++------ test/python/opflow/test_gradients.py | 26 ++++++++++++++----- test/python/opflow/test_matrix_expectation.py | 9 ++++++- test/python/opflow/test_pauli_expectation.py | 18 +++++++++++-- .../python/opflow/test_state_op_meas_evals.py | 9 +++++-- 7 files changed, 77 insertions(+), 26 deletions(-) diff --git a/test/python/circuit/library/test_evolution_gate.py b/test/python/circuit/library/test_evolution_gate.py index 2e2e629874fc..2574c856408a 100644 --- a/test/python/circuit/library/test_evolution_gate.py +++ b/test/python/circuit/library/test_evolution_gate.py @@ -171,7 +171,7 @@ def test_qdrift_manual(self, op, time, reps, sampled_ops): evo_gate.definition.decompose() # manually construct expected evolution - expected = QuantumCircuit(1)∂ + expected = QuantumCircuit(1) for pauli in sampled_ops: if pauli[0].to_label() == "X": expected.rx(2 * pauli[1], 0) diff --git a/test/python/opflow/test_aer_pauli_expectation.py b/test/python/opflow/test_aer_pauli_expectation.py index ecff4df898a8..32e2acd51fe0 100644 --- a/test/python/opflow/test_aer_pauli_expectation.py +++ b/test/python/opflow/test_aer_pauli_expectation.py @@ -61,9 +61,9 @@ def setUp(self) -> None: q_instance = QuantumInstance( self.backend, seed_simulator=self.seed, seed_transpiler=self.seed ) + self.sampler = CircuitSampler(q_instance, attach_results=True) + self.expect = AerPauliExpectation() self.assertTrue(len(caught_warnings) > 0) - self.sampler = CircuitSampler(q_instance, attach_results=True) - self.expect = AerPauliExpectation() def test_pauli_expect_pair(self): """pauli expect pair test""" @@ -232,10 +232,15 @@ def test_parameterized_qobj(self): + (0.18093119978423156 * X ^ X) ) - aer_sampler = CircuitSampler( - self.sampler.quantum_instance, param_qobj=True, attach_results=True - ) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + aer_sampler = CircuitSampler( + self.sampler.quantum_instance, param_qobj=True, attach_results=True + ) + self.assertTrue(len(caught_warnings) > 0) ansatz = RealAmplitudes() ansatz.num_qubits = 2 diff --git a/test/python/opflow/test_expectation_factory.py b/test/python/opflow/test_expectation_factory.py index 83cee6a0bcbb..20c21851e384 100644 --- a/test/python/opflow/test_expectation_factory.py +++ b/test/python/opflow/test_expectation_factory.py @@ -13,6 +13,7 @@ """Test the expectation factory.""" import unittest +import warnings from test.python.opflow import QiskitOpflowTestCase from qiskit.opflow import PauliExpectation, AerPauliExpectation, ExpectationFactory, Z, I, X @@ -29,11 +30,16 @@ def test_aer_simulator_pauli_sum(self): backend = AerSimulator() op = 0.2 * (X ^ X) + 0.1 * (Z ^ I) - - with self.subTest("Defaults"): - expectation = ExpectationFactory.build(op, backend, include_custom=False) - self.assertIsInstance(expectation, PauliExpectation) - - with self.subTest("Include custom"): - expectation = ExpectationFactory.build(op, backend, include_custom=True) - self.assertIsInstance(expectation, AerPauliExpectation) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + with self.subTest("Defaults"): + expectation = ExpectationFactory.build(op, backend, include_custom=False) + self.assertIsInstance(expectation, PauliExpectation) + + with self.subTest("Include custom"): + expectation = ExpectationFactory.build(op, backend, include_custom=True) + self.assertIsInstance(expectation, AerPauliExpectation) + self.assertTrue(len(caught_warnings) > 0) diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 73f4e0b6c44b..374631bd65cc 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -1121,9 +1121,16 @@ def test_gradient_wrapper(self, backend_type): operator=op, bind_params=params, backend=q_instance ) else: - prob_grad = Gradient(grad_method=method).gradient_wrapper( - operator=op, bind_params=params, backend=q_instance - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + prob_grad = Gradient(grad_method=method).gradient_wrapper( + operator=op, bind_params=params, backend=q_instance + ) + self.assertTrue(len(caught_warnings) > 0) + values = [[np.pi / 4, 0], [np.pi / 4, np.pi / 4], [np.pi / 2, np.pi]] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], @@ -1665,9 +1672,16 @@ def test_nat_grad_error(self): backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) self.assertTrue(len(caught_warnings) > 0) - grad = NaturalGradient(grad_method=method).gradient_wrapper( - operator=op, bind_params=params, backend=q_instance - ) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + grad = NaturalGradient(grad_method=method).gradient_wrapper( + operator=op, bind_params=params, backend=q_instance + ) + self.assertTrue(len(caught_warnings) > 0) + with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index c3f78ebafa84..a9931bd4eb88 100644 --- a/test/python/opflow/test_matrix_expectation.py +++ b/test/python/opflow/test_matrix_expectation.py @@ -55,8 +55,15 @@ def setUp(self) -> None: backend, seed_simulator=self.seed, seed_transpiler=self.seed ) self.assertTrue(len(caught_warnings) > 0) - self.sampler = CircuitSampler(q_instance, attach_results=True) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.sampler = CircuitSampler(q_instance, attach_results=True) + self.expect = MatrixExpectation() + self.assertTrue(len(caught_warnings) > 0) def test_pauli_expect_pair(self): """pauli expect pair test""" diff --git a/test/python/opflow/test_pauli_expectation.py b/test/python/opflow/test_pauli_expectation.py index 5482623a2229..e01806d06a1a 100644 --- a/test/python/opflow/test_pauli_expectation.py +++ b/test/python/opflow/test_pauli_expectation.py @@ -60,7 +60,14 @@ def setUp(self) -> None: backend, seed_simulator=self.seed, seed_transpiler=self.seed ) self.assertTrue(len(caught_warnings) > 0) - self.sampler = CircuitSampler(q_instance, attach_results=True) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.sampler = CircuitSampler(q_instance, attach_results=True) + self.assertTrue(len(caught_warnings) > 0) + self.expect = PauliExpectation() def test_pauli_expect_pair(self): @@ -269,7 +276,14 @@ def test_grouped_pauli_expectation(self): seed_transpiler=self.seed, ) self.assertTrue(len(caught_warnings) > 0) - sampler = CircuitSampler(q_instance) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampler = CircuitSampler(q_instance) + self.assertTrue(len(caught_warnings) > 0) + sampler._extract_circuitstatefns(expect_op_grouped) num_circuits_grouped = len(sampler._circuit_ops_cache) self.assertEqual(num_circuits_grouped, 2) diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index ead2bc527400..da84d504242a 100644 --- a/test/python/opflow/test_state_op_meas_evals.py +++ b/test/python/opflow/test_state_op_meas_evals.py @@ -211,8 +211,13 @@ def test_circuit_sampler_caching(self, caching): circuit.ry(x, 0) expr1 = ~StateFn(H) @ StateFn(circuit) expr2 = ~StateFn(X) @ StateFn(circuit) - - sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector"), caching=caching) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector"), caching=caching) + self.assertTrue(len(caught_warnings) > 0) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( From 759a4801d6fa7995cb577208c6cebb267e521404 Mon Sep 17 00:00:00 2001 From: ElePT Date: Fri, 14 Apr 2023 16:16:32 +0200 Subject: [PATCH 24/47] Remove opflow from qaoa ansatz tests --- test/python/circuit/library/test_qaoa_ansatz.py | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/test/python/circuit/library/test_qaoa_ansatz.py b/test/python/circuit/library/test_qaoa_ansatz.py index 7d08c1e20f9b..29eb13a56dcd 100644 --- a/test/python/circuit/library/test_qaoa_ansatz.py +++ b/test/python/circuit/library/test_qaoa_ansatz.py @@ -82,7 +82,7 @@ def test_custom_operator_mixer(self): circuit = circuit.decompose() self.assertEqual(1, len(parameters)) self.assertIsInstance(circuit.data[0].operation, HGate) - self.assertIsInstance(circuit.data[1].operation, RYGate) + self.assertIsInstance(circuit.decompose().data[1].operation, RYGate) def test_parameter_bounds(self): """Test the parameter bounds.""" @@ -107,13 +107,22 @@ def test_all_custom_parameters(self): circuit = QAOAAnsatz( cost_operator=Pauli("I"), reps=2, initial_state=initial_state, mixer_operator=mixer ) - parameters = circuit.parameters + + # To be removed once QAOAAnsatz drops support for opflow + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + parameters = circuit.parameters + self.assertTrue(len(caught_warnings) > 0) circuit = circuit.decompose() + self.assertEqual(2, len(parameters)) self.assertIsInstance(circuit.data[0].operation, YGate) - self.assertIsInstance(circuit.data[1].operation, RZGate) - self.assertIsInstance(circuit.data[2].operation, RZGate) + self.assertIsInstance(circuit.decompose().data[1].operation, RZGate) + self.assertIsInstance(circuit.decompose().data[2].operation, RZGate) def test_configuration(self): """Test configuration checks.""" From 0d8f939dde85b92f4f3a9beebe878b94d3634284 Mon Sep 17 00:00:00 2001 From: ElePT Date: Fri, 14 Apr 2023 16:28:13 +0200 Subject: [PATCH 25/47] Remove opflow from non-related tests --- .../circuit/test_circuit_load_from_qpy.py | 88 ++++++------------- .../transpiler/test_swap_strategy_router.py | 25 +++--- 2 files changed, 39 insertions(+), 74 deletions(-) diff --git a/test/python/circuit/test_circuit_load_from_qpy.py b/test/python/circuit/test_circuit_load_from_qpy.py index 1abf13be5d13..b0aefbce67a1 100644 --- a/test/python/circuit/test_circuit_load_from_qpy.py +++ b/test/python/circuit/test_circuit_load_from_qpy.py @@ -13,10 +13,10 @@ """Test cases for the circuit qasm_file and qasm_string method.""" -import warnings import io import json import random +import warnings import numpy as np @@ -42,9 +42,9 @@ from qiskit.circuit.parametervector import ParameterVector from qiskit.synthesis import LieTrotter, SuzukiTrotter from qiskit.extensions import UnitaryGate -from qiskit.opflow import I, X, Y, Z from qiskit.test import QiskitTestCase from qiskit.qpy import dump, load +from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.quantum_info.random import random_unitary from qiskit.circuit.controlledgate import ControlledGate @@ -303,13 +303,12 @@ def test_parameter_expression(self): def test_string_parameter(self): """Test a PauliGate instruction that has string parameters.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - circ = (X ^ Y ^ Z).to_circuit_op().to_circuit() - self.assertTrue(len(caught_warnings) > 0) + + circ = QuantumCircuit(3) + circ.z(0) + circ.y(1) + circ.x(2) + qpy_file = io.BytesIO() dump(circ, qpy_file) qpy_file.seek(0) @@ -683,22 +682,11 @@ def test_single_bit_teleportation(self): def test_qaoa(self): """Test loading a QAOA circuit works.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - cost_operator = Z ^ I ^ I ^ Z - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - qaoa = QAOAAnsatz(cost_operator, reps=2) - qpy_file = io.BytesIO() - dump(qaoa, qpy_file) - self.assertTrue(len(caught_warnings) > 0) + cost_operator = Pauli("ZIIZ") + qaoa = QAOAAnsatz(cost_operator, reps=2) + + qpy_file = io.BytesIO() + dump(qaoa, qpy_file) qpy_file.seek(0) new_circ = load(qpy_file)[0] self.assertEqual(qaoa, new_circ) @@ -710,13 +698,15 @@ def test_qaoa(self): def test_evolutiongate(self): """Test loading a circuit with evolution gate works.""" synthesis = LieTrotter(reps=2) + # To be removed once PauliEvolutionGate drops support for opflow with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=2, synthesis=synthesis) + evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=2, synthesis=synthesis) self.assertTrue(len(caught_warnings) > 0) + qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -737,13 +727,8 @@ def test_evolutiongate_param_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time, synthesis=synthesis) - self.assertTrue(len(caught_warnings) > 0) + evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=time, synthesis=synthesis) + qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -764,13 +749,8 @@ def test_evolutiongate_param_expr_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time * time, synthesis=synthesis) - self.assertTrue(len(caught_warnings) > 0) + evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=time * time, synthesis=synthesis) + qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -791,13 +771,8 @@ def test_evolutiongate_param_vec_time(self): """Test loading a an evolution gate that has a param vector element for time.""" synthesis = LieTrotter(reps=2) time = ParameterVector("TimeVec", 1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=time[0], synthesis=synthesis) - self.assertTrue(len(caught_warnings) > 0) + evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=time[0], synthesis=synthesis) + qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -816,13 +791,8 @@ def test_evolutiongate_param_vec_time(self): def test_op_list_evolutiongate(self): """Test loading a circuit with evolution gate works.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo = PauliEvolutionGate([(Z ^ I) + (I ^ Z)] * 5, time=0.2, synthesis=None) - self.assertTrue(len(caught_warnings) > 0) + + evo = PauliEvolutionGate([SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)])] * 5, time=0.2, synthesis=None) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -842,13 +812,8 @@ def test_op_list_evolutiongate(self): def test_op_evolution_gate_suzuki_trotter(self): """Test qpy path with a suzuki trotter synthesis method on an evolution gate.""" synthesis = SuzukiTrotter() - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo = PauliEvolutionGate((Z ^ I) + (I ^ Z), time=0.2, synthesis=synthesis) - self.assertTrue(len(caught_warnings) > 0) + evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=0.2, synthesis=synthesis) + qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -1371,3 +1336,4 @@ def test_qpy_deprecation(self): with self.assertWarnsRegex(DeprecationWarning, "is deprecated"): # pylint: disable=no-name-in-module, unused-import, redefined-outer-name, reimported from qiskit.circuit.qpy_serialization import dump, load + diff --git a/test/python/transpiler/test_swap_strategy_router.py b/test/python/transpiler/test_swap_strategy_router.py index 292e826a3e73..66d391342623 100644 --- a/test/python/transpiler/test_swap_strategy_router.py +++ b/test/python/transpiler/test_swap_strategy_router.py @@ -22,8 +22,7 @@ from qiskit.circuit.library.n_local import QAOAAnsatz from qiskit.converters import circuit_to_dag from qiskit.exceptions import QiskitError -from qiskit.opflow import PauliSumOp -from qiskit.quantum_info import Pauli +from qiskit.quantum_info import Pauli,SparsePauliOp from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout @@ -83,7 +82,7 @@ def test_basic_zz(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) @@ -125,7 +124,7 @@ def test_basic_xx(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) + op = SparsePauliOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) @@ -168,7 +167,7 @@ def test_idle_qubit(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("IIXX", 1), ("IXIX", 2)]) + op = SparsePauliOp.from_list([("IIXX", 1), ("IXIX", 2)]) self.assertTrue(len(caught_warnings) > 0) cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (2, 3)]) @@ -215,7 +214,7 @@ def test_basic_xx_with_measure(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) + op = SparsePauliOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4, 4) @@ -288,7 +287,7 @@ def test_qaoa(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QAOAAnsatz(op, reps=2, mixer_operator=mixer) swapped = self.pm_.run(circ.decompose()) self.assertTrue(len(caught_warnings) > 0) @@ -339,7 +338,7 @@ def test_enlarge_with_ancilla(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) @@ -422,7 +421,7 @@ def test_ccx(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("IZZ", 1), ("ZIZ", 2)]) + op = SparsePauliOp.from_list([("IZZ", 1), ("ZIZ", 2)]) self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(3)) @@ -473,7 +472,7 @@ def test_t_device(self): category=DeprecationWarning, ) # A dense Pauli op. - op = PauliSumOp.from_list( + op = SparsePauliOp.from_list( [ ("IIIZZ", 1), ("IIZIZ", 2), @@ -549,7 +548,7 @@ def test_single_qubit_circuit(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("IIIX", 1), ("IIXI", 2), ("IZII", 3), ("XIII", 4)]) + op = SparsePauliOp.from_list([("IIIX", 1), ("IIXI", 2), ("IZII", 3), ("XIII", 4)]) self.assertTrue(len(caught_warnings) > 0) circ = QuantumCircuit(4) @@ -568,7 +567,7 @@ def test_edge_coloring(self, edge_coloring): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list([("IIZZ", 1), ("IZZI", 2), ("ZZII", 3), ("ZIZI", 4)]) + op = SparsePauliOp.from_list([("IIZZ", 1), ("IZZI", 2), ("ZZII", 3), ("ZIZI", 4)]) self.assertTrue(len(caught_warnings) > 0) swaps = (((1, 2),),) @@ -638,7 +637,7 @@ def setUp(self): "always", category=DeprecationWarning, ) - op = PauliSumOp.from_list( + op = SparsePauliOp.from_list( [("IIZZ", 1), ("IZIZ", 1), ("ZIIZ", 1), ("IZZI", 1), ("ZIZI", 1), ("ZZII", 1)] ) self.assertTrue(len(caught_warnings) > 0) From c07e69db3e263c5815f9e24dba507f9709f85609 Mon Sep 17 00:00:00 2001 From: ElePT Date: Fri, 14 Apr 2023 16:32:13 +0200 Subject: [PATCH 26/47] Restore some opflow tests for completion --- test/python/circuit/library/test_qaoa_ansatz.py | 15 ++++----------- 1 file changed, 4 insertions(+), 11 deletions(-) diff --git a/test/python/circuit/library/test_qaoa_ansatz.py b/test/python/circuit/library/test_qaoa_ansatz.py index 29eb13a56dcd..94d190259e89 100644 --- a/test/python/circuit/library/test_qaoa_ansatz.py +++ b/test/python/circuit/library/test_qaoa_ansatz.py @@ -19,6 +19,7 @@ from qiskit.circuit import QuantumCircuit, Parameter from qiskit.circuit.library import HGate, RXGate, YGate, RYGate, RZGate from qiskit.circuit.library.n_local.qaoa_ansatz import QAOAAnsatz +from qiskit.opflow import I from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.test import QiskitTestCase @@ -29,7 +30,8 @@ class TestQAOAAnsatz(QiskitTestCase): def test_default_qaoa(self): """Test construction of the default circuit.""" - circuit = QAOAAnsatz(Pauli("I"), 1) + # To be changed once QAOAAnsatz drops support for opflow + circuit = QAOAAnsatz(I, 1) parameters = circuit.parameters circuit = circuit.decompose() @@ -107,16 +109,7 @@ def test_all_custom_parameters(self): circuit = QAOAAnsatz( cost_operator=Pauli("I"), reps=2, initial_state=initial_state, mixer_operator=mixer ) - - # To be removed once QAOAAnsatz drops support for opflow - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - parameters = circuit.parameters - self.assertTrue(len(caught_warnings) > 0) - + parameters = circuit.parameters circuit = circuit.decompose() self.assertEqual(2, len(parameters)) From 57c022b92f5ee459e15c9aa16f2e5e4af34ce5d0 Mon Sep 17 00:00:00 2001 From: ElePT Date: Fri, 14 Apr 2023 16:35:03 +0200 Subject: [PATCH 27/47] Fix black --- qiskit/circuit/library/n_local/qaoa_ansatz.py | 1 + .../circuit/test_circuit_load_from_qpy.py | 25 +++++++++++++------ .../transpiler/test_swap_strategy_router.py | 2 +- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/qiskit/circuit/library/n_local/qaoa_ansatz.py b/qiskit/circuit/library/n_local/qaoa_ansatz.py index 98edc465bdcc..c8da8d271e2f 100644 --- a/qiskit/circuit/library/n_local/qaoa_ansatz.py +++ b/qiskit/circuit/library/n_local/qaoa_ansatz.py @@ -22,6 +22,7 @@ from qiskit.circuit.quantumregister import QuantumRegister from qiskit.quantum_info import SparsePauliOp + class QAOAAnsatz(EvolvedOperatorAnsatz): """A generalized QAOA quantum circuit with a support of custom initial states and mixers. diff --git a/test/python/circuit/test_circuit_load_from_qpy.py b/test/python/circuit/test_circuit_load_from_qpy.py index b0aefbce67a1..7ed64b0c0678 100644 --- a/test/python/circuit/test_circuit_load_from_qpy.py +++ b/test/python/circuit/test_circuit_load_from_qpy.py @@ -704,7 +704,9 @@ def test_evolutiongate(self): "always", category=DeprecationWarning, ) - evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=2, synthesis=synthesis) + evo = PauliEvolutionGate( + SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=2, synthesis=synthesis + ) self.assertTrue(len(caught_warnings) > 0) qc = QuantumCircuit(2) @@ -727,7 +729,9 @@ def test_evolutiongate_param_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") - evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=time, synthesis=synthesis) + evo = PauliEvolutionGate( + SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time, synthesis=synthesis + ) qc = QuantumCircuit(2) qc.append(evo, range(2)) @@ -749,7 +753,9 @@ def test_evolutiongate_param_expr_time(self): """Test loading a circuit with an evolution gate that has a parameter for time.""" synthesis = LieTrotter(reps=2) time = Parameter("t") - evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=time * time, synthesis=synthesis) + evo = PauliEvolutionGate( + SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time * time, synthesis=synthesis + ) qc = QuantumCircuit(2) qc.append(evo, range(2)) @@ -771,7 +777,9 @@ def test_evolutiongate_param_vec_time(self): """Test loading a an evolution gate that has a param vector element for time.""" synthesis = LieTrotter(reps=2) time = ParameterVector("TimeVec", 1) - evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=time[0], synthesis=synthesis) + evo = PauliEvolutionGate( + SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=time[0], synthesis=synthesis + ) qc = QuantumCircuit(2) qc.append(evo, range(2)) @@ -792,7 +800,9 @@ def test_evolutiongate_param_vec_time(self): def test_op_list_evolutiongate(self): """Test loading a circuit with evolution gate works.""" - evo = PauliEvolutionGate([SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)])] * 5, time=0.2, synthesis=None) + evo = PauliEvolutionGate( + [SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)])] * 5, time=0.2, synthesis=None + ) qc = QuantumCircuit(2) qc.append(evo, range(2)) qpy_file = io.BytesIO() @@ -812,7 +822,9 @@ def test_op_list_evolutiongate(self): def test_op_evolution_gate_suzuki_trotter(self): """Test qpy path with a suzuki trotter synthesis method on an evolution gate.""" synthesis = SuzukiTrotter() - evo = PauliEvolutionGate(SparsePauliOp.from_list([('ZI', 1), ('IZ', 1)]), time=0.2, synthesis=synthesis) + evo = PauliEvolutionGate( + SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=0.2, synthesis=synthesis + ) qc = QuantumCircuit(2) qc.append(evo, range(2)) @@ -1336,4 +1348,3 @@ def test_qpy_deprecation(self): with self.assertWarnsRegex(DeprecationWarning, "is deprecated"): # pylint: disable=no-name-in-module, unused-import, redefined-outer-name, reimported from qiskit.circuit.qpy_serialization import dump, load - diff --git a/test/python/transpiler/test_swap_strategy_router.py b/test/python/transpiler/test_swap_strategy_router.py index 66d391342623..6c8ccbd6a91c 100644 --- a/test/python/transpiler/test_swap_strategy_router.py +++ b/test/python/transpiler/test_swap_strategy_router.py @@ -22,7 +22,7 @@ from qiskit.circuit.library.n_local import QAOAAnsatz from qiskit.converters import circuit_to_dag from qiskit.exceptions import QiskitError -from qiskit.quantum_info import Pauli,SparsePauliOp +from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.transpiler.passes import FullAncillaAllocation from qiskit.transpiler.passes import EnlargeWithAncilla from qiskit.transpiler.passes import ApplyLayout From efbe2c993383a910c60933442ecd66107c602a96 Mon Sep 17 00:00:00 2001 From: ElePT Date: Fri, 14 Apr 2023 17:13:46 +0200 Subject: [PATCH 28/47] Remove catch warnings --- .../transpiler/test_swap_strategy_router.py | 127 +++++------------- 1 file changed, 32 insertions(+), 95 deletions(-) diff --git a/test/python/transpiler/test_swap_strategy_router.py b/test/python/transpiler/test_swap_strategy_router.py index 6c8ccbd6a91c..9c234cd63e2c 100644 --- a/test/python/transpiler/test_swap_strategy_router.py +++ b/test/python/transpiler/test_swap_strategy_router.py @@ -77,13 +77,7 @@ def test_basic_zz(self): """ - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) - self.assertTrue(len(caught_warnings) > 0) + op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) @@ -119,13 +113,7 @@ def test_basic_xx(self): └─────────────────┘ └────────────────┘ """ - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) - self.assertTrue(len(caught_warnings) > 0) + op = SparsePauliOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 3), range(4)) @@ -162,13 +150,8 @@ def test_idle_qubit(self): q_3: ───────────────────────────────────────── """ - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("IIXX", 1), ("IXIX", 2)]) - self.assertTrue(len(caught_warnings) > 0) + + op = SparsePauliOp.from_list([("IIXX", 1), ("IXIX", 2)]) cmap = CouplingMap(couplinglist=[(0, 1), (1, 2), (2, 3)]) swap_strat = SwapStrategy(cmap, swap_layers=(((0, 1),),)) @@ -209,13 +192,7 @@ def test_basic_xx_with_measure(self): 0 1 2 3 """ - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) - self.assertTrue(len(caught_warnings) > 0) + op = SparsePauliOp.from_list([("XXII", -1), ("IIXX", 1), ("XIIX", -2), ("IXIX", 2)]) circ = QuantumCircuit(4, 4) circ.append(PauliEvolutionGate(op, 3), range(4)) @@ -282,15 +259,9 @@ def test_qaoa(self): for idx in range(4): mixer.ry(-idx, idx) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) - circ = QAOAAnsatz(op, reps=2, mixer_operator=mixer) - swapped = self.pm_.run(circ.decompose()) - self.assertTrue(len(caught_warnings) > 0) + op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) + circ = QAOAAnsatz(op, reps=2, mixer_operator=mixer) + swapped = self.pm_.run(circ.decompose()) param_dict = {p: idx + 1 for idx, p in enumerate(swapped.parameters)} swapped.assign_parameters(param_dict, inplace=True) @@ -333,13 +304,7 @@ def test_enlarge_with_ancilla(self): """This pass tests that idle qubits after an embedding are left idle.""" # Create a four qubit problem. - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) - self.assertTrue(len(caught_warnings) > 0) + op = SparsePauliOp.from_list([("IZZI", 1), ("ZIIZ", 2), ("ZIZI", 3)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) @@ -416,13 +381,7 @@ def test_ccx(self): Commuting2qGateRouter(swap_strat), ] ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("IZZ", 1), ("ZIZ", 2)]) - self.assertTrue(len(caught_warnings) > 0) + op = SparsePauliOp.from_list([("IZZ", 1), ("ZIZ", 2)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(3)) circ.ccx(0, 2, 1) @@ -466,27 +425,21 @@ def test_t_device(self): swap_strat = SwapStrategy(cmap, swaps) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - # A dense Pauli op. - op = SparsePauliOp.from_list( - [ - ("IIIZZ", 1), - ("IIZIZ", 2), - ("IZIIZ", 3), - ("ZIIIZ", 4), - ("IIZZI", 5), - ("IZIZI", 6), - ("ZIIZI", 7), - ("IZZII", 8), - ("ZIZII", 9), - ("ZZIII", 10), - ] - ) - self.assertTrue(len(caught_warnings) > 0) + # A dense Pauli op. + op = SparsePauliOp.from_list( + [ + ("IIIZZ", 1), + ("IIZIZ", 2), + ("IZIIZ", 3), + ("ZIIIZ", 4), + ("IIZZI", 5), + ("IZIZI", 6), + ("ZIIZI", 7), + ("IZZII", 8), + ("ZIZII", 9), + ("ZZIII", 10), + ] + ) circ = QuantumCircuit(5) circ.append(PauliEvolutionGate(op, 1), range(5)) @@ -543,13 +496,8 @@ def inst_info(op, qargs, qreg): def test_single_qubit_circuit(self): """Test that a circuit with only single qubit gates is left unchanged.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("IIIX", 1), ("IIXI", 2), ("IZII", 3), ("XIII", 4)]) - self.assertTrue(len(caught_warnings) > 0) + + op = SparsePauliOp.from_list([("IIIX", 1), ("IIXI", 2), ("IZII", 3), ("XIII", 4)]) circ = QuantumCircuit(4) circ.append(PauliEvolutionGate(op, 1), range(4)) @@ -562,13 +510,8 @@ def test_single_qubit_circuit(self): ) def test_edge_coloring(self, edge_coloring): """Test that the edge coloring works.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list([("IIZZ", 1), ("IZZI", 2), ("ZZII", 3), ("ZIZI", 4)]) - self.assertTrue(len(caught_warnings) > 0) + + op = SparsePauliOp.from_list([("IIZZ", 1), ("IZZI", 2), ("ZZII", 3), ("ZIZI", 4)]) swaps = (((1, 2),),) cmap = CouplingMap([[0, 1], [1, 2], [2, 3]]) @@ -632,15 +575,9 @@ def setUp(self): super().setUp() # A fully connected problem. - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - op = SparsePauliOp.from_list( - [("IIZZ", 1), ("IZIZ", 1), ("ZIIZ", 1), ("IZZI", 1), ("ZIZI", 1), ("ZZII", 1)] - ) - self.assertTrue(len(caught_warnings) > 0) + op = SparsePauliOp.from_list( + [("IIZZ", 1), ("IZIZ", 1), ("ZIIZ", 1), ("IZZI", 1), ("ZIZI", 1), ("ZZII", 1)] + ) self.circ = QuantumCircuit(4) self.circ.append(PauliEvolutionGate(op, 1), range(4)) From 383db230a42155a058c8aedd6f47bc1ec1eb763f Mon Sep 17 00:00:00 2001 From: ElePT Date: Fri, 14 Apr 2023 17:35:51 +0200 Subject: [PATCH 29/47] Refactor adaptVQE tests, remove opflow from observables evaluator --- qiskit/algorithms/observables_evaluator.py | 3 +- .../minimum_eigensolvers/test_adapt_vqe.py | 126 ++++++++++-------- 2 files changed, 69 insertions(+), 60 deletions(-) diff --git a/qiskit/algorithms/observables_evaluator.py b/qiskit/algorithms/observables_evaluator.py index 3e8f11dfd6e6..6d40239e229e 100644 --- a/qiskit/algorithms/observables_evaluator.py +++ b/qiskit/algorithms/observables_evaluator.py @@ -20,6 +20,7 @@ from qiskit import QuantumCircuit from qiskit.opflow import PauliSumOp +from qiskit.quantum_info import SparsePauliOp from .exceptions import AlgorithmError from .list_or_dict import ListOrDict from ..primitives import BaseEstimator @@ -88,7 +89,7 @@ def _handle_zero_ops( """Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp`` operator.""" if observables_list: - zero_op = PauliSumOp.from_list([("I" * observables_list[0].num_qubits, 0)]) + zero_op = SparsePauliOp.from_list([("I" * observables_list[0].num_qubits, 0)]) for ind, observable in enumerate(observables_list): if observable == 0: observables_list[ind] = zero_op diff --git a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py index 1f6d11f81051..aed3eb83044f 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py @@ -38,54 +38,62 @@ class TestAdaptVQE(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() algorithm_globals.random_seed = 42 - self.h2_op = PauliSumOp.from_list( - [ - ("IIII", -0.8105479805373266), - ("ZZII", -0.2257534922240251), - ("IIZI", +0.12091263261776641), - ("ZIZI", +0.12091263261776641), - ("IZZI", +0.17218393261915543), - ("IIIZ", +0.17218393261915546), - ("IZIZ", +0.1661454325638243), - ("ZZIZ", +0.1661454325638243), - ("IIZZ", -0.2257534922240251), - ("IZZZ", +0.16892753870087926), - ("ZZZZ", +0.17464343068300464), - ("IXIX", +0.04523279994605788), - ("ZXIX", +0.04523279994605788), - ("IXZX", -0.04523279994605788), - ("ZXZX", -0.04523279994605788), - ] - ) - self.excitation_pool = [ - PauliSumOp( - SparsePauliOp(["IIIY", "IIZY"], coeffs=[0.5 + 0.0j, -0.5 + 0.0j]), coeff=1.0 - ), - PauliSumOp( - SparsePauliOp(["ZYII", "IYZI"], coeffs=[-0.5 + 0.0j, 0.5 + 0.0j]), coeff=1.0 - ), - PauliSumOp( - SparsePauliOp( - ["ZXZY", "IXIY", "IYIX", "ZYZX", "IYZX", "ZYIX", "ZXIY", "IXZY"], - coeffs=[ - -0.125 + 0.0j, - 0.125 + 0.0j, - -0.125 + 0.0j, - 0.125 + 0.0j, - 0.125 + 0.0j, - -0.125 + 0.0j, - 0.125 + 0.0j, - -0.125 + 0.0j, - ], + + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + self.h2_op = PauliSumOp.from_list( + [ + ("IIII", -0.8105479805373266), + ("ZZII", -0.2257534922240251), + ("IIZI", +0.12091263261776641), + ("ZIZI", +0.12091263261776641), + ("IZZI", +0.17218393261915543), + ("IIIZ", +0.17218393261915546), + ("IZIZ", +0.1661454325638243), + ("ZZIZ", +0.1661454325638243), + ("IIZZ", -0.2257534922240251), + ("IZZZ", +0.16892753870087926), + ("ZZZZ", +0.17464343068300464), + ("IXIX", +0.04523279994605788), + ("ZXIX", +0.04523279994605788), + ("IXZX", -0.04523279994605788), + ("ZXZX", -0.04523279994605788), + ] + ) + self.excitation_pool = [ + PauliSumOp( + SparsePauliOp(["IIIY", "IIZY"], coeffs=[0.5 + 0.0j, -0.5 + 0.0j]), coeff=1.0 + ), + PauliSumOp( + SparsePauliOp(["ZYII", "IYZI"], coeffs=[-0.5 + 0.0j, 0.5 + 0.0j]), coeff=1.0 + ), + PauliSumOp( + SparsePauliOp( + ["ZXZY", "IXIY", "IYIX", "ZYZX", "IYZX", "ZYIX", "ZXIY", "IXZY"], + coeffs=[ + -0.125 + 0.0j, + 0.125 + 0.0j, + -0.125 + 0.0j, + 0.125 + 0.0j, + 0.125 + 0.0j, + -0.125 + 0.0j, + 0.125 + 0.0j, + -0.125 + 0.0j, + ], + ), + coeff=1.0, ), - coeff=1.0, - ), - ] - self.initial_state = QuantumCircuit(QuantumRegister(4)) - self.initial_state.x(0) - self.initial_state.x(1) - self.ansatz = EvolvedOperatorAnsatz(self.excitation_pool, initial_state=self.initial_state) - self.optimizer = SLSQP() + ] + self.initial_state = QuantumCircuit(QuantumRegister(4)) + self.initial_state.x(0) + self.initial_state.x(1) + self.ansatz = EvolvedOperatorAnsatz(self.excitation_pool, initial_state=self.initial_state) + self.optimizer = SLSQP() + + self.assertTrue(len(caught_warnings) > 0) def test_default(self): """Default execution""" @@ -152,7 +160,7 @@ def test_maximum(self): def test_eigenvalue_threshold(self): """Test for the eigenvalue_threshold attribute.""" - operator = PauliSumOp.from_list( + operator = SparsePauliOp.from_list( [ ("XX", 1.0), ("ZX", -0.5), @@ -161,8 +169,8 @@ def test_eigenvalue_threshold(self): ) ansatz = EvolvedOperatorAnsatz( [ - PauliSumOp.from_list([("YZ", 0.4)]), - PauliSumOp.from_list([("ZY", 0.5)]), + SparsePauliOp.from_list([("YZ", 0.4)]), + SparsePauliOp.from_list([("ZY", 0.5)]), ], initial_state=QuantumCircuit(2), ) @@ -182,8 +190,14 @@ def test_threshold_attribute(self): VQE(Estimator(), self.ansatz, self.optimizer), threshold=1e-3, ) - res = calc.compute_minimum_eigenvalue(operator=self.h2_op) - + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + res = calc.compute_minimum_eigenvalue(operator=self.h2_op) + + self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res.termination_criterion, TerminationCriterion.CONVERGED) @data( @@ -236,13 +250,7 @@ def test_gradient_calculation(self): solver = VQE(Estimator(), QuantumCircuit(1), self.optimizer) calc = AdaptVQE(solver) calc._excitation_pool = [SparsePauliOp("X")] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - res = calc._compute_gradients(operator=SparsePauliOp("Y"), theta=[]) - self.assertTrue(len(caught_warnings) > 0) + res = calc._compute_gradients(operator=SparsePauliOp("Y"), theta=[]) # compare with manually computed reference value self.assertAlmostEqual(res[0][0], 2.0) From ccc6925c03f28a4d01521fffb04b7387c4e3e4d5 Mon Sep 17 00:00:00 2001 From: ElePT Date: Fri, 14 Apr 2023 17:58:38 +0200 Subject: [PATCH 30/47] Fix tests, lint Fix tests, lint Fix CI failures Fix tests CI Fix unit tests Fix CI again Fix lint Restore vqd test Remove unused import --- qiskit/opflow/gradients/derivative_base.py | 1 - qiskit/utils/quantum_instance.py | 17 +--- .../algorithms/eigensolvers/test_vqd.py | 67 ++++----------- .../minimum_eigensolvers/test_adapt_vqe.py | 4 +- .../minimum_eigensolvers/test_sampling_vqe.py | 17 +--- .../minimum_eigensolvers/test_vqe.py | 16 +--- test/python/algorithms/test_grover.py | 7 +- .../algorithms/test_observables_evaluator.py | 8 +- .../python/algorithms/test_phase_estimator.py | 5 +- .../time_evolvers/test_trotter_qrte.py | 8 +- .../variational/test_var_qite.py | 18 +--- .../variational/test_var_qrte.py | 17 +--- .../circuit/library/test_evolved_op_ansatz.py | 84 ++++++++----------- .../circuit/library/test_qaoa_ansatz.py | 1 - .../circuit/test_circuit_load_from_qpy.py | 14 +--- .../python/opflow/test_state_op_meas_evals.py | 12 +-- test/python/primitives/test_estimator.py | 1 - .../transpiler/test_swap_strategy_router.py | 1 - 18 files changed, 83 insertions(+), 215 deletions(-) diff --git a/qiskit/opflow/gradients/derivative_base.py b/qiskit/opflow/gradients/derivative_base.py index 9f2037cf5d45..9ffbc6f0cdf0 100644 --- a/qiskit/opflow/gradients/derivative_base.py +++ b/qiskit/opflow/gradients/derivative_base.py @@ -20,7 +20,6 @@ from qiskit.utils.quantum_instance import QuantumInstance from qiskit.circuit import ParameterExpression, ParameterVector from qiskit.providers import Backend -from qiskit.utils.deprecation import deprecate_func from ..converters.converter_base import ConverterBase from ..expectations import ExpectationBase, PauliExpectation from ..list_ops.composed_op import ComposedOp diff --git a/qiskit/utils/quantum_instance.py b/qiskit/utils/quantum_instance.py index df15fea66c73..a4bbb76e1b00 100644 --- a/qiskit/utils/quantum_instance.py +++ b/qiskit/utils/quantum_instance.py @@ -34,7 +34,6 @@ _get_backend_provider, _get_backend_interface_version, ) -from qiskit.utils.deprecation import deprecate_arg from qiskit.utils.mitigation import ( CompleteMeasFitter, TensoredMeasFitter, @@ -130,7 +129,7 @@ class QuantumInstance: _BACKEND_CONFIG = ["basis_gates", "coupling_map"] _COMPILE_CONFIG = ["initial_layout", "seed_transpiler", "optimization_level"] - _RUN_CONFIG = ["shots", "max_credits", "memory", "seed_simulator"] + _RUN_CONFIG = ["shots", "memory", "seed_simulator"] _QJOB_CONFIG = ["timeout", "wait"] _NOISE_CONFIG = ["noise_model"] @@ -149,21 +148,12 @@ class QuantumInstance: since="0.24.0", additional_msg="For code migration guidelines, visit https://qisk.it/qi_migration.", ) - @deprecate_arg( - "max_credits", - since="0.20.0", - additional_msg=( - "This parameter has no effect on modern IBM Quantum systems, and no " - "alternative is necessary." - ), - ) def __init__( self, backend, # run config shots: Optional[int] = None, seed_simulator: Optional[int] = None, - max_credits: int = None, # backend properties basis_gates: Optional[List[str]] = None, coupling_map=None, @@ -198,9 +188,6 @@ def __init__( shots: Number of repetitions of each circuit, for sampling. If None, the shots are extracted from the backend. If the backend has none set, the default is 1024. seed_simulator: Random seed for simulators - max_credits: DEPRECATED This parameter is deprecated as of - Qiskit Terra 0.20.0, and will be removed in a future release. This parameter has - no effect on modern IBM Quantum systems, and no alternative is necessary. basis_gates: List of basis gate names supported by the target. Defaults to basis gates of the backend. coupling_map (Optional[Union['CouplingMap', List[List]]]): @@ -279,7 +266,7 @@ def __init__( # pylint: disable=cyclic-import from qiskit.assembler.run_config import RunConfig - run_config = RunConfig(shots=shots, max_credits=max_credits) + run_config = RunConfig(shots=shots) if seed_simulator is not None: run_config.seed_simulator = seed_simulator diff --git a/test/python/algorithms/eigensolvers/test_vqd.py b/test/python/algorithms/eigensolvers/test_vqd.py index 6e8ad57efc66..95efa27f5968 100644 --- a/test/python/algorithms/eigensolvers/test_vqd.py +++ b/test/python/algorithms/eigensolvers/test_vqd.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022, 2023. +# (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 @@ -10,19 +10,22 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -"""Test VQD""" +""" Test VQD """ import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from ddt import data, ddt from qiskit import QuantumCircuit -from qiskit.algorithms.eigensolvers import VQD, VQDResult +from qiskit.algorithms.eigensolvers import VQD from qiskit.algorithms import AlgorithmError -from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA +from qiskit.algorithms.optimizers import ( + COBYLA, + L_BFGS_B, + SLSQP, +) from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import TwoLocal, RealAmplitudes from qiskit.opflow import PauliSumOp @@ -204,7 +207,6 @@ def store_intermediate_result(eval_count, parameters, mean, metadata, step): @data(H2_PAULI, H2_OP, H2_SPARSE_PAULI) def test_vqd_optimizer(self, op): """Test running same VQD twice to re-use optimizer, then switch optimizer""" - vqd = VQD( estimator=self.estimator, fidelity=self.fidelity, @@ -229,17 +231,6 @@ def run_check(): vqd.optimizer = L_BFGS_B() run_check() - with self.subTest("Batched optimizer replace"): - vqd.optimizer = SLSQP(maxiter=60, max_evals_grouped=10) - run_check() - - with self.subTest("SPSA replace"): - # SPSA takes too long to converge, so we will - # only check that it runs with no errors. - vqd.optimizer = SPSA(maxiter=5, learning_rate=0.01, perturbation=0.01) - result = vqd.compute_eigenvalues(operator=op) - self.assertIsInstance(result, VQDResult) - @data(H2_PAULI, H2_OP, H2_SPARSE_PAULI) def test_aux_operators_list(self, op): """Test list-based aux_operators.""" @@ -264,12 +255,7 @@ def test_aux_operators_list(self, op): aux_op1 = SparsePauliOp.from_list([("II", 2.0)]) aux_op2 = SparsePauliOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) aux_ops = [aux_op1, aux_op2] - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited[:2], decimal=2 ) @@ -283,12 +269,7 @@ def test_aux_operators_list(self, op): # Go again with additional None and zero operators extra_ops = [*aux_ops, None, 0] - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) + result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) np.testing.assert_array_almost_equal( result.eigenvalues.real, self.h2_energy_excited[:2], decimal=2 ) @@ -326,12 +307,7 @@ def test_aux_operators_dict(self, op): aux_op1 = SparsePauliOp.from_list([("II", 2.0)]) aux_op2 = SparsePauliOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) self.assertEqual(len(result.eigenvalues), 2) self.assertEqual(result.eigenvalues.dtype, np.complex128) self.assertAlmostEqual(result.eigenvalues[0], -1.85727503, 2) @@ -346,12 +322,7 @@ def test_aux_operators_dict(self, op): # Go again with additional None and zero operators extra_ops = {**aux_ops, "None_operator": None, "zero_operator": 0} - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) + result = vqd.compute_eigenvalues(op, aux_operators=extra_ops) self.assertEqual(len(result.eigenvalues), 2) self.assertEqual(result.eigenvalues.dtype, np.complex128) self.assertAlmostEqual(result.eigenvalues[0], -1.85727503, places=5) @@ -393,12 +364,7 @@ def test_aux_operator_std_dev(self, op): aux_op1 = SparsePauliOp.from_list([("II", 2.0)]) aux_op2 = SparsePauliOp.from_list([("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)]) aux_ops = [aux_op1, aux_op2] - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0][0], 2.0, places=1) @@ -411,12 +377,7 @@ def test_aux_operator_std_dev(self, op): # Go again with additional None and zero operators aux_ops = [*aux_ops, None, 0] - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) + result = vqd.compute_eigenvalues(op, aux_operators=aux_ops) self.assertEqual(len(result.aux_operators_evaluated[0]), 4) # expectation values self.assertAlmostEqual(result.aux_operators_evaluated[0][0][0], 2.0, places=1) diff --git a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py index aed3eb83044f..9cae7279fb45 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py @@ -90,7 +90,9 @@ def setUp(self): self.initial_state = QuantumCircuit(QuantumRegister(4)) self.initial_state.x(0) self.initial_state.x(1) - self.ansatz = EvolvedOperatorAnsatz(self.excitation_pool, initial_state=self.initial_state) + self.ansatz = EvolvedOperatorAnsatz( + self.excitation_pool, initial_state=self.initial_state + ) self.optimizer = SLSQP() self.assertTrue(len(caught_warnings) > 0) diff --git a/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py index dd129a065542..27cf6c46cfb0 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py @@ -13,7 +13,6 @@ """Test the Sampler VQE.""" import unittest -import warnings from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase @@ -206,13 +205,7 @@ def test_auxops(self, op): as_list = [Pauli("ZZ"), Pauli("II")] with self.subTest(auxops=as_list): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_list) - self.assertTrue(len(caught_warnings) > 0) + result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_list) self.assertIsInstance(result.aux_operators_evaluated, list) self.assertEqual(len(result.aux_operators_evaluated), 2) self.assertAlmostEqual(result.aux_operators_evaluated[0][0], -1 + 0j, places=5) @@ -220,13 +213,7 @@ def test_auxops(self, op): as_dict = {"magnetization": SparsePauliOp(["ZI", "IZ"])} with self.subTest(auxops=as_dict): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_dict) - self.assertTrue(len(caught_warnings) > 0) + result = vqe.compute_minimum_eigenvalue(op, aux_operators=as_dict) self.assertIsInstance(result.aux_operators_evaluated, dict) self.assertEqual(len(result.aux_operators_evaluated.keys()), 1) self.assertAlmostEqual(result.aux_operators_evaluated["magnetization"][0], 0j, places=5) diff --git a/test/python/algorithms/minimum_eigensolvers/test_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_vqe.py index 0fc5ddc4ab6e..222b616c07a3 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_vqe.py @@ -436,13 +436,7 @@ def test_aux_operators_list(self): with self.subTest("Test with additional zero operator."): extra_ops = [*aux_ops, 0] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) - self.assertTrue(len(caught_warnings) > 0) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values @@ -489,13 +483,7 @@ def test_aux_operators_dict(self): with self.subTest("Test with additional zero operator."): extra_ops = {**aux_ops, "zero_operator": 0} - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) - self.assertTrue(len(caught_warnings) > 0) + result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=extra_ops) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 3) # expectation values diff --git a/test/python/algorithms/test_grover.py b/test/python/algorithms/test_grover.py index b77bd190fa28..5f8adea010e2 100644 --- a/test/python/algorithms/test_grover.py +++ b/test/python/algorithms/test_grover.py @@ -143,7 +143,12 @@ def test_iterations_with_good_state_sample_from_iterations(self, use_sampler, it """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations, sample_from_iterations=True) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - result = grover.amplify(problem) + with warnings.catch_warnings(record=True): + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @data("ideal", "shots", False) diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index f454f3de1702..4edf619fa212 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -152,13 +152,7 @@ def test_estimate_observables_zero_op(self): state = bound_ansatz estimator = Estimator() observables = [SparsePauliOp(["XX", "YY"]), 0] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = estimate_observables(estimator, state, observables, None, self.threshold) - self.assertTrue(len(caught_warnings) > 0) + result = estimate_observables(estimator, state, observables, None, self.threshold) expected_result = [(0.015607318055509564, {}), (0.0, {})] means = [element[0] for element in result] expected_means = [element[0] for element in expected_result] diff --git a/test/python/algorithms/test_phase_estimator.py b/test/python/algorithms/test_phase_estimator.py index 0e5a872c1d24..1a2e981606d7 100644 --- a/test/python/algorithms/test_phase_estimator.py +++ b/test/python/algorithms/test_phase_estimator.py @@ -35,7 +35,6 @@ Y, Z, I, - T, StateFn, PauliTrotterEvolution, MatrixEvolution, @@ -644,7 +643,9 @@ def test_qpe_RZ_sampler(self, state_preparation, expected_phase, phase_estimator @unpack def test_qpe_two_qubit_unitary(self, state_preparation, expected_phase, phase_estimator): """two qubit unitary T ^ T""" - unitary_circuit = (T ^ T).to_circuit() + unitary_circuit = QuantumCircuit(2) + unitary_circuit.t(0) + unitary_circuit.t(1) phase = self.one_phase_sampler( unitary_circuit, state_preparation, diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index 727900ab7b41..b460fafea761 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -102,13 +102,7 @@ def test_trotter_qrte_trotter(self, operator, t_param): algorithm_globals.random_seed = 0 trotter_qrte = TrotterQRTE(estimator=estimator, num_timesteps=num_timesteps) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evolution_result = trotter_qrte.evolve(evolution_problem) - self.assertTrue(len(caught_warnings) > 0) + evolution_result = trotter_qrte.evolve(evolution_problem) np.testing.assert_array_almost_equal( Statevector.from_instruction(evolution_result.evolved_state).data, diff --git a/test/python/algorithms/time_evolvers/variational/test_var_qite.py b/test/python/algorithms/time_evolvers/variational/test_var_qite.py index 2f4d7a08c674..636798d7947e 100644 --- a/test/python/algorithms/time_evolvers/variational/test_var_qite.py +++ b/test/python/algorithms/time_evolvers/variational/test_var_qite.py @@ -13,7 +13,6 @@ """Test Variational Quantum Imaginary Time Evolution algorithm.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt import numpy as np @@ -100,13 +99,8 @@ def test_run_d_1_with_aux_ops(self): var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evolution_result = var_qite.evolve(evolution_problem) - self.assertTrue(len(caught_warnings) > 0) + + evolution_result = var_qite.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] @@ -133,13 +127,7 @@ def test_run_d_1_with_aux_ops(self): var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evolution_result = var_qite.evolve(evolution_problem) - self.assertTrue(len(caught_warnings) > 0) + evolution_result = var_qite.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] diff --git a/test/python/algorithms/time_evolvers/variational/test_var_qrte.py b/test/python/algorithms/time_evolvers/variational/test_var_qrte.py index f5f5724f6d4f..1682c60b842b 100644 --- a/test/python/algorithms/time_evolvers/variational/test_var_qrte.py +++ b/test/python/algorithms/time_evolvers/variational/test_var_qrte.py @@ -13,7 +13,6 @@ """Test Variational Quantum Real Time Evolution algorithm.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt @@ -131,13 +130,7 @@ def test_run_d_1_with_aux_ops(self): var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evolution_result = var_qrte.evolve(evolution_problem) - self.assertTrue(len(caught_warnings) > 0) + evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] @@ -164,13 +157,7 @@ def test_run_d_1_with_aux_ops(self): var_qrte = VarQRTE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evolution_result = var_qrte.evolve(evolution_problem) - self.assertTrue(len(caught_warnings) > 0) + evolution_result = var_qrte.evolve(evolution_problem) aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] diff --git a/test/python/circuit/library/test_evolved_op_ansatz.py b/test/python/circuit/library/test_evolved_op_ansatz.py index 0e7dddf50602..00e3b09623d2 100644 --- a/test/python/circuit/library/test_evolved_op_ansatz.py +++ b/test/python/circuit/library/test_evolved_op_ansatz.py @@ -33,29 +33,25 @@ class TestEvolvedOperatorAnsatz(QiskitTestCase): def test_evolved_op_ansatz(self, use_opflow): """Test the default evolution.""" num_qubits = 3 - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - ops = [Z ^ num_qubits, Y ^ num_qubits, X ^ num_qubits] - strings = ["z" * num_qubits, "y" * num_qubits, "x" * num_qubits] * 2 - evo = EvolvedOperatorAnsatz(ops, 2) - reference = QuantumCircuit(num_qubits) - parameters = evo.parameters - self.assertTrue(len(caught_warnings) > 0) - if use_opflow: - ops = [Z ^ num_qubits, Y ^ num_qubits, X ^ num_qubits] - else: - ops = [Pauli("Z" * num_qubits), Pauli("Y" * num_qubits), Pauli("X" * num_qubits)] + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + ops = [Z ^ num_qubits, Y ^ num_qubits, X ^ num_qubits] + evo = EvolvedOperatorAnsatz(ops, 2) + parameters = evo.parameters - strings = ["z" * num_qubits, "y" * num_qubits, "x" * num_qubits] * 2 + self.assertTrue(len(caught_warnings) > 0) - evo = EvolvedOperatorAnsatz(ops, 2) + else: + ops = [Pauli("Z" * num_qubits), Pauli("Y" * num_qubits), Pauli("X" * num_qubits)] + evo = EvolvedOperatorAnsatz(ops, 2) + parameters = evo.parameters reference = QuantumCircuit(num_qubits) - parameters = evo.parameters + strings = ["z" * num_qubits, "y" * num_qubits, "x" * num_qubits] * 2 for string, time in zip(strings, parameters): reference.compose(evolve(string, time), inplace=True) @@ -65,16 +61,25 @@ def test_evolved_op_ansatz(self, use_opflow): def test_custom_evolution(self, use_opflow): """Test using another evolution than the default (e.g. matrix evolution).""" if use_opflow: - op = X ^ I ^ Z - matrix = op.to_matrix() - evolution = MatrixEvolution() + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + op = X ^ I ^ Z + matrix = op.to_matrix() + evolution = MatrixEvolution() + evo = EvolvedOperatorAnsatz(op, evolution=evolution) + parameters = evo.parameters + + self.assertTrue(len(caught_warnings) > 0) + else: op = SparsePauliOp(["ZIX"]) matrix = np.array(op) evolution = MatrixExponential() - - evo = EvolvedOperatorAnsatz(op, evolution=evolution) - parameters = evo.parameters + evo = EvolvedOperatorAnsatz(op, evolution=evolution) + parameters = evo.parameters reference = QuantumCircuit(3) reference.hamiltonian(matrix, parameters[0], [0, 1, 2]) @@ -107,14 +112,8 @@ def test_changing_operators(self): def test_invalid_reps(self): """Test setting an invalid number of reps.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - with self.assertRaises(ValueError): - _ = EvolvedOperatorAnsatz(X, reps=-1) - self.assertTrue(len(caught_warnings) > 0) + with self.assertRaises(ValueError): + _ = EvolvedOperatorAnsatz(X, reps=-1) def test_insert_barriers(self): """Test using insert_barriers.""" @@ -125,28 +124,15 @@ def test_insert_barriers(self): ) evo = EvolvedOperatorAnsatz(Z, reps=4, insert_barriers=True) ref = QuantumCircuit(1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - for parameter in evo.parameters: - ref.rz(2.0 * parameter, 0) - ref.barrier() - self.assertTrue(len(caught_warnings) > 0) - + for parameter in evo.parameters: + ref.rz(2.0 * parameter, 0) + ref.barrier() self.assertEqual(evo.decompose(), ref) self.assertTrue(len(caught_warnings) > 0) def test_empty_build_fails(self): """Test setting no operators to evolve raises the appropriate error.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo = EvolvedOperatorAnsatz() - self.assertTrue(len(caught_warnings) > 0) + evo = EvolvedOperatorAnsatz() with self.assertRaises(ValueError): _ = evo.draw() diff --git a/test/python/circuit/library/test_qaoa_ansatz.py b/test/python/circuit/library/test_qaoa_ansatz.py index 94d190259e89..dfbf25da69d4 100644 --- a/test/python/circuit/library/test_qaoa_ansatz.py +++ b/test/python/circuit/library/test_qaoa_ansatz.py @@ -12,7 +12,6 @@ """Test QAOA ansatz from the library.""" -import warnings import numpy as np from ddt import ddt, data diff --git a/test/python/circuit/test_circuit_load_from_qpy.py b/test/python/circuit/test_circuit_load_from_qpy.py index 7ed64b0c0678..29f4e2599213 100644 --- a/test/python/circuit/test_circuit_load_from_qpy.py +++ b/test/python/circuit/test_circuit_load_from_qpy.py @@ -16,7 +16,6 @@ import io import json import random -import warnings import numpy as np @@ -698,16 +697,9 @@ def test_qaoa(self): def test_evolutiongate(self): """Test loading a circuit with evolution gate works.""" synthesis = LieTrotter(reps=2) - # To be removed once PauliEvolutionGate drops support for opflow - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - evo = PauliEvolutionGate( - SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=2, synthesis=synthesis - ) - self.assertTrue(len(caught_warnings) > 0) + evo = PauliEvolutionGate( + SparsePauliOp.from_list([("ZI", 1), ("IZ", 1)]), time=2, synthesis=synthesis + ) qc = QuantumCircuit(2) qc.append(evo, range(2)) diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index da84d504242a..7f44c1c0b865 100644 --- a/test/python/opflow/test_state_op_meas_evals.py +++ b/test/python/opflow/test_state_op_meas_evals.py @@ -148,16 +148,16 @@ def test_parameter_binding_on_listop(self): circuit3 = QuantumCircuit(1) circuit3.p(y, 0) - bindings = {x: -0.4, y: 0.4} - listop = ListOp([StateFn(circuit) for circuit in [circuit1, circuit2, circuit3]]) - - sampler = CircuitSampler(Aer.get_backend("aer_simulator")) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) + bindings = {x: -0.4, y: 0.4} + listop = ListOp([StateFn(circuit) for circuit in [circuit1, circuit2, circuit3]]) + sampler = CircuitSampler(Aer.get_backend("aer_simulator")) sampled = sampler.convert(listop, params=bindings) + self.assertTrue(len(caught_warnings) > 0) self.assertTrue(all(len(op.parameters) == 0 for op in sampled.oplist)) @@ -186,12 +186,12 @@ def test_single_parameter_binds(self): circuit.ry(x, 0) expr = ~StateFn(H) @ StateFn(circuit) - sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector")) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) + sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector")) res = sampler.convert(expr, params={x: 0}).eval() self.assertTrue(len(caught_warnings) > 0) @@ -267,12 +267,12 @@ def test_quantum_instance_with_backend_shots(self): self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") backend = AerSimulator(shots=10) - sampler = CircuitSampler(backend) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) + sampler = CircuitSampler(backend) res = sampler.convert(~Plus @ Plus).eval() self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(res, 1 + 0j, places=2) diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index 5cab8a171256..73f20f449d71 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -13,7 +13,6 @@ """Tests for Estimator.""" import unittest -import warnings import numpy as np from ddt import data, ddt, unpack diff --git a/test/python/transpiler/test_swap_strategy_router.py b/test/python/transpiler/test_swap_strategy_router.py index 9c234cd63e2c..67f746d66724 100644 --- a/test/python/transpiler/test_swap_strategy_router.py +++ b/test/python/transpiler/test_swap_strategy_router.py @@ -12,7 +12,6 @@ """Tests for swap strategy routers.""" -import warnings from ddt import ddt, data from qiskit.circuit import QuantumCircuit, Qubit, QuantumRegister From bd9090f9b262113bbbc26b87719ead61ce379ac8 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 10:31:35 +0200 Subject: [PATCH 31/47] Delete qobj test to fix CI until #9322 is merged --- test/python/qobj/test_qobj_deprecated.py | 69 ------------------------ 1 file changed, 69 deletions(-) delete mode 100644 test/python/qobj/test_qobj_deprecated.py diff --git a/test/python/qobj/test_qobj_deprecated.py b/test/python/qobj/test_qobj_deprecated.py deleted file mode 100644 index be1f57b3068d..000000000000 --- a/test/python/qobj/test_qobj_deprecated.py +++ /dev/null @@ -1,69 +0,0 @@ -# This code is part of Qiskit. -# -# (C) Copyright IBM 2017, 2018. -# -# 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. - - -"""Qobj tests.""" - - -from qiskit import QuantumCircuit, execute, BasicAer -from qiskit.compiler import assemble -from qiskit.qobj import PulseQobjConfig, PulseLibraryItem, QasmQobjConfig -from qiskit.test import QiskitTestCase -from qiskit.utils import QuantumInstance - - -class TestMaxCreditsDeprecated(QiskitTestCase): - """Tests for max_credits deprecation.""" - - def test_assemble_warns(self): - """Test that assemble function displays a deprecation warning if max_credits is used""" - circuit = QuantumCircuit(1, 1) - with self.assertWarns(DeprecationWarning): - assemble(circuit, max_credits=10) - - def test_execute_warns(self): - """Test that execute function displays a deprecation warning if max_credits is used""" - backend = BasicAer.get_backend("statevector_simulator") - circuit = QuantumCircuit(1, 1) - with self.assertWarns(DeprecationWarning): - execute(circuit, backend, max_credits=10) - - def test_qasm_obj_config_warns(self): - """Test that QasmQobjConfig constructor displays a deprecation - warning if max_credits is used""" - with self.assertWarns(DeprecationWarning): - QasmQobjConfig(shots=1024, memory_slots=2, max_credits=10) - - def test_quantum_instance_warns(self): - """Test that QuantumInstance constructor displays a deprecation - warning if max_credits is used""" - with self.assertWarns(DeprecationWarning): - QuantumInstance(BasicAer.get_backend("statevector_simulator"), max_credits=10) - - def test_pulse_obj_config_warns(self): - """Test that PulseQobjConfig constructor displays a deprecation - warning if max_credits is used""" - with self.assertWarns(DeprecationWarning): - PulseQobjConfig( - shots=1024, - memory_slots=2, - max_credits=10, - meas_level=1, - memory_slot_size=8192, - meas_return="avg", - pulse_library=[ - PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j]) - ], - qubit_lo_freq=[4.9], - meas_lo_freq=[6.9], - rep_time=1000, - ) From 9c0a37f3bc3068a9b1ccd122298cfefe556d4135 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 14:02:35 +0200 Subject: [PATCH 32/47] Refactor gradients test warnings --- test/python/opflow/test_gradients.py | 601 +++++++++++++-------------- 1 file changed, 293 insertions(+), 308 deletions(-) diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 374631bd65cc..48266c78dea6 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -15,7 +15,6 @@ import unittest from test.python.opflow import QiskitOpflowTestCase -import warnings from itertools import product import numpy as np from ddt import ddt, data, idata, unpack @@ -68,16 +67,18 @@ def test_gradient_p(self, method): Tr(|psi>/da = - 0.5 sin(a) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-0.5 / np.sqrt(2), 0, -0.5] @@ -103,9 +104,11 @@ def test_gradient_u(self, method): qc.h(q) qc.u(a, b, c, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a, b, c] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4, b: 0, c: 0}, {a: np.pi / 4, b: np.pi / 4, c: np.pi / 4}] correct_values = [[0.3536, 0, 0], [0.3232, -0.42678, -0.92678]] for i, value_dict in enumerate(values_dict): @@ -122,9 +125,11 @@ def test_gradient_u(self, method): qc.h(q) qc.u(a, a, a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-1.03033], [-1]] for i, value_dict in enumerate(values_dict): @@ -135,16 +140,18 @@ def test_gradient_u(self, method): @data("lin_comb", "param_shift") def test_gradient_efficient_su2(self, method): """Test the state gradient for EfficientSU2""" - observable = SummedOp( - [ - 0.2252 * (I ^ I), - 0.5716 * (Z ^ Z), - 0.3435 * (I ^ Z), - -0.4347 * (Z ^ I), - 0.091 * (Y ^ Y), - 0.091 * (X ^ X), - ] - ).reduce() + + with self.assertWarns(DeprecationWarning): + observable = SummedOp( + [ + 0.2252 * (I ^ I), + 0.5716 * (Z ^ Z), + 0.3435 * (I ^ Z), + -0.4347 * (Z ^ I), + 0.091 * (Y ^ Y), + 0.091 * (X ^ X), + ] + ).reduce() d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) @@ -152,7 +159,8 @@ def test_gradient_efficient_su2(self, method): # Define a set of initial parameters parameters = ansatz.ordered_parameters - operator = ~StateFn(observable) @ StateFn(ansatz) + with self.assertWarns(DeprecationWarning): + operator = ~StateFn(observable) @ StateFn(ansatz) values_dict = [ {param: np.pi / 4 for param in parameters}, @@ -189,7 +197,9 @@ def test_gradient_efficient_su2(self, method): ], ] - state_grad = Gradient(method).convert(operator, parameters) + with self.assertWarns(DeprecationWarning): + state_grad = Gradient(method).convert(operator, parameters) + for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 @@ -198,7 +208,6 @@ def test_gradient_efficient_su2(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rxx(self, method): """Test the state gradient for XX rotation""" - ham = TensoredOp([Z, X]) a = Parameter("a") q = QuantumRegister(2) @@ -206,9 +215,12 @@ def test_gradient_rxx(self, method): qc.h(q[0]) qc.rxx(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = TensoredOp([Z, X]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): @@ -220,15 +232,17 @@ def test_gradient_rxx(self, method): def test_gradient_ryy(self, method): """Test the state gradient for YY rotation""" alpha = Parameter("alpha") - ham = TensoredOp([Y, alpha * Y]) a = Parameter("a") q = QuantumRegister(2) qc = QuantumCircuit(q) qc.ryy(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=a) + with self.assertWarns(DeprecationWarning): + ham = TensoredOp([Y, alpha * Y]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=a) + values_dict = [{a: np.pi / 8}, {a: np.pi}] correct_values = [[0], [0]] for i, value_dict in enumerate(values_dict): @@ -240,7 +254,6 @@ def test_gradient_ryy(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzz(self, method): """Test the state gradient for ZZ rotation""" - ham = Z ^ X a = Parameter("a") q = QuantumRegister(2) @@ -248,9 +261,12 @@ def test_gradient_rzz(self, method): qc.h(q[0]) qc.rzz(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = Z ^ X + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): @@ -261,7 +277,6 @@ def test_gradient_rzz(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzx(self, method): """Test the state gradient for ZX rotation""" - ham = Z ^ Z a = Parameter("a") q = QuantumRegister(2) @@ -269,9 +284,12 @@ def test_gradient_rzx(self, method): qc.h(q) qc.rzx(a, q[0], q[1]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = Z ^ Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 8}, {a: np.pi / 2}] correct_values = [[0.0], [0.0]] for i, value_dict in enumerate(values_dict): @@ -289,7 +307,6 @@ def test_state_gradient1(self, method): d/db = - 1 sin(a)cos(b) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] @@ -299,9 +316,12 @@ def test_state_gradient1(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -326,7 +346,6 @@ def test_state_gradient2(self, method): Tr(|psi>/da = - 0.5 sin(a) - 2 cos(a)sin(a) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = [a] @@ -336,9 +355,12 @@ def test_state_gradient2(self, method): qc.h(q) qc.rz(a, q[0]) qc.rx(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.353553, -0, -0.5] @@ -355,7 +377,6 @@ def test_state_gradient3(self, method): Tr(|psi>/da = - 0.5 sin(a) - 1 cos(a)sin(cos(a)+1) + 1 sin^2(a)cos(cos(a)+1) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = a @@ -365,9 +386,12 @@ def test_state_gradient3(self, method): qc.h(q) qc.rz(a, q[0]) qc.rx(c, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.1220, -0.9093, 0.0403] for i, value_dict in enumerate(values_dict): @@ -382,7 +406,6 @@ def test_state_gradient4(self, method): daTr(|psi>/da1 = - 1 sin(a0)cos(a1) """ - ham = 0.5 * X - 1 * Z a = ParameterVector("a", 2) params = a @@ -421,9 +446,12 @@ def test_state_gradient5(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + values_dict = [ {a: [np.pi / 4, np.pi]}, {a: [np.pi / 4, np.pi / 4]}, @@ -452,7 +480,6 @@ def test_state_hessian(self, method): d^2/db^2 = + 1 sin(a)sin(b) """ - ham = 0.5 * X - 1 * Z params = ParameterVector("a", 2) q = QuantumRegister(1) @@ -461,8 +488,10 @@ def test_state_hessian(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_hess = Hessian(hess_method=method).convert(operator=op) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_hess = Hessian(hess_method=method).convert(operator=op) values_dict = [ {params[0]: np.pi / 4, params[1]: np.pi}, @@ -492,7 +521,6 @@ def test_state_hessian_custom_combo_fn(self, method): d^2/db^2 = + 1 sin(a)sin(b) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [(a, a), (a, b), (b, b)] @@ -503,11 +531,13 @@ def test_state_hessian_custom_combo_fn(self, method): qc.rz(a, q[0]) qc.rx(b, q[0]) - op = ListOp( - [~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)], - combo_fn=lambda x: x[0] ** 3 + 4 * x[0], - ) - state_hess = Hessian(hess_method=method).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ListOp( + [~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)], + combo_fn=lambda x: x[0] ** 3 + 4 * x[0], + ) + state_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, @@ -546,9 +576,10 @@ def test_prob_grad(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) - prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: 0}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -585,9 +616,10 @@ def test_prob_hess(self, method): qc.rz(a, q[0]) qc.rx(b, q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_hess = Hessian(hess_method=method).convert(operator=op, params=params) - prob_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4, b: 0}, {a: np.pi / 4, b: np.pi / 4}, {a: np.pi / 2, b: np.pi}] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], @@ -611,7 +643,6 @@ def test_natural_gradient(self, method, regularization): """Test the natural gradient""" try: for params in (ParameterVector("a", 2), [Parameter("a"), Parameter("b")]): - ham = 0.5 * X - 1 * Z q = QuantumRegister(1) qc = QuantumCircuit(q) @@ -619,10 +650,13 @@ def test_natural_gradient(self, method, regularization): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - nat_grad = NaturalGradient( - grad_method=method, regularization=regularization - ).convert(operator=op) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + nat_grad = NaturalGradient( + grad_method=method, regularization=regularization + ).convert(operator=op) + values_dict = [{params[0]: np.pi / 4, params[1]: np.pi / 2}] # reference values obtained by classically computing the natural gradients @@ -649,7 +683,9 @@ def test_natural_gradient2(self): @unpack def test_natural_gradient3(self, qfi_method, circuit_qfi): """Test the natural gradient 3""" - nat_grad = NaturalGradient(qfi_method=qfi_method) + with self.assertWarns(DeprecationWarning): + nat_grad = NaturalGradient(qfi_method=qfi_method) + self.assertIsInstance(nat_grad.qfi_method, circuit_qfi) @idata( @@ -665,7 +701,6 @@ def test_natural_gradient4(self, grad_method, qfi_method, regularization): # Avoid regularization = lasso intentionally because it does not converge try: - ham = 0.5 * X - 1 * Z a = Parameter("a") params = a @@ -674,10 +709,13 @@ def test_natural_gradient4(self, grad_method, qfi_method, regularization): qc.h(q) qc.rz(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - nat_grad = NaturalGradient( - grad_method=grad_method, qfi_method=qfi_method, regularization=regularization - ).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + nat_grad = NaturalGradient( + grad_method=grad_method, qfi_method=qfi_method, regularization=regularization + ).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}] correct_values = [[0.0]] if regularization == "ridge" else [[-1.41421342]] for i, value_dict in enumerate(values_dict): @@ -693,16 +731,18 @@ def test_gradient_p_imag(self): = iexp(-ia)/2 <1|H(|0>+exp(ia)|1>) Im() = 0.5 cos(a). """ - ham = X a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params) + with self.assertWarns(DeprecationWarning): + ham = X + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params) + values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [1 / np.sqrt(2), 1, 0] @@ -718,7 +758,6 @@ def test_qfi_p_imag(self): circuit = QuantumCircuit(1) circuit.ry(y, 0) circuit.rx(x, 0) - state = StateFn(circuit) dx = ( lambda x, y: (-1) @@ -745,9 +784,12 @@ def test_qfi_p_imag(self): ) ) - state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert( - operator=state, params=[x, y] - ) + with self.assertWarns(DeprecationWarning): + state = StateFn(circuit) + state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert( + operator=state, params=[x, y] + ) + values_dict = [{x: 0, y: np.pi / 4}, {x: 0, y: np.pi / 2}, {x: np.pi / 2, y: 0}] for value_dict in values_dict: @@ -799,16 +841,18 @@ def combo_fn(x): def grad_combo_fn(x): return np.array([2 * x[0], -np.sin(x[1])]) - op = ListOp( - [ - ~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0), - ~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0), - ], - combo_fn=combo_fn, - grad_combo_fn=None if autograd else grad_combo_fn, - ) + with self.assertWarns(DeprecationWarning): + + op = ListOp( + [ + ~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0), + ~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0), + ], + combo_fn=combo_fn, + grad_combo_fn=None if autograd else grad_combo_fn, + ) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -839,8 +883,11 @@ def grad_combo_fn(x): return grad qc = RealAmplitudes(2, reps=1) - grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn) - grad = Gradient(grad_method=method).convert(grad_op) + + with self.assertWarns(DeprecationWarning): + grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn) + grad = Gradient(grad_method=method).convert(grad_op) + value_dict = dict(zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters)))) correct_values = [ [(-0.16666259133549044 + 0j)], @@ -871,12 +918,14 @@ def grad_combo_fn(x): try: qc = RealAmplitudes(2, reps=1) - grad_op = ListOp( - [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn - ) - grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert( - grad_op, qc.ordered_parameters - ) + + with self.assertWarns(DeprecationWarning): + grad_op = ListOp( + [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn + ) + grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert( + grad_op, qc.ordered_parameters + ) value_dict = dict( zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters))) ) @@ -904,10 +953,13 @@ def test_operator_coefficient_gradient(self, method): coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") - ham = coeff_0 * X + coeff_1 * Z - op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) - gradient_coeffs = [coeff_0, coeff_1] - coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs) + + with self.assertWarns(DeprecationWarning): + ham = coeff_0 * X + coeff_1 * Z + op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) + gradient_coeffs = [coeff_0, coeff_1] + coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs) + values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, @@ -941,10 +993,13 @@ def test_operator_coefficient_hessian(self, method): coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") - ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z - op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) - gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)] - coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs) + + with self.assertWarns(DeprecationWarning): + ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z + op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) + gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)] + coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs) + values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, @@ -967,7 +1022,6 @@ def test_circuit_sampler(self, method): d/db = - 1 sin(a)cos(b) """ - ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] @@ -977,16 +1031,19 @@ def test_circuit_sampler(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - shots = 8000 - if method == "fin_diff": - np.random.seed(8) - state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( - operator=op - ) - else: - state_grad = Gradient(grad_method=method).convert(operator=op) + with self.assertWarns(DeprecationWarning): + ham = 0.5 * X - 1 * Z + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + shots = 8000 + if method == "fin_diff": + np.random.seed(8) + state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( + operator=op + ) + else: + state_grad = Gradient(grad_method=method).convert(operator=op) + values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -999,19 +1056,10 @@ def test_circuit_sampler(self, method): ] backend = BasicAer.get_backend("qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for i, value_dict in enumerate(values_dict): sampler = CircuitSampler(backend=q_instance).convert( state_grad, params={k: [v] for k, v in value_dict.items()} @@ -1019,7 +1067,6 @@ def test_circuit_sampler(self, method): np.testing.assert_array_almost_equal( sampler.eval()[0], correct_values[i], decimal=1 ) - self.assertTrue(len(caught_warnings) > 0) @data("lin_comb", "param_shift", "fin_diff") def test_circuit_sampler2(self, method): @@ -1041,16 +1088,17 @@ def test_circuit_sampler2(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + shots = 8000 + if method == "fin_diff": + np.random.seed(8) + prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( + operator=op, params=params + ) + else: + prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) - shots = 8000 - if method == "fin_diff": - np.random.seed(8) - prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( - operator=op, params=params - ) - else: - prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: [np.pi / 4], b: [0]}, {params[0]: [np.pi / 4], params[1]: [np.pi / 4]}, @@ -1063,25 +1111,15 @@ def test_circuit_sampler2(self, method): ] backend = BasicAer.get_backend("qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for i, value_dict in enumerate(values_dict): sampler = CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict) result = sampler.eval()[0] self.assertTrue(np.allclose(result[0].toarray(), correct_values[i][0], atol=0.1)) self.assertTrue(np.allclose(result[1].toarray(), correct_values[i][1], atol=0.1)) - self.assertTrue(len(caught_warnings) > 0) @idata(["statevector_simulator", "qasm_simulator"]) def test_gradient_wrapper(self, backend_type): @@ -1102,34 +1140,25 @@ def test_gradient_wrapper(self, backend_type): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 backend = BasicAer.get_backend(backend_type) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) - self.assertTrue(len(caught_warnings) > 0) - if method == "fin_diff": - np.random.seed(8) - prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( - operator=op, bind_params=params, backend=q_instance - ) - else: - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - prob_grad = Gradient(grad_method=method).gradient_wrapper( + with self.assertWarns(DeprecationWarning): + if method == "fin_diff": + np.random.seed(8) + prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) - self.assertTrue(len(caught_warnings) > 0) + else: + prob_grad = Gradient(grad_method=method).gradient_wrapper( + operator=op, bind_params=params, backend=q_instance + ) values = [[np.pi / 4, 0], [np.pi / 4, np.pi / 4], [np.pi / 2, np.pi]] correct_values = [ @@ -1137,11 +1166,7 @@ def test_gradient_wrapper(self, backend_type): [[1 / 4, -1 / 4], [1 / 4, -1 / 4]], [[0, 0], [-1 / 2, 1 / 2]], ] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for i, value in enumerate(values): result = prob_grad(value) if backend_type == "qasm_simulator": # sparse result @@ -1149,7 +1174,6 @@ def test_gradient_wrapper(self, backend_type): self.assertTrue(np.allclose(result[0], correct_values[i][0], atol=0.1)) self.assertTrue(np.allclose(result[1], correct_values[i][1], atol=0.1)) - self.assertTrue(len(caught_warnings) > 0) @data(("statevector_simulator", 1e-7), ("qasm_simulator", 2e-1)) @unpack @@ -1176,35 +1200,27 @@ def test_gradient_wrapper2(self, backend_type, atol): qc.rz(params[1], 0) qc.h(1) - obs = (Z ^ X) - (Y ^ Y) - op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) + with self.assertWarns(DeprecationWarning): + obs = (Z ^ X) - (Y ^ Y) + op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) shots = 8192 if backend_type == "qasm_simulator" else 1 values = [[0, np.pi / 2], [np.pi / 4, np.pi / 4], [np.pi / 3, np.pi / 9]] correct_values = [[-4.0, 0], [-2.0, -4.82842712], [-0.68404029, -7.01396121]] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - for i, value in enumerate(values): - backend = BasicAer.get_backend(backend_type) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - q_instance = QuantumInstance( - backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 - ) - self.assertTrue(len(caught_warnings) > 0) + + for i, value in enumerate(values): + backend = BasicAer.get_backend(backend_type) + with self.assertWarns(DeprecationWarning): + q_instance = QuantumInstance( + backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 + ) + with self.assertWarns(DeprecationWarning): grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) result = grad(value) - self.assertTrue(np.allclose(result, correct_values[i], atol=atol)) - self.assertTrue(len(caught_warnings) > 0) + self.assertTrue(np.allclose(result, correct_values[i], atol=atol)) @slow_test def test_vqe(self): @@ -1212,19 +1228,14 @@ def test_vqe(self): method = "lin_comb" backend = "qasm_simulator" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2 ) - self.assertTrue(len(caught_warnings) > 0) - # Define the Hamiltonian - h2_hamiltonian = ( - -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) - ) + # Define the Hamiltonian + h2_hamiltonian = ( + -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) + ) h2_energy = -1.85727503 # Define the Ansatz @@ -1241,22 +1252,17 @@ def test_vqe(self): wavefunction.rz(next(itr), 0) wavefunction.rz(next(itr), 1) - # Conjugate Gradient algorithm - optimizer = CG(maxiter=10) - - grad = Gradient(grad_method=method) + with self.assertWarns(DeprecationWarning): + # Conjugate Gradient algorithm + optimizer = CG(maxiter=10) + grad = Gradient(grad_method=method) # Gradient callable - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): vqe = VQE( ansatz=wavefunction, optimizer=optimizer, gradient=grad, quantum_instance=q_instance ) result = vqe.compute_minimum_eigenvalue(operator=h2_hamiltonian) - self.assertTrue(len(caught_warnings) > 0) np.testing.assert_almost_equal(result.optimal_value, h2_energy, decimal=0) def test_qfi_overlap_works_with_bound_parameters(self): @@ -1266,15 +1272,18 @@ def test_qfi_overlap_works_with_bound_parameters(self): circuit = QuantumCircuit(1) circuit.ry(np.pi / 4, 0) circuit.rx(x, 0) - state = StateFn(circuit) + + with self.assertWarns(DeprecationWarning): + state = StateFn(circuit) methods = ["lin_comb_full", "overlap_diag", "overlap_block_diag"] reference = 0.5 for method in methods: with self.subTest(method): - qfi = QFI(method) - value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval()) + with self.assertWarns(DeprecationWarning): + qfi = QFI(method) + value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval()) self.assertAlmostEqual(value[0][0], reference) @@ -1336,9 +1345,10 @@ def test_qfi_simple(self, method): qc.rz(a, 0) qc.rx(b, 0) - # convert the circuit to a QFI object - op = CircuitStateFn(qc) - qfi = QFI(qfi_method=method).convert(operator=op) + with self.assertWarns(DeprecationWarning): + # convert the circuit to a QFI object + op = CircuitStateFn(qc) + qfi = QFI(qfi_method=method).convert(operator=op) # test for different values values_dict = [{a: np.pi / 4, b: 0.1}, {a: np.pi, b: 0.1}, {a: np.pi / 2, b: 0.1}] @@ -1360,15 +1370,17 @@ def test_qfi_phase_fix(self): qc.rz(a, 0) qc.rx(b, 0) - # convert the circuit to a QFI object - op = CircuitStateFn(qc) - qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b]) + with self.assertWarns(DeprecationWarning): + # convert the circuit to a QFI object + op = CircuitStateFn(qc) + qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b]) # test for different values value_dict = {a: np.pi / 4, b: 0.1} correct_values = [[1, 0], [0, 1]] - actual = qfi.assign_parameters(value_dict).eval() + with self.assertWarns(DeprecationWarning): + actual = qfi.assign_parameters(value_dict).eval() np.testing.assert_array_almost_equal(actual, correct_values, decimal=2) def test_qfi_maxcut(self): @@ -1405,9 +1417,10 @@ def expiz(qubit0, qubit1): # reference computed via finite difference reference = np.array([[16.0, -5.551], [-5.551, 18.497]]) - # QFI from gradient framework - qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:]) - actual = np.array(qfi.bind_parameters(point).eval()).real + with self.assertWarns(DeprecationWarning): + # QFI from gradient framework + qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:]) + actual = np.array(qfi.bind_parameters(point).eval()).real np.testing.assert_array_almost_equal(actual, reference, decimal=3) def test_qfi_circuit_shared_params(self): @@ -1476,28 +1489,29 @@ def test_qfi_circuit_shared_params(self): circuit6.cx(1, 0) circuit6.h(1) - # compare - qfi = QFI().convert(StateFn(circuit), params=[x]) + with self.assertWarns(DeprecationWarning): + # compare + qfi = QFI().convert(StateFn(circuit), params=[x]) - circuit_sets = ( - [circuit1, circuit2, circuit3, circuit4], - [circuit5, circuit6], - [circuit5, circuit6], - ) - list_ops = ( - qfi.oplist[0].oplist[0].oplist[:-1], - qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist, - qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist, - ) + circuit_sets = ( + [circuit1, circuit2, circuit3, circuit4], + [circuit5, circuit6], + [circuit5, circuit6], + ) + list_ops = ( + qfi.oplist[0].oplist[0].oplist[:-1], + qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist, + qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist, + ) - # compose both on the same circuit such that the comparison works - base = QuantumCircuit(2) + # compose both on the same circuit such that the comparison works + base = QuantumCircuit(2) - for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)): - for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)): - with self.subTest(f"set {i} circuit {j}"): - primitive = composed_op[1].primitive - self.assertEqual(base.compose(primitive), base.compose(reference)) + for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)): + for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)): + with self.subTest(f"set {i} circuit {j}"): + primitive = composed_op[1].primitive + self.assertEqual(base.compose(primitive), base.compose(reference)) def test_overlap_qfi_bound_parameters(self): """Test the overlap QFI works on a circuit with multi-parameter bound gates.""" @@ -1506,8 +1520,10 @@ def test_overlap_qfi_bound_parameters(self): circuit.u(1, 2, 3, 0) circuit.rx(x, 0) - qfi = QFI("overlap_diag").convert(StateFn(circuit), [x]) - value = qfi.bind_parameters({x: 1}).eval()[0][0] + with self.assertWarns(DeprecationWarning): + qfi = QFI("overlap_diag").convert(StateFn(circuit), [x]) + value = qfi.bind_parameters({x: 1}).eval()[0][0] + ref = 0.87737713 self.assertAlmostEqual(value, ref) @@ -1518,7 +1534,8 @@ def test_overlap_qfi_raises_on_multiparam(self): circuit.u(x[0], x[1], 2, 0) with self.assertRaises(NotImplementedError): - _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + with self.assertWarns(DeprecationWarning): + _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) def test_overlap_qfi_raises_on_unsupported_gate(self): """Test the overlap QFI raises an appropriate error on multi-param unbound gates.""" @@ -1527,7 +1544,8 @@ def test_overlap_qfi_raises_on_unsupported_gate(self): circuit.p(x, 0) with self.assertRaises(NotImplementedError): - _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + with self.assertWarns(DeprecationWarning): + _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) @data(-Y, Z - 1j * Y) def test_aux_meas_op(self, aux_meas_op): @@ -1535,7 +1553,6 @@ def test_aux_meas_op(self, aux_meas_op): Gradient. """ - a = Parameter("a") b = Parameter("b") params = [a, b] @@ -1546,11 +1563,11 @@ def test_aux_meas_op(self, aux_meas_op): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) shots = 10000 - - prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) value_dicts = [{a: [np.pi / 4], b: [0]}, {a: [np.pi / 2], b: [np.pi / 4]}] if aux_meas_op == -Y: correct_values = [ @@ -1566,33 +1583,22 @@ def test_aux_meas_op(self, aux_meas_op): ], ] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - for backend_type in ["qasm_simulator", "statevector_simulator"]: - - for j, value_dict in enumerate(value_dicts): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - q_instance = QuantumInstance( - backend=BasicAer.get_backend(backend_type), shots=shots - ) - self.assertTrue(len(caught_warnings) > 0) + for backend_type in ["qasm_simulator", "statevector_simulator"]: + for j, value_dict in enumerate(value_dicts): + with self.assertWarns(DeprecationWarning): + q_instance = QuantumInstance( + backend=BasicAer.get_backend(backend_type), shots=shots + ) + with self.assertWarns(DeprecationWarning): result = ( CircuitSampler(backend=q_instance) .convert(prob_grad, params=value_dict) .eval()[0] ) - if backend_type == "qasm_simulator": # sparse result - result = [result[0].toarray()[0], result[1].toarray()[0]] - for i, item in enumerate(result): - np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1) - self.assertTrue(len(caught_warnings) > 0) + if backend_type == "qasm_simulator": # sparse result + result = [result[0].toarray()[0], result[1].toarray()[0]] + for i, item in enumerate(result): + np.testing.assert_array_almost_equal(item, correct_values[j][i], decimal=1) def test_unsupported_aux_meas_op(self): """Test error for unsupported auxiliary measurement operator in LinComb Gradient. @@ -1613,25 +1619,20 @@ def test_unsupported_aux_meas_op(self): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - op = CircuitStateFn(primitive=qc, coeff=1.0) + with self.assertWarns(DeprecationWarning): + op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 aux_meas_op = X + with self.assertWarns(DeprecationWarning): + with self.assertRaises(ValueError): + prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) + value_dict = {a: [np.pi / 4], b: [0]} - with self.assertRaises(ValueError): - prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) - value_dict = {a: [np.pi / 4], b: [0]} - - backend = BasicAer.get_backend("qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + backend = BasicAer.get_backend("qasm_simulator") q_instance = QuantumInstance(backend=backend, shots=shots) - self.assertTrue(len(caught_warnings) > 0) - CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() + CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() def test_nat_grad_error(self): """Test the NaturalGradient throws an Error. @@ -1655,41 +1656,25 @@ def test_nat_grad_error(self): qc.rz(params[1], 0) qc.h(1) - obs = (Z ^ X) - (Y ^ Y) - op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) + with self.assertWarns(DeprecationWarning): + obs = (Z ^ X) - (Y ^ Y) + op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) backend_type = "qasm_simulator" shots = 1 value = [0, np.pi / 2] backend = BasicAer.get_backend(backend_type) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) - self.assertTrue(len(caught_warnings) > 0) - - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) with self.assertRaises(ValueError): grad(value) - self.assertTrue(len(caught_warnings) > 0) if __name__ == "__main__": From 541cb252cddfbcf87369c152d37771bf6f23f560 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 14:27:34 +0200 Subject: [PATCH 33/47] Remove warning filter --- test/python/opflow/opflow_test_case.py | 10 +- test/python/opflow/test_matrix_expectation.py | 172 +++----- test/python/opflow/test_pauli_expectation.py | 410 ++++++++---------- 3 files changed, 243 insertions(+), 349 deletions(-) diff --git a/test/python/opflow/opflow_test_case.py b/test/python/opflow/opflow_test_case.py index 545634ffcd55..ebd0d5d6b377 100644 --- a/test/python/opflow/opflow_test_case.py +++ b/test/python/opflow/opflow_test_case.py @@ -19,12 +19,4 @@ class QiskitOpflowTestCase(QiskitTestCase): """Opflow test Case""" - def setUp(self): - super().setUp() - # ignore opflow msgs - warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*opflow.*") - - def tearDown(self): - super().tearDown() - # restore opflow msgs - warnings.filterwarnings("error", category=DeprecationWarning, message=r".*opflow.*") + pass diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index a9931bd4eb88..d51d841715b6 100644 --- a/test/python/opflow/test_matrix_expectation.py +++ b/test/python/opflow/test_matrix_expectation.py @@ -14,7 +14,6 @@ import unittest from test.python.opflow import QiskitOpflowTestCase -import warnings import itertools import numpy as np @@ -46,51 +45,34 @@ def setUp(self) -> None: super().setUp() self.seed = 97 backend = BasicAer.get_backend("statevector_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend, seed_simulator=self.seed, seed_transpiler=self.seed ) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) self.sampler = CircuitSampler(q_instance, attach_results=True) - self.expect = MatrixExpectation() - self.assertTrue(len(caught_warnings) > 0) + with self.assertWarns(DeprecationWarning): + self.expect = MatrixExpectation() def test_pauli_expect_pair(self): """pauli expect pair test""" - op = Z ^ Z - # wf = (Pl^Pl) + (Ze^Ze) - wf = CX @ (H ^ I) @ Zero - - converted_meas = self.expect.convert(~StateFn(op) @ wf) - self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + op = Z ^ Z + # wf = (Pl^Pl) + (Ze^Ze) + wf = CX @ (H ^ I) @ Zero + converted_meas = self.expect.convert(~StateFn(op) @ wf) + self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) - self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) + self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" - paulis = [Z, X, Y, I] - states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + paulis = [Z, X, Y, I] + states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] for pauli, state in itertools.product(paulis, states): converted_meas = self.expect.convert(~StateFn(pauli) @ state) matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() @@ -98,18 +80,14 @@ def test_pauli_expect_single(self): sampled = self.sampler.convert(converted_meas) self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) - self.assertTrue(len(caught_warnings) > 0) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" - paulis_op = ListOp([X, Y, Z, I]) - converted_meas = self.expect.convert(~StateFn(paulis_op)) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + paulis_op = ListOp([X, Y, Z, I]) + converted_meas = self.expect.convert(~StateFn(paulis_op)) + plus_mean = converted_meas @ Plus np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) sampled_plus = self.sampler.convert(plus_mean) @@ -129,90 +107,76 @@ def test_pauli_expect_op_vector(self): sum_zero_mean = converted_meas @ sum_zero np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1) sampled_zero = self.sampler.convert(sum_zero) - self.assertTrue(len(caught_warnings) > 0) - - np.testing.assert_array_almost_equal( - (converted_meas @ sampled_zero).eval(), [0, 0, 1, 1], decimal=1 - ) - for i, op in enumerate(paulis_op.oplist): - mat_op = op.to_matrix() np.testing.assert_array_almost_equal( - zero_mean.eval()[i], - Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - plus_mean.eval()[i], - Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - minus_mean.eval()[i], - Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), - decimal=1, + (converted_meas @ sampled_zero).eval(), [0, 0, 1, 1], decimal=1 ) + for i, op in enumerate(paulis_op.oplist): + mat_op = op.to_matrix() + np.testing.assert_array_almost_equal( + zero_mean.eval()[i], + Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + plus_mean.eval()[i], + Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + minus_mean.eval()[i], + Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), + decimal=1, + ) + def test_pauli_expect_state_vector(self): """pauli expect state vector test""" - states_op = ListOp([One, Zero, Plus, Minus]) - - paulis_op = X - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + states_op = ListOp([One, Zero, Plus, Minus]) + paulis_op = X + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) + np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) - # Small test to see if execution results are accessible - for composed_op in sampled: - self.assertIn("statevector", composed_op[1].execution_results) + # Small test to see if execution results are accessible + for composed_op in sampled: + self.assertIn("statevector", composed_op[1].execution_results) def test_pauli_expect_op_vector_state_vector(self): """pauli expect op vector state vector test""" - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) - valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] - converted_meas = self.expect.convert(~StateFn(paulis_op)) - np.testing.assert_array_almost_equal((converted_meas @ states_op).eval(), valids, decimal=1) + with self.assertWarns(DeprecationWarning): + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) + + valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] + converted_meas = self.expect.convert(~StateFn(paulis_op)) + np.testing.assert_array_almost_equal((converted_meas @ states_op).eval(), valids, decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) sampled = self.sampler.convert(states_op) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal((converted_meas @ sampled).eval(), valids, decimal=1) + np.testing.assert_array_almost_equal((converted_meas @ sampled).eval(), valids, decimal=1) def test_multi_representation_ops(self): """Test observables with mixed representations""" - mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) - converted_meas = self.expect.convert(~StateFn(mixed_ops)) - - plus_mean = converted_meas @ Plus - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) + converted_meas = self.expect.convert(~StateFn(mixed_ops)) + + plus_mean = converted_meas @ Plus sampled_plus = self.sampler.convert(plus_mean) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal( - sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 - ) + np.testing.assert_array_almost_equal( + sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 + ) def test_matrix_expectation_non_hermite_op(self): """Test MatrixExpectation for non hermitian operator""" - exp = ~StateFn(1j * Z) @ One - self.assertEqual(self.expect.convert(exp).eval(), 1j) + with self.assertWarns(DeprecationWarning): + exp = ~StateFn(1j * Z) @ One + self.assertEqual(self.expect.convert(exp).eval(), 1j) if __name__ == "__main__": diff --git a/test/python/opflow/test_pauli_expectation.py b/test/python/opflow/test_pauli_expectation.py index e01806d06a1a..ebc5df503809 100644 --- a/test/python/opflow/test_pauli_expectation.py +++ b/test/python/opflow/test_pauli_expectation.py @@ -15,7 +15,6 @@ import itertools import unittest from test.python.opflow import QiskitOpflowTestCase -import warnings import numpy as np @@ -51,242 +50,195 @@ def setUp(self) -> None: super().setUp() self.seed = 97 backend = BasicAer.get_backend("qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend, seed_simulator=self.seed, seed_transpiler=self.seed ) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): self.sampler = CircuitSampler(q_instance, attach_results=True) - self.assertTrue(len(caught_warnings) > 0) - - self.expect = PauliExpectation() + self.expect = PauliExpectation() def test_pauli_expect_pair(self): """pauli expect pair test""" - op = Z ^ Z - # wf = (Pl^Pl) + (Ze^Ze) - wf = CX @ (H ^ I) @ Zero - - converted_meas = self.expect.convert(~StateFn(op) @ wf) - self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + op = Z ^ Z + # wf = (Pl^Pl) + (Ze^Ze) + wf = CX @ (H ^ I) @ Zero + + converted_meas = self.expect.convert(~StateFn(op) @ wf) + self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) - self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) + self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" - paulis = [Z, X, Y, I] - states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - for pauli, state in itertools.product(paulis, states): - converted_meas = self.expect.convert(~StateFn(pauli) @ state) - matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() - self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) - - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + paulis = [Z, X, Y, I] + states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] + for pauli, state in itertools.product(paulis, states): + converted_meas = self.expect.convert(~StateFn(pauli) @ state) + matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() + self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) + sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) - self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" - paulis_op = ListOp([X, Y, Z, I]) - converted_meas = self.expect.convert(~StateFn(paulis_op)) - - plus_mean = converted_meas @ Plus - np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + paulis_op = ListOp([X, Y, Z, I]) + converted_meas = self.expect.convert(~StateFn(paulis_op)) + + plus_mean = converted_meas @ Plus + np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) + sampled_plus = self.sampler.convert(plus_mean) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) - - minus_mean = converted_meas @ Minus - np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) + + minus_mean = converted_meas @ Minus + np.testing.assert_array_almost_equal(minus_mean.eval(), [-1, 0, 0, 1], decimal=1) + sampled_minus = self.sampler.convert(minus_mean) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) - - zero_mean = converted_meas @ Zero - np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) + + zero_mean = converted_meas @ Zero + np.testing.assert_array_almost_equal(zero_mean.eval(), [0, 0, 1, 1], decimal=1) + sampled_zero = self.sampler.convert(zero_mean) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) - - sum_zero = (Plus + Minus) * (0.5**0.5) - sum_zero_mean = converted_meas @ sum_zero - np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) + + sum_zero = (Plus + Minus) * (0.5**0.5) + sum_zero_mean = converted_meas @ sum_zero + np.testing.assert_array_almost_equal(sum_zero_mean.eval(), [0, 0, 1, 1], decimal=1) + sampled_zero_mean = self.sampler.convert(sum_zero_mean) - self.assertTrue(len(caught_warnings) > 0) - # !!NOTE!!: Depolarizing channel (Sampling) means interference - # does not happen between circuits in sum, so expectation does - # not equal expectation for Zero!! - np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1], decimal=1) - - for i, op in enumerate(paulis_op.oplist): - mat_op = op.to_matrix() - np.testing.assert_array_almost_equal( - zero_mean.eval()[i], - Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - plus_mean.eval()[i], - Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - minus_mean.eval()[i], - Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), - decimal=1, - ) + + # !!NOTE!!: Depolarizing channel (Sampling) means interference + # does not happen between circuits in sum, so expectation does + # not equal expectation for Zero!! + np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1], decimal=1) + + for i, op in enumerate(paulis_op.oplist): + mat_op = op.to_matrix() + np.testing.assert_array_almost_equal( + zero_mean.eval()[i], + Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + plus_mean.eval()[i], + Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + minus_mean.eval()[i], + Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), + decimal=1, + ) def test_pauli_expect_state_vector(self): """pauli expect state vector test""" - states_op = ListOp([One, Zero, Plus, Minus]) - - paulis_op = X - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + states_op = ListOp([One, Zero, Plus, Minus]) + + paulis_op = X + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) + sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) + np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) - # Small test to see if execution results are accessible - for composed_op in sampled: - self.assertIn("counts", composed_op[1].execution_results) + # Small test to see if execution results are accessible + for composed_op in sampled: + self.assertIn("counts", composed_op[1].execution_results) def test_pauli_expect_op_vector_state_vector(self): """pauli expect op vector state vector test""" - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) - - valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) + + valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1) + sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) + np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_to_matrix_called(self): """test to matrix called in different situations""" qs = 45 - states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) - paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) - - # 45 qubit calculation - throws exception if to_matrix is called - # massive is False - with self.assertRaises(ValueError): - states_op.to_matrix() - paulis_op.to_matrix() - - # now set global variable or argument - try: - algorithm_globals.massive = True - with self.assertRaises(MemoryError): + + with self.assertWarns(DeprecationWarning): + states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) + paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) + + # 45 qubit calculation - throws exception if to_matrix is called + # massive is False + with self.assertRaises(ValueError): states_op.to_matrix() paulis_op.to_matrix() - algorithm_globals.massive = False - with self.assertRaises(MemoryError): - states_op.to_matrix(massive=True) - paulis_op.to_matrix(massive=True) - finally: - algorithm_globals.massive = False + + # now set global variable or argument + try: + algorithm_globals.massive = True + with self.assertRaises(MemoryError): + states_op.to_matrix() + paulis_op.to_matrix() + algorithm_globals.massive = False + with self.assertRaises(MemoryError): + states_op.to_matrix(massive=True) + paulis_op.to_matrix(massive=True) + finally: + algorithm_globals.massive = False def test_not_to_matrix_called(self): """45 qubit calculation - literally will not work if to_matrix is somehow called (in addition to massive=False throwing an error)""" qs = 45 - states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) - paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) + with self.assertWarns(DeprecationWarning): + states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) + paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), [[1, -1, 0], [1, -1, 0]]) + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), [[1, -1, 0], [1, -1, 0]]) def test_grouped_pauli_expectation(self): """grouped pauli expectation test""" - two_qubit_H2 = ( - (-1.052373245772859 * I ^ I) - + (0.39793742484318045 * I ^ Z) - + (-0.39793742484318045 * Z ^ I) - + (-0.01128010425623538 * Z ^ Z) - + (0.18093119978423156 * X ^ X) - ) - wf = CX @ (H ^ I) @ Zero - expect_op = PauliExpectation(group_paulis=False).convert(~StateFn(two_qubit_H2) @ wf) - self.sampler._extract_circuitstatefns(expect_op) - num_circuits_ungrouped = len(self.sampler._circuit_ops_cache) - self.assertEqual(num_circuits_ungrouped, 5) - - expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, + + with self.assertWarns(DeprecationWarning): + two_qubit_H2 = ( + (-1.052373245772859 * I ^ I) + + (0.39793742484318045 * I ^ Z) + + (-0.39793742484318045 * Z ^ I) + + (-0.01128010425623538 * Z ^ Z) + + (0.18093119978423156 * X ^ X) ) + wf = CX @ (H ^ I) @ Zero + expect_op = PauliExpectation(group_paulis=False).convert(~StateFn(two_qubit_H2) @ wf) + self.sampler._extract_circuitstatefns(expect_op) + num_circuits_ungrouped = len(self.sampler._circuit_ops_cache) + self.assertEqual(num_circuits_ungrouped, 5) + + expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf) + q_instance = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=self.seed, seed_transpiler=self.seed, ) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + sampler = CircuitSampler(q_instance) - self.assertTrue(len(caught_warnings) > 0) - sampler._extract_circuitstatefns(expect_op_grouped) - num_circuits_grouped = len(sampler._circuit_ops_cache) - self.assertEqual(num_circuits_grouped, 2) + sampler._extract_circuitstatefns(expect_op_grouped) + num_circuits_grouped = len(sampler._circuit_ops_cache) + self.assertEqual(num_circuits_grouped, 2) @unittest.skip(reason="IBMQ testing not available in general.") def test_ibmq_grouped_pauli_expectation(self): @@ -295,76 +247,62 @@ def test_ibmq_grouped_pauli_expectation(self): p = IBMQ.load_account() backend = p.get_backend("ibmq_qasm_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend, seed_simulator=self.seed, seed_transpiler=self.seed ) - self.assertTrue(len(caught_warnings) > 0) - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) - valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - sampled = CircuitSampler(q_instance).convert(converted_meas) - np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) + valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + sampled = CircuitSampler(q_instance).convert(converted_meas) + np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_multi_representation_ops(self): """Test observables with mixed representations""" - mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) - converted_meas = self.expect.convert(~StateFn(mixed_ops)) - - plus_mean = converted_meas @ Plus - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) + converted_meas = self.expect.convert(~StateFn(mixed_ops)) + + plus_mean = converted_meas @ Plus sampled_plus = self.sampler.convert(plus_mean) - self.assertTrue(len(caught_warnings) > 0) - np.testing.assert_array_almost_equal( - sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 - ) + np.testing.assert_array_almost_equal( + sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 + ) def test_pauli_expectation_non_hermite_op(self): """Test PauliExpectation for non hermitian operator""" - exp = ~StateFn(1j * Z) @ One - self.assertEqual(self.expect.convert(exp).eval(), 1j) + + with self.assertWarns(DeprecationWarning): + exp = ~StateFn(1j * Z) @ One + self.assertEqual(self.expect.convert(exp).eval(), 1j) def test_list_pauli_sum_op(self): """Test PauliExpectation for List[PauliSumOp]""" - test_op = ListOp([~StateFn(PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)]))]) - observable = self.expect.convert(test_op) - self.assertIsInstance(observable, ListOp) - self.assertIsInstance(observable[0][0][0].primitive, PauliSumOp) - self.assertIsInstance(observable[0][1][0].primitive, PauliSumOp) + + with self.assertWarns(DeprecationWarning): + test_op = ListOp([~StateFn(PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)]))]) + observable = self.expect.convert(test_op) + self.assertIsInstance(observable, ListOp) + self.assertIsInstance(observable[0][0][0].primitive, PauliSumOp) + self.assertIsInstance(observable[0][1][0].primitive, PauliSumOp) def test_expectation_with_coeff(self): """Test PauliExpectation with coefficients.""" - with self.subTest("integer coefficients"): - exp = 3 * ~StateFn(X) @ (2 * Minus) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + + with self.subTest("integer coefficients"): + exp = 3 * ~StateFn(X) @ (2 * Minus) target = self.sampler.convert(self.expect.convert(exp)).eval() - self.assertTrue(len(caught_warnings) > 0) - self.assertEqual(target, -12) - - with self.subTest("complex coefficients"): - exp = 3j * ~StateFn(X) @ (2j * Minus) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + self.assertEqual(target, -12) + + with self.subTest("complex coefficients"): + exp = 3j * ~StateFn(X) @ (2j * Minus) target = self.sampler.convert(self.expect.convert(exp)).eval() - self.assertTrue(len(caught_warnings) > 0) - self.assertEqual(target, -12j) + self.assertEqual(target, -12j) if __name__ == "__main__": From 374209c960f593976925ac7085ab80cddf5f9e68 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 14:27:54 +0200 Subject: [PATCH 34/47] Refactor rest of tests to assert warnings --- .../minimum_eigensolvers/test_adapt_vqe.py | 52 +--- .../minimum_eigensolvers/test_qaoa.py | 70 +----- .../minimum_eigensolvers/test_vqe.py | 23 +- .../optimizers/test_gradient_descent.py | 15 +- test/python/algorithms/test_grover.py | 152 +++++------ .../algorithms/test_observables_evaluator.py | 19 +- .../algorithms/test_skip_qobj_validation.py | 31 +-- .../test_scipy_imaginary_evolver.py | 8 +- .../algorithms/time_evolvers/test_pvqd.py | 8 +- .../test_time_evolution_problem.py | 29 +-- .../time_evolvers/test_trotter_qrte.py | 29 +-- .../circuit/library/test_evolution_gate.py | 107 ++------ .../circuit/library/test_evolved_op_ansatz.py | 30 +-- test/python/circuit/library/test_qft.py | 10 +- .../opflow/test_aer_pauli_expectation.py | 235 ++++++------------ .../python/opflow/test_expectation_factory.py | 9 +- .../python/opflow/test_state_op_meas_evals.py | 193 ++++++-------- test/python/result/test_sampled_expval.py | 15 +- test/python/utils/mitigation/test_meas.py | 133 ++-------- 19 files changed, 308 insertions(+), 860 deletions(-) diff --git a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py index 9cae7279fb45..ea0198259560 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_adapt_vqe.py @@ -13,7 +13,6 @@ """Test of the AdaptVQE minimum eigensolver""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack @@ -39,11 +38,7 @@ def setUp(self): super().setUp() algorithm_globals.random_seed = 42 - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): self.h2_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), @@ -95,18 +90,12 @@ def setUp(self): ) self.optimizer = SLSQP() - self.assertTrue(len(caught_warnings) > 0) - def test_default(self): """Default execution""" calc = AdaptVQE(VQE(Estimator(), self.ansatz, self.optimizer)) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): res = calc.compute_minimum_eigenvalue(operator=self.h2_op) - self.assertTrue(len(caught_warnings) > 0) expected_eigenvalue = -1.85727503 @@ -134,13 +123,8 @@ def test_converged(self): VQE(Estimator(), self.ansatz, self.optimizer), gradient_threshold=1e-3, ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): res = calc.compute_minimum_eigenvalue(operator=self.h2_op) - self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res.termination_criterion, TerminationCriterion.CONVERGED) @@ -150,13 +134,8 @@ def test_maximum(self): VQE(Estimator(), self.ansatz, self.optimizer), max_iterations=1, ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): res = calc.compute_minimum_eigenvalue(operator=self.h2_op) - self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res.termination_criterion, TerminationCriterion.MAXIMUM) @@ -192,14 +171,9 @@ def test_threshold_attribute(self): VQE(Estimator(), self.ansatz, self.optimizer), threshold=1e-3, ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): res = calc.compute_minimum_eigenvalue(operator=self.h2_op) - self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res.termination_criterion, TerminationCriterion.CONVERGED) @data( @@ -238,14 +212,9 @@ def test_vqe_solver(self): """Test to check if the VQE solver remains the same or not""" solver = VQE(Estimator(), self.ansatz, self.optimizer) calc = AdaptVQE(solver) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): _ = calc.compute_minimum_eigenvalue(operator=self.h2_op) self.assertEqual(solver.ansatz, calc.solver.ansatz) - self.assertTrue(len(caught_warnings) > 0) def test_gradient_calculation(self): """Test to check if the gradient calculation""" @@ -259,13 +228,8 @@ def test_gradient_calculation(self): def test_supports_aux_operators(self): """Test that auxiliary operators are supported""" calc = AdaptVQE(VQE(Estimator(), self.ansatz, self.optimizer)) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): res = calc.compute_minimum_eigenvalue(operator=self.h2_op, aux_operators=[self.h2_op]) - self.assertTrue(len(caught_warnings) > 0) expected_eigenvalue = -1.85727503 diff --git a/test/python/algorithms/minimum_eigensolvers/test_qaoa.py b/test/python/algorithms/minimum_eigensolvers/test_qaoa.py index e62a8743f4f1..ff3cce47e239 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_qaoa.py +++ b/test/python/algorithms/minimum_eigensolvers/test_qaoa.py @@ -13,7 +13,6 @@ """Test the QAOA algorithm.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial @@ -82,13 +81,8 @@ def test_qaoa(self, w, reps, mixer, solutions): qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, COBYLA(), reps=reps, mixer=mixer) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @@ -117,13 +111,8 @@ def test_qaoa_qc_mixer(self, w, prob, solutions): mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=prob, mixer=mixer) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) self.assertIn(graph_solution, solutions) @@ -140,13 +129,8 @@ def test_qaoa_qc_mixer_many_parameters(self): mixer.rx(theta, range(num_qubits)) qaoa = QAOA(self.sampler, optimizer, reps=2, mixer=mixer) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) self.log.debug(x) graph_solution = self._get_graph_solution(x) @@ -162,13 +146,8 @@ def test_qaoa_qc_mixer_no_parameters(self): mixer.rx(np.pi / 2, range(num_qubits)) qaoa = QAOA(self.sampler, COBYLA(), reps=1, mixer=mixer) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) # we just assert that we get a result, it is not meaningful. self.assertIsNotNone(result.eigenstate) @@ -178,13 +157,8 @@ def test_change_operator_size(self): np.array([[0, 1, 0, 1], [1, 0, 1, 0], [0, 1, 0, 1], [1, 0, 1, 0]]) ) qaoa = QAOA(self.sampler, COBYLA(), reps=1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 4x4"): @@ -202,13 +176,8 @@ def test_change_operator_size(self): ] ) ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) with self.subTest(msg="QAOA 6x6"): @@ -233,13 +202,8 @@ def cb_callback(eval_count, parameters, mean, metadata): initial_point=init_pt, callback=cb_callback, ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) x = self._sample_most_likely(result.eigenstate) graph_solution = self._get_graph_solution(x) @@ -260,13 +224,8 @@ def test_qaoa_random_initial_point(self): ) qubit_op, _ = self._get_operator(w) qaoa = QAOA(self.sampler, NELDER_MEAD(disp=True), reps=2) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(operator=qubit_op) - self.assertTrue(len(caught_warnings) > 0) self.assertLess(result.eigenvalue, -0.97) @@ -280,13 +239,8 @@ def test_optimizer_scipy_callable(self): self.sampler, partial(scipy_minimize, method="Nelder-Mead", options={"maxiter": 2}), ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = qaoa.compute_minimum_eigenvalue(qubit_op) - self.assertTrue(len(caught_warnings) > 0) self.assertEqual(result.cost_function_evals, 5) def _get_operator(self, weight_matrix): @@ -313,11 +267,7 @@ def _get_operator(self, weight_matrix): pauli_list.append([0.5 * weight_matrix[i, j], Pauli((z_p, x_p))]) shift -= 0.5 * weight_matrix[i, j] opflow_list = [(pauli[1].to_label(), pauli[0]) for pauli in pauli_list] - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): return PauliSumOp.from_list(opflow_list), shift def _get_graph_solution(self, x: np.ndarray) -> str: diff --git a/test/python/algorithms/minimum_eigensolvers/test_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_vqe.py index 222b616c07a3..4e61aa89f704 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_vqe.py @@ -13,7 +13,6 @@ """Test the variational quantum eigensolver algorithm.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial @@ -209,11 +208,7 @@ def test_gradient_run(self): def test_with_two_qubit_reduction(self): """Test the VQE using TwoQubitReduction.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): qubit_op = PauliSumOp.from_list( [ ("IIII", -0.8105479805373266), @@ -234,7 +229,6 @@ def test_with_two_qubit_reduction(self): ] ) tapered_qubit_op = TwoQubitReduction(num_particles=2).convert(qubit_op) - self.assertTrue(len(caught_warnings) > 0) vqe = VQE( Estimator(), self.ry_wavefunction, @@ -413,18 +407,14 @@ def test_aux_operators_list(self): self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = [aux_op1, aux_op2] result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) - self.assertTrue(len(caught_warnings) > 0) + self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=5) self.assertEqual(len(result.aux_operators_evaluated), 2) # expectation values @@ -459,18 +449,13 @@ def test_aux_operators_dict(self): self.assertEqual(len(result.aux_operators_evaluated), 0) with self.subTest("Test with two auxiliary operators."): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): aux_op1 = PauliSumOp.from_list([("II", 2.0)]) aux_op2 = PauliSumOp.from_list( [("II", 0.5), ("ZZ", 0.5), ("YY", 0.5), ("XX", -0.5)] ) aux_ops = {"aux_op1": aux_op1, "aux_op2": aux_op2} result = vqe.compute_minimum_eigenvalue(self.h2_op, aux_operators=aux_ops) - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(result.eigenvalue.real, self.h2_energy, places=6) self.assertEqual(len(result.aux_operators_evaluated), 2) diff --git a/test/python/algorithms/optimizers/test_gradient_descent.py b/test/python/algorithms/optimizers/test_gradient_descent.py index 02ae33c12ecb..8d2396650176 100644 --- a/test/python/algorithms/optimizers/test_gradient_descent.py +++ b/test/python/algorithms/optimizers/test_gradient_descent.py @@ -12,7 +12,6 @@ """Tests for the Gradient Descent optimizer.""" -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np from qiskit.algorithms.optimizers import GradientDescent, GradientDescentState @@ -41,14 +40,9 @@ def test_pauli_two_design(self): """Test standard gradient descent on the Pauli two-design example.""" circuit = PauliTwoDesign(3, reps=3, seed=2) parameters = list(circuit.parameters) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): obs = Z ^ Z ^ I expr = ~StateFn(obs) @ StateFn(circuit) - self.assertTrue(len(caught_warnings) > 0) initial_point = np.array( [ @@ -72,13 +66,8 @@ def objective_pauli(x): optimizer = GradientDescent(maxiter=100, learning_rate=0.1, perturbation=0.1) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): result = optimizer.minimize(objective_pauli, x0=initial_point) - self.assertTrue(len(caught_warnings) > 0) self.assertLess(result.fun, -0.95) # final loss self.assertEqual(result.nfev, 1300) # function evaluations diff --git a/test/python/algorithms/test_grover.py b/test/python/algorithms/test_grover.py index 3410ca7849f2..8fdeb12a7964 100644 --- a/test/python/algorithms/test_grover.py +++ b/test/python/algorithms/test_grover.py @@ -14,7 +14,6 @@ import itertools import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase import numpy as np @@ -92,18 +91,13 @@ class TestGrover(QiskitAlgorithmsTestCase): def setUp(self): super().setUp() - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): self.statevector = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=12, seed_transpiler=32 ) self.qasm = QuantumInstance( BasicAer.get_backend("qasm_simulator"), seed_simulator=12, seed_transpiler=32 ) - self.assertTrue(len(caught_warnings) > 0) self._sampler = Sampler() self._sampler_with_shots = Sampler(options={"shots": 1024, "seed": 123}) algorithm_globals.random_seed = 123 @@ -115,11 +109,10 @@ def test_implicit_phase_oracle_is_good_state(self, use_sampler): grover = self._prepare_grover(use_sampler) oracle = PhaseOracle("x & y") problem = AmplificationProblem(oracle) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "11") @@ -129,11 +122,10 @@ def test_iterations_with_good_state(self, use_sampler, iterations): """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @@ -143,11 +135,10 @@ def test_iterations_with_good_state_sample_from_iterations(self, use_sampler, it """Test the algorithm with different iteration types and with good state""" grover = self._prepare_grover(use_sampler, iterations, sample_from_iterations=True) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @@ -156,11 +147,10 @@ def test_fixed_iterations_without_good_state(self, use_sampler): """Test the algorithm with iterations as an int and without good state""" grover = self._prepare_grover(use_sampler, iterations=2) problem = AmplificationProblem(Statevector.from_label("111")) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @@ -170,14 +160,14 @@ def test_iterations_without_good_state(self, use_sampler, iterations): """Test the correct error is thrown for none/list of iterations and without good state""" grover = self._prepare_grover(use_sampler, iterations=iterations) problem = AmplificationProblem(Statevector.from_label("111")) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - with self.assertRaisesRegex( - TypeError, "An is_good_state function is required with the provided oracle" - ): + + with self.assertRaisesRegex( + TypeError, "An is_good_state function is required with the provided oracle" + ): + if not use_sampler: + with self.assertWarns(DeprecationWarning): + grover.amplify(problem) + else: grover.amplify(problem) @data("ideal", "shots", False) @@ -195,11 +185,10 @@ def iterator(): grover = self._prepare_grover(use_sampler, iterations=iterator()) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @@ -208,11 +197,10 @@ def test_growth_rate(self, use_sampler): """Test running the algorithm on a growth rate""" grover = self._prepare_grover(use_sampler, growth_rate=8 / 7) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertEqual(result.top_measurement, "111") @@ -227,11 +215,10 @@ def zero(): grover = self._prepare_grover(use_sampler, iterations=zero()) n = 5 problem = AmplificationProblem(Statevector.from_label("1" * n), is_good_state=["1" * n]) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertEqual(len(result.iterations), 2**n) @@ -241,12 +228,7 @@ def test_max_power(self, use_sampler): lam = 10.0 grover = self._prepare_grover(use_sampler, growth_rate=lam) problem = AmplificationProblem(Statevector.from_label("111"), is_good_state=["111"]) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = grover.amplify(problem) + result = grover.amplify(problem) self.assertEqual(len(result.iterations), 0) @data("ideal", "shots", False) @@ -256,11 +238,10 @@ def test_run_circuit_oracle(self, use_sampler): oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @@ -270,11 +251,10 @@ def test_run_state_vector_oracle(self, use_sampler): mark_state = Statevector.from_label("11") problem = AmplificationProblem(mark_state, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @@ -288,13 +268,12 @@ def test_run_custom_grover_operator(self, use_sampler): oracle=oracle, grover_operator=grover_op, is_good_state=["11"] ) grover = self._prepare_grover(use_sampler) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - ret = grover.amplify(problem) - self.assertIn(ret.top_measurement, ["11"]) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: + result = grover.amplify(problem) + self.assertIn(result.top_measurement, ["11"]) def test_optimal_num_iterations(self): """Test optimal_num_iterations""" @@ -328,11 +307,10 @@ def test_circuit_result(self, use_sampler): # is_good_state=['00'] is intentionally selected to obtain a list of results problem = AmplificationProblem(oracle, is_good_state=["00"]) grover = self._prepare_grover(use_sampler, iterations=[1, 2, 3, 4]) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) if use_sampler: for i, dist in enumerate(result.circuit_results): @@ -359,11 +337,10 @@ def test_max_probability(self, use_sampler): oracle.cz(0, 1) problem = AmplificationProblem(oracle, is_good_state=["11"]) grover = self._prepare_grover(use_sampler) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertAlmostEqual(result.max_probability, 1.0) @@ -374,11 +351,10 @@ def test_oracle_evaluation(self, use_sampler): oracle = PhaseOracle("x1 & x2 & (not x3)") problem = AmplificationProblem(oracle, is_good_state=oracle.evaluate_bitstring) grover = self._prepare_grover(use_sampler) - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + if not use_sampler: + with self.assertWarns(DeprecationWarning): + result = grover.amplify(problem) + else: result = grover.amplify(problem) self.assertTrue(result.oracle_evaluation) self.assertEqual("011", result.top_measurement) diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 4edf619fa212..7284313e53eb 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -14,7 +14,6 @@ from __future__ import annotations import unittest -import warnings from typing import Tuple from test.python.algorithms import QiskitAlgorithmsTestCase @@ -73,14 +72,9 @@ def _run_test( observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): - with warnings.catch_warnings(record=True): - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) - result = estimate_observables( - estimator, quantum_state, observables, None, self.threshold - ) + result = estimate_observables( + estimator, quantum_state, observables, None, self.threshold + ) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) @@ -173,14 +167,9 @@ def test_estimate_observables_shots(self): bound_ansatz = ansatz.bind_parameters(parameters) state = bound_ansatz estimator = Estimator(options={"shots": 2048}) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): observables = [PauliSumOp.from_list([("ZZ", 2.0)])] result = estimate_observables(estimator, state, observables, None, self.threshold) - self.assertTrue(len(caught_warnings) > 0) exact_result = self.get_exact_expectation(bound_ansatz, observables) expected_result = [(exact_result[0][0], {"variance": 1.0898, "shots": 2048})] diff --git a/test/python/algorithms/test_skip_qobj_validation.py b/test/python/algorithms/test_skip_qobj_validation.py index 04c5131635dc..0474d6cff794 100644 --- a/test/python/algorithms/test_skip_qobj_validation.py +++ b/test/python/algorithms/test_skip_qobj_validation.py @@ -13,7 +13,6 @@ """Test Skip Qobj Validation""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister from qiskit import BasicAer @@ -63,11 +62,7 @@ def setUp(self): def test_wo_backend_options(self): """without backend options test""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, @@ -80,7 +75,7 @@ def test_wo_backend_options(self): quantum_instance.reset_execution_results() quantum_instance.skip_qobj_validation = True res_wo_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) - self.assertTrue(len(caught_warnings) > 0) + self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_wo_bo, res_wo_bo_skip_validation)) @@ -88,11 +83,7 @@ def test_wo_backend_options(self): def test_w_backend_options(self): """with backend options test""" # run with backend_options - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, @@ -105,7 +96,7 @@ def test_w_backend_options(self): quantum_instance.reset_execution_results() quantum_instance.skip_qobj_validation = True res_w_bo_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) - self.assertTrue(len(caught_warnings) > 0) + self.assertGreaterEqual(quantum_instance.time_taken, 0.0) quantum_instance.reset_execution_results() self.assertTrue(_compare_dict(res_w_bo, res_w_bo_skip_validation)) @@ -128,11 +119,7 @@ def test_w_noise(self): noise_model = NoiseModel() noise_model.add_readout_error([probs_given0, probs_given1], [0]) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( self.backend, seed_transpiler=self.random_seed, @@ -143,15 +130,10 @@ def test_w_noise(self): res_w_noise = quantum_instance.execute(self.qc).get_counts(self.qc) quantum_instance.skip_qobj_validation = True res_w_noise_skip_validation = quantum_instance.execute(self.qc).get_counts(self.qc) - self.assertTrue(len(caught_warnings) > 0) self.assertTrue(_compare_dict(res_w_noise, res_w_noise_skip_validation)) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # BasicAer should fail: with self.assertRaises(QiskitError): _ = QuantumInstance(BasicAer.get_backend("qasm_simulator"), noise_model=noise_model) @@ -159,7 +141,6 @@ def test_w_noise(self): with self.assertRaises(QiskitError): quantum_instance = QuantumInstance(BasicAer.get_backend("qasm_simulator")) quantum_instance.set_config(noise_model=noise_model) - self.assertTrue(len(caught_warnings) > 0) if __name__ == "__main__": diff --git a/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py b/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py index 43c262715a1c..5671bf221284 100644 --- a/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py +++ b/test/python/algorithms/time_evolvers/classical_methods/test_scipy_imaginary_evolver.py @@ -12,7 +12,6 @@ """Test Classical Imaginary Evolver.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt, unpack import numpy as np @@ -124,11 +123,7 @@ def test_quantum_circuit_initial_state(self): def test_paulisumop_hamiltonian(self): """Tests if the hamiltonian can be a PauliSumOp""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp.from_list( [ ("XI", 1), @@ -136,7 +131,6 @@ def test_paulisumop_hamiltonian(self): ] ) observable = PauliSumOp.from_list([("ZZ", 1)]) - self.assertTrue(len(caught_warnings) > 0) evolution_problem = TimeEvolutionProblem( hamiltonian=hamiltonian, time=1.0, diff --git a/test/python/algorithms/time_evolvers/test_pvqd.py b/test/python/algorithms/time_evolvers/test_pvqd.py index eab47f22d14a..f0e3b3ae4471 100644 --- a/test/python/algorithms/time_evolvers/test_pvqd.py +++ b/test/python/algorithms/time_evolvers/test_pvqd.py @@ -12,7 +12,6 @@ """Tests for PVQD.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from functools import partial @@ -75,13 +74,8 @@ def test_pvqd(self, hamiltonian_type, gradient, num_timesteps): if hamiltonian_type == "ising": hamiltonian = self.hamiltonian elif hamiltonian_type == "pauli_sum_op": - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(self.hamiltonian) - self.assertTrue(len(caught_warnings) > 0) else: # hamiltonian_type == "pauli": hamiltonian = Pauli("XX") 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 e069d18884ee..1982fb203749 100644 --- a/test/python/algorithms/time_evolvers/test_time_evolution_problem.py +++ b/test/python/algorithms/time_evolvers/test_time_evolution_problem.py @@ -12,7 +12,6 @@ """Test evolver problem class.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import data, ddt from numpy.testing import assert_raises @@ -53,13 +52,8 @@ def test_init_default(self): def test_init_all(self, initial_state): """Tests that all fields are initialized correctly.""" t_parameter = Parameter("t") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): hamiltonian = t_parameter * Z + Y - self.assertTrue(len(caught_warnings) > 0) time = 2 aux_operators = [X, Y] param_value_dict = {t_parameter: 3.2} @@ -73,26 +67,16 @@ def test_init_all(self, initial_state): param_value_map=param_value_dict, ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): expected_hamiltonian = Y + t_parameter * Z - self.assertTrue(len(caught_warnings) > 0) expected_time = 2 expected_type = QuantumCircuit expected_aux_operators = [X, Y] expected_t_param = t_parameter expected_param_value_dict = {t_parameter: 3.2} - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): self.assertEqual(evo_problem.hamiltonian, expected_hamiltonian) - self.assertTrue(len(caught_warnings) > 0) self.assertEqual(evo_problem.time, expected_time) self.assertEqual(type(evo_problem.initial_state), expected_type) self.assertEqual(evo_problem.aux_operators, expected_aux_operators) @@ -103,13 +87,8 @@ 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."): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): hamiltonian = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Y")]), param_x) - self.assertTrue(len(caught_warnings) > 0) evolution_problem = TimeEvolutionProblem(hamiltonian, 2, Zero) with assert_raises(ValueError): evolution_problem.validate_params() diff --git a/test/python/algorithms/time_evolvers/test_trotter_qrte.py b/test/python/algorithms/time_evolvers/test_trotter_qrte.py index b460fafea761..c784d2e31363 100644 --- a/test/python/algorithms/time_evolvers/test_trotter_qrte.py +++ b/test/python/algorithms/time_evolvers/test_trotter_qrte.py @@ -13,7 +13,6 @@ """Test TrotterQRTE.""" import unittest -import warnings from test.python.algorithms import QiskitAlgorithmsTestCase from ddt import ddt, data, unpack import numpy as np @@ -53,13 +52,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.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) - self.assertTrue(len(caught_warnings) > 0) initial_state = QuantumCircuit(1) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) @@ -175,13 +169,8 @@ 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.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X"), Pauli("Z")])) - self.assertTrue(len(caught_warnings) > 0) time = 1 evolution_problem = TimeEvolutionProblem(operator, time, initial_state) @@ -198,15 +187,10 @@ def test_trotter_qrte_qdrift(self, initial_state, expected_state): @unpack def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): """Test TrotterQRTE with raising errors for parameters.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): operator = Parameter("t") * PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) - self.assertTrue(len(caught_warnings) > 0) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, None, None, t_param, param_value_dict) @@ -214,15 +198,10 @@ def test_trotter_qrte_trotter_param_errors(self, t_param, param_value_dict): @unpack def test_trotter_qrte_trotter_aux_ops_errors(self, aux_ops, estimator): """Test TrotterQRTE with raising errors.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): operator = PauliSumOp(SparsePauliOp([Pauli("X")])) + PauliSumOp( SparsePauliOp([Pauli("Z")]) ) - self.assertTrue(len(caught_warnings) > 0) initial_state = QuantumCircuit(1) self._run_error_test(initial_state, operator, aux_ops, estimator, None, None) diff --git a/test/python/circuit/library/test_evolution_gate.py b/test/python/circuit/library/test_evolution_gate.py index 0ed16986de7e..f6e625f2c0ce 100644 --- a/test/python/circuit/library/test_evolution_gate.py +++ b/test/python/circuit/library/test_evolution_gate.py @@ -12,7 +12,6 @@ """Test the evolution gate.""" -import warnings import unittest import numpy as np import scipy @@ -39,13 +38,8 @@ def setUp(self): def test_matrix_decomposition(self): """Test the default decomposition.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) - self.assertTrue(len(caught_warnings) > 0) time = 0.123 matrix = op.to_matrix() @@ -57,13 +51,8 @@ def test_matrix_decomposition(self): def test_lie_trotter(self): """Test constructing the circuit with Lie Trotter decomposition.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) - self.assertTrue(len(caught_warnings) > 0) time = 0.123 reps = 4 evo_gate = PauliEvolutionGate(op, time, synthesis=LieTrotter(reps=reps)) @@ -72,11 +61,7 @@ def test_lie_trotter(self): def test_rzx_order(self): """Test ZX and XZ is mapped onto the correct qubits.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) for op, indices in zip([X ^ Z, Z ^ X], [(0, 1), (1, 0)]): with self.subTest(op=op, indices=indices): @@ -97,17 +82,11 @@ def test_rzx_order(self): # don't use circuit equality since RZX here decomposes with RZ on the bottom self.assertTrue(Operator(decomposed).equiv(ref)) - self.assertTrue(len(caught_warnings) > 0) def test_suzuki_trotter(self): """Test constructing the circuit with Lie Trotter decomposition.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = (X ^ 3) + (Y ^ 3) + (Z ^ 3) - self.assertTrue(len(caught_warnings) > 0) time = 0.123 reps = 4 for order in [2, 4, 6]: @@ -129,13 +108,8 @@ def test_suzuki_trotter(self): def test_suzuki_trotter_manual(self): """Test the evolution circuit of Suzuki Trotter against a manually constructed circuit.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = X + Y - self.assertTrue(len(caught_warnings) > 0) time = 0.1 reps = 1 evo_gate = PauliEvolutionGate(op, time, synthesis=SuzukiTrotter(order=4, reps=reps)) @@ -183,16 +157,10 @@ def test_qdrift_manual(self, op, time, reps, sampled_ops): def test_qdrift_evolution(self): """Test QDrift on an example.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = 0.1 * (Z ^ Z) + (X ^ I) + (I ^ X) + 0.2 * (X ^ X) - self.assertTrue(len(caught_warnings) > 0) reps = 20 qdrift = PauliEvolutionGate(op, time=0.5 / reps, synthesis=QDrift(reps=reps)).definition - self.assertTrue(len(caught_warnings) > 0) exact = scipy.linalg.expm(-0.5j * op.to_matrix()).dot(np.eye(4)[0, :]) def energy(evo): @@ -202,13 +170,8 @@ def energy(evo): def test_passing_grouped_paulis(self): """Test passing a list of already grouped Paulis.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): grouped_ops = [(X ^ Y) + (Y ^ X), (Z ^ I) + (Z ^ Z) + (I ^ Z), (X ^ X)] - self.assertTrue(len(caught_warnings) > 0) evo_gate = PauliEvolutionGate(grouped_ops, time=0.12, synthesis=LieTrotter()) decomposed = evo_gate.definition.decompose() self.assertEqual(decomposed.count_ops()["rz"], 4) @@ -217,13 +180,8 @@ def test_passing_grouped_paulis(self): def test_list_from_grouped_paulis(self): """Test getting a string representation from grouped Paulis.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): grouped_ops = [(X ^ Y) + (Y ^ X), (Z ^ I) + (Z ^ Z) + (I ^ Z), (X ^ X)] - self.assertTrue(len(caught_warnings) > 0) evo_gate = PauliEvolutionGate(grouped_ops, time=0.12, synthesis=LieTrotter()) pauli_strings = [] @@ -243,13 +201,8 @@ def test_list_from_grouped_paulis(self): def test_dag_conversion(self): """Test constructing a circuit with evolutions yields a DAG with evolution blocks.""" time = Parameter("t") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): evo = PauliEvolutionGate((Z ^ 2) + (X ^ 2), time=time) - self.assertTrue(len(caught_warnings) > 0) circuit = QuantumCircuit(2) circuit.h(circuit.qubits) @@ -267,13 +220,8 @@ def test_dag_conversion(self): def test_cnot_chain_options(self, option): """Test selecting different kinds of CNOT chains.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = Z ^ Z ^ Z - self.assertTrue(len(caught_warnings) > 0) synthesis = LieTrotter(reps=1, cx_structure=option) evo = PauliEvolutionGate(op, synthesis=synthesis) @@ -317,26 +265,16 @@ def test_different_input_types(self, op): def test_pauliop_coefficients_respected(self): """Test that global ``PauliOp`` coefficients are being taken care of.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): evo = PauliEvolutionGate(5 * (Z ^ I), time=1, synthesis=LieTrotter()) - self.assertTrue(len(caught_warnings) > 0) circuit = evo.definition.decompose() rz_angle = circuit.data[0].operation.params[0] self.assertEqual(rz_angle, 10) def test_paulisumop_coefficients_respected(self): """Test that global ``PauliSumOp`` coefficients are being taken care of.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): evo = PauliEvolutionGate(5 * (2 * X + 3 * Y - Z), time=1, synthesis=LieTrotter()) - self.assertTrue(len(caught_warnings) > 0) circuit = evo.definition.decompose() rz_angles = [ circuit.data[0].operation.params[0], # X @@ -350,13 +288,8 @@ def test_lie_trotter_two_qubit_correct_order(self): Regression test of Qiskit/qiskit-terra#7544. """ - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): operator = I ^ Z ^ Z - self.assertTrue(len(caught_warnings) > 0) time = 0.5 exact = scipy.linalg.expm(-1j * time * operator.to_matrix()) lie_trotter = PauliEvolutionGate(operator, time, synthesis=LieTrotter()) @@ -376,13 +309,8 @@ def test_paramtrized_op_raises(self): @data(LieTrotter, MatrixExponential) def test_inverse(self, synth_cls): """Test calculating the inverse is correct.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): evo = PauliEvolutionGate(X + Y, time=0.12, synthesis=synth_cls()) - self.assertTrue(len(caught_warnings) > 0) circuit = QuantumCircuit(1) circuit.append(evo, circuit.qubits) @@ -392,13 +320,8 @@ def test_inverse(self, synth_cls): def test_labels_and_name(self): """Test the name and labels are correct.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): operators = [X, (X + Y), ((I ^ Z) + (Z ^ I) - 0.2 * (X ^ X))] - self.assertTrue(len(caught_warnings) > 0) # note: the labels do not show coefficients! expected_labels = ["X", "(X + Y)", "(IZ + ZI + XX)"] diff --git a/test/python/circuit/library/test_evolved_op_ansatz.py b/test/python/circuit/library/test_evolved_op_ansatz.py index 00e3b09623d2..b4c65defd1a4 100644 --- a/test/python/circuit/library/test_evolved_op_ansatz.py +++ b/test/python/circuit/library/test_evolved_op_ansatz.py @@ -12,7 +12,6 @@ """Test the evolved operator ansatz.""" -import warnings from ddt import ddt, data import numpy as np @@ -34,16 +33,11 @@ def test_evolved_op_ansatz(self, use_opflow): """Test the default evolution.""" num_qubits = 3 if use_opflow: - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): ops = [Z ^ num_qubits, Y ^ num_qubits, X ^ num_qubits] evo = EvolvedOperatorAnsatz(ops, 2) parameters = evo.parameters - self.assertTrue(len(caught_warnings) > 0) else: ops = [Pauli("Z" * num_qubits), Pauli("Y" * num_qubits), Pauli("X" * num_qubits)] @@ -61,19 +55,13 @@ def test_evolved_op_ansatz(self, use_opflow): def test_custom_evolution(self, use_opflow): """Test using another evolution than the default (e.g. matrix evolution).""" if use_opflow: - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): op = X ^ I ^ Z matrix = op.to_matrix() evolution = MatrixEvolution() evo = EvolvedOperatorAnsatz(op, evolution=evolution) parameters = evo.parameters - self.assertTrue(len(caught_warnings) > 0) - else: op = SparsePauliOp(["ZIX"]) matrix = np.array(op) @@ -94,15 +82,10 @@ def test_changing_operators(self): """Test rebuilding after the operators changed.""" ops = [X, Y, Z] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): evo = EvolvedOperatorAnsatz(ops) evo.operators = [X, Y] parameters = evo.parameters - self.assertTrue(len(caught_warnings) > 0) reference = QuantumCircuit(1) reference.rx(2 * parameters[0], 0) @@ -117,18 +100,13 @@ def test_invalid_reps(self): def test_insert_barriers(self): """Test using insert_barriers.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): evo = EvolvedOperatorAnsatz(Z, reps=4, insert_barriers=True) ref = QuantumCircuit(1) for parameter in evo.parameters: ref.rz(2.0 * parameter, 0) ref.barrier() self.assertEqual(evo.decompose(), ref) - self.assertTrue(len(caught_warnings) > 0) def test_empty_build_fails(self): """Test setting no operators to evolve raises the appropriate error.""" diff --git a/test/python/circuit/library/test_qft.py b/test/python/circuit/library/test_qft.py index fa5305aa3631..49e34736616d 100644 --- a/test/python/circuit/library/test_qft.py +++ b/test/python/circuit/library/test_qft.py @@ -13,7 +13,6 @@ """Test library of QFT circuits.""" import unittest -import warnings import numpy as np from ddt import ddt, data, unpack @@ -185,18 +184,11 @@ def __init__(self, *_args, **_kwargs): # We don't want to issue a warning on mutation until we know that the values are # finalised; this is because a user might want to mutate the number of qubits and the # approximation degree. In these cases, wait until we try to build the circuit. - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=RuntimeWarning, - module=r"qiskit\..*", - message=r".*precision loss in QFT.*", - ) + with self.assertWarns(DeprecationWarning): qft = QFT() # Even with the approximation this will trigger the warning. qft.num_qubits = 1080 qft.approximation_degree = 20 - self.assertFalse(caught_warnings) # Short-circuit the build method so it exits after input validation, but without actually # spinning the CPU to build a huge, useless object. diff --git a/test/python/opflow/test_aer_pauli_expectation.py b/test/python/opflow/test_aer_pauli_expectation.py index 32e2acd51fe0..690c44bade1e 100644 --- a/test/python/opflow/test_aer_pauli_expectation.py +++ b/test/python/opflow/test_aer_pauli_expectation.py @@ -15,7 +15,6 @@ import itertools import unittest from test.python.opflow import QiskitOpflowTestCase -import warnings import numpy as np from qiskit.circuit.library import RealAmplitudes @@ -53,61 +52,41 @@ def setUp(self) -> None: self.seed = 97 self.backend = AerSimulator() - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( self.backend, seed_simulator=self.seed, seed_transpiler=self.seed ) self.sampler = CircuitSampler(q_instance, attach_results=True) self.expect = AerPauliExpectation() - self.assertTrue(len(caught_warnings) > 0) def test_pauli_expect_pair(self): """pauli expect pair test""" - op = Z ^ Z - # wvf = (Pl^Pl) + (Ze^Ze) - wvf = CX @ (H ^ I) @ Zero - - converted_meas = self.expect.convert(~StateFn(op) @ wvf) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + op = Z ^ Z + # wvf = (Pl^Pl) + (Ze^Ze) + wvf = CX @ (H ^ I) @ Zero + converted_meas = self.expect.convert(~StateFn(op) @ wvf) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" - paulis = [Z, X, Y, I] - states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + paulis = [Z, X, Y, I] + states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] for pauli, state in itertools.product(paulis, states): converted_meas = self.expect.convert(~StateFn(pauli) @ state) matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() sampled = self.sampler.convert(converted_meas) self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) - self.assertTrue(len(caught_warnings) > 0) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" - paulis_op = ListOp([X, Y, Z, I]) - converted_meas = self.expect.convert(~StateFn(paulis_op)) - - plus_mean = converted_meas @ Plus - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + paulis_op = ListOp([X, Y, Z, I]) + converted_meas = self.expect.convert(~StateFn(paulis_op)) + + plus_mean = converted_meas @ Plus sampled_plus = self.sampler.convert(plus_mean) np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) @@ -122,7 +101,6 @@ def test_pauli_expect_op_vector(self): sum_zero = (Plus + Minus) * (0.5**0.5) sum_zero_mean = converted_meas @ sum_zero sampled_zero_mean = self.sampler.convert(sum_zero_mean) - self.assertTrue(len(caught_warnings) > 0) # !!NOTE!!: Depolarizing channel (Sampling) means interference # does not happen between circuits in sum, so expectation does @@ -131,17 +109,11 @@ def test_pauli_expect_op_vector(self): def test_pauli_expect_state_vector(self): """pauli expect state vector test""" - states_op = ListOp([One, Zero, Plus, Minus]) - - paulis_op = X - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + states_op = ListOp([One, Zero, Plus, Minus]) + paulis_op = X + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) # Small test to see if execution results are accessible for composed_op in sampled: @@ -151,102 +123,75 @@ def test_pauli_expect_state_vector(self): def test_pauli_expect_non_hermitian_matrixop(self): """pauli expect state vector with non hermitian operator test""" - states_op = ListOp([One, Zero, Plus, Minus]) - - op_mat = np.array([[0, 1], [2, 3]]) - op = MatrixOp(op_mat) - - converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + states_op = ListOp([One, Zero, Plus, Minus]) + op_mat = np.array([[0, 1], [2, 3]]) + op = MatrixOp(op_mat) + converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), [3, 0, 3, 0], decimal=1) def test_pauli_expect_non_hermitian_pauliop(self): """pauli expect state vector with non hermitian operator test""" - states_op = ListOp([One, Zero, Plus, Minus]) - - op = 1j * X - - converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + states_op = ListOp([One, Zero, Plus, Minus]) + op = 1j * X + converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1j, -1j], decimal=1) def test_pauli_expect_op_vector_state_vector(self): """pauli expect op vector state vector test""" - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) - - valids = [ - [+0, 0, 1, -1], - [+0, 0, 0, 0], - [-1, 1, 0, -0], - [+1, 1, 1, 1], - ] - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) + + valids = [ + [+0, 0, 1, -1], + [+0, 0, 0, 0], + [-1, 1, 0, -0], + [+1, 1, 1, 1], + ] + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) sampled = self.sampler.convert(converted_meas) - self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_multi_representation_ops(self): """Test observables with mixed representations""" - mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) - converted_meas = self.expect.convert(~StateFn(mixed_ops)) - - plus_mean = converted_meas @ Plus - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) + converted_meas = self.expect.convert(~StateFn(mixed_ops)) + + plus_mean = converted_meas @ Plus sampled_plus = self.sampler.convert(plus_mean) - self.assertTrue(len(caught_warnings) > 0) np.testing.assert_array_almost_equal( sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 ) def test_parameterized_qobj(self): """grouped pauli expectation test""" - two_qubit_h2 = ( - (-1.052373245772859 * I ^ I) - + (0.39793742484318045 * I ^ Z) - + (-0.39793742484318045 * Z ^ I) - + (-0.01128010425623538 * Z ^ Z) - + (0.18093119978423156 * X ^ X) - ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, + with self.assertWarns(DeprecationWarning): + two_qubit_h2 = ( + (-1.052373245772859 * I ^ I) + + (0.39793742484318045 * I ^ Z) + + (-0.39793742484318045 * Z ^ I) + + (-0.01128010425623538 * Z ^ Z) + + (0.18093119978423156 * X ^ X) ) + aer_sampler = CircuitSampler( self.sampler.quantum_instance, param_qobj=True, attach_results=True ) - self.assertTrue(len(caught_warnings) > 0) - ansatz = RealAmplitudes() - ansatz.num_qubits = 2 + ansatz = RealAmplitudes() + ansatz.num_qubits = 2 - observable_meas = self.expect.convert(StateFn(two_qubit_h2, is_measurement=True)) - ansatz_circuit_op = CircuitStateFn(ansatz) - expect_op = observable_meas.compose(ansatz_circuit_op).reduce() + observable_meas = self.expect.convert(StateFn(two_qubit_h2, is_measurement=True)) + ansatz_circuit_op = CircuitStateFn(ansatz) + expect_op = observable_meas.compose(ansatz_circuit_op).reduce() def generate_parameters(num): param_bindings = {} @@ -258,14 +203,9 @@ def generate_parameters(num): return param_bindings def validate_sampler(ideal, sut, param_bindings): - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): expect_sampled = ideal.convert(expect_op, params=param_bindings).eval() actual_sampled = sut.convert(expect_op, params=param_bindings).eval() - self.assertTrue(len(caught_warnings) > 0) self.assertTrue( np.allclose(actual_sampled, expect_sampled), f"{actual_sampled} != {expect_sampled}", @@ -299,31 +239,22 @@ def validate_aer_templates_reused(prev_templates, cur_templates): def test_pauli_expectation_param_qobj(self): """Test PauliExpectation with param_qobj""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( self.backend, seed_simulator=self.seed, seed_transpiler=self.seed, shots=10000 ) - self.assertTrue(len(caught_warnings) > 0) - qubit_op = (0.1 * I ^ I) + (0.2 * I ^ Z) + (0.3 * Z ^ I) + (0.4 * Z ^ Z) + (0.5 * X ^ X) - ansatz = RealAmplitudes(qubit_op.num_qubits) - ansatz_circuit_op = CircuitStateFn(ansatz) - observable = PauliExpectation().convert(~StateFn(qubit_op)) - expect_op = observable.compose(ansatz_circuit_op).reduce() - params1 = {} - params2 = {} - for param in ansatz.parameters: - params1[param] = [0] - params2[param] = [0, 0] - - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + qubit_op = (0.1 * I ^ I) + (0.2 * I ^ Z) + (0.3 * Z ^ I) + (0.4 * Z ^ Z) + (0.5 * X ^ X) + ansatz = RealAmplitudes(qubit_op.num_qubits) + ansatz_circuit_op = CircuitStateFn(ansatz) + observable = PauliExpectation().convert(~StateFn(qubit_op)) + expect_op = observable.compose(ansatz_circuit_op).reduce() + params1 = {} + params2 = {} + for param in ansatz.parameters: + params1[param] = [0] + params2[param] = [0, 0] + + with self.assertWarns(DeprecationWarning): sampler1 = CircuitSampler(backend=q_instance, param_qobj=False) samples1 = sampler1.convert(expect_op, params=params1) val1 = np.real(samples1.eval())[0] @@ -333,7 +264,6 @@ def test_pauli_expectation_param_qobj(self): samples3 = sampler2.convert(expect_op, params=params1) val3 = np.real(samples3.eval()) samples4 = sampler2.convert(expect_op, params=params2) - self.assertTrue(len(caught_warnings) > 0) val4 = np.real(samples4.eval()) np.testing.assert_array_almost_equal([val1] * 2, val2, decimal=2) @@ -342,8 +272,9 @@ def test_pauli_expectation_param_qobj(self): def test_list_pauli_sum(self): """Test AerPauliExpectation for ListOp[PauliSumOp]""" - test_op = ListOp([PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)])]) - observable = AerPauliExpectation().convert(~StateFn(test_op)) + with self.assertWarns(DeprecationWarning): + test_op = ListOp([PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)])]) + observable = AerPauliExpectation().convert(~StateFn(test_op)) self.assertIsInstance(observable, ListOp) self.assertIsInstance(observable[0], CircuitStateFn) self.assertTrue(observable[0].is_measurement) @@ -351,25 +282,15 @@ def test_list_pauli_sum(self): def test_expectation_with_coeff(self): """Test AerPauliExpectation with coefficients.""" with self.subTest("integer coefficients"): - exp = 3 * ~StateFn(X) @ (2 * Minus) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + exp = 3 * ~StateFn(X) @ (2 * Minus) target = self.sampler.convert(self.expect.convert(exp)).eval() - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(target, -12) with self.subTest("complex coefficients"): - exp = 3j * ~StateFn(X) @ (2j * Minus) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + exp = 3j * ~StateFn(X) @ (2j * Minus) target = self.sampler.convert(self.expect.convert(exp)).eval() - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(target, -12j) diff --git a/test/python/opflow/test_expectation_factory.py b/test/python/opflow/test_expectation_factory.py index 20c21851e384..7ba539048499 100644 --- a/test/python/opflow/test_expectation_factory.py +++ b/test/python/opflow/test_expectation_factory.py @@ -13,7 +13,6 @@ """Test the expectation factory.""" import unittest -import warnings from test.python.opflow import QiskitOpflowTestCase from qiskit.opflow import PauliExpectation, AerPauliExpectation, ExpectationFactory, Z, I, X @@ -30,11 +29,7 @@ def test_aer_simulator_pauli_sum(self): backend = AerSimulator() op = 0.2 * (X ^ X) + 0.1 * (Z ^ I) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): with self.subTest("Defaults"): expectation = ExpectationFactory.build(op, backend, include_custom=False) self.assertIsInstance(expectation, PauliExpectation) @@ -42,4 +37,4 @@ def test_aer_simulator_pauli_sum(self): with self.subTest("Include custom"): expectation = ExpectationFactory.build(op, backend, include_custom=True) self.assertIsInstance(expectation, AerPauliExpectation) - self.assertTrue(len(caught_warnings) > 0) +∂ diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index 7f44c1c0b865..ac0d2ea8c781 100644 --- a/test/python/opflow/test_state_op_meas_evals.py +++ b/test/python/opflow/test_state_op_meas_evals.py @@ -17,7 +17,6 @@ import unittest from test.python.opflow import QiskitOpflowTestCase -import warnings from ddt import ddt, data import numpy @@ -34,35 +33,38 @@ class TestStateOpMeasEvals(QiskitOpflowTestCase): def test_statefn_overlaps(self): """state functions overlaps test""" - wf = (4 * StateFn({"101010": 0.5, "111111": 0.3})) + ((3 + 0.1j) * (Zero ^ 6)) - wf_vec = StateFn(wf.to_matrix()) - self.assertAlmostEqual(wf.adjoint().eval(wf), 14.45) - self.assertAlmostEqual(wf_vec.adjoint().eval(wf_vec), 14.45) - self.assertAlmostEqual(wf_vec.adjoint().eval(wf), 14.45) - self.assertAlmostEqual(wf.adjoint().eval(wf_vec), 14.45) + with self.assertWarns(DeprecationWarning): + wf = (4 * StateFn({"101010": 0.5, "111111": 0.3})) + ((3 + 0.1j) * (Zero ^ 6)) + wf_vec = StateFn(wf.to_matrix()) + self.assertAlmostEqual(wf.adjoint().eval(wf), 14.45) + self.assertAlmostEqual(wf_vec.adjoint().eval(wf_vec), 14.45) + self.assertAlmostEqual(wf_vec.adjoint().eval(wf), 14.45) + self.assertAlmostEqual(wf.adjoint().eval(wf_vec), 14.45) def test_wf_evals_x(self): """wf evals x test""" qbits = 4 - wf = ((Zero ^ qbits) + (One ^ qbits)) * (1 / 2**0.5) - # Note: wf = Plus^qbits fails because TensoredOp can't handle it. - wf_vec = StateFn(wf.to_matrix()) - op = X ^ qbits - # op = I^6 - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 1) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 1) - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 1) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 1) - - # op = (H^X^Y)^2 - op = H ^ 6 - wf = ((Zero ^ 6) + (One ^ 6)) * (1 / 2**0.5) - wf_vec = StateFn(wf.to_matrix()) - # print(wf.adjoint().to_matrix() @ op.to_matrix() @ wf.to_matrix()) - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 0.25) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 0.25) - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 0.25) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 0.25) + + with self.assertWarns(DeprecationWarning): + wf = ((Zero ^ qbits) + (One ^ qbits)) * (1 / 2**0.5) + # Note: wf = Plus^qbits fails because TensoredOp can't handle it. + wf_vec = StateFn(wf.to_matrix()) + op = X ^ qbits + # op = I^6 + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 1) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 1) + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 1) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 1) + + # op = (H^X^Y)^2 + op = H ^ 6 + wf = ((Zero ^ 6) + (One ^ 6)) * (1 / 2**0.5) + wf_vec = StateFn(wf.to_matrix()) + # print(wf.adjoint().to_matrix() @ op.to_matrix() @ wf.to_matrix()) + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 0.25) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 0.25) + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 0.25) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 0.25) def test_coefficients_correctly_propagated(self): """Test that the coefficients in SummedOp and states are correctly used.""" @@ -72,40 +74,26 @@ def test_coefficients_correctly_propagated(self): self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") return with self.subTest("zero coeff in SummedOp"): - op = 0 * (I + Z) - state = Plus - self.assertEqual((~StateFn(op) @ state).eval(), 0j) + with self.assertWarns(DeprecationWarning): + op = 0 * (I + Z) + state = Plus + self.assertEqual((~StateFn(op) @ state).eval(), 0j) backend = Aer.get_backend("aer_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend, seed_simulator=97, seed_transpiler=97) - self.assertTrue(len(caught_warnings) > 0) - op = I + op = I with self.subTest("zero coeff in summed StateFn and CircuitSampler"): - state = 0 * (Plus + Minus) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + state = 0 * (Plus + Minus) sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state) - self.assertTrue(len(caught_warnings) > 0) - self.assertEqual(sampler.eval(), 0j) + self.assertEqual(sampler.eval(), 0j) with self.subTest("coeff gets squared in CircuitSampler shot-based readout"): - state = (Plus + Minus) / numpy.sqrt(2) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + state = (Plus + Minus) / numpy.sqrt(2) sampler = CircuitSampler(q_instance).convert(~StateFn(op) @ state) - self.assertTrue(len(caught_warnings) > 0) - self.assertAlmostEqual(sampler.eval(), 1 + 0j) + self.assertAlmostEqual(sampler.eval(), 1 + 0j) def test_is_measurement_correctly_propagated(self): """Test if is_measurement property of StateFn is propagated to converted StateFn.""" @@ -115,22 +103,12 @@ def test_is_measurement_correctly_propagated(self): self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") return backend = Aer.get_backend("aer_simulator") - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend) # no seeds needed since no values are compared - self.assertTrue(len(caught_warnings) > 0) - state = Plus - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + state = Plus sampler = CircuitSampler(q_instance).convert(~state @ state) - self.assertTrue(len(caught_warnings) > 0) - self.assertTrue(sampler.oplist[0].is_measurement) + self.assertTrue(sampler.oplist[0].is_measurement) def test_parameter_binding_on_listop(self): """Test passing a ListOp with differing parameters works with the circuit sampler.""" @@ -148,30 +126,26 @@ def test_parameter_binding_on_listop(self): circuit3 = QuantumCircuit(1) circuit3.p(y, 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): bindings = {x: -0.4, y: 0.4} listop = ListOp([StateFn(circuit) for circuit in [circuit1, circuit2, circuit3]]) sampler = CircuitSampler(Aer.get_backend("aer_simulator")) sampled = sampler.convert(listop, params=bindings) - self.assertTrue(len(caught_warnings) > 0) - self.assertTrue(all(len(op.parameters) == 0 for op in sampled.oplist)) def test_list_op_eval_coeff_with_nonlinear_combofn(self): """Test evaluating a ListOp with non-linear combo function works with coefficients.""" - state = One - op = ListOp(5 * [I], coeff=2, combo_fn=numpy.prod) - expr1 = ~StateFn(op) @ state - expr2 = ListOp(5 * [~state @ I @ state], coeff=2, combo_fn=numpy.prod) + with self.assertWarns(DeprecationWarning): + state = One + op = ListOp(5 * [I], coeff=2, combo_fn=numpy.prod) + expr1 = ~StateFn(op) @ state + + expr2 = ListOp(5 * [~state @ I @ state], coeff=2, combo_fn=numpy.prod) - self.assertEqual(expr1.eval(), 2) # if the coeff is propagated too far the result is 4 - self.assertEqual(expr2.eval(), 2) + self.assertEqual(expr1.eval(), 2) # if the coeff is propagated too far the result is 4 + self.assertEqual(expr2.eval(), 2) def test_single_parameter_binds(self): """Test passing parameter binds as a dictionary to the circuit sampler.""" @@ -184,16 +158,11 @@ def test_single_parameter_binds(self): x = Parameter("x") circuit = QuantumCircuit(1) circuit.ry(x, 0) - expr = ~StateFn(H) @ StateFn(circuit) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): + expr = ~StateFn(H) @ StateFn(circuit) sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector")) res = sampler.convert(expr, params={x: 0}).eval() - self.assertTrue(len(caught_warnings) > 0) self.assertIsInstance(res, complex) @@ -209,26 +178,17 @@ def test_circuit_sampler_caching(self, caching): x = Parameter("x") circuit = QuantumCircuit(1) circuit.ry(x, 0) - expr1 = ~StateFn(H) @ StateFn(circuit) - expr2 = ~StateFn(X) @ StateFn(circuit) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): + + expr1 = ~StateFn(H) @ StateFn(circuit) + expr2 = ~StateFn(X) @ StateFn(circuit) sampler = CircuitSampler(Aer.get_backend("aer_simulator_statevector"), caching=caching) - self.assertTrue(len(caught_warnings) > 0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) res1 = sampler.convert(expr1, params={x: 0}).eval() res2 = sampler.convert(expr2, params={x: 0}).eval() res3 = sampler.convert(expr1, params={x: 0}).eval() res4 = sampler.convert(expr2, params={x: 0}).eval() - self.assertTrue(len(caught_warnings) > 0) self.assertEqual(res1, res3) self.assertEqual(res2, res4) @@ -242,8 +202,9 @@ def test_adjoint_nonunitary_circuit_raises(self): circuit = QuantumCircuit(1) circuit.reset(0) - with self.assertRaises(OpflowError): - _ = StateFn(circuit).adjoint() + with self.assertWarns(DeprecationWarning): + with self.assertRaises(OpflowError): + _ = StateFn(circuit).adjoint() def test_evaluating_nonunitary_circuit_state(self): """Test evaluating a circuit works even if it contains non-unitary instruction (resets). @@ -254,9 +215,11 @@ def test_evaluating_nonunitary_circuit_state(self): """ circuit = QuantumCircuit(1) circuit.initialize([0, 1], [0]) - op = Z - res = (~StateFn(op) @ StateFn(circuit)).eval() + with self.assertWarns(DeprecationWarning): + op = Z + res = (~StateFn(op) @ StateFn(circuit)).eval() + self.assertAlmostEqual(-1 + 0j, res) def test_quantum_instance_with_backend_shots(self): @@ -267,27 +230,25 @@ def test_quantum_instance_with_backend_shots(self): self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") backend = AerSimulator(shots=10) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + + with self.assertWarns(DeprecationWarning): sampler = CircuitSampler(backend) res = sampler.convert(~Plus @ Plus).eval() - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(res, 1 + 0j, places=2) def test_adjoint_vector_to_circuit_fn(self): """Test it is possible to adjoint a VectorStateFn that was converted to a CircuitStateFn.""" - left = StateFn([0, 1]) - left_circuit = left.to_circuit_op().primitive - right_circuit = QuantumCircuit(1) - right_circuit.x(0) + with self.assertWarns(DeprecationWarning): + left = StateFn([0, 1]) + left_circuit = left.to_circuit_op().primitive + + right_circuit = QuantumCircuit(1) + right_circuit.x(0) - circuit = left_circuit.inverse().compose(right_circuit) + circuit = left_circuit.inverse().compose(right_circuit) - self.assertTrue(Statevector(circuit).equiv([1, 0])) + self.assertTrue(Statevector(circuit).equiv([1, 0])) if __name__ == "__main__": diff --git a/test/python/result/test_sampled_expval.py b/test/python/result/test_sampled_expval.py index 8cac9042b406..f7cb06c5b86b 100644 --- a/test/python/result/test_sampled_expval.py +++ b/test/python/result/test_sampled_expval.py @@ -13,7 +13,6 @@ """Tests for qiskit.quantum_info.analysis""" import unittest -import warnings from qiskit.result import Counts, QuasiDistribution, ProbDistribution, sampled_expectation_value from qiskit.quantum_info import Pauli, SparsePauliOp from qiskit.opflow import PauliOp, PauliSumOp @@ -83,23 +82,13 @@ def test_same(self): exp2 = sampled_expectation_value(counts, Pauli(oper)) self.assertAlmostEqual(exp2, ans) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): exp3 = sampled_expectation_value(counts, PauliOp(Pauli(oper))) - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(exp3, ans) spo = SparsePauliOp([oper], coeffs=[1]) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): exp4 = sampled_expectation_value(counts, PauliSumOp(spo, coeff=2)) - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual(exp4, 2 * ans) exp5 = sampled_expectation_value(counts, SparsePauliOp.from_list([[oper, 1]])) diff --git a/test/python/utils/mitigation/test_meas.py b/test/python/utils/mitigation/test_meas.py index e10f47ea77f9..a5105b5ba4d5 100644 --- a/test/python/utils/mitigation/test_meas.py +++ b/test/python/utils/mitigation/test_meas.py @@ -28,7 +28,6 @@ """ import unittest -import warnings import numpy as np import qiskit @@ -279,30 +278,20 @@ def test_ideal_meas_cal(self): # Generate the quantum register according to the pattern qubits, weight = self.choose_calibration(nq, pattern_type) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Generate the calibration circuits meas_calibs, state_labels = complete_meas_cal( qubit_list=qubits, circlabel="test" ) - self.assertTrue(len(caught_warnings) > 0) # Perform an ideal execution on the generated circuits backend = AerSimulator() job = qiskit.execute(meas_calibs, backend=backend, shots=self.shots) cal_results = job.result() - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Make a calibration matrix meas_cal = CompleteMeasFitter(cal_results, state_labels, circlabel="test") - self.assertTrue(len(caught_warnings) > 0) # Assert that the calibration matrix is equal to identity IdentityMatrix = np.identity(2**weight) @@ -322,14 +311,9 @@ def test_ideal_meas_cal(self): # Generate ideal (equally distributed) results results_dict, results_list = self.generate_ideal_results(state_labels, weight) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Output the filter meas_filter = meas_cal.filter - self.assertTrue(len(caught_warnings) > 0) # Apply the calibration matrix to results # in list and dict forms using different methods @@ -350,13 +334,8 @@ def test_ideal_meas_cal(self): def test_meas_cal_on_circuit(self): """Test an execution on a circuit.""" # Generate the calibration circuits - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): meas_calibs, state_labels, ghz = meas_calib_circ_creation() - self.assertTrue(len(caught_warnings) > 0) # Run the calibration circuits backend = AerSimulator() @@ -369,14 +348,9 @@ def test_meas_cal_on_circuit(self): ) cal_results = job.result() - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Make a calibration matrix meas_cal = CompleteMeasFitter(cal_results, state_labels) - self.assertTrue(len(caught_warnings) > 0) # Calculate the fidelity fidelity = meas_cal.readout_fidelity() @@ -388,13 +362,8 @@ def test_meas_cal_on_circuit(self): # Predicted equally distributed results predicted_results = {"000": 0.5, "111": 0.5} - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): meas_filter = meas_cal.filter - self.assertTrue(len(caught_warnings) > 0) # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( @@ -429,26 +398,16 @@ def test_ideal_tensored_meas_cal(self): meas_layout = [1, 2, 3, 4, 5, 6] # Generate the calibration circuits - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): meas_calibs, _ = tensored_meas_cal(mit_pattern=mit_pattern) - self.assertTrue(len(caught_warnings) > 0) # Perform an ideal execution on the generated circuits backend = AerSimulator() cal_results = qiskit.execute(meas_calibs, backend=backend, shots=self.shots).result() - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Make calibration matrices meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) - self.assertTrue(len(caught_warnings) > 0) # Assert that the calibration matrices are equal to identity cal_matrices = meas_cal.cal_matrices @@ -470,11 +429,7 @@ def test_ideal_tensored_meas_cal(self): "Error: the average fidelity is not equal to 1", ) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Generate ideal (equally distributed) results results_dict, _ = self.generate_ideal_results(count_keys(6), 6) # Output the filter @@ -487,7 +442,6 @@ def test_ideal_tensored_meas_cal(self): results_dict_0 = meas_filter.apply( results_dict, method="pseudo_inverse", meas_layout=meas_layout ) - self.assertTrue(len(caught_warnings) > 0) # Assert that the results are equally distributed self.assertDictEqual(results_dict, results_dict_0) @@ -499,14 +453,9 @@ def test_ideal_tensored_meas_cal(self): def test_tensored_meas_cal_on_circuit(self): """Test an execution on a circuit.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Generate the calibration circuits meas_calibs, mit_pattern, ghz, meas_layout = tensored_calib_circ_creation() - self.assertTrue(len(caught_warnings) > 0) # Run the calibration circuits backend = AerSimulator() @@ -518,14 +467,9 @@ def test_tensored_meas_cal_on_circuit(self): seed_transpiler=SEED, ).result() - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): # Make a calibration matrix meas_cal = TensoredMeasFitter(cal_results, mit_pattern=mit_pattern) - self.assertTrue(len(caught_warnings) > 0) # Calculate the fidelity fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1) @@ -536,11 +480,7 @@ def test_tensored_meas_cal_on_circuit(self): # Predicted equally distributed results predicted_results = {"000": 0.5, "111": 0.5} - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): meas_filter = meas_cal.filter # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( @@ -549,7 +489,6 @@ def test_tensored_meas_cal_on_circuit(self): output_results_least_square = meas_filter.apply( results, method="least_squares", meas_layout=meas_layout ).get_counts(0) - self.assertTrue(len(caught_warnings) > 0) # Compare with expected fidelity and expected results self.assertAlmostEqual(fidelity, 1.0) @@ -573,11 +512,7 @@ def test_meas_fitter_with_noise(self): """Test the MeasurementFitter with noise.""" tests = [] runs = 3 - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for run in range(runs): cal_results, state_labels, circuit_results = meas_calibration_circ_execution( 1000, SEED + run @@ -643,15 +578,10 @@ def test_meas_fitter_with_noise(self): tests[tst_index]["results_least_square"]["111"], places=0, ) - self.assertTrue(len(caught_warnings) > 0) def test_tensored_meas_fitter_with_noise(self): """Test the TensoredFitter with noise.""" - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): cal_results, mit_pattern, circuit_results, meas_layout = tensored_calib_circ_execution( 1000, SEED ) @@ -664,7 +594,6 @@ def test_tensored_meas_fitter_with_noise(self): results_least_square = meas_filter.apply( circuit_results.get_counts(), method="least_squares", meas_layout=meas_layout ) - self.assertTrue(len(caught_warnings) > 0) saved_info = { "cal_results": cal_results.to_dict(), @@ -679,26 +608,17 @@ def test_tensored_meas_fitter_with_noise(self): saved_info["cal_results"] = Result.from_dict(saved_info["cal_results"]) saved_info["results"] = Result.from_dict(saved_info["results"]) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): meas_cal = TensoredMeasFitter( saved_info["cal_results"], mit_pattern=saved_info["mit_pattern"] ) - self.assertTrue(len(caught_warnings) > 0) + # Calculate the fidelity + fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1) + # Compare with expected fidelity and expected results - # Calculate the fidelity - fidelity = meas_cal.readout_fidelity(0) * meas_cal.readout_fidelity(1) - # Compare with expected fidelity and expected results self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): meas_filter = meas_cal.filter # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( @@ -709,7 +629,6 @@ def test_tensored_meas_fitter_with_noise(self): output_results_least_square = meas_filter.apply( saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"] ) - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual( output_results_pseudo_inverse["000"], @@ -736,11 +655,7 @@ def test_tensored_meas_fitter_with_noise(self): ) substates_list = [] - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): for qubit_list in saved_info["mit_pattern"]: substates_list.append(count_keys(len(qubit_list))[::-1]) fitter_other_order = TensoredMeasFitter( @@ -748,17 +663,12 @@ def test_tensored_meas_fitter_with_noise(self): substate_labels_list=substates_list, mit_pattern=saved_info["mit_pattern"], ) - self.assertTrue(len(caught_warnings) > 0) fidelity = fitter_other_order.readout_fidelity(0) * meas_cal.readout_fidelity(1) self.assertAlmostEqual(fidelity, saved_info["fidelity"], places=0) - with warnings.catch_warnings(record=True) as caught_warnings: - warnings.filterwarnings( - "always", - category=DeprecationWarning, - ) + with self.assertWarns(DeprecationWarning): meas_filter = fitter_other_order.filter # Calculate the results after mitigation output_results_pseudo_inverse = meas_filter.apply( @@ -769,7 +679,6 @@ def test_tensored_meas_fitter_with_noise(self): output_results_least_square = meas_filter.apply( saved_info["results"], method="least_squares", meas_layout=saved_info["meas_layout"] ) - self.assertTrue(len(caught_warnings) > 0) self.assertAlmostEqual( output_results_pseudo_inverse["000"], From e9e6a4fa08fdb737de58998384369c6c83b8e06d Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 14:30:28 +0200 Subject: [PATCH 35/47] Fix formatting --- .../algorithms/test_observables_evaluator.py | 4 +--- .../circuit/library/test_evolved_op_ansatz.py | 1 - test/python/opflow/test_expectation_factory.py | 1 - test/python/opflow/test_gradients.py | 16 +++++++++------- test/python/opflow/test_matrix_expectation.py | 8 ++++++-- test/python/opflow/test_pauli_expectation.py | 4 +++- 6 files changed, 19 insertions(+), 15 deletions(-) diff --git a/test/python/algorithms/test_observables_evaluator.py b/test/python/algorithms/test_observables_evaluator.py index 7284313e53eb..f4df4ba4bdf5 100644 --- a/test/python/algorithms/test_observables_evaluator.py +++ b/test/python/algorithms/test_observables_evaluator.py @@ -72,9 +72,7 @@ def _run_test( observables: ListOrDict[BaseOperator | PauliSumOp], estimator: Estimator, ): - result = estimate_observables( - estimator, quantum_state, observables, None, self.threshold - ) + result = estimate_observables(estimator, quantum_state, observables, None, self.threshold) if isinstance(observables, dict): np.testing.assert_equal(list(result.keys()), list(expected_result.keys())) diff --git a/test/python/circuit/library/test_evolved_op_ansatz.py b/test/python/circuit/library/test_evolved_op_ansatz.py index b4c65defd1a4..c809fe438820 100644 --- a/test/python/circuit/library/test_evolved_op_ansatz.py +++ b/test/python/circuit/library/test_evolved_op_ansatz.py @@ -38,7 +38,6 @@ def test_evolved_op_ansatz(self, use_opflow): evo = EvolvedOperatorAnsatz(ops, 2) parameters = evo.parameters - else: ops = [Pauli("Z" * num_qubits), Pauli("Y" * num_qubits), Pauli("X" * num_qubits)] evo = EvolvedOperatorAnsatz(ops, 2) diff --git a/test/python/opflow/test_expectation_factory.py b/test/python/opflow/test_expectation_factory.py index 7ba539048499..f03a8517733d 100644 --- a/test/python/opflow/test_expectation_factory.py +++ b/test/python/opflow/test_expectation_factory.py @@ -37,4 +37,3 @@ def test_aer_simulator_pauli_sum(self): with self.subTest("Include custom"): expectation = ExpectationFactory.build(op, backend, include_custom=True) self.assertIsInstance(expectation, AerPauliExpectation) -∂ diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 48266c78dea6..4bfcdff773ab 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -885,7 +885,9 @@ def grad_combo_fn(x): qc = RealAmplitudes(2, reps=1) with self.assertWarns(DeprecationWarning): - grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn) + grad_op = ListOp( + [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn + ) grad = Gradient(grad_method=method).convert(grad_op) value_dict = dict(zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters)))) @@ -1152,13 +1154,13 @@ def test_gradient_wrapper(self, backend_type): with self.assertWarns(DeprecationWarning): if method == "fin_diff": np.random.seed(8) - prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( + prob_grad = Gradient( + grad_method=method, epsilon=shots ** (-1 / 6.0) + ).gradient_wrapper(operator=op, bind_params=params, backend=q_instance) + else: + prob_grad = Gradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) - else: - prob_grad = Gradient(grad_method=method).gradient_wrapper( - operator=op, bind_params=params, backend=q_instance - ) values = [[np.pi / 4, 0], [np.pi / 4, np.pi / 4], [np.pi / 2, np.pi]] correct_values = [ @@ -1535,7 +1537,7 @@ def test_overlap_qfi_raises_on_multiparam(self): with self.assertRaises(NotImplementedError): with self.assertWarns(DeprecationWarning): - _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) def test_overlap_qfi_raises_on_unsupported_gate(self): """Test the overlap QFI raises an appropriate error on multi-param unbound gates.""" diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index d51d841715b6..867c9d36b6d1 100644 --- a/test/python/opflow/test_matrix_expectation.py +++ b/test/python/opflow/test_matrix_expectation.py @@ -154,10 +154,14 @@ def test_pauli_expect_op_vector_state_vector(self): valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] converted_meas = self.expect.convert(~StateFn(paulis_op)) - np.testing.assert_array_almost_equal((converted_meas @ states_op).eval(), valids, decimal=1) + np.testing.assert_array_almost_equal( + (converted_meas @ states_op).eval(), valids, decimal=1 + ) sampled = self.sampler.convert(states_op) - np.testing.assert_array_almost_equal((converted_meas @ sampled).eval(), valids, decimal=1) + np.testing.assert_array_almost_equal( + (converted_meas @ sampled).eval(), valids, decimal=1 + ) def test_multi_representation_ops(self): """Test observables with mixed representations""" diff --git a/test/python/opflow/test_pauli_expectation.py b/test/python/opflow/test_pauli_expectation.py index ebc5df503809..f46c68bd50d8 100644 --- a/test/python/opflow/test_pauli_expectation.py +++ b/test/python/opflow/test_pauli_expectation.py @@ -226,7 +226,9 @@ def test_grouped_pauli_expectation(self): num_circuits_ungrouped = len(self.sampler._circuit_ops_cache) self.assertEqual(num_circuits_ungrouped, 5) - expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf) + expect_op_grouped = PauliExpectation(group_paulis=True).convert( + ~StateFn(two_qubit_H2) @ wf + ) q_instance = QuantumInstance( BasicAer.get_backend("statevector_simulator"), From 8b3136a1d0f5e3439cce3f813466b31f680e19d3 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 14:32:07 +0200 Subject: [PATCH 36/47] Restore unchanged unit tests Restore opflow test case Restore estimator test Restore unchanged tests --- .../algorithms/eigensolvers/test_vqd.py | 22 +++++++++++++------ .../gradients/test_estimator_gradient.py | 6 +++-- test/python/algorithms/gradients/test_qgt.py | 3 ++- .../gradients/test_sampler_gradient.py | 7 ++++-- .../minimum_eigensolvers/test_sampling_vqe.py | 3 ++- .../variational/test_var_qite.py | 3 ++- .../variational/test_var_qrte.py | 2 ++ test/python/circuit/library/test_qft.py | 10 ++++++++- test/python/opflow/opflow_test_case.py | 3 +-- test/python/primitives/test_estimator.py | 3 ++- 10 files changed, 44 insertions(+), 18 deletions(-) diff --git a/test/python/algorithms/eigensolvers/test_vqd.py b/test/python/algorithms/eigensolvers/test_vqd.py index 295308ca0aff..16652a259ebd 100644 --- a/test/python/algorithms/eigensolvers/test_vqd.py +++ b/test/python/algorithms/eigensolvers/test_vqd.py @@ -10,7 +10,7 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -""" Test VQD """ +"""Test VQD""" import unittest from test.python.algorithms import QiskitAlgorithmsTestCase @@ -19,13 +19,9 @@ from ddt import data, ddt from qiskit import QuantumCircuit -from qiskit.algorithms.eigensolvers import VQD +from qiskit.algorithms.eigensolvers import VQD, VQDResult from qiskit.algorithms import AlgorithmError -from qiskit.algorithms.optimizers import ( - COBYLA, - L_BFGS_B, - SLSQP, -) +from qiskit.algorithms.optimizers import COBYLA, L_BFGS_B, SLSQP, SPSA from qiskit.algorithms.state_fidelities import ComputeUncompute from qiskit.circuit.library import TwoLocal, RealAmplitudes from qiskit.opflow import PauliSumOp @@ -207,6 +203,7 @@ def store_intermediate_result(eval_count, parameters, mean, metadata, step): @data(H2_PAULI, H2_OP, H2_SPARSE_PAULI) def test_vqd_optimizer(self, op): """Test running same VQD twice to re-use optimizer, then switch optimizer""" + vqd = VQD( estimator=self.estimator, fidelity=self.fidelity, @@ -231,6 +228,17 @@ def run_check(): vqd.optimizer = L_BFGS_B() run_check() + with self.subTest("Batched optimizer replace"): + vqd.optimizer = SLSQP(maxiter=60, max_evals_grouped=10) + run_check() + + with self.subTest("SPSA replace"): + # SPSA takes too long to converge, so we will + # only check that it runs with no errors. + vqd.optimizer = SPSA(maxiter=5, learning_rate=0.01, perturbation=0.01) + result = vqd.compute_eigenvalues(operator=op) + self.assertIsInstance(result, VQDResult) + @data(H2_PAULI, H2_OP, H2_SPARSE_PAULI) def test_optimizer_list(self, op): """Test sending an optimizer list""" diff --git a/test/python/algorithms/gradients/test_estimator_gradient.py b/test/python/algorithms/gradients/test_estimator_gradient.py index ae6dbfa2930d..c84450313b61 100644 --- a/test/python/algorithms/gradients/test_estimator_gradient.py +++ b/test/python/algorithms/gradients/test_estimator_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2023. +# (C) Copyright IBM 2019, 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 @@ -14,7 +14,7 @@ """Test Estimator Gradients""" import unittest -from test.python.algorithms.gradients.logging_primitives import LoggingEstimator + import numpy as np from ddt import ddt, data, unpack @@ -35,6 +35,8 @@ from qiskit.quantum_info.random import random_pauli_list from qiskit.test import QiskitTestCase +from .logging_primitives import LoggingEstimator + gradient_factories = [ lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="central"), lambda estimator: FiniteDiffEstimatorGradient(estimator, epsilon=1e-6, method="forward"), diff --git a/test/python/algorithms/gradients/test_qgt.py b/test/python/algorithms/gradients/test_qgt.py index df8eecdd8478..74f22d462d7c 100644 --- a/test/python/algorithms/gradients/test_qgt.py +++ b/test/python/algorithms/gradients/test_qgt.py @@ -14,7 +14,6 @@ """Test QGT.""" import unittest -from test.python.algorithms.gradients.logging_primitives import LoggingEstimator from ddt import ddt, data import numpy as np @@ -26,6 +25,8 @@ from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase +from .logging_primitives import LoggingEstimator + @ddt class TestQGT(QiskitTestCase): diff --git a/test/python/algorithms/gradients/test_sampler_gradient.py b/test/python/algorithms/gradients/test_sampler_gradient.py index 2c9f93a9f17e..b4caac078502 100644 --- a/test/python/algorithms/gradients/test_sampler_gradient.py +++ b/test/python/algorithms/gradients/test_sampler_gradient.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2019, 2023. +# (C) Copyright IBM 2019, 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 @@ -15,9 +15,10 @@ import unittest from typing import List -from test.python.algorithms.gradients.logging_primitives import LoggingSampler + import numpy as np from ddt import ddt, data + from qiskit import QuantumCircuit from qiskit.algorithms.gradients import ( FiniteDiffSamplerGradient, @@ -32,6 +33,8 @@ from qiskit.result import QuasiDistribution from qiskit.test import QiskitTestCase +from .logging_primitives import LoggingSampler + gradient_factories = [ lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="central"), lambda sampler: FiniteDiffSamplerGradient(sampler, epsilon=1e-6, method="forward"), diff --git a/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py b/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py index 27cf6c46cfb0..8e364e3800c4 100644 --- a/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py +++ b/test/python/algorithms/minimum_eigensolvers/test_sampling_vqe.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2023. +# (C) Copyright IBM 2018, 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 @@ -12,6 +12,7 @@ """Test the Sampler VQE.""" + import unittest from functools import partial from test.python.algorithms import QiskitAlgorithmsTestCase diff --git a/test/python/algorithms/time_evolvers/variational/test_var_qite.py b/test/python/algorithms/time_evolvers/variational/test_var_qite.py index 636798d7947e..9c79a0024885 100644 --- a/test/python/algorithms/time_evolvers/variational/test_var_qite.py +++ b/test/python/algorithms/time_evolvers/variational/test_var_qite.py @@ -99,8 +99,8 @@ def test_run_d_1_with_aux_ops(self): var_qite = VarQITE( ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) - evolution_result = var_qite.evolve(evolution_problem) + aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] @@ -128,6 +128,7 @@ def test_run_d_1_with_aux_ops(self): ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qite.evolve(evolution_problem) + aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] diff --git a/test/python/algorithms/time_evolvers/variational/test_var_qrte.py b/test/python/algorithms/time_evolvers/variational/test_var_qrte.py index 1682c60b842b..b7dfaf59f12b 100644 --- a/test/python/algorithms/time_evolvers/variational/test_var_qrte.py +++ b/test/python/algorithms/time_evolvers/variational/test_var_qrte.py @@ -131,6 +131,7 @@ def test_run_d_1_with_aux_ops(self): ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) + aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] @@ -158,6 +159,7 @@ def test_run_d_1_with_aux_ops(self): ansatz, init_param_values, var_principle, estimator, num_timesteps=25 ) evolution_result = var_qrte.evolve(evolution_problem) + aux_ops = evolution_result.aux_ops_evaluated parameter_values = evolution_result.parameter_values[-1] diff --git a/test/python/circuit/library/test_qft.py b/test/python/circuit/library/test_qft.py index 49e34736616d..fa5305aa3631 100644 --- a/test/python/circuit/library/test_qft.py +++ b/test/python/circuit/library/test_qft.py @@ -13,6 +13,7 @@ """Test library of QFT circuits.""" import unittest +import warnings import numpy as np from ddt import ddt, data, unpack @@ -184,11 +185,18 @@ def __init__(self, *_args, **_kwargs): # We don't want to issue a warning on mutation until we know that the values are # finalised; this is because a user might want to mutate the number of qubits and the # approximation degree. In these cases, wait until we try to build the circuit. - with self.assertWarns(DeprecationWarning): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=RuntimeWarning, + module=r"qiskit\..*", + message=r".*precision loss in QFT.*", + ) qft = QFT() # Even with the approximation this will trigger the warning. qft.num_qubits = 1080 qft.approximation_degree = 20 + self.assertFalse(caught_warnings) # Short-circuit the build method so it exits after input validation, but without actually # spinning the CPU to build a huge, useless object. diff --git a/test/python/opflow/opflow_test_case.py b/test/python/opflow/opflow_test_case.py index ebd0d5d6b377..ef8d8c6824c7 100644 --- a/test/python/opflow/opflow_test_case.py +++ b/test/python/opflow/opflow_test_case.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2018, 2023. +# (C) Copyright IBM 2018, 2020. # # 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 @@ -12,7 +12,6 @@ """Opflow Test Case""" -import warnings from qiskit.test import QiskitTestCase diff --git a/test/python/primitives/test_estimator.py b/test/python/primitives/test_estimator.py index 73f20f449d71..4a9209e7fa8a 100644 --- a/test/python/primitives/test_estimator.py +++ b/test/python/primitives/test_estimator.py @@ -1,6 +1,6 @@ # This code is part of Qiskit. # -# (C) Copyright IBM 2022, 2023. +# (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 @@ -13,6 +13,7 @@ """Tests for Estimator.""" import unittest + import numpy as np from ddt import data, ddt, unpack From eaf7e920758173071d56c6902b8cf792ee7fe7eb Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 15:24:36 +0200 Subject: [PATCH 37/47] Go back to old opflow test setup --- test/python/opflow/opflow_test_case.py | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/test/python/opflow/opflow_test_case.py b/test/python/opflow/opflow_test_case.py index ef8d8c6824c7..54a2f715b110 100644 --- a/test/python/opflow/opflow_test_case.py +++ b/test/python/opflow/opflow_test_case.py @@ -13,9 +13,17 @@ """Opflow Test Case""" from qiskit.test import QiskitTestCase - +import warnings class QiskitOpflowTestCase(QiskitTestCase): """Opflow test Case""" - pass + def setUp(self): + super().setUp() + # ignore opflow msgs + warnings.filterwarnings("ignore", category=DeprecationWarning, message=r".*opflow.*") + + def tearDown(self): + super().tearDown() + # restore opflow msgs + warnings.filterwarnings("error", category=DeprecationWarning, message=r".*opflow.*") From 72ee9b4fcd9c3cd78fb524e864747dd1874672db Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 15:41:56 +0200 Subject: [PATCH 38/47] Revert "Refactor gradients test warnings", only keep qi assertWarns This reverts commit 9c0a37f3bc3068a9b1ccd122298cfefe556d4135. --- test/python/opflow/test_gradients.py | 465 ++++++++++++--------------- 1 file changed, 199 insertions(+), 266 deletions(-) diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 4bfcdff773ab..327613252ec1 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -67,18 +67,16 @@ def test_gradient_p(self, method): Tr(|psi>/da = - 0.5 sin(a) """ + ham = 0.5 * X - 1 * Z a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-0.5 / np.sqrt(2), 0, -0.5] @@ -104,11 +102,9 @@ def test_gradient_u(self, method): qc.h(q) qc.u(a, b, c, q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a, b, c] - with self.assertWarns(DeprecationWarning): - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4, b: 0, c: 0}, {a: np.pi / 4, b: np.pi / 4, c: np.pi / 4}] correct_values = [[0.3536, 0, 0], [0.3232, -0.42678, -0.92678]] for i, value_dict in enumerate(values_dict): @@ -125,11 +121,9 @@ def test_gradient_u(self, method): qc.h(q) qc.u(a, a, a, q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - with self.assertWarns(DeprecationWarning): - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-1.03033], [-1]] for i, value_dict in enumerate(values_dict): @@ -140,18 +134,16 @@ def test_gradient_u(self, method): @data("lin_comb", "param_shift") def test_gradient_efficient_su2(self, method): """Test the state gradient for EfficientSU2""" - - with self.assertWarns(DeprecationWarning): - observable = SummedOp( - [ - 0.2252 * (I ^ I), - 0.5716 * (Z ^ Z), - 0.3435 * (I ^ Z), - -0.4347 * (Z ^ I), - 0.091 * (Y ^ Y), - 0.091 * (X ^ X), - ] - ).reduce() + observable = SummedOp( + [ + 0.2252 * (I ^ I), + 0.5716 * (Z ^ Z), + 0.3435 * (I ^ Z), + -0.4347 * (Z ^ I), + 0.091 * (Y ^ Y), + 0.091 * (X ^ X), + ] + ).reduce() d = 2 ansatz = EfficientSU2(observable.num_qubits, reps=d) @@ -159,8 +151,7 @@ def test_gradient_efficient_su2(self, method): # Define a set of initial parameters parameters = ansatz.ordered_parameters - with self.assertWarns(DeprecationWarning): - operator = ~StateFn(observable) @ StateFn(ansatz) + operator = ~StateFn(observable) @ StateFn(ansatz) values_dict = [ {param: np.pi / 4 for param in parameters}, @@ -197,9 +188,7 @@ def test_gradient_efficient_su2(self, method): ], ] - with self.assertWarns(DeprecationWarning): - state_grad = Gradient(method).convert(operator, parameters) - + state_grad = Gradient(method).convert(operator, parameters) for i, value_dict in enumerate(values_dict): np.testing.assert_array_almost_equal( state_grad.assign_parameters(value_dict).eval(), correct_values[i], decimal=1 @@ -208,6 +197,7 @@ def test_gradient_efficient_su2(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rxx(self, method): """Test the state gradient for XX rotation""" + ham = TensoredOp([Z, X]) a = Parameter("a") q = QuantumRegister(2) @@ -215,12 +205,9 @@ def test_gradient_rxx(self, method): qc.h(q[0]) qc.rxx(a, q[0], q[1]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - with self.assertWarns(DeprecationWarning): - ham = TensoredOp([Z, X]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): @@ -232,17 +219,15 @@ def test_gradient_rxx(self, method): def test_gradient_ryy(self, method): """Test the state gradient for YY rotation""" alpha = Parameter("alpha") + ham = TensoredOp([Y, alpha * Y]) a = Parameter("a") q = QuantumRegister(2) qc = QuantumCircuit(q) qc.ryy(a, q[0], q[1]) - with self.assertWarns(DeprecationWarning): - ham = TensoredOp([Y, alpha * Y]) - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=a) - + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_grad = Gradient(grad_method=method).convert(operator=op, params=a) values_dict = [{a: np.pi / 8}, {a: np.pi}] correct_values = [[0], [0]] for i, value_dict in enumerate(values_dict): @@ -254,6 +239,7 @@ def test_gradient_ryy(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzz(self, method): """Test the state gradient for ZZ rotation""" + ham = Z ^ X a = Parameter("a") q = QuantumRegister(2) @@ -261,12 +247,9 @@ def test_gradient_rzz(self, method): qc.h(q[0]) qc.rzz(a, q[0], q[1]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - with self.assertWarns(DeprecationWarning): - ham = Z ^ X - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: np.pi / 2}] correct_values = [[-0.707], [-1.0]] for i, value_dict in enumerate(values_dict): @@ -277,6 +260,7 @@ def test_gradient_rzz(self, method): @data("lin_comb", "param_shift", "fin_diff") def test_gradient_rzx(self, method): """Test the state gradient for ZX rotation""" + ham = Z ^ Z a = Parameter("a") q = QuantumRegister(2) @@ -284,12 +268,9 @@ def test_gradient_rzx(self, method): qc.h(q) qc.rzx(a, q[0], q[1]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) params = [a] - with self.assertWarns(DeprecationWarning): - ham = Z ^ Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 8}, {a: np.pi / 2}] correct_values = [[0.0], [0.0]] for i, value_dict in enumerate(values_dict): @@ -307,6 +288,7 @@ def test_state_gradient1(self, method): d/db = - 1 sin(a)cos(b) """ + ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] @@ -316,12 +298,9 @@ def test_state_gradient1(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -346,6 +325,7 @@ def test_state_gradient2(self, method): Tr(|psi>/da = - 0.5 sin(a) - 2 cos(a)sin(a) """ + ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = [a] @@ -355,12 +335,9 @@ def test_state_gradient2(self, method): qc.h(q) qc.rz(a, q[0]) qc.rx(a, q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.353553, -0, -0.5] @@ -377,6 +354,7 @@ def test_state_gradient3(self, method): Tr(|psi>/da = - 0.5 sin(a) - 1 cos(a)sin(cos(a)+1) + 1 sin^2(a)cos(cos(a)+1) """ + ham = 0.5 * X - 1 * Z a = Parameter("a") # b = Parameter('b') params = a @@ -386,12 +364,9 @@ def test_state_gradient3(self, method): qc.h(q) qc.rz(a, q[0]) qc.rx(c, q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [-1.1220, -0.9093, 0.0403] for i, value_dict in enumerate(values_dict): @@ -406,6 +381,7 @@ def test_state_gradient4(self, method): daTr(|psi>/da1 = - 1 sin(a0)cos(a1) """ + ham = 0.5 * X - 1 * Z a = ParameterVector("a", 2) params = a @@ -446,12 +420,9 @@ def test_state_gradient5(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) - + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: [np.pi / 4, np.pi]}, {a: [np.pi / 4, np.pi / 4]}, @@ -480,6 +451,7 @@ def test_state_hessian(self, method): d^2/db^2 = + 1 sin(a)sin(b) """ + ham = 0.5 * X - 1 * Z params = ParameterVector("a", 2) q = QuantumRegister(1) @@ -488,10 +460,8 @@ def test_state_hessian(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_hess = Hessian(hess_method=method).convert(operator=op) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + state_hess = Hessian(hess_method=method).convert(operator=op) values_dict = [ {params[0]: np.pi / 4, params[1]: np.pi}, @@ -521,6 +491,7 @@ def test_state_hessian_custom_combo_fn(self, method): d^2/db^2 = + 1 sin(a)sin(b) """ + ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [(a, a), (a, b), (b, b)] @@ -531,13 +502,11 @@ def test_state_hessian_custom_combo_fn(self, method): qc.rz(a, q[0]) qc.rx(b, q[0]) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ListOp( - [~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)], - combo_fn=lambda x: x[0] ** 3 + 4 * x[0], - ) - state_hess = Hessian(hess_method=method).convert(operator=op, params=params) + op = ListOp( + [~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0)], + combo_fn=lambda x: x[0] ** 3 + 4 * x[0], + ) + state_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, @@ -576,10 +545,9 @@ def test_prob_grad(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - with self.assertWarns(DeprecationWarning): - op = CircuitStateFn(primitive=qc, coeff=1.0) - prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: 0}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -616,10 +584,9 @@ def test_prob_hess(self, method): qc.rz(a, q[0]) qc.rx(b, q[0]) - with self.assertWarns(DeprecationWarning): - op = CircuitStateFn(primitive=qc, coeff=1.0) - prob_hess = Hessian(hess_method=method).convert(operator=op, params=params) + op = CircuitStateFn(primitive=qc, coeff=1.0) + prob_hess = Hessian(hess_method=method).convert(operator=op, params=params) values_dict = [{a: np.pi / 4, b: 0}, {a: np.pi / 4, b: np.pi / 4}, {a: np.pi / 2, b: np.pi}] correct_values = [ [[0, 0], [1 / (2 * np.sqrt(2)), -1 / (2 * np.sqrt(2))]], @@ -643,6 +610,7 @@ def test_natural_gradient(self, method, regularization): """Test the natural gradient""" try: for params in (ParameterVector("a", 2), [Parameter("a"), Parameter("b")]): + ham = 0.5 * X - 1 * Z q = QuantumRegister(1) qc = QuantumCircuit(q) @@ -650,13 +618,10 @@ def test_natural_gradient(self, method, regularization): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - nat_grad = NaturalGradient( - grad_method=method, regularization=regularization - ).convert(operator=op) - + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + nat_grad = NaturalGradient( + grad_method=method, regularization=regularization + ).convert(operator=op) values_dict = [{params[0]: np.pi / 4, params[1]: np.pi / 2}] # reference values obtained by classically computing the natural gradients @@ -683,9 +648,7 @@ def test_natural_gradient2(self): @unpack def test_natural_gradient3(self, qfi_method, circuit_qfi): """Test the natural gradient 3""" - with self.assertWarns(DeprecationWarning): - nat_grad = NaturalGradient(qfi_method=qfi_method) - + nat_grad = NaturalGradient(qfi_method=qfi_method) self.assertIsInstance(nat_grad.qfi_method, circuit_qfi) @idata( @@ -701,6 +664,7 @@ def test_natural_gradient4(self, grad_method, qfi_method, regularization): # Avoid regularization = lasso intentionally because it does not converge try: + ham = 0.5 * X - 1 * Z a = Parameter("a") params = a @@ -709,13 +673,10 @@ def test_natural_gradient4(self, grad_method, qfi_method, regularization): qc.h(q) qc.rz(a, q[0]) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - nat_grad = NaturalGradient( - grad_method=grad_method, qfi_method=qfi_method, regularization=regularization - ).convert(operator=op, params=params) - + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) + nat_grad = NaturalGradient( + grad_method=grad_method, qfi_method=qfi_method, regularization=regularization + ).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}] correct_values = [[0.0]] if regularization == "ridge" else [[-1.41421342]] for i, value_dict in enumerate(values_dict): @@ -731,18 +692,16 @@ def test_gradient_p_imag(self): = iexp(-ia)/2 <1|H(|0>+exp(ia)|1>) Im() = 0.5 cos(a). """ + ham = X a = Parameter("a") params = a q = QuantumRegister(1) qc = QuantumCircuit(q) qc.h(q) qc.p(a, q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - with self.assertWarns(DeprecationWarning): - ham = X - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params) - + state_grad = LinComb(aux_meas_op=(-1) * Y).convert(operator=op, params=params) values_dict = [{a: np.pi / 4}, {a: 0}, {a: np.pi / 2}] correct_values = [1 / np.sqrt(2), 1, 0] @@ -758,6 +717,7 @@ def test_qfi_p_imag(self): circuit = QuantumCircuit(1) circuit.ry(y, 0) circuit.rx(x, 0) + state = StateFn(circuit) dx = ( lambda x, y: (-1) @@ -784,12 +744,9 @@ def test_qfi_p_imag(self): ) ) - with self.assertWarns(DeprecationWarning): - state = StateFn(circuit) - state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert( - operator=state, params=[x, y] - ) - + state_grad = LinCombFull(aux_meas_op=-1 * Y, phase_fix=False).convert( + operator=state, params=[x, y] + ) values_dict = [{x: 0, y: np.pi / 4}, {x: 0, y: np.pi / 2}, {x: np.pi / 2, y: 0}] for value_dict in values_dict: @@ -841,18 +798,16 @@ def combo_fn(x): def grad_combo_fn(x): return np.array([2 * x[0], -np.sin(x[1])]) - with self.assertWarns(DeprecationWarning): - - op = ListOp( - [ - ~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0), - ~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0), - ], - combo_fn=combo_fn, - grad_combo_fn=None if autograd else grad_combo_fn, - ) - state_grad = Gradient(grad_method=method).convert(operator=op, params=params) + op = ListOp( + [ + ~StateFn(X) @ CircuitStateFn(primitive=qc, coeff=1.0), + ~StateFn(Z) @ CircuitStateFn(primitive=qc, coeff=1.0), + ], + combo_fn=combo_fn, + grad_combo_fn=None if autograd else grad_combo_fn, + ) + state_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -883,12 +838,8 @@ def grad_combo_fn(x): return grad qc = RealAmplitudes(2, reps=1) - - with self.assertWarns(DeprecationWarning): - grad_op = ListOp( - [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn - ) - grad = Gradient(grad_method=method).convert(grad_op) + grad_op = ListOp([StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn) + grad = Gradient(grad_method=method).convert(grad_op) value_dict = dict(zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters)))) correct_values = [ @@ -920,14 +871,12 @@ def grad_combo_fn(x): try: qc = RealAmplitudes(2, reps=1) - - with self.assertWarns(DeprecationWarning): - grad_op = ListOp( - [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn - ) - grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert( - grad_op, qc.ordered_parameters - ) + grad_op = ListOp( + [StateFn(qc.decompose())], combo_fn=combo_fn, grad_combo_fn=grad_combo_fn + ) + grad = NaturalGradient(grad_method="lin_comb", regularization="ridge").convert( + grad_op, qc.ordered_parameters + ) value_dict = dict( zip(qc.ordered_parameters, np.random.rand(len(qc.ordered_parameters))) ) @@ -955,13 +904,10 @@ def test_operator_coefficient_gradient(self, method): coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") - - with self.assertWarns(DeprecationWarning): - ham = coeff_0 * X + coeff_1 * Z - op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) - gradient_coeffs = [coeff_0, coeff_1] - coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs) - + ham = coeff_0 * X + coeff_1 * Z + op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) + gradient_coeffs = [coeff_0, coeff_1] + coeff_grad = Gradient(grad_method=method).convert(op, gradient_coeffs) values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, @@ -995,13 +941,10 @@ def test_operator_coefficient_hessian(self, method): coeff_0 = Parameter("c_0") coeff_1 = Parameter("c_1") - - with self.assertWarns(DeprecationWarning): - ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z - op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) - gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)] - coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs) - + ham = coeff_0 * coeff_0 * X + coeff_1 * coeff_0 * Z + op = StateFn(ham, is_measurement=True) @ CircuitStateFn(primitive=qc, coeff=1.0) + gradient_coeffs = [(coeff_0, coeff_0), (coeff_0, coeff_1), (coeff_1, coeff_1)] + coeff_grad = Hessian(hess_method=method).convert(op, gradient_coeffs) values_dict = [ {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi}, {coeff_0: 0.5, coeff_1: -1, a: np.pi / 4, b: np.pi / 4}, @@ -1024,6 +967,7 @@ def test_circuit_sampler(self, method): d/db = - 1 sin(a)cos(b) """ + ham = 0.5 * X - 1 * Z a = Parameter("a") b = Parameter("b") params = [a, b] @@ -1033,19 +977,16 @@ def test_circuit_sampler(self, method): qc.h(q) qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) + op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - with self.assertWarns(DeprecationWarning): - ham = 0.5 * X - 1 * Z - op = ~StateFn(ham) @ CircuitStateFn(primitive=qc, coeff=1.0) - shots = 8000 - if method == "fin_diff": - np.random.seed(8) - state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( - operator=op - ) - else: - state_grad = Gradient(grad_method=method).convert(operator=op) - + shots = 8000 + if method == "fin_diff": + np.random.seed(8) + state_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( + operator=op + ) + else: + state_grad = Gradient(grad_method=method).convert(operator=op) values_dict = [ {a: np.pi / 4, b: np.pi}, {params[0]: np.pi / 4, params[1]: np.pi / 4}, @@ -1090,17 +1031,16 @@ def test_circuit_sampler2(self, method): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - with self.assertWarns(DeprecationWarning): - op = CircuitStateFn(primitive=qc, coeff=1.0) - shots = 8000 - if method == "fin_diff": - np.random.seed(8) - prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( - operator=op, params=params - ) - else: - prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) + op = CircuitStateFn(primitive=qc, coeff=1.0) + shots = 8000 + if method == "fin_diff": + np.random.seed(8) + prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).convert( + operator=op, params=params + ) + else: + prob_grad = Gradient(grad_method=method).convert(operator=op, params=params) values_dict = [ {a: [np.pi / 4], b: [0]}, {params[0]: [np.pi / 4], params[1]: [np.pi / 4]}, @@ -1142,22 +1082,24 @@ def test_gradient_wrapper(self, backend_type): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - with self.assertWarns(DeprecationWarning): - op = CircuitStateFn(primitive=qc, coeff=1.0) + op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 backend = BasicAer.get_backend(backend_type) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) - with self.assertWarns(DeprecationWarning): - if method == "fin_diff": - np.random.seed(8) - prob_grad = Gradient( - grad_method=method, epsilon=shots ** (-1 / 6.0) - ).gradient_wrapper(operator=op, bind_params=params, backend=q_instance) - else: + + if method == "fin_diff": + np.random.seed(8) + prob_grad = Gradient(grad_method=method, epsilon=shots ** (-1 / 6.0)).gradient_wrapper( + operator=op, bind_params=params, backend=q_instance + ) + else: + + with self.assertWarns(DeprecationWarning): prob_grad = Gradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) @@ -1202,22 +1144,19 @@ def test_gradient_wrapper2(self, backend_type, atol): qc.rz(params[1], 0) qc.h(1) - with self.assertWarns(DeprecationWarning): - obs = (Z ^ X) - (Y ^ Y) - op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) + obs = (Z ^ X) - (Y ^ Y) + op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) shots = 8192 if backend_type == "qasm_simulator" else 1 values = [[0, np.pi / 2], [np.pi / 4, np.pi / 4], [np.pi / 3, np.pi / 9]] correct_values = [[-4.0, 0], [-2.0, -4.82842712], [-0.68404029, -7.01396121]] - for i, value in enumerate(values): backend = BasicAer.get_backend(backend_type) with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) - with self.assertWarns(DeprecationWarning): grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) @@ -1230,14 +1169,16 @@ def test_vqe(self): method = "lin_comb" backend = "qasm_simulator" + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( BasicAer.get_backend(backend), seed_simulator=79, seed_transpiler=2 ) - # Define the Hamiltonian - h2_hamiltonian = ( - -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) - ) + + # Define the Hamiltonian + h2_hamiltonian = ( + -1.05 * (I ^ I) + 0.39 * (I ^ Z) - 0.39 * (Z ^ I) - 0.01 * (Z ^ Z) + 0.18 * (X ^ X) + ) h2_energy = -1.85727503 # Define the Ansatz @@ -1254,10 +1195,10 @@ def test_vqe(self): wavefunction.rz(next(itr), 0) wavefunction.rz(next(itr), 1) - with self.assertWarns(DeprecationWarning): - # Conjugate Gradient algorithm - optimizer = CG(maxiter=10) - grad = Gradient(grad_method=method) + # Conjugate Gradient algorithm + optimizer = CG(maxiter=10) + + grad = Gradient(grad_method=method) # Gradient callable with self.assertWarns(DeprecationWarning): @@ -1274,18 +1215,15 @@ def test_qfi_overlap_works_with_bound_parameters(self): circuit = QuantumCircuit(1) circuit.ry(np.pi / 4, 0) circuit.rx(x, 0) - - with self.assertWarns(DeprecationWarning): - state = StateFn(circuit) + state = StateFn(circuit) methods = ["lin_comb_full", "overlap_diag", "overlap_block_diag"] reference = 0.5 for method in methods: with self.subTest(method): - with self.assertWarns(DeprecationWarning): - qfi = QFI(method) - value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval()) + qfi = QFI(method) + value = np.real(qfi.convert(state, [x]).bind_parameters({x: 0.12}).eval()) self.assertAlmostEqual(value[0][0], reference) @@ -1347,10 +1285,9 @@ def test_qfi_simple(self, method): qc.rz(a, 0) qc.rx(b, 0) - with self.assertWarns(DeprecationWarning): - # convert the circuit to a QFI object - op = CircuitStateFn(qc) - qfi = QFI(qfi_method=method).convert(operator=op) + # convert the circuit to a QFI object + op = CircuitStateFn(qc) + qfi = QFI(qfi_method=method).convert(operator=op) # test for different values values_dict = [{a: np.pi / 4, b: 0.1}, {a: np.pi, b: 0.1}, {a: np.pi / 2, b: 0.1}] @@ -1372,17 +1309,15 @@ def test_qfi_phase_fix(self): qc.rz(a, 0) qc.rx(b, 0) - with self.assertWarns(DeprecationWarning): - # convert the circuit to a QFI object - op = CircuitStateFn(qc) - qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b]) + # convert the circuit to a QFI object + op = CircuitStateFn(qc) + qfi = LinCombFull(phase_fix=False).convert(operator=op, params=[a, b]) # test for different values value_dict = {a: np.pi / 4, b: 0.1} correct_values = [[1, 0], [0, 1]] - with self.assertWarns(DeprecationWarning): - actual = qfi.assign_parameters(value_dict).eval() + actual = qfi.assign_parameters(value_dict).eval() np.testing.assert_array_almost_equal(actual, correct_values, decimal=2) def test_qfi_maxcut(self): @@ -1419,10 +1354,9 @@ def expiz(qubit0, qubit1): # reference computed via finite difference reference = np.array([[16.0, -5.551], [-5.551, 18.497]]) - with self.assertWarns(DeprecationWarning): - # QFI from gradient framework - qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:]) - actual = np.array(qfi.bind_parameters(point).eval()).real + # QFI from gradient framework + qfi = QFI().convert(CircuitStateFn(ansatz), params=x[:]) + actual = np.array(qfi.bind_parameters(point).eval()).real np.testing.assert_array_almost_equal(actual, reference, decimal=3) def test_qfi_circuit_shared_params(self): @@ -1491,29 +1425,28 @@ def test_qfi_circuit_shared_params(self): circuit6.cx(1, 0) circuit6.h(1) - with self.assertWarns(DeprecationWarning): - # compare - qfi = QFI().convert(StateFn(circuit), params=[x]) + # compare + qfi = QFI().convert(StateFn(circuit), params=[x]) - circuit_sets = ( - [circuit1, circuit2, circuit3, circuit4], - [circuit5, circuit6], - [circuit5, circuit6], - ) - list_ops = ( - qfi.oplist[0].oplist[0].oplist[:-1], - qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist, - qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist, - ) + circuit_sets = ( + [circuit1, circuit2, circuit3, circuit4], + [circuit5, circuit6], + [circuit5, circuit6], + ) + list_ops = ( + qfi.oplist[0].oplist[0].oplist[:-1], + qfi.oplist[0].oplist[0].oplist[-1].oplist[0].oplist, + qfi.oplist[0].oplist[0].oplist[-1].oplist[1].oplist, + ) - # compose both on the same circuit such that the comparison works - base = QuantumCircuit(2) + # compose both on the same circuit such that the comparison works + base = QuantumCircuit(2) - for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)): - for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)): - with self.subTest(f"set {i} circuit {j}"): - primitive = composed_op[1].primitive - self.assertEqual(base.compose(primitive), base.compose(reference)) + for i, (circuit_set, list_op) in enumerate(zip(circuit_sets, list_ops)): + for j, (reference, composed_op) in enumerate(zip(circuit_set, list_op)): + with self.subTest(f"set {i} circuit {j}"): + primitive = composed_op[1].primitive + self.assertEqual(base.compose(primitive), base.compose(reference)) def test_overlap_qfi_bound_parameters(self): """Test the overlap QFI works on a circuit with multi-parameter bound gates.""" @@ -1522,10 +1455,8 @@ def test_overlap_qfi_bound_parameters(self): circuit.u(1, 2, 3, 0) circuit.rx(x, 0) - with self.assertWarns(DeprecationWarning): - qfi = QFI("overlap_diag").convert(StateFn(circuit), [x]) - value = qfi.bind_parameters({x: 1}).eval()[0][0] - + qfi = QFI("overlap_diag").convert(StateFn(circuit), [x]) + value = qfi.bind_parameters({x: 1}).eval()[0][0] ref = 0.87737713 self.assertAlmostEqual(value, ref) @@ -1536,8 +1467,8 @@ def test_overlap_qfi_raises_on_multiparam(self): circuit.u(x[0], x[1], 2, 0) with self.assertRaises(NotImplementedError): - with self.assertWarns(DeprecationWarning): - _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + def test_overlap_qfi_raises_on_unsupported_gate(self): """Test the overlap QFI raises an appropriate error on multi-param unbound gates.""" @@ -1546,8 +1477,7 @@ def test_overlap_qfi_raises_on_unsupported_gate(self): circuit.p(x, 0) with self.assertRaises(NotImplementedError): - with self.assertWarns(DeprecationWarning): - _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) + _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) @data(-Y, Z - 1j * Y) def test_aux_meas_op(self, aux_meas_op): @@ -1555,6 +1485,7 @@ def test_aux_meas_op(self, aux_meas_op): Gradient. """ + a = Parameter("a") b = Parameter("b") params = [a, b] @@ -1565,11 +1496,11 @@ def test_aux_meas_op(self, aux_meas_op): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - with self.assertWarns(DeprecationWarning): - op = CircuitStateFn(primitive=qc, coeff=1.0) - prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) + op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 10000 + + prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) value_dicts = [{a: [np.pi / 4], b: [0]}, {a: [np.pi / 2], b: [np.pi / 4]}] if aux_meas_op == -Y: correct_values = [ @@ -1586,12 +1517,12 @@ def test_aux_meas_op(self, aux_meas_op): ] for backend_type in ["qasm_simulator", "statevector_simulator"]: + for j, value_dict in enumerate(value_dicts): with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( backend=BasicAer.get_backend(backend_type), shots=shots ) - with self.assertWarns(DeprecationWarning): result = ( CircuitSampler(backend=q_instance) .convert(prob_grad, params=value_dict) @@ -1621,20 +1552,20 @@ def test_unsupported_aux_meas_op(self): qc.rz(params[0], q[0]) qc.rx(params[1], q[0]) - with self.assertWarns(DeprecationWarning): - op = CircuitStateFn(primitive=qc, coeff=1.0) + op = CircuitStateFn(primitive=qc, coeff=1.0) shots = 8000 aux_meas_op = X - with self.assertWarns(DeprecationWarning): - with self.assertRaises(ValueError): - prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) - value_dict = {a: [np.pi / 4], b: [0]} - backend = BasicAer.get_backend("qasm_simulator") + with self.assertRaises(ValueError): + prob_grad = LinComb(aux_meas_op=aux_meas_op).convert(operator=op, params=params) + value_dict = {a: [np.pi / 4], b: [0]} + + backend = BasicAer.get_backend("qasm_simulator") + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend=backend, shots=shots) - CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() + CircuitSampler(backend=q_instance).convert(prob_grad, params=value_dict).eval() def test_nat_grad_error(self): """Test the NaturalGradient throws an Error. @@ -1658,9 +1589,8 @@ def test_nat_grad_error(self): qc.rz(params[1], 0) qc.h(1) - with self.assertWarns(DeprecationWarning): - obs = (Z ^ X) - (Y ^ Y) - op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) + obs = (Z ^ X) - (Y ^ Y) + op = StateFn(obs, is_measurement=True) @ CircuitStateFn(primitive=qc) backend_type = "qasm_simulator" shots = 1 @@ -1671,10 +1601,13 @@ def test_nat_grad_error(self): q_instance = QuantumInstance( backend=backend, shots=shots, seed_simulator=2, seed_transpiler=2 ) + with self.assertWarns(DeprecationWarning): grad = NaturalGradient(grad_method=method).gradient_wrapper( operator=op, bind_params=params, backend=q_instance ) + + with self.assertWarns(DeprecationWarning): with self.assertRaises(ValueError): grad(value) From db0abd8e648bbb4ca6fb18e5dee2b1cdd9a29b86 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 16:19:48 +0200 Subject: [PATCH 39/47] Restore opflow unittests --- test/python/opflow/opflow_test_case.py | 1 + .../opflow/test_aer_pauli_expectation.py | 208 +++++++------- test/python/opflow/test_gradients.py | 1 - test/python/opflow/test_matrix_expectation.py | 129 +++++---- test/python/opflow/test_pauli_expectation.py | 259 +++++++++--------- .../python/opflow/test_state_op_meas_evals.py | 97 +++---- 6 files changed, 335 insertions(+), 360 deletions(-) diff --git a/test/python/opflow/opflow_test_case.py b/test/python/opflow/opflow_test_case.py index 54a2f715b110..e66020cdc4bd 100644 --- a/test/python/opflow/opflow_test_case.py +++ b/test/python/opflow/opflow_test_case.py @@ -15,6 +15,7 @@ from qiskit.test import QiskitTestCase import warnings + class QiskitOpflowTestCase(QiskitTestCase): """Opflow test Case""" diff --git a/test/python/opflow/test_aer_pauli_expectation.py b/test/python/opflow/test_aer_pauli_expectation.py index 690c44bade1e..70edbed272b1 100644 --- a/test/python/opflow/test_aer_pauli_expectation.py +++ b/test/python/opflow/test_aer_pauli_expectation.py @@ -61,46 +61,43 @@ def setUp(self) -> None: def test_pauli_expect_pair(self): """pauli expect pair test""" - with self.assertWarns(DeprecationWarning): - op = Z ^ Z - # wvf = (Pl^Pl) + (Ze^Ze) - wvf = CX @ (H ^ I) @ Zero - converted_meas = self.expect.convert(~StateFn(op) @ wvf) - sampled = self.sampler.convert(converted_meas) + op = Z ^ Z + # wvf = (Pl^Pl) + (Ze^Ze) + wvf = CX @ (H ^ I) @ Zero + converted_meas = self.expect.convert(~StateFn(op) @ wvf) + sampled = self.sampler.convert(converted_meas) self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" - with self.assertWarns(DeprecationWarning): - paulis = [Z, X, Y, I] - states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - for pauli, state in itertools.product(paulis, states): - converted_meas = self.expect.convert(~StateFn(pauli) @ state) - matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() - sampled = self.sampler.convert(converted_meas) - self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + paulis = [Z, X, Y, I] + states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] + for pauli, state in itertools.product(paulis, states): + converted_meas = self.expect.convert(~StateFn(pauli) @ state) + matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() + sampled = self.sampler.convert(converted_meas) + self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" - with self.assertWarns(DeprecationWarning): - paulis_op = ListOp([X, Y, Z, I]) - converted_meas = self.expect.convert(~StateFn(paulis_op)) + paulis_op = ListOp([X, Y, Z, I]) + converted_meas = self.expect.convert(~StateFn(paulis_op)) - plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) - np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) + plus_mean = converted_meas @ Plus + sampled_plus = self.sampler.convert(plus_mean) + np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) - minus_mean = converted_meas @ Minus - sampled_minus = self.sampler.convert(minus_mean) - np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) + minus_mean = converted_meas @ Minus + sampled_minus = self.sampler.convert(minus_mean) + np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) - zero_mean = converted_meas @ Zero - sampled_zero = self.sampler.convert(zero_mean) - np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) + zero_mean = converted_meas @ Zero + sampled_zero = self.sampler.convert(zero_mean) + np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) - sum_zero = (Plus + Minus) * (0.5**0.5) - sum_zero_mean = converted_meas @ sum_zero - sampled_zero_mean = self.sampler.convert(sum_zero_mean) + sum_zero = (Plus + Minus) * (0.5**0.5) + sum_zero_mean = converted_meas @ sum_zero + sampled_zero_mean = self.sampler.convert(sum_zero_mean) # !!NOTE!!: Depolarizing channel (Sampling) means interference # does not happen between circuits in sum, so expectation does @@ -109,11 +106,10 @@ def test_pauli_expect_op_vector(self): def test_pauli_expect_state_vector(self): """pauli expect state vector test""" - with self.assertWarns(DeprecationWarning): - states_op = ListOp([One, Zero, Plus, Minus]) - paulis_op = X - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - sampled = self.sampler.convert(converted_meas) + states_op = ListOp([One, Zero, Plus, Minus]) + paulis_op = X + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + sampled = self.sampler.convert(converted_meas) # Small test to see if execution results are accessible for composed_op in sampled: @@ -123,50 +119,46 @@ def test_pauli_expect_state_vector(self): def test_pauli_expect_non_hermitian_matrixop(self): """pauli expect state vector with non hermitian operator test""" - with self.assertWarns(DeprecationWarning): - states_op = ListOp([One, Zero, Plus, Minus]) - op_mat = np.array([[0, 1], [2, 3]]) - op = MatrixOp(op_mat) - converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - sampled = self.sampler.convert(converted_meas) + states_op = ListOp([One, Zero, Plus, Minus]) + op_mat = np.array([[0, 1], [2, 3]]) + op = MatrixOp(op_mat) + converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) + sampled = self.sampler.convert(converted_meas) np.testing.assert_array_almost_equal(sampled.eval(), [3, 0, 3, 0], decimal=1) def test_pauli_expect_non_hermitian_pauliop(self): """pauli expect state vector with non hermitian operator test""" - with self.assertWarns(DeprecationWarning): - states_op = ListOp([One, Zero, Plus, Minus]) - op = 1j * X - converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - sampled = self.sampler.convert(converted_meas) + states_op = ListOp([One, Zero, Plus, Minus]) + op = 1j * X + converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) + sampled = self.sampler.convert(converted_meas) np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1j, -1j], decimal=1) def test_pauli_expect_op_vector_state_vector(self): """pauli expect op vector state vector test""" - with self.assertWarns(DeprecationWarning): - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) - - valids = [ - [+0, 0, 1, -1], - [+0, 0, 0, 0], - [-1, 1, 0, -0], - [+1, 1, 1, 1], - ] - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - sampled = self.sampler.convert(converted_meas) + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) + + valids = [ + [+0, 0, 1, -1], + [+0, 0, 0, 0], + [-1, 1, 0, -0], + [+1, 1, 1, 1], + ] + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + sampled = self.sampler.convert(converted_meas) np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_multi_representation_ops(self): """Test observables with mixed representations""" - with self.assertWarns(DeprecationWarning): - mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) - converted_meas = self.expect.convert(~StateFn(mixed_ops)) + mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) + converted_meas = self.expect.convert(~StateFn(mixed_ops)) - plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) + plus_mean = converted_meas @ Plus + sampled_plus = self.sampler.convert(plus_mean) np.testing.assert_array_almost_equal( sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 ) @@ -174,24 +166,23 @@ def test_multi_representation_ops(self): def test_parameterized_qobj(self): """grouped pauli expectation test""" - with self.assertWarns(DeprecationWarning): - two_qubit_h2 = ( - (-1.052373245772859 * I ^ I) - + (0.39793742484318045 * I ^ Z) - + (-0.39793742484318045 * Z ^ I) - + (-0.01128010425623538 * Z ^ Z) - + (0.18093119978423156 * X ^ X) - ) + two_qubit_h2 = ( + (-1.052373245772859 * I ^ I) + + (0.39793742484318045 * I ^ Z) + + (-0.39793742484318045 * Z ^ I) + + (-0.01128010425623538 * Z ^ Z) + + (0.18093119978423156 * X ^ X) + ) - aer_sampler = CircuitSampler( - self.sampler.quantum_instance, param_qobj=True, attach_results=True - ) - ansatz = RealAmplitudes() - ansatz.num_qubits = 2 + aer_sampler = CircuitSampler( + self.sampler.quantum_instance, param_qobj=True, attach_results=True + ) + ansatz = RealAmplitudes() + ansatz.num_qubits = 2 - observable_meas = self.expect.convert(StateFn(two_qubit_h2, is_measurement=True)) - ansatz_circuit_op = CircuitStateFn(ansatz) - expect_op = observable_meas.compose(ansatz_circuit_op).reduce() + observable_meas = self.expect.convert(StateFn(two_qubit_h2, is_measurement=True)) + ansatz_circuit_op = CircuitStateFn(ansatz) + expect_op = observable_meas.compose(ansatz_circuit_op).reduce() def generate_parameters(num): param_bindings = {} @@ -203,9 +194,8 @@ def generate_parameters(num): return param_bindings def validate_sampler(ideal, sut, param_bindings): - with self.assertWarns(DeprecationWarning): - expect_sampled = ideal.convert(expect_op, params=param_bindings).eval() - actual_sampled = sut.convert(expect_op, params=param_bindings).eval() + expect_sampled = ideal.convert(expect_op, params=param_bindings).eval() + actual_sampled = sut.convert(expect_op, params=param_bindings).eval() self.assertTrue( np.allclose(actual_sampled, expect_sampled), f"{actual_sampled} != {expect_sampled}", @@ -243,27 +233,26 @@ def test_pauli_expectation_param_qobj(self): q_instance = QuantumInstance( self.backend, seed_simulator=self.seed, seed_transpiler=self.seed, shots=10000 ) - qubit_op = (0.1 * I ^ I) + (0.2 * I ^ Z) + (0.3 * Z ^ I) + (0.4 * Z ^ Z) + (0.5 * X ^ X) - ansatz = RealAmplitudes(qubit_op.num_qubits) - ansatz_circuit_op = CircuitStateFn(ansatz) - observable = PauliExpectation().convert(~StateFn(qubit_op)) - expect_op = observable.compose(ansatz_circuit_op).reduce() - params1 = {} - params2 = {} - for param in ansatz.parameters: - params1[param] = [0] - params2[param] = [0, 0] - - with self.assertWarns(DeprecationWarning): - sampler1 = CircuitSampler(backend=q_instance, param_qobj=False) - samples1 = sampler1.convert(expect_op, params=params1) - val1 = np.real(samples1.eval())[0] - samples2 = sampler1.convert(expect_op, params=params2) - val2 = np.real(samples2.eval()) - sampler2 = CircuitSampler(backend=q_instance, param_qobj=True) - samples3 = sampler2.convert(expect_op, params=params1) - val3 = np.real(samples3.eval()) - samples4 = sampler2.convert(expect_op, params=params2) + qubit_op = (0.1 * I ^ I) + (0.2 * I ^ Z) + (0.3 * Z ^ I) + (0.4 * Z ^ Z) + (0.5 * X ^ X) + ansatz = RealAmplitudes(qubit_op.num_qubits) + ansatz_circuit_op = CircuitStateFn(ansatz) + observable = PauliExpectation().convert(~StateFn(qubit_op)) + expect_op = observable.compose(ansatz_circuit_op).reduce() + params1 = {} + params2 = {} + for param in ansatz.parameters: + params1[param] = [0] + params2[param] = [0, 0] + + sampler1 = CircuitSampler(backend=q_instance, param_qobj=False) + samples1 = sampler1.convert(expect_op, params=params1) + val1 = np.real(samples1.eval())[0] + samples2 = sampler1.convert(expect_op, params=params2) + val2 = np.real(samples2.eval()) + sampler2 = CircuitSampler(backend=q_instance, param_qobj=True) + samples3 = sampler2.convert(expect_op, params=params1) + val3 = np.real(samples3.eval()) + samples4 = sampler2.convert(expect_op, params=params2) val4 = np.real(samples4.eval()) np.testing.assert_array_almost_equal([val1] * 2, val2, decimal=2) @@ -272,9 +261,8 @@ def test_pauli_expectation_param_qobj(self): def test_list_pauli_sum(self): """Test AerPauliExpectation for ListOp[PauliSumOp]""" - with self.assertWarns(DeprecationWarning): - test_op = ListOp([PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)])]) - observable = AerPauliExpectation().convert(~StateFn(test_op)) + test_op = ListOp([PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)])]) + observable = AerPauliExpectation().convert(~StateFn(test_op)) self.assertIsInstance(observable, ListOp) self.assertIsInstance(observable[0], CircuitStateFn) self.assertTrue(observable[0].is_measurement) @@ -282,15 +270,13 @@ def test_list_pauli_sum(self): def test_expectation_with_coeff(self): """Test AerPauliExpectation with coefficients.""" with self.subTest("integer coefficients"): - with self.assertWarns(DeprecationWarning): - exp = 3 * ~StateFn(X) @ (2 * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + exp = 3 * ~StateFn(X) @ (2 * Minus) + target = self.sampler.convert(self.expect.convert(exp)).eval() self.assertAlmostEqual(target, -12) with self.subTest("complex coefficients"): - with self.assertWarns(DeprecationWarning): - exp = 3j * ~StateFn(X) @ (2j * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + exp = 3j * ~StateFn(X) @ (2j * Minus) + target = self.sampler.convert(self.expect.convert(exp)).eval() self.assertAlmostEqual(target, -12j) diff --git a/test/python/opflow/test_gradients.py b/test/python/opflow/test_gradients.py index 327613252ec1..07ada8e56ef9 100644 --- a/test/python/opflow/test_gradients.py +++ b/test/python/opflow/test_gradients.py @@ -1469,7 +1469,6 @@ def test_overlap_qfi_raises_on_multiparam(self): with self.assertRaises(NotImplementedError): _ = QFI("overlap_diag").convert(StateFn(circuit), [x]) - def test_overlap_qfi_raises_on_unsupported_gate(self): """Test the overlap QFI raises an appropriate error on multi-param unbound gates.""" x = Parameter("x") diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index 867c9d36b6d1..10448c3a64e1 100644 --- a/test/python/opflow/test_matrix_expectation.py +++ b/test/python/opflow/test_matrix_expectation.py @@ -52,41 +52,40 @@ def setUp(self) -> None: ) self.sampler = CircuitSampler(q_instance, attach_results=True) - with self.assertWarns(DeprecationWarning): - self.expect = MatrixExpectation() + self.expect = MatrixExpectation() def test_pauli_expect_pair(self): """pauli expect pair test""" + op = Z ^ Z + # wf = (Pl^Pl) + (Ze^Ze) + wf = CX @ (H ^ I) @ Zero + converted_meas = self.expect.convert(~StateFn(op) @ wf) + self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) with self.assertWarns(DeprecationWarning): - op = Z ^ Z - # wf = (Pl^Pl) + (Ze^Ze) - wf = CX @ (H ^ I) @ Zero - converted_meas = self.expect.convert(~StateFn(op) @ wf) - self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) sampled = self.sampler.convert(converted_meas) - self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) + self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" - with self.assertWarns(DeprecationWarning): - paulis = [Z, X, Y, I] - states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - for pauli, state in itertools.product(paulis, states): - converted_meas = self.expect.convert(~StateFn(pauli) @ state) - matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() - self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) - + paulis = [Z, X, Y, I] + states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] + for pauli, state in itertools.product(paulis, states): + converted_meas = self.expect.convert(~StateFn(pauli) @ state) + matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() + self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) + with self.assertWarns(DeprecationWarning): sampled = self.sampler.convert(converted_meas) - self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" + paulis_op = ListOp([X, Y, Z, I]) + converted_meas = self.expect.convert(~StateFn(paulis_op)) + with self.assertWarns(DeprecationWarning): - paulis_op = ListOp([X, Y, Z, I]) - converted_meas = self.expect.convert(~StateFn(paulis_op)) plus_mean = converted_meas @ Plus np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) @@ -112,75 +111,73 @@ def test_pauli_expect_op_vector(self): (converted_meas @ sampled_zero).eval(), [0, 0, 1, 1], decimal=1 ) - for i, op in enumerate(paulis_op.oplist): - mat_op = op.to_matrix() - np.testing.assert_array_almost_equal( - zero_mean.eval()[i], - Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - plus_mean.eval()[i], - Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - minus_mean.eval()[i], - Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), - decimal=1, - ) + for i, op in enumerate(paulis_op.oplist): + mat_op = op.to_matrix() + np.testing.assert_array_almost_equal( + zero_mean.eval()[i], + Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + plus_mean.eval()[i], + Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + minus_mean.eval()[i], + Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), + decimal=1, + ) def test_pauli_expect_state_vector(self): """pauli expect state vector test""" + states_op = ListOp([One, Zero, Plus, Minus]) + paulis_op = X + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) with self.assertWarns(DeprecationWarning): - states_op = ListOp([One, Zero, Plus, Minus]) - paulis_op = X - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) sampled = self.sampler.convert(converted_meas) - np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) + np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) - # Small test to see if execution results are accessible - for composed_op in sampled: - self.assertIn("statevector", composed_op[1].execution_results) + # Small test to see if execution results are accessible + for composed_op in sampled: + self.assertIn("statevector", composed_op[1].execution_results) def test_pauli_expect_op_vector_state_vector(self): """pauli expect op vector state vector test""" - with self.assertWarns(DeprecationWarning): - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) - - valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] - converted_meas = self.expect.convert(~StateFn(paulis_op)) - np.testing.assert_array_almost_equal( - (converted_meas @ states_op).eval(), valids, decimal=1 - ) + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) + valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] + converted_meas = self.expect.convert(~StateFn(paulis_op)) + np.testing.assert_array_almost_equal((converted_meas @ states_op).eval(), valids, decimal=1) + with self.assertWarns(DeprecationWarning): sampled = self.sampler.convert(states_op) - np.testing.assert_array_almost_equal( - (converted_meas @ sampled).eval(), valids, decimal=1 - ) + + np.testing.assert_array_almost_equal((converted_meas @ sampled).eval(), valids, decimal=1) def test_multi_representation_ops(self): """Test observables with mixed representations""" - with self.assertWarns(DeprecationWarning): - mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) - converted_meas = self.expect.convert(~StateFn(mixed_ops)) + mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) + converted_meas = self.expect.convert(~StateFn(mixed_ops)) - plus_mean = converted_meas @ Plus + plus_mean = converted_meas @ Plus + + with self.assertWarns(DeprecationWarning): sampled_plus = self.sampler.convert(plus_mean) - np.testing.assert_array_almost_equal( - sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 - ) + + np.testing.assert_array_almost_equal( + sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 + ) def test_matrix_expectation_non_hermite_op(self): """Test MatrixExpectation for non hermitian operator""" - with self.assertWarns(DeprecationWarning): - exp = ~StateFn(1j * Z) @ One - self.assertEqual(self.expect.convert(exp).eval(), 1j) + + exp = ~StateFn(1j * Z) @ One + self.assertEqual(self.expect.convert(exp).eval(), 1j) if __name__ == "__main__": diff --git a/test/python/opflow/test_pauli_expectation.py b/test/python/opflow/test_pauli_expectation.py index f46c68bd50d8..f50ddc347b62 100644 --- a/test/python/opflow/test_pauli_expectation.py +++ b/test/python/opflow/test_pauli_expectation.py @@ -54,47 +54,47 @@ def setUp(self) -> None: q_instance = QuantumInstance( backend, seed_simulator=self.seed, seed_transpiler=self.seed ) - with self.assertWarns(DeprecationWarning): self.sampler = CircuitSampler(q_instance, attach_results=True) - self.expect = PauliExpectation() + self.expect = PauliExpectation() def test_pauli_expect_pair(self): """pauli expect pair test""" - with self.assertWarns(DeprecationWarning): - op = Z ^ Z - # wf = (Pl^Pl) + (Ze^Ze) - wf = CX @ (H ^ I) @ Zero + op = Z ^ Z + # wf = (Pl^Pl) + (Ze^Ze) + wf = CX @ (H ^ I) @ Zero - converted_meas = self.expect.convert(~StateFn(op) @ wf) - self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) + converted_meas = self.expect.convert(~StateFn(op) @ wf) + self.assertAlmostEqual(converted_meas.eval(), 0, delta=0.1) + with self.assertWarns(DeprecationWarning): sampled = self.sampler.convert(converted_meas) - self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) + self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): """pauli expect single test""" - with self.assertWarns(DeprecationWarning): - paulis = [Z, X, Y, I] - states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] - for pauli, state in itertools.product(paulis, states): - converted_meas = self.expect.convert(~StateFn(pauli) @ state) - matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() - self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) + paulis = [Z, X, Y, I] + states = [Zero, One, Plus, Minus, S @ Plus, S @ Minus] + for pauli, state in itertools.product(paulis, states): + converted_meas = self.expect.convert(~StateFn(pauli) @ state) + matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() + self.assertAlmostEqual(converted_meas.eval(), matmulmean, delta=0.1) + with self.assertWarns(DeprecationWarning): sampled = self.sampler.convert(converted_meas) - self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) + + self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) def test_pauli_expect_op_vector(self): """pauli expect op vector test""" - with self.assertWarns(DeprecationWarning): - paulis_op = ListOp([X, Y, Z, I]) - converted_meas = self.expect.convert(~StateFn(paulis_op)) + paulis_op = ListOp([X, Y, Z, I]) + converted_meas = self.expect.convert(~StateFn(paulis_op)) - plus_mean = converted_meas @ Plus - np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) + plus_mean = converted_meas @ Plus + np.testing.assert_array_almost_equal(plus_mean.eval(), [1, 0, 0, 1], decimal=1) + with self.assertWarns(DeprecationWarning): sampled_plus = self.sampler.convert(plus_mean) np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) @@ -116,120 +116,118 @@ def test_pauli_expect_op_vector(self): sampled_zero_mean = self.sampler.convert(sum_zero_mean) - # !!NOTE!!: Depolarizing channel (Sampling) means interference - # does not happen between circuits in sum, so expectation does - # not equal expectation for Zero!! - np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1], decimal=1) - - for i, op in enumerate(paulis_op.oplist): - mat_op = op.to_matrix() - np.testing.assert_array_almost_equal( - zero_mean.eval()[i], - Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - plus_mean.eval()[i], - Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), - decimal=1, - ) - np.testing.assert_array_almost_equal( - minus_mean.eval()[i], - Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), - decimal=1, - ) + # !!NOTE!!: Depolarizing channel (Sampling) means interference + # does not happen between circuits in sum, so expectation does + # not equal expectation for Zero!! + np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1], decimal=1) + + for i, op in enumerate(paulis_op.oplist): + mat_op = op.to_matrix() + np.testing.assert_array_almost_equal( + zero_mean.eval()[i], + Zero.adjoint().to_matrix() @ mat_op @ Zero.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + plus_mean.eval()[i], + Plus.adjoint().to_matrix() @ mat_op @ Plus.to_matrix(), + decimal=1, + ) + np.testing.assert_array_almost_equal( + minus_mean.eval()[i], + Minus.adjoint().to_matrix() @ mat_op @ Minus.to_matrix(), + decimal=1, + ) def test_pauli_expect_state_vector(self): """pauli expect state vector test""" - with self.assertWarns(DeprecationWarning): - states_op = ListOp([One, Zero, Plus, Minus]) + states_op = ListOp([One, Zero, Plus, Minus]) - paulis_op = X - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) + paulis_op = X + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), [0, 0, 1, -1], decimal=1) + with self.assertWarns(DeprecationWarning): sampled = self.sampler.convert(converted_meas) - np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) - # Small test to see if execution results are accessible - for composed_op in sampled: - self.assertIn("counts", composed_op[1].execution_results) + np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1, -1], decimal=1) + + # Small test to see if execution results are accessible + for composed_op in sampled: + self.assertIn("counts", composed_op[1].execution_results) def test_pauli_expect_op_vector_state_vector(self): """pauli expect op vector state vector test""" - with self.assertWarns(DeprecationWarning): - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) - valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1) + valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), valids, decimal=1) + with self.assertWarns(DeprecationWarning): sampled = self.sampler.convert(converted_meas) - np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) + + np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_to_matrix_called(self): """test to matrix called in different situations""" qs = 45 - with self.assertWarns(DeprecationWarning): - states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) - paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) + states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) + paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) + + # 45 qubit calculation - throws exception if to_matrix is called + # massive is False + with self.assertRaises(ValueError): + states_op.to_matrix() + paulis_op.to_matrix() - # 45 qubit calculation - throws exception if to_matrix is called - # massive is False - with self.assertRaises(ValueError): + # now set global variable or argument + try: + algorithm_globals.massive = True + with self.assertRaises(MemoryError): states_op.to_matrix() paulis_op.to_matrix() - - # now set global variable or argument - try: - algorithm_globals.massive = True - with self.assertRaises(MemoryError): - states_op.to_matrix() - paulis_op.to_matrix() - algorithm_globals.massive = False - with self.assertRaises(MemoryError): - states_op.to_matrix(massive=True) - paulis_op.to_matrix(massive=True) - finally: - algorithm_globals.massive = False + algorithm_globals.massive = False + with self.assertRaises(MemoryError): + states_op.to_matrix(massive=True) + paulis_op.to_matrix(massive=True) + finally: + algorithm_globals.massive = False def test_not_to_matrix_called(self): """45 qubit calculation - literally will not work if to_matrix is somehow called (in addition to massive=False throwing an error)""" qs = 45 - with self.assertWarns(DeprecationWarning): - states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) - paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) + states_op = ListOp([Zero ^ qs, One ^ qs, (Zero ^ qs) + (One ^ qs)]) + paulis_op = ListOp([Z ^ qs, (I ^ Z ^ I) ^ int(qs / 3)]) - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - np.testing.assert_array_almost_equal(converted_meas.eval(), [[1, -1, 0], [1, -1, 0]]) + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + np.testing.assert_array_almost_equal(converted_meas.eval(), [[1, -1, 0], [1, -1, 0]]) def test_grouped_pauli_expectation(self): """grouped pauli expectation test""" - with self.assertWarns(DeprecationWarning): - two_qubit_H2 = ( - (-1.052373245772859 * I ^ I) - + (0.39793742484318045 * I ^ Z) - + (-0.39793742484318045 * Z ^ I) - + (-0.01128010425623538 * Z ^ Z) - + (0.18093119978423156 * X ^ X) - ) - wf = CX @ (H ^ I) @ Zero - expect_op = PauliExpectation(group_paulis=False).convert(~StateFn(two_qubit_H2) @ wf) - self.sampler._extract_circuitstatefns(expect_op) - num_circuits_ungrouped = len(self.sampler._circuit_ops_cache) - self.assertEqual(num_circuits_ungrouped, 5) - - expect_op_grouped = PauliExpectation(group_paulis=True).convert( - ~StateFn(two_qubit_H2) @ wf - ) + two_qubit_H2 = ( + (-1.052373245772859 * I ^ I) + + (0.39793742484318045 * I ^ Z) + + (-0.39793742484318045 * Z ^ I) + + (-0.01128010425623538 * Z ^ Z) + + (0.18093119978423156 * X ^ X) + ) + wf = CX @ (H ^ I) @ Zero + expect_op = PauliExpectation(group_paulis=False).convert(~StateFn(two_qubit_H2) @ wf) + self.sampler._extract_circuitstatefns(expect_op) + num_circuits_ungrouped = len(self.sampler._circuit_ops_cache) + self.assertEqual(num_circuits_ungrouped, 5) + + expect_op_grouped = PauliExpectation(group_paulis=True).convert(~StateFn(two_qubit_H2) @ wf) + with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance( BasicAer.get_backend("statevector_simulator"), seed_simulator=self.seed, @@ -237,10 +235,10 @@ def test_grouped_pauli_expectation(self): ) sampler = CircuitSampler(q_instance) - sampler._extract_circuitstatefns(expect_op_grouped) num_circuits_grouped = len(sampler._circuit_ops_cache) - self.assertEqual(num_circuits_grouped, 2) + + self.assertEqual(num_circuits_grouped, 2) @unittest.skip(reason="IBMQ testing not available in general.") def test_ibmq_grouped_pauli_expectation(self): @@ -254,57 +252,58 @@ def test_ibmq_grouped_pauli_expectation(self): q_instance = QuantumInstance( backend, seed_simulator=self.seed, seed_transpiler=self.seed ) - paulis_op = ListOp([X, Y, Z, I]) - states_op = ListOp([One, Zero, Plus, Minus]) + paulis_op = ListOp([X, Y, Z, I]) + states_op = ListOp([One, Zero, Plus, Minus]) + + valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] + converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - valids = [[+0, 0, 1, -1], [+0, 0, 0, 0], [-1, 1, 0, -0], [+1, 1, 1, 1]] - converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) + with self.assertWarns(DeprecationWarning): sampled = CircuitSampler(q_instance).convert(converted_meas) np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_multi_representation_ops(self): """Test observables with mixed representations""" - with self.assertWarns(DeprecationWarning): - mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) - converted_meas = self.expect.convert(~StateFn(mixed_ops)) + mixed_ops = ListOp([X.to_matrix_op(), H, H + I, X]) + converted_meas = self.expect.convert(~StateFn(mixed_ops)) + plus_mean = converted_meas @ Plus - plus_mean = converted_meas @ Plus + with self.assertWarns(DeprecationWarning): sampled_plus = self.sampler.convert(plus_mean) - np.testing.assert_array_almost_equal( - sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 - ) + np.testing.assert_array_almost_equal( + sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 + ) def test_pauli_expectation_non_hermite_op(self): """Test PauliExpectation for non hermitian operator""" - with self.assertWarns(DeprecationWarning): - exp = ~StateFn(1j * Z) @ One - self.assertEqual(self.expect.convert(exp).eval(), 1j) + exp = ~StateFn(1j * Z) @ One + self.assertEqual(self.expect.convert(exp).eval(), 1j) def test_list_pauli_sum_op(self): """Test PauliExpectation for List[PauliSumOp]""" - with self.assertWarns(DeprecationWarning): - test_op = ListOp([~StateFn(PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)]))]) - observable = self.expect.convert(test_op) - self.assertIsInstance(observable, ListOp) - self.assertIsInstance(observable[0][0][0].primitive, PauliSumOp) - self.assertIsInstance(observable[0][1][0].primitive, PauliSumOp) + test_op = ListOp([~StateFn(PauliSumOp.from_list([("XX", 1), ("ZI", 3), ("ZZ", 5)]))]) + observable = self.expect.convert(test_op) + self.assertIsInstance(observable, ListOp) + self.assertIsInstance(observable[0][0][0].primitive, PauliSumOp) + self.assertIsInstance(observable[0][1][0].primitive, PauliSumOp) def test_expectation_with_coeff(self): """Test PauliExpectation with coefficients.""" - with self.assertWarns(DeprecationWarning): - with self.subTest("integer coefficients"): - exp = 3 * ~StateFn(X) @ (2 * Minus) + with self.subTest("integer coefficients"): + exp = 3 * ~StateFn(X) @ (2 * Minus) + with self.assertWarns(DeprecationWarning): target = self.sampler.convert(self.expect.convert(exp)).eval() - self.assertEqual(target, -12) + self.assertEqual(target, -12) - with self.subTest("complex coefficients"): - exp = 3j * ~StateFn(X) @ (2j * Minus) + with self.subTest("complex coefficients"): + exp = 3j * ~StateFn(X) @ (2j * Minus) + with self.assertWarns(DeprecationWarning): target = self.sampler.convert(self.expect.convert(exp)).eval() - self.assertEqual(target, -12j) + self.assertEqual(target, -12j) if __name__ == "__main__": diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index ac0d2ea8c781..e6d23390ea78 100644 --- a/test/python/opflow/test_state_op_meas_evals.py +++ b/test/python/opflow/test_state_op_meas_evals.py @@ -33,38 +33,36 @@ class TestStateOpMeasEvals(QiskitOpflowTestCase): def test_statefn_overlaps(self): """state functions overlaps test""" - with self.assertWarns(DeprecationWarning): - wf = (4 * StateFn({"101010": 0.5, "111111": 0.3})) + ((3 + 0.1j) * (Zero ^ 6)) - wf_vec = StateFn(wf.to_matrix()) - self.assertAlmostEqual(wf.adjoint().eval(wf), 14.45) - self.assertAlmostEqual(wf_vec.adjoint().eval(wf_vec), 14.45) - self.assertAlmostEqual(wf_vec.adjoint().eval(wf), 14.45) - self.assertAlmostEqual(wf.adjoint().eval(wf_vec), 14.45) + wf = (4 * StateFn({"101010": 0.5, "111111": 0.3})) + ((3 + 0.1j) * (Zero ^ 6)) + wf_vec = StateFn(wf.to_matrix()) + self.assertAlmostEqual(wf.adjoint().eval(wf), 14.45) + self.assertAlmostEqual(wf_vec.adjoint().eval(wf_vec), 14.45) + self.assertAlmostEqual(wf_vec.adjoint().eval(wf), 14.45) + self.assertAlmostEqual(wf.adjoint().eval(wf_vec), 14.45) def test_wf_evals_x(self): """wf evals x test""" qbits = 4 - with self.assertWarns(DeprecationWarning): - wf = ((Zero ^ qbits) + (One ^ qbits)) * (1 / 2**0.5) - # Note: wf = Plus^qbits fails because TensoredOp can't handle it. - wf_vec = StateFn(wf.to_matrix()) - op = X ^ qbits - # op = I^6 - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 1) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 1) - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 1) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 1) - - # op = (H^X^Y)^2 - op = H ^ 6 - wf = ((Zero ^ 6) + (One ^ 6)) * (1 / 2**0.5) - wf_vec = StateFn(wf.to_matrix()) - # print(wf.adjoint().to_matrix() @ op.to_matrix() @ wf.to_matrix()) - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 0.25) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 0.25) - self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 0.25) - self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 0.25) + wf = ((Zero ^ qbits) + (One ^ qbits)) * (1 / 2**0.5) + # Note: wf = Plus^qbits fails because TensoredOp can't handle it. + wf_vec = StateFn(wf.to_matrix()) + op = X ^ qbits + # op = I^6 + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 1) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 1) + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 1) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 1) + + # op = (H^X^Y)^2 + op = H ^ 6 + wf = ((Zero ^ 6) + (One ^ 6)) * (1 / 2**0.5) + wf_vec = StateFn(wf.to_matrix()) + # print(wf.adjoint().to_matrix() @ op.to_matrix() @ wf.to_matrix()) + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf)), 0.25) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf)), 0.25) + self.assertAlmostEqual(wf.adjoint().eval(op.eval(wf_vec)), 0.25) + self.assertAlmostEqual(wf_vec.adjoint().eval(op.eval(wf_vec)), 0.25) def test_coefficients_correctly_propagated(self): """Test that the coefficients in SummedOp and states are correctly used.""" @@ -74,15 +72,14 @@ def test_coefficients_correctly_propagated(self): self.skipTest(f"Aer doesn't appear to be installed. Error: '{str(ex)}'") return with self.subTest("zero coeff in SummedOp"): - with self.assertWarns(DeprecationWarning): - op = 0 * (I + Z) - state = Plus - self.assertEqual((~StateFn(op) @ state).eval(), 0j) + op = 0 * (I + Z) + state = Plus + self.assertEqual((~StateFn(op) @ state).eval(), 0j) backend = Aer.get_backend("aer_simulator") with self.assertWarns(DeprecationWarning): q_instance = QuantumInstance(backend, seed_simulator=97, seed_transpiler=97) - op = I + op = I with self.subTest("zero coeff in summed StateFn and CircuitSampler"): with self.assertWarns(DeprecationWarning): state = 0 * (Plus + Minus) @@ -137,15 +134,14 @@ def test_parameter_binding_on_listop(self): def test_list_op_eval_coeff_with_nonlinear_combofn(self): """Test evaluating a ListOp with non-linear combo function works with coefficients.""" - with self.assertWarns(DeprecationWarning): - state = One - op = ListOp(5 * [I], coeff=2, combo_fn=numpy.prod) - expr1 = ~StateFn(op) @ state + state = One + op = ListOp(5 * [I], coeff=2, combo_fn=numpy.prod) + expr1 = ~StateFn(op) @ state - expr2 = ListOp(5 * [~state @ I @ state], coeff=2, combo_fn=numpy.prod) + expr2 = ListOp(5 * [~state @ I @ state], coeff=2, combo_fn=numpy.prod) - self.assertEqual(expr1.eval(), 2) # if the coeff is propagated too far the result is 4 - self.assertEqual(expr2.eval(), 2) + self.assertEqual(expr1.eval(), 2) # if the coeff is propagated too far the result is 4 + self.assertEqual(expr2.eval(), 2) def test_single_parameter_binds(self): """Test passing parameter binds as a dictionary to the circuit sampler.""" @@ -202,9 +198,8 @@ def test_adjoint_nonunitary_circuit_raises(self): circuit = QuantumCircuit(1) circuit.reset(0) - with self.assertWarns(DeprecationWarning): - with self.assertRaises(OpflowError): - _ = StateFn(circuit).adjoint() + with self.assertRaises(OpflowError): + _ = StateFn(circuit).adjoint() def test_evaluating_nonunitary_circuit_state(self): """Test evaluating a circuit works even if it contains non-unitary instruction (resets). @@ -216,9 +211,8 @@ def test_evaluating_nonunitary_circuit_state(self): circuit = QuantumCircuit(1) circuit.initialize([0, 1], [0]) - with self.assertWarns(DeprecationWarning): - op = Z - res = (~StateFn(op) @ StateFn(circuit)).eval() + op = Z + res = (~StateFn(op) @ StateFn(circuit)).eval() self.assertAlmostEqual(-1 + 0j, res) @@ -239,16 +233,15 @@ def test_quantum_instance_with_backend_shots(self): def test_adjoint_vector_to_circuit_fn(self): """Test it is possible to adjoint a VectorStateFn that was converted to a CircuitStateFn.""" - with self.assertWarns(DeprecationWarning): - left = StateFn([0, 1]) - left_circuit = left.to_circuit_op().primitive + left = StateFn([0, 1]) + left_circuit = left.to_circuit_op().primitive - right_circuit = QuantumCircuit(1) - right_circuit.x(0) + right_circuit = QuantumCircuit(1) + right_circuit.x(0) - circuit = left_circuit.inverse().compose(right_circuit) + circuit = left_circuit.inverse().compose(right_circuit) - self.assertTrue(Statevector(circuit).equiv([1, 0])) + self.assertTrue(Statevector(circuit).equiv([1, 0])) if __name__ == "__main__": From bef13d56d05c679d22f8f4eb21742e720208256e Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 17:15:44 +0200 Subject: [PATCH 40/47] Fix tests --- test/python/algorithms/test_vqe.py | 7 +- .../opflow/test_aer_pauli_expectation.py | 105 ++++++++++-------- 2 files changed, 64 insertions(+), 48 deletions(-) diff --git a/test/python/algorithms/test_vqe.py b/test/python/algorithms/test_vqe.py index 7fa4368cbb51..c9fee9547d19 100644 --- a/test/python/algorithms/test_vqe.py +++ b/test/python/algorithms/test_vqe.py @@ -326,10 +326,11 @@ def test_with_aer_qasm_snapshot_mode(self): ) def test_with_gradient(self, optimizer): """Test VQE using Gradient().""" + from qiskit_aer import AerSimulator with self.assertWarns(DeprecationWarning): quantum_instance = QuantumInstance( - backend=Aer.get_backend("qasm_simulator"), + backend=AerSimulator(), shots=1, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, @@ -731,6 +732,8 @@ def test_aux_operator_std_dev_pauli(self): @unittest.skipUnless(optionals.HAS_AER, "Qiskit aer is required to run these tests") def test_aux_operator_std_dev_aer_pauli(self): """Test non-zero standard deviations of aux operators with AerPauliExpectation.""" + from qiskit_aer import AerSimulator + wavefunction = self.ry_wavefunction with self.assertWarns(DeprecationWarning): vqe = VQE( @@ -738,7 +741,7 @@ def test_aux_operator_std_dev_aer_pauli(self): expectation=AerPauliExpectation(), optimizer=COBYLA(maxiter=0), quantum_instance=QuantumInstance( - backend=Aer.get_backend("qasm_simulator"), + backend=AerSimulator(), shots=1, seed_simulator=algorithm_globals.random_seed, seed_transpiler=algorithm_globals.random_seed, diff --git a/test/python/opflow/test_aer_pauli_expectation.py b/test/python/opflow/test_aer_pauli_expectation.py index 70edbed272b1..808f7bab8716 100644 --- a/test/python/opflow/test_aer_pauli_expectation.py +++ b/test/python/opflow/test_aer_pauli_expectation.py @@ -65,7 +65,8 @@ def test_pauli_expect_pair(self): # wvf = (Pl^Pl) + (Ze^Ze) wvf = CX @ (H ^ I) @ Zero converted_meas = self.expect.convert(~StateFn(op) @ wvf) - sampled = self.sampler.convert(converted_meas) + with self.assertWarns(DeprecationWarning): + sampled = self.sampler.convert(converted_meas) self.assertAlmostEqual(sampled.eval(), 0, delta=0.1) def test_pauli_expect_single(self): @@ -75,7 +76,8 @@ def test_pauli_expect_single(self): for pauli, state in itertools.product(paulis, states): converted_meas = self.expect.convert(~StateFn(pauli) @ state) matmulmean = state.adjoint().to_matrix() @ pauli.to_matrix() @ state.to_matrix() - sampled = self.sampler.convert(converted_meas) + with self.assertWarns(DeprecationWarning): + sampled = self.sampler.convert(converted_meas) self.assertAlmostEqual(sampled.eval(), matmulmean, delta=0.1) def test_pauli_expect_op_vector(self): @@ -83,33 +85,36 @@ def test_pauli_expect_op_vector(self): paulis_op = ListOp([X, Y, Z, I]) converted_meas = self.expect.convert(~StateFn(paulis_op)) - plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) - np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) + with self.assertWarns(DeprecationWarning): + plus_mean = converted_meas @ Plus + sampled_plus = self.sampler.convert(plus_mean) + np.testing.assert_array_almost_equal(sampled_plus.eval(), [1, 0, 0, 1], decimal=1) - minus_mean = converted_meas @ Minus - sampled_minus = self.sampler.convert(minus_mean) - np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) + minus_mean = converted_meas @ Minus + sampled_minus = self.sampler.convert(minus_mean) + np.testing.assert_array_almost_equal(sampled_minus.eval(), [-1, 0, 0, 1], decimal=1) - zero_mean = converted_meas @ Zero - sampled_zero = self.sampler.convert(zero_mean) - np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) + zero_mean = converted_meas @ Zero + sampled_zero = self.sampler.convert(zero_mean) + np.testing.assert_array_almost_equal(sampled_zero.eval(), [0, 0, 1, 1], decimal=1) - sum_zero = (Plus + Minus) * (0.5**0.5) - sum_zero_mean = converted_meas @ sum_zero - sampled_zero_mean = self.sampler.convert(sum_zero_mean) + sum_zero = (Plus + Minus) * (0.5**0.5) + sum_zero_mean = converted_meas @ sum_zero + sampled_zero_mean = self.sampler.convert(sum_zero_mean) - # !!NOTE!!: Depolarizing channel (Sampling) means interference - # does not happen between circuits in sum, so expectation does - # not equal expectation for Zero!! - np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1]) + # !!NOTE!!: Depolarizing channel (Sampling) means interference + # does not happen between circuits in sum, so expectation does + # not equal expectation for Zero!! + np.testing.assert_array_almost_equal(sampled_zero_mean.eval(), [0, 0, 0, 1]) def test_pauli_expect_state_vector(self): """pauli expect state vector test""" states_op = ListOp([One, Zero, Plus, Minus]) paulis_op = X converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - sampled = self.sampler.convert(converted_meas) + + with self.assertWarns(DeprecationWarning): + sampled = self.sampler.convert(converted_meas) # Small test to see if execution results are accessible for composed_op in sampled: @@ -123,7 +128,8 @@ def test_pauli_expect_non_hermitian_matrixop(self): op_mat = np.array([[0, 1], [2, 3]]) op = MatrixOp(op_mat) converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - sampled = self.sampler.convert(converted_meas) + with self.assertWarns(DeprecationWarning): + sampled = self.sampler.convert(converted_meas) np.testing.assert_array_almost_equal(sampled.eval(), [3, 0, 3, 0], decimal=1) @@ -132,8 +138,8 @@ def test_pauli_expect_non_hermitian_pauliop(self): states_op = ListOp([One, Zero, Plus, Minus]) op = 1j * X converted_meas = self.expect.convert(StateFn(op, is_measurement=True) @ states_op) - sampled = self.sampler.convert(converted_meas) - + with self.assertWarns(DeprecationWarning): + sampled = self.sampler.convert(converted_meas) np.testing.assert_array_almost_equal(sampled.eval(), [0, 0, 1j, -1j], decimal=1) def test_pauli_expect_op_vector_state_vector(self): @@ -148,7 +154,8 @@ def test_pauli_expect_op_vector_state_vector(self): [+1, 1, 1, 1], ] converted_meas = self.expect.convert(~StateFn(paulis_op) @ states_op) - sampled = self.sampler.convert(converted_meas) + with self.assertWarns(DeprecationWarning): + sampled = self.sampler.convert(converted_meas) np.testing.assert_array_almost_equal(sampled.eval(), valids, decimal=1) def test_multi_representation_ops(self): @@ -158,7 +165,9 @@ def test_multi_representation_ops(self): converted_meas = self.expect.convert(~StateFn(mixed_ops)) plus_mean = converted_meas @ Plus - sampled_plus = self.sampler.convert(plus_mean) + with self.assertWarns(DeprecationWarning): + sampled_plus = self.sampler.convert(plus_mean) + np.testing.assert_array_almost_equal( sampled_plus.eval(), [1, 0.5**0.5, (1 + 0.5**0.5), 1], decimal=1 ) @@ -173,10 +182,10 @@ def test_parameterized_qobj(self): + (-0.01128010425623538 * Z ^ Z) + (0.18093119978423156 * X ^ X) ) - - aer_sampler = CircuitSampler( - self.sampler.quantum_instance, param_qobj=True, attach_results=True - ) + with self.assertWarns(DeprecationWarning): + aer_sampler = CircuitSampler( + self.sampler.quantum_instance, param_qobj=True, attach_results=True + ) ansatz = RealAmplitudes() ansatz.num_qubits = 2 @@ -194,12 +203,13 @@ def generate_parameters(num): return param_bindings def validate_sampler(ideal, sut, param_bindings): - expect_sampled = ideal.convert(expect_op, params=param_bindings).eval() - actual_sampled = sut.convert(expect_op, params=param_bindings).eval() - self.assertTrue( - np.allclose(actual_sampled, expect_sampled), - f"{actual_sampled} != {expect_sampled}", - ) + with self.assertWarns(DeprecationWarning): + expect_sampled = ideal.convert(expect_op, params=param_bindings).eval() + actual_sampled = sut.convert(expect_op, params=param_bindings).eval() + self.assertTrue( + np.allclose(actual_sampled, expect_sampled), + f"{actual_sampled} != {expect_sampled}", + ) def get_circuit_templates(sampler): return sampler._transpiled_circ_templates @@ -244,16 +254,17 @@ def test_pauli_expectation_param_qobj(self): params1[param] = [0] params2[param] = [0, 0] - sampler1 = CircuitSampler(backend=q_instance, param_qobj=False) - samples1 = sampler1.convert(expect_op, params=params1) - val1 = np.real(samples1.eval())[0] - samples2 = sampler1.convert(expect_op, params=params2) - val2 = np.real(samples2.eval()) - sampler2 = CircuitSampler(backend=q_instance, param_qobj=True) - samples3 = sampler2.convert(expect_op, params=params1) - val3 = np.real(samples3.eval()) - samples4 = sampler2.convert(expect_op, params=params2) - val4 = np.real(samples4.eval()) + with self.assertWarns(DeprecationWarning): + sampler1 = CircuitSampler(backend=q_instance, param_qobj=False) + samples1 = sampler1.convert(expect_op, params=params1) + val1 = np.real(samples1.eval())[0] + samples2 = sampler1.convert(expect_op, params=params2) + val2 = np.real(samples2.eval()) + sampler2 = CircuitSampler(backend=q_instance, param_qobj=True) + samples3 = sampler2.convert(expect_op, params=params1) + val3 = np.real(samples3.eval()) + samples4 = sampler2.convert(expect_op, params=params2) + val4 = np.real(samples4.eval()) np.testing.assert_array_almost_equal([val1] * 2, val2, decimal=2) np.testing.assert_array_almost_equal(val1, val3, decimal=2) @@ -271,12 +282,14 @@ def test_expectation_with_coeff(self): """Test AerPauliExpectation with coefficients.""" with self.subTest("integer coefficients"): exp = 3 * ~StateFn(X) @ (2 * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + with self.assertWarns(DeprecationWarning): + target = self.sampler.convert(self.expect.convert(exp)).eval() self.assertAlmostEqual(target, -12) with self.subTest("complex coefficients"): exp = 3j * ~StateFn(X) @ (2j * Minus) - target = self.sampler.convert(self.expect.convert(exp)).eval() + with self.assertWarns(DeprecationWarning): + target = self.sampler.convert(self.expect.convert(exp)).eval() self.assertAlmostEqual(target, -12j) From d31e095c054fae52231a74561f5f6284dfd9ee57 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 20:48:33 +0200 Subject: [PATCH 41/47] Fix lint --- test/python/opflow/opflow_test_case.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/python/opflow/opflow_test_case.py b/test/python/opflow/opflow_test_case.py index e66020cdc4bd..142fb1db76b5 100644 --- a/test/python/opflow/opflow_test_case.py +++ b/test/python/opflow/opflow_test_case.py @@ -12,8 +12,8 @@ """Opflow Test Case""" -from qiskit.test import QiskitTestCase import warnings +from qiskit.test import QiskitTestCase class QiskitOpflowTestCase(QiskitTestCase): From b22e933b12c79619eeca5f35a0e3f1246abe0f0d Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 22:26:09 +0200 Subject: [PATCH 42/47] Fix qaoa repeated test --- test/python/algorithms/test_qaoa.py | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/test/python/algorithms/test_qaoa.py b/test/python/algorithms/test_qaoa.py index 40107f063f27..7c743af7e263 100644 --- a/test/python/algorithms/test_qaoa.py +++ b/test/python/algorithms/test_qaoa.py @@ -334,18 +334,6 @@ def test_qaoa_construct_circuit_update(self): circ4 = qaoa.construct_circuit([0, 0], I ^ Z)[0] self.assertEqual(circ4, ref) - def test_optimizer_scipy_callable(self): - """Test passing a SciPy optimizer directly as callable.""" - with self.assertWarns(DeprecationWarning): - qaoa = QAOA() - ref = qaoa.construct_circuit([0, 0], I ^ Z)[0] - circ2 = qaoa.construct_circuit([0, 0], I ^ Z)[0] - self.assertEqual(circ2, ref) - circ3 = qaoa.construct_circuit([0, 0], Z ^ I)[0] - self.assertNotEqual(circ3, ref) - circ4 = qaoa.construct_circuit([0, 0], I ^ Z)[0] - self.assertEqual(circ4, ref) - def test_optimizer_scipy_callable(self): """Test passing a SciPy optimizer directly as callable.""" with self.assertWarns(DeprecationWarning): From 384636ef99ef54a5debb05c31bd0e9a6907cd97e Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 22:43:39 +0200 Subject: [PATCH 43/47] Add module deprecation warning --- qiskit/opflow/__init__.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/qiskit/opflow/__init__.py b/qiskit/opflow/__init__.py index ff4c19cef509..19aaddc3f5d6 100644 --- a/qiskit/opflow/__init__.py +++ b/qiskit/opflow/__init__.py @@ -327,3 +327,9 @@ "anti_commutator", "double_commutator", ] + +import warnings + +message = "The ``qiskit.opflow`` module is deprecated as of qiskit-terra 0.24.0. It will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration." + +warnings.warn(message, category=DeprecationWarning, stacklevel=2) From 71e82e29e3d5c72d5c0c9e4c9b78cb404b38a739 Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 23:05:02 +0200 Subject: [PATCH 44/47] Divide message in multiple lines --- qiskit/opflow/__init__.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/qiskit/opflow/__init__.py b/qiskit/opflow/__init__.py index 19aaddc3f5d6..66cc9cea4e1a 100644 --- a/qiskit/opflow/__init__.py +++ b/qiskit/opflow/__init__.py @@ -330,6 +330,11 @@ import warnings -message = "The ``qiskit.opflow`` module is deprecated as of qiskit-terra 0.24.0. It will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration." -warnings.warn(message, category=DeprecationWarning, stacklevel=2) +warnings.warn( + "The ``qiskit.opflow`` module is deprecated as of qiskit-terra 0.24.0. " + "It will be removed no earlier than 3 months after the release date. " + "For code migration guidelines, visit https://qisk.it/opflow_migration.", + category=DeprecationWarning, + stacklevel=2, +) From 17ab34d5257596be7d91414aaced84a0ca54a1ca Mon Sep 17 00:00:00 2001 From: ElePT Date: Mon, 17 Apr 2023 23:08:30 +0200 Subject: [PATCH 45/47] Fix lint --- qiskit/opflow/__init__.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/qiskit/opflow/__init__.py b/qiskit/opflow/__init__.py index 66cc9cea4e1a..7bd53caec535 100644 --- a/qiskit/opflow/__init__.py +++ b/qiskit/opflow/__init__.py @@ -165,6 +165,7 @@ OpflowError """ +import warnings # New Operators from .operator_base import OperatorBase @@ -328,9 +329,6 @@ "double_commutator", ] -import warnings - - warnings.warn( "The ``qiskit.opflow`` module is deprecated as of qiskit-terra 0.24.0. " "It will be removed no earlier than 3 months after the release date. " From 329b450892138895f7e4e6cdeddeaf9f8d349b21 Mon Sep 17 00:00:00 2001 From: woodsp-ibm Date: Tue, 18 Apr 2023 14:36:56 -0400 Subject: [PATCH 46/47] :mod:: -> :mod: --- qiskit/opflow/__init__.py | 2 +- qiskit/opflow/converters/__init__.py | 2 +- qiskit/opflow/evolutions/__init__.py | 2 +- qiskit/opflow/expectations/__init__.py | 2 +- qiskit/opflow/gradients/__init__.py | 2 +- qiskit/opflow/list_ops/__init__.py | 2 +- qiskit/opflow/primitive_ops/__init__.py | 2 +- qiskit/opflow/state_fns/__init__.py | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/qiskit/opflow/__init__.py b/qiskit/opflow/__init__.py index 7bd53caec535..9551dd3f318b 100644 --- a/qiskit/opflow/__init__.py +++ b/qiskit/opflow/__init__.py @@ -19,7 +19,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. diff --git a/qiskit/opflow/converters/__init__.py b/qiskit/opflow/converters/__init__.py index b830e4206530..8c2236eaec77 100644 --- a/qiskit/opflow/converters/__init__.py +++ b/qiskit/opflow/converters/__init__.py @@ -18,7 +18,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. diff --git a/qiskit/opflow/evolutions/__init__.py b/qiskit/opflow/evolutions/__init__.py index abe3ae0a96d2..6bfeb7d1490d 100644 --- a/qiskit/opflow/evolutions/__init__.py +++ b/qiskit/opflow/evolutions/__init__.py @@ -18,7 +18,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. diff --git a/qiskit/opflow/expectations/__init__.py b/qiskit/opflow/expectations/__init__.py index f12b3efd0328..885d4b7e36f6 100644 --- a/qiskit/opflow/expectations/__init__.py +++ b/qiskit/opflow/expectations/__init__.py @@ -18,7 +18,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. diff --git a/qiskit/opflow/gradients/__init__.py b/qiskit/opflow/gradients/__init__.py index f1642caa0c86..9c2625d078ca 100644 --- a/qiskit/opflow/gradients/__init__.py +++ b/qiskit/opflow/gradients/__init__.py @@ -16,7 +16,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. diff --git a/qiskit/opflow/list_ops/__init__.py b/qiskit/opflow/list_ops/__init__.py index 700ff46ce774..b4e4a45b3d72 100644 --- a/qiskit/opflow/list_ops/__init__.py +++ b/qiskit/opflow/list_ops/__init__.py @@ -18,7 +18,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. diff --git a/qiskit/opflow/primitive_ops/__init__.py b/qiskit/opflow/primitive_ops/__init__.py index 20c5fa5946cd..7e5cc72fad6b 100644 --- a/qiskit/opflow/primitive_ops/__init__.py +++ b/qiskit/opflow/primitive_ops/__init__.py @@ -18,7 +18,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. diff --git a/qiskit/opflow/state_fns/__init__.py b/qiskit/opflow/state_fns/__init__.py index 0b2a53edcbe8..69b7d960bc20 100644 --- a/qiskit/opflow/state_fns/__init__.py +++ b/qiskit/opflow/state_fns/__init__.py @@ -16,7 +16,7 @@ .. deprecated:: 0.24.0 - The :mod::`qiskit.opflow` module is deprecated and will be removed no earlier + The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier than 3 months after the release date. For code migration guidelines, visit https://qisk.it/opflow_migration. From 0ee225aa33a3e117ace2d2aa7cee56969b9a932c Mon Sep 17 00:00:00 2001 From: ElePT Date: Tue, 18 Apr 2023 22:13:18 +0200 Subject: [PATCH 47/47] Deprecate Z2 symmetries --- qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py index 49d96547fe2b..9411afc71f26 100644 --- a/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py +++ b/qiskit/opflow/primitive_ops/tapered_pauli_sum_op.py @@ -86,8 +86,12 @@ def assign_parameters(self, param_dict: dict) -> OperatorBase: class Z2Symmetries: - """Z2 Symmetries""" + """Deprecated: Z2 Symmetries""" + @deprecate_func( + since="0.24.0", + additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.", + ) def __init__( self, symmetries: List[Pauli],