Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate QuantumInstance and Opflow #9176

Merged
merged 56 commits into from
Apr 18, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
Show all changes
56 commits
Select commit Hold shift + click to select a range
07e5304
Deprecate QuantumInstance and Opflow
manoelmarques Nov 22, 2022
0f93f42
Add .. deprecated:: to init modules
manoelmarques Dec 12, 2022
24dc678
Add link to url guide
manoelmarques Feb 8, 2023
a6c3b9e
Merge from main, fix conflicts
ElePT Mar 15, 2023
62160e7
Remove internal use of opflow
ElePT Mar 20, 2023
c3dde51
Fix black
ElePT Mar 20, 2023
6e42e42
Merge branch 'main' of https://github.com/Qiskit/qiskit-terra into op…
ElePT Mar 20, 2023
8924a73
Merge branch 'main' into opflow
ElePT Mar 20, 2023
050d8fb
Merge branch 'opflow' of https://github.com/manoelmarques/qiskit-terr…
ElePT Mar 20, 2023
b41b304
Discard old changes in deprecation.py
ElePT Mar 20, 2023
974654d
Update decorators
ElePT Mar 29, 2023
15fce2b
Merge from main
ElePT Mar 29, 2023
50e5954
Remove from docstring
ElePT Mar 29, 2023
11e74bd
Update sphinx deprecations, fix lint, fix tests
ElePT Mar 29, 2023
cfb04f5
Remove hanging Deprecated in docstring
ElePT Mar 29, 2023
69c0119
Remove old Deprecation messages
ElePT Mar 29, 2023
f7835e3
Revert "Remove old Deprecation messages"
ElePT Mar 30, 2023
fbd0438
Revert "Remove hanging Deprecated in docstring"
ElePT Mar 30, 2023
96ccbd2
Revert "Remove from docstring"
ElePT Mar 30, 2023
ad9249e
Change Deprecation to Deprecated
ElePT Mar 30, 2023
82efe0b
Remove catch warnings in main code
ElePT Mar 30, 2023
6f9e54d
Fix missing decorators
ElePT Mar 30, 2023
153b9a0
Fix tests
ElePT Mar 30, 2023
ba9f614
Shorten message
ElePT Mar 30, 2023
6b6b2bc
Fix black
ElePT Mar 30, 2023
585903b
Shorten qi message
ElePT Mar 30, 2023
40771b7
Remove checks for QDrift's internal use of opflow (changed in this PR)
ElePT Mar 30, 2023
42ae937
Add warning catchers to unit tests
ElePT Mar 30, 2023
1fa4aa2
Merge from main, fix conflict
ElePT Apr 6, 2023
da6a163
Merge, fix conflicts, fix qaoa ansatz test
ElePT Apr 14, 2023
759a480
Remove opflow from qaoa ansatz tests
ElePT Apr 14, 2023
0d8f939
Remove opflow from non-related tests
ElePT Apr 14, 2023
c07e69d
Restore some opflow tests for completion
ElePT Apr 14, 2023
57c022b
Fix black
ElePT Apr 14, 2023
efbe2c9
Remove catch warnings
ElePT Apr 14, 2023
383db23
Refactor adaptVQE tests, remove opflow from observables evaluator
ElePT Apr 14, 2023
ccc6925
Fix tests, lint
ElePT Apr 14, 2023
bd9090f
Delete qobj test to fix CI until #9322 is merged
ElePT Apr 17, 2023
2613874
Merge from main, apply algo deprecation, use assertWarns instead of w…
ElePT Apr 17, 2023
9c0a37f
Refactor gradients test warnings
ElePT Apr 17, 2023
541cb25
Remove warning filter
ElePT Apr 17, 2023
374209c
Refactor rest of tests to assert warnings
ElePT Apr 17, 2023
e9e6a4f
Fix formatting
ElePT Apr 17, 2023
8b3136a
Restore unchanged unit tests
ElePT Apr 17, 2023
eaf7e92
Go back to old opflow test setup
ElePT Apr 17, 2023
72ee9b4
Revert "Refactor gradients test warnings", only keep qi assertWarns
ElePT Apr 17, 2023
db0abd8
Restore opflow unittests
ElePT Apr 17, 2023
c8f974b
Fix conflict from #9322
ElePT Apr 17, 2023
bef13d5
Fix tests
ElePT Apr 17, 2023
d31e095
Fix lint
ElePT Apr 17, 2023
b22e933
Fix qaoa repeated test
ElePT Apr 17, 2023
384636e
Add module deprecation warning
ElePT Apr 17, 2023
71e82e2
Divide message in multiple lines
ElePT Apr 17, 2023
17ab34d
Fix lint
ElePT Apr 17, 2023
329b450
:mod:: -> :mod:
woodsp-ibm Apr 18, 2023
0ee225a
Deprecate Z2 symmetries
ElePT Apr 18, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 20 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
woodsp-ibm marked this conversation as resolved.
Show resolved Hide resolved
than 3 months after the release date. For code migration guidelines,
visit https://qisk.it/opflow_migration.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adding a deprecation warning at the top should be enough, right? I considered reiterating this for each submodule listed.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This only causes the deprecation to show up when reading docs. It does not issue a runtime warning. For that, you need to call warnings.warn() because I did not yet add a helper function for deprecating a module.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since there are deprecation warnings in the code for each class adding another here in the code should not be needed I think. However having a note in the main opflow page about deprecations is highly desirable for when coming to this from the index. Yes with the new decorators it will be in each class docs too, but that is navigating away from this index page.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right, that is why I kept the warning in this page in particular. Once you go to the class docs, you should get the specific deprecation warning for that class.

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 @@ -90,8 +97,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 @@ -108,8 +115,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 @@ -122,12 +129,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
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
8 changes: 7 additions & 1 deletion 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,6 +27,7 @@
from qiskit.opflow.primitive_ops.pauli_op import PauliOp
from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
from qiskit.utils.deprecation import deprecate_func


