diff --git a/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py b/qiskit/algorithms/evolvers/trotterization/trotter_qrte.py index aa599ecf219c..211937271604 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..c7f6f6fc8f01 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 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..4d48f92b6927 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 @@ -22,8 +22,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 +36,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 +73,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: 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 76f6addfaad6..d571caadc636 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 @@ -34,7 +34,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 f9e5aad9e3fc..a5f3e766ae05 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 numbers import Number from typing import Any, Callable, Dict, Iterator, List, Optional, Set, Sequence, Union, cast @@ -56,7 +55,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__( @@ -79,9 +78,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 e1faeb602304..599da734ef03 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 f63f31a37461..38773b2c043b 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 0aacf383adf1..4abb4e7b6061 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 54537c0e9311..7a3b8146aedc 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/quantum_instance.py b/qiskit/utils/quantum_instance.py index ffda8d6469fa..7a457e41c223 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__( @@ -599,27 +599,31 @@ def _find_save_state(data): mit_pattern=mit_pattern, ) if use_different_shots: - cals_result = run_circuits( - cal_circuits, - self._backend, - qjob_config=self._qjob_config, - backend_options=self._backend_options, - noise_config=self._noise_config, - run_config=self._run_config.to_dict(), - job_callback=self._job_callback, - max_job_retries=self._max_job_retries, - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + cals_result = run_circuits( + cal_circuits, + self._backend, + qjob_config=self._qjob_config, + backend_options=self._backend_options, + noise_config=self._noise_config, + run_config=self._run_config.to_dict(), + job_callback=self._job_callback, + max_job_retries=self._max_job_retries, + ) self._time_taken += cals_result.time_taken - result = run_circuits( - circuits, - self._backend, - qjob_config=self.qjob_config, - backend_options=self.backend_options, - noise_config=self._noise_config, - run_config=self.run_config.to_dict(), - job_callback=self._job_callback, - max_job_retries=self._max_job_retries, - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = run_circuits( + circuits, + self._backend, + qjob_config=self.qjob_config, + backend_options=self.backend_options, + noise_config=self._noise_config, + run_config=self.run_config.to_dict(), + job_callback=self._job_callback, + max_job_retries=self._max_job_retries, + ) self._time_taken += result.time_taken else: circuits[0:0] = cal_circuits @@ -629,16 +633,18 @@ def _find_save_state(data): cal_run_config.parameterizations[0:0] = [[]] * len(cal_circuits) else: cal_run_config = self.run_config - result = run_circuits( - circuits, - self._backend, - qjob_config=self.qjob_config, - backend_options=self.backend_options, - noise_config=self._noise_config, - run_config=cal_run_config.to_dict(), - job_callback=self._job_callback, - max_job_retries=self._max_job_retries, - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = run_circuits( + circuits, + self._backend, + qjob_config=self.qjob_config, + backend_options=self.backend_options, + noise_config=self._noise_config, + run_config=cal_run_config.to_dict(), + job_callback=self._job_callback, + max_job_retries=self._max_job_retries, + ) self._time_taken += result.time_taken cals_result = result logger.info("Building calibration matrix for measurement error mitigation.") @@ -656,16 +662,18 @@ def _find_save_state(data): time.time(), ) else: - result = run_circuits( - circuits, - self._backend, - qjob_config=self.qjob_config, - backend_options=self.backend_options, - noise_config=self._noise_config, - run_config=self._run_config.to_dict(), - job_callback=self._job_callback, - max_job_retries=self._max_job_retries, - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = run_circuits( + circuits, + self._backend, + qjob_config=self.qjob_config, + backend_options=self.backend_options, + noise_config=self._noise_config, + run_config=self._run_config.to_dict(), + job_callback=self._job_callback, + max_job_retries=self._max_job_retries, + ) self._time_taken += result.time_taken if meas_error_mitigation_fitter is not None: @@ -719,16 +727,18 @@ def _find_save_state(data): result.results[n] = tmp_result.results[i] else: - result = run_circuits( - circuits, - self._backend, - qjob_config=self.qjob_config, - backend_options=self.backend_options, - noise_config=self._noise_config, - run_config=self._run_config.to_dict(), - job_callback=self._job_callback, - max_job_retries=self._max_job_retries, - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + result = run_circuits( + circuits, + self._backend, + qjob_config=self.qjob_config, + backend_options=self.backend_options, + noise_config=self._noise_config, + run_config=self._run_config.to_dict(), + job_callback=self._job_callback, + max_job_retries=self._max_job_retries, + ) self._time_taken += result.time_taken if self._circuit_summary: 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/test/python/algorithms/algorithms_test_case.py b/test/python/algorithms/algorithms_test_case.py index 2a54c84e9f21..46b0a0d30e01 100644 --- a/test/python/algorithms/algorithms_test_case.py +++ b/test/python/algorithms/algorithms_test_case.py @@ -12,10 +12,19 @@ """ Algorithms Test Case """ +import warnings from qiskit.test import QiskitTestCase class QiskitAlgorithmsTestCase(QiskitTestCase): """Algorithms 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/algorithms/evolvers/trotterization/test_trotter_qrte.py b/test/python/algorithms/evolvers/trotterization/test_trotter_qrte.py index 39fecf18fe63..d3bb243a0e8d 100644 --- a/test/python/algorithms/evolvers/trotterization/test_trotter_qrte.py +++ b/test/python/algorithms/evolvers/trotterization/test_trotter_qrte.py @@ -53,18 +53,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, diff --git a/test/python/algorithms/gradients/test_estimator_gradient.py b/test/python/algorithms/gradients/test_estimator_gradient.py index 5ee28890f64e..14c2fff9d115 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 @@ -34,8 +34,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_qfi.py b/test/python/algorithms/gradients/test_qfi.py index 16d1e94b649a..e31a9616c04e 100644 --- a/test/python/algorithms/gradients/test_qfi.py +++ b/test/python/algorithms/gradients/test_qfi.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,7 +14,7 @@ """ Test QFI""" import unittest - +from test.python.algorithms.gradients.logging_primitives import LoggingEstimator import numpy as np from qiskit import QuantumCircuit @@ -26,8 +26,6 @@ from qiskit.primitives import Estimator from qiskit.test import QiskitTestCase -from .logging_primitives import LoggingEstimator - class TestQFI(QiskitTestCase): """Test QFI""" 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/test_amplitude_estimators.py b/test/python/algorithms/test_amplitude_estimators.py index 6beacda97cd8..faf882cc551c 100644 --- a/test/python/algorithms/test_amplitude_estimators.py +++ b/test/python/algorithms/test_amplitude_estimators.py @@ -91,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 @@ -386,21 +399,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 @@ -720,9 +746,15 @@ 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 with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( diff --git a/test/python/algorithms/test_aux_ops_evaluator.py b/test/python/algorithms/test_aux_ops_evaluator.py index fb02940559c4..ccde3c740d92 100644 --- a/test/python/algorithms/test_aux_ops_evaluator.py +++ b/test/python/algorithms/test_aux_ops_evaluator.py @@ -138,12 +138,18 @@ 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, - ) + 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, + ) + self.assertTrue(len(caught_warnings) > 0) expectation = ExpectationFactory.build( operator=self.h2_op, backend=quantum_instance, diff --git a/test/python/algorithms/test_backendv1.py b/test/python/algorithms/test_backendv1.py index 89f9bc4e02a1..df777e82e137 100644 --- a/test/python/algorithms/test_backendv1.py +++ b/test/python/algorithms/test_backendv1.py @@ -40,17 +40,16 @@ 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) @@ -66,21 +65,20 @@ def test_vqe_qasm(self): ) 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 - ) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) + 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) @@ -90,11 +88,16 @@ 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(DeprecationWarning): + 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) + self.assertTrue(len(caught_warnings) > 0) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @@ -105,9 +108,14 @@ 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(DeprecationWarning): + 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) + self.assertTrue(len(caught_warnings) > 0) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @@ -127,14 +135,19 @@ def test_measurement_error_mitigation_with_vqe(self): noise_model.add_all_qubit_readout_error(read_err) backend = self._qasm - - quantum_instance = QuantumInstance( - backend=backend, - seed_simulator=167, - seed_transpiler=167, - noise_model=noise_model, - measurement_error_mitigation_cls=CompleteMeasFitter, - ) + 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, + ) + self.assertTrue(len(caught_warnings) > 0) h2_hamiltonian = ( -1.052373245772859 * (I ^ I) diff --git a/test/python/algorithms/test_backendv2.py b/test/python/algorithms/test_backendv2.py index 8e39486fcc91..85d0f0fbaef6 100644 --- a/test/python/algorithms/test_backendv2.py +++ b/test/python/algorithms/test_backendv2.py @@ -40,17 +40,16 @@ 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) @@ -66,21 +65,20 @@ def test_vqe_qasm(self): ) 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 - ) with warnings.catch_warnings(record=True) as caught_warnings: warnings.filterwarnings( "always", category=DeprecationWarning, ) + 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) @@ -90,11 +88,16 @@ 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(DeprecationWarning): + 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) + self.assertTrue(len(caught_warnings) > 0) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) @@ -105,11 +108,16 @@ 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(DeprecationWarning): + 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) + self.assertTrue(len(caught_warnings) > 0) result = grover.amplify(problem) self.assertIn(result.top_measurement, ["11"]) diff --git a/test/python/algorithms/test_grover.py b/test/python/algorithms/test_grover.py index 2435daba19b3..db850cfa1892 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 diff --git a/test/python/algorithms/test_linear_solvers.py b/test/python/algorithms/test_linear_solvers.py index c2cb747e2799..75df6a009954 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 @@ -345,7 +345,13 @@ 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")) + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.filterwarnings( + "always", + category=DeprecationWarning, + ) + qinst = QuantumInstance(backend=BasicAer.get_backend("qasm_simulator")) + self.assertTrue(len(caught_warnings) > 0) hhl.quantum_instance = qinst self.assertEqual(hhl.quantum_instance, qinst) diff --git a/test/python/algorithms/test_measure_error_mitigation.py b/test/python/algorithms/test_measure_error_mitigation.py index 07be29c340bb..68411349c68a 100644 --- a/test/python/algorithms/test_measure_error_mitigation.py +++ b/test/python/algorithms/test_measure_error_mitigation.py @@ -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) @@ -133,14 +139,20 @@ 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) @@ -202,16 +214,16 @@ 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, - ) 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, @@ -227,20 +239,19 @@ 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, - ) - 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, @@ -266,15 +277,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) @@ -329,14 +346,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) @@ -370,24 +393,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." ) @@ -403,13 +432,19 @@ 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. diff --git a/test/python/algorithms/test_phase_estimator.py b/test/python/algorithms/test_phase_estimator.py index a93c9ce65e79..d1e3cf7da817 100644 --- a/test/python/algorithms/test_phase_estimator.py +++ b/test/python/algorithms/test_phase_estimator.py @@ -48,12 +48,12 @@ 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) 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 ) @@ -153,12 +153,12 @@ def _setup_from_bound(self, evolution, op_class): if op_class == "MatrixOp": hamiltonian = hamiltonian.to_matrix_op() backend = qiskit.BasicAer.get_backend("statevector_simulator") - qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) 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( @@ -325,7 +325,6 @@ 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 with warnings.catch_warnings(record=True) as caught_warnings: @@ -333,6 +332,7 @@ def one_phase( "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: @@ -412,12 +412,12 @@ def phase_estimation( """ if backend is None: backend = qiskit.BasicAer.get_backend("statevector_simulator") - qi = qiskit.utils.QuantumInstance(backend=backend, shots=10000) 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 ) diff --git a/test/python/algorithms/test_qaoa.py b/test/python/algorithms/test_qaoa.py index cfa4d613e168..e4049d6315b1 100644 --- a/test/python/algorithms/test_qaoa.py +++ b/test/python/algorithms/test_qaoa.py @@ -63,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( [ 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..9c581d73de6e 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,12 +63,18 @@ 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, - ) + 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, + ) + self.assertTrue(len(caught_warnings) > 0) # 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) @@ -82,13 +88,19 @@ 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]}, - ) + 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]}, + ) + self.assertTrue(len(caught_warnings) > 0) 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() @@ -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, - ) + 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, + ) + self.assertTrue(len(caught_warnings) > 0) 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)) - # 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) + 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 52a739a5ad0c..735f85675a3b 100644 --- a/test/python/algorithms/test_vqd.py +++ b/test/python/algorithms/test_vqd.py @@ -70,18 +70,24 @@ 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.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): @@ -214,16 +220,16 @@ 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, - ) 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, @@ -246,16 +252,16 @@ 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, - ) 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, @@ -279,17 +285,17 @@ 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, - ) 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, @@ -441,12 +447,12 @@ def test_backend_change(self, user_expectation): quantum_instance=BasicAer.get_backend("statevector_simulator"), ) result0 = vqd.compute_eigenvalues(operator=self.h2_op) - self.assertTrue(len(caught_warnings) > 0) - if user_expectation is not None: - with self.subTest("User expectation kept."): - self.assertEqual(vqd.expectation, user_expectation) + 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 with warnings.catch_warnings(record=True) as caught_warnings: diff --git a/test/python/algorithms/test_vqe.py b/test/python/algorithms/test_vqe.py index 270a27923c89..c2bd45df617c 100644 --- a/test/python/algorithms/test_vqe.py +++ b/test/python/algorithms/test_vqe.py @@ -99,18 +99,24 @@ def setUp(self): 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.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.""" @@ -272,23 +278,22 @@ 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, - ) 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) @@ -302,16 +307,16 @@ def test_with_aer_qasm(self): 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, - ) 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, @@ -332,17 +337,17 @@ def test_with_aer_qasm_snapshot_mode(self): 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, - ) 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, @@ -366,17 +371,17 @@ def test_with_gradient(self, optimizer): """Test VQE using Gradient().""" from qiskit_aer import AerSimulator - quantum_instance = QuantumInstance( - backend=AerSimulator(), - shots=1, - seed_simulator=algorithm_globals.random_seed, - seed_transpiler=algorithm_globals.random_seed, - ) 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, @@ -550,14 +555,13 @@ def test_backend_change(self, user_expectation): 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 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: @@ -914,19 +918,18 @@ 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) 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) @@ -957,14 +960,14 @@ def test_construct_eigenstate_from_optpoint(self): # 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"] - ) 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"] + ) vqe = VQE(optimizer=optimizer, quantum_instance=quantum_instance) result = vqe.compute_minimum_eigenvalue(hamiltonian) self.assertTrue(len(caught_warnings) > 0) diff --git a/test/python/algorithms/time_evolvers/test_pvqd.py b/test/python/algorithms/time_evolvers/test_pvqd.py index 7e9f8c33241c..a7dc6d272d72 100644 --- a/test/python/algorithms/time_evolvers/test_pvqd.py +++ b/test/python/algorithms/time_evolvers/test_pvqd.py @@ -12,6 +12,7 @@ """Tests for PVQD.""" import unittest +import warnings from functools import partial import numpy as np @@ -73,7 +74,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/circuit/library/test_evolution_gate.py b/test/python/circuit/library/test_evolution_gate.py index b646dc234555..ef4ee22c0028 100644 --- a/test/python/circuit/library/test_evolution_gate.py +++ b/test/python/circuit/library/test_evolution_gate.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 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()) @@ -289,7 +381,13 @@ def test_complex_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) @@ -299,7 +397,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 db4e62c5999a..261b71a36992 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 @@ -262,7 +263,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) @@ -587,10 +594,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) @@ -601,7 +620,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() @@ -621,7 +646,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() @@ -641,7 +672,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() @@ -661,7 +698,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() @@ -679,7 +722,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() @@ -698,7 +747,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 58b8c99e6737..de8eb18e6980 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 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""" @@ -236,9 +239,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) 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..bee0e0b7d051 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,7 +999,13 @@ 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( @@ -1048,7 +1055,13 @@ 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) @@ -1079,9 +1092,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( @@ -1139,9 +1158,15 @@ def test_gradient_wrapper2(self, backend_type, atol): 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 - ) + 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 ) @@ -1154,9 +1179,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 +1214,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): @@ -1500,10 +1536,15 @@ 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 - ) + 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) @@ -1544,7 +1585,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,9 +1624,15 @@ 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 ) diff --git a/test/python/opflow/test_matrix_expectation.py b/test/python/opflow/test_matrix_expectation.py index 06fb28efce78..56fed82f6083 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() diff --git a/test/python/opflow/test_pauli_expectation.py b/test/python/opflow/test_pauli_expectation.py index a70ae06da9d0..3fff3a41b1e2 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() @@ -203,11 +212,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 +235,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]) diff --git a/test/python/opflow/test_state_op_meas_evals.py b/test/python/opflow/test_state_op_meas_evals.py index c39da2f359f2..cf414a141796 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,7 +77,13 @@ 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) @@ -96,7 +103,13 @@ 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) self.assertTrue(sampler.oplist[0].is_measurement) 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))