Skip to content

Commit

Permalink
Deprecate QuantumInstance and Opflow (#9176)
Browse files Browse the repository at this point in the history
* Deprecate QuantumInstance and Opflow

* Add .. deprecated:: to init modules

* Add link to url guide

* Remove internal use of opflow

* Fix black

* Discard old changes in deprecation.py

* Update decorators

* Remove  from docstring

* Update sphinx deprecations, fix lint, fix tests

* Remove hanging Deprecated in docstring

* Remove old Deprecation messages

* Revert "Remove old Deprecation messages"

This reverts commit 6924130.

* Revert "Remove hanging Deprecated in docstring"

This reverts commit cfb04f5.

* Revert "Remove  from docstring"

This reverts commit 50e5954.

* Change Deprecation to Deprecated

* Remove catch warnings in main code

* Fix missing decorators

* Fix tests

* Shorten message

* Fix black

* Shorten qi message

* Remove checks for QDrift's internal use of opflow (changed in this PR)

* Add warning catchers to unit tests

* Remove opflow from qaoa ansatz tests

* Remove opflow from non-related tests

* Restore some opflow tests for completion

* Fix black

* Remove catch warnings

* Refactor adaptVQE tests, remove opflow from observables evaluator

* Fix tests, lint

Fix tests, lint

Fix CI failures

Fix tests CI

Fix unit tests

Fix CI again

Fix lint

Restore vqd test

Remove unused import

* Delete qobj test to fix CI until #9322 is merged

* Refactor gradients test warnings

* Remove warning filter

* Refactor rest of tests to assert warnings

* Fix formatting

* Restore unchanged unit tests

Restore opflow test case

Restore estimator test

Restore unchanged tests

* Go back to old opflow test setup

* Revert "Refactor gradients test warnings", only keep qi assertWarns

This reverts commit 9c0a37f.

* Restore opflow unittests

* Fix tests

* Fix lint

* Fix qaoa repeated test

* Add module deprecation warning

* Divide message in multiple lines

* Fix lint

* :mod:: -> :mod:

* Deprecate Z2 symmetries

---------

Co-authored-by: ElePT <epenatap@gmail.com>
Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com>
Co-authored-by: woodsp-ibm <woodsp@us.ibm.com>
  • Loading branch information
4 people authored Apr 18, 2023
1 parent e18e4d2 commit 5128c67
Show file tree
Hide file tree
Showing 124 changed files with 2,710 additions and 1,571 deletions.
3 changes: 2 additions & 1 deletion qiskit/algorithms/observables_evaluator.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@

from qiskit import QuantumCircuit
from qiskit.opflow import PauliSumOp
from qiskit.quantum_info import SparsePauliOp
from .exceptions import AlgorithmError
from .list_or_dict import ListOrDict
from ..primitives import BaseEstimator
Expand Down Expand Up @@ -88,7 +89,7 @@ def _handle_zero_ops(
"""Replaces all occurrence of operators equal to 0 in the list with an equivalent ``PauliSumOp``
operator."""
if observables_list:
zero_op = PauliSumOp.from_list([("I" * observables_list[0].num_qubits, 0)])
zero_op = SparsePauliOp.from_list([("I" * observables_list[0].num_qubits, 0)])
for ind, observable in enumerate(observables_list):
if observable == 0:
observables_list[ind] = zero_op
Expand Down
5 changes: 2 additions & 3 deletions qiskit/circuit/library/n_local/qaoa_ansatz.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
from qiskit.circuit.parametervector import ParameterVector
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.quantum_info import SparsePauliOp


class QAOAAnsatz(EvolvedOperatorAnsatz):
Expand Down Expand Up @@ -219,16 +220,14 @@ def mixer_operator(self):
# if no mixer is passed and we know the number of qubits, then initialize it.
if self.cost_operator is not None:
# local imports to avoid circular imports
from qiskit.opflow import PauliSumOp

num_qubits = self.cost_operator.num_qubits

# Mixer is just a sum of single qubit X's on each qubit. Evolving by this operator
# will simply produce rx's on each qubit.
mixer_terms = [
("I" * left + "X" + "I" * (num_qubits - left - 1), 1) for left in range(num_qubits)
]
mixer = PauliSumOp.from_list(mixer_terms)
mixer = SparsePauliOp.from_list(mixer_terms)
return mixer

# otherwise we cannot provide a default
Expand Down
42 changes: 29 additions & 13 deletions qiskit/opflow/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -17,6 +17,12 @@
.. currentmodule:: qiskit.opflow
.. deprecated:: 0.24.0
The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier
than 3 months after the release date. For code migration guidelines,
visit https://qisk.it/opflow_migration.
Operators and State functions are the building blocks of Quantum Algorithms.
A library for Quantum Algorithms & Applications is more than a collection of
Expand Down Expand Up @@ -77,8 +83,9 @@
Operator Base Class
===================
The OperatorBase serves as the base class for all Operators, State functions and measurements, and
enforces the presence and consistency of methods to manipulate these objects conveniently.
The OperatorBase serves as the base class for all Operators, State functions
and measurements, and enforces the presence and consistency of methods to manipulate these
objects conveniently.
.. autosummary::
:toctree: ../stubs/
Expand All @@ -91,8 +98,8 @@
Operator Globals
================
The :mod:`operator_globals` is a set of immutable Operator instances that are convenient building
blocks to reach for while working with the Operator flow.
The :mod:`operator_globals` is a set of immutable Operator instances that are
convenient building blocks to reach for while working with the Operator flow.
One qubit Pauli operators:
:attr:`X`, :attr:`Y`, :attr:`Z`, :attr:`I`
Expand All @@ -109,8 +116,8 @@
Operators
---------
The Operators submodules include the PrimitiveOp, ListOp, and StateFn class groups which
represent the primary Operator modules.
The Operators submodules include the PrimitiveOp, ListOp, and StateFn class
groups which represent the primary Operator modules.
.. autosummary::
:toctree: ../stubs/
Expand All @@ -123,12 +130,12 @@
Converters
----------
The Converter submodules include objects which manipulate Operators, usually recursing over an
Operator structure and changing certain Operators' representation. For example, the
:class:`~.expectations.PauliExpectation` traverses an Operator structure, and replaces all of the
:class:`~.state_fns.OperatorStateFn` measurements containing non-diagonal Pauli terms into
diagonalizing circuits following by :class:`~.state_fns.OperatorStateFn` measurement containing
only diagonal Paulis.
The Converter submodules include objects which manipulate Operators,
usually recursing over an Operator structure and changing certain Operators' representation.
For example, the :class:`~.expectations.PauliExpectation` traverses an Operator structure, and
replaces all of the :class:`~.state_fns.OperatorStateFn` measurements containing non-diagonal
Pauli terms into diagonalizing circuits following by :class:`~.state_fns.OperatorStateFn`
measurement containing only diagonal Paulis.
.. autosummary::
:toctree: ../stubs/
Expand Down Expand Up @@ -158,6 +165,7 @@
OpflowError
"""
import warnings

# New Operators
from .operator_base import OperatorBase
Expand Down Expand Up @@ -320,3 +328,11 @@
"anti_commutator",
"double_commutator",
]

warnings.warn(
"The ``qiskit.opflow`` module is deprecated as of qiskit-terra 0.24.0. "
"It will be removed no earlier than 3 months after the release date. "
"For code migration guidelines, visit https://qisk.it/opflow_migration.",
category=DeprecationWarning,
stacklevel=2,
)
9 changes: 8 additions & 1 deletion qiskit/opflow/converters/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -16,6 +16,12 @@
.. currentmodule:: qiskit.opflow.converters
.. deprecated:: 0.24.0
The :mod:`qiskit.opflow` module is deprecated and will be removed no earlier
than 3 months after the release date. For code migration guidelines,
visit https://qisk.it/opflow_migration.
Converters are objects which manipulate Operators, usually traversing an Operator to
change certain sub-Operators into a desired representation. Often the converted Operator is
isomorphic or approximate to the original Operator in some way, but not always. For example,
Expand All @@ -31,6 +37,7 @@
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`
and :mod:`~qiskit.opflow.evolutions` are also converters.
Expand Down
10 changes: 8 additions & 2 deletions qiskit/opflow/converters/abelian_grouper.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -27,10 +27,11 @@
from qiskit.opflow.primitive_ops.pauli_op import PauliOp
from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
from qiskit.utils.deprecation import deprecate_func


class AbelianGrouper(ConverterBase):
"""The AbelianGrouper converts SummedOps into a sum of Abelian sums.
"""Deprecated: The AbelianGrouper converts SummedOps into a sum of Abelian sums.
Meaning, it will traverse the Operator, and when it finds a SummedOp, it will evaluate which of
the summed sub-Operators commute with one another. It will then convert each of the groups of
Expand All @@ -41,12 +42,17 @@ class AbelianGrouper(ConverterBase):
diagonalized together.
"""

@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(self, traverse: bool = True) -> None:
"""
Args:
traverse: Whether to convert only the Operator passed to ``convert``, or traverse
down that Operator.
"""
super().__init__()
self._traverse = traverse

def convert(self, operator: OperatorBase) -> OperatorBase:
Expand Down
11 changes: 9 additions & 2 deletions qiskit/opflow/converters/circuit_sampler.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -32,13 +32,14 @@
from qiskit.providers import Backend
from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend
from qiskit.utils.quantum_instance import QuantumInstance
from qiskit.utils.deprecation import deprecate_func

logger = logging.getLogger(__name__)


class CircuitSampler(ConverterBase):
"""
The CircuitSampler traverses an Operator and converts any CircuitStateFns into
Deprecated: The CircuitSampler traverses an Operator and converts any CircuitStateFns into
approximations of the state function by a DictStateFn or VectorStateFn using a quantum
backend. Note that in order to approximate the value of the CircuitStateFn, it must 1) send
state function through a depolarizing channel, which will destroy all phase information and
Expand All @@ -51,6 +52,10 @@ class CircuitSampler(ConverterBase):
you are better off using a different CircuitSampler for each Operator to avoid cache thrashing.
"""

@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
backend: Union[Backend, QuantumInstance],
Expand All @@ -76,6 +81,8 @@ def __init__(
Raises:
ValueError: Set statevector or param_qobj True when not supported by backend.
"""
super().__init__()

self._quantum_instance = (
backend if isinstance(backend, QuantumInstance) else QuantumInstance(backend=backend)
)
Expand Down
12 changes: 10 additions & 2 deletions qiskit/opflow/converters/converter_base.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -15,11 +15,12 @@
from abc import ABC, abstractmethod

from qiskit.opflow.operator_base import OperatorBase
from qiskit.utils.deprecation import deprecate_func


class ConverterBase(ABC):
r"""
Converters take an Operator and return a new Operator, generally isomorphic
Deprecated: Converters take an Operator and return a new Operator, generally isomorphic
in some way with the first, but with certain desired properties. For example,
a converter may accept ``CircuitOp`` and return a ``SummedOp`` of
``PauliOps`` representing the circuit unitary. Converters may not
Expand All @@ -29,6 +30,13 @@ class ConverterBase(ABC):
in the number of qubits unless a clever trick is known (such as the use of sparse
matrices)."""

@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(self) -> None:
pass

@abstractmethod
def convert(self, operator: OperatorBase) -> OperatorBase:
"""Accept the Operator and return the converted Operator
Expand Down
14 changes: 10 additions & 4 deletions qiskit/opflow/converters/dict_to_circuit_sum.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -18,16 +18,21 @@
from qiskit.opflow.state_fns.circuit_state_fn import CircuitStateFn
from qiskit.opflow.state_fns.dict_state_fn import DictStateFn
from qiskit.opflow.state_fns.vector_state_fn import VectorStateFn
from qiskit.utils.deprecation import deprecate_func


class DictToCircuitSum(ConverterBase):
r"""
Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns`` or sums
thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op`` on
an Operator, but with the added control of choosing whether to convert only ``DictStateFns``
Deprecated: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns``
or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op``
on an Operator, but with the added control of choosing whether to convert only ``DictStateFns``
or ``VectorStateFns``, rather than both.
"""

@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True
) -> None:
Expand All @@ -38,6 +43,7 @@ def __init__(
convert_dicts: Whether to convert VectorStateFn.
convert_vectors: Whether to convert DictStateFns.
"""
super().__init__()
self._traverse = traverse
self._convert_dicts = convert_dicts
self._convert_vectors = convert_vectors
Expand Down
10 changes: 8 additions & 2 deletions qiskit/opflow/converters/pauli_basis_change.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -30,11 +30,12 @@
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
from qiskit.opflow.state_fns.state_fn import StateFn
from qiskit.quantum_info import Pauli
from qiskit.utils.deprecation import deprecate_func


class PauliBasisChange(ConverterBase):
r"""
Converter for changing Paulis into other bases. By default, the diagonal basis
Deprecated: Converter for changing Paulis into other bases. By default, the diagonal basis
composed only of Pauli {Z, I}^n is used as the destination basis to which to convert.
Meaning, if a Pauli containing X or Y terms is passed in, which cannot be
sampled or evolved natively on some Quantum hardware, the Pauli can be replaced by a
Expand All @@ -55,6 +56,10 @@ class PauliBasisChange(ConverterBase):
this method, such as the placement of the CNOT chains.
"""

@deprecate_func(
since="0.24.0",
additional_msg="For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
destination_basis: Optional[Union[Pauli, PauliOp]] = None,
Expand Down Expand Up @@ -83,6 +88,7 @@ def __init__(
beginning and ending operators are equivalent.
"""
super().__init__()
if destination_basis is not None:
self.destination = destination_basis # type: ignore
else:
Expand Down
Loading

0 comments on commit 5128c67

Please sign in to comment.