class AbelianGrouper(ConverterBase):
Expand All @@ -41,12 +42,17 @@ class AbelianGrouper(ConverterBase):
diagonalized together.
"""

@deprecate_func(
since="0.24.0",
additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about the "deprecation effort" part of the message. I now realize I should probably also split this message along 2 lines, the string is too long.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure about the "deprecation effort" part of the message.

Yeah, seems fine to remove.

I now realize I should probably also split this message along 2 lines, the string is too long.

+1. I like using implicit string concatenation like this:

additional_msg=(
   "Sentence 1. "
    "More text."
),

Note the space after the period in the first line.

It will not work to use """ because it messes up the add_deprecation_to_docstring helper function we call via these decorators.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That whole first sentence can likely go. And since it seems whatever text we end up with is in all of the warnings I do not know if there abetter way to facilitate this.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You could always create a private helper function that wraps @deprecate_func to DRY things. Emphasis on private because we don't want this to be a long lasting public API; it's only to DRY this specific set of deprecations.

I'm not sure if that messes up the stacktrace level though -- you would want to experiment with that to confirm.

)
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
47 changes: 30 additions & 17 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 All @@ -14,6 +14,7 @@


import logging
import warnings
from functools import partial
from time import time
from typing import Any, Dict, List, Optional, Tuple, Union, cast
Expand All @@ -32,6 +33,7 @@
from qiskit.providers import Backend
from qiskit.utils.backend_utils import is_aer_provider, is_statevector_backend
from qiskit.utils.quantum_instance import QuantumInstance
from qiskit.utils.deprecation import deprecate_func

logger = logging.getLogger(__name__)

Expand All @@ -51,6 +53,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="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self,
backend: Union[Backend, QuantumInstance],
Expand All @@ -76,12 +82,17 @@ def __init__(
Raises:
ValueError: Set statevector or param_qobj True when not supported by backend.
"""
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
)
super().__init__()
with warnings.catch_warnings():
ElePT marked this conversation as resolved.
Show resolved Hide resolved
warnings.simplefilter("ignore")
self._quantum_instance = (
backend
if isinstance(backend, QuantumInstance)
else QuantumInstance(backend=backend)
)
self._statevector = (
statevector if statevector is not None else self.quantum_instance.is_statevector
)
self._param_qobj = param_qobj
self._attach_results = attach_results

Expand All @@ -105,17 +116,19 @@ def _check_quantum_instance_and_modes_consistent(self) -> None:
Raises:
ValueError: statevector or param_qobj are True when not supported by backend.
"""
if self._statevector and not is_statevector_backend(self.quantum_instance.backend):
raise ValueError(
"Statevector mode for circuit sampling requires statevector "
"backend, not {}.".format(self.quantum_instance.backend)
)
with warnings.catch_warnings():
ElePT marked this conversation as resolved.
Show resolved Hide resolved
warnings.simplefilter("ignore")
if self._statevector and not is_statevector_backend(self.quantum_instance.backend):
raise ValueError(
"Statevector mode for circuit sampling requires statevector "
"backend, not {}.".format(self.quantum_instance.backend)
)

if self._param_qobj and not is_aer_provider(self.quantum_instance.backend):
raise ValueError(
"Parameterized Qobj mode requires Aer "
"backend, not {}.".format(self.quantum_instance.backend)
)
if self._param_qobj and not is_aer_provider(self.quantum_instance.backend):
raise ValueError(
"Parameterized Qobj mode requires Aer "
"backend, not {}.".format(self.quantum_instance.backend)
)

@property
def quantum_instance(self) -> QuantumInstance:
Expand Down
10 changes: 9 additions & 1 deletion 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,6 +15,7 @@
from abc import ABC, abstractmethod

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


class ConverterBase(ABC):
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="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(self) -> None:
pass

@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``
Deprecation: Converts ``DictStateFns`` or ``VectorStateFns`` to equivalent ``CircuitStateFns``
or sums thereof. The behavior of this class can be mostly replicated by calling ``to_circuit_op``
on an Operator, but with the added control of choosing whether to convert only ``DictStateFns``
or ``VectorStateFns``, rather than both.
"""

@deprecate_func(
since="0.24.0",
additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(
self, traverse: bool = True, convert_dicts: bool = True, convert_vectors: bool = True
) -> 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
8 changes: 7 additions & 1 deletion 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,6 +30,7 @@
from qiskit.opflow.state_fns.operator_state_fn import OperatorStateFn
from qiskit.opflow.state_fns.state_fn import StateFn
from qiskit.quantum_info import Pauli
from qiskit.utils.deprecation import deprecate_func


class PauliBasisChange(ConverterBase):
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="This deprecation is part of the opflow module deprecation effort. 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
12 changes: 9 additions & 3 deletions qiskit/opflow/converters/two_qubit_reduction.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 @@ -20,27 +20,33 @@
from qiskit.opflow.primitive_ops.pauli_sum_op import PauliSumOp
from qiskit.opflow.primitive_ops.tapered_pauli_sum_op import Z2Symmetries
from qiskit.quantum_info import Pauli
from qiskit.utils.deprecation import deprecate_func

logger = logging.getLogger(__name__)


class TwoQubitReduction(ConverterBase):
"""
Two qubit reduction converter which eliminates the central and last qubit in a list of Pauli
that has diagonal operators (Z,I) at those positions.
Two qubit reduction converter which eliminates the central and last
qubit in a list of Pauli that has diagonal operators (Z,I) at those positions.

Chemistry specific method:
It can be used to taper two qubits in parity and binary-tree mapped
fermionic Hamiltonians when the spin orbitals are ordered in two spin
sectors, (block spin order) according to the number of particles in the system.
"""

@deprecate_func(
since="0.24.0",
additional_msg="This deprecation is part of the opflow module deprecation effort. For code migration guidelines, visit https://qisk.it/opflow_migration.",
)
def __init__(self, num_particles: Union[int, List[int], Tuple[int, int]]):
"""
Args:
num_particles: number of particles, if it is a list,
the first number is alpha and the second number if beta.
"""
super().__init__()
if isinstance(num_particles, (tuple, list)):
num_alpha = num_particles[0]
num_beta = num_particles[1]
Expand Down
Loading