diff --git a/qiskit/primitives/backend_estimator_v2.py b/qiskit/primitives/backend_estimator_v2.py index 47352dd3de22..9c72cf99f29a 100644 --- a/qiskit/primitives/backend_estimator_v2.py +++ b/qiskit/primitives/backend_estimator_v2.py @@ -15,6 +15,7 @@ from __future__ import annotations import math +import warnings from collections import defaultdict from collections.abc import Iterable from dataclasses import dataclass @@ -131,12 +132,28 @@ def __init__( options: dict | None = None, ): """ + .. deprecated:: 1.4 + The method ``BackendEstimatorV2.__init__`` will stop supporting inputs of type + :class:`.BackendV1` in the `backend` parameter in a future release no + earlier than 2.0. :class:`.BackendV1` is deprecated and implementations should + move to :class:`.BackendV2`. + Args: backend: The backend to run the primitive on. options: The options to control the default precision (``default_precision``), the operator grouping (``abelian_grouping``), and the random seed for the simulator (``seed_simulator``). """ + + if not isinstance(backend, BackendV2): + warnings.warn( + "The method `BackendEstimatorV2.__init__` will stop supporting inputs of " + f"type `BackendV1` ( {backend} ) in the `backend` parameter in a future " + "release no earlier than 2.0. `BackendV1` is deprecated and implementations " + "should move to `BackendV2`.", + category=DeprecationWarning, + stacklevel=2, + ) self._backend = backend self._options = Options(**options) if options else Options() diff --git a/qiskit/primitives/backend_sampler_v2.py b/qiskit/primitives/backend_sampler_v2.py index 40a6d8560e07..395cac0a1c45 100644 --- a/qiskit/primitives/backend_sampler_v2.py +++ b/qiskit/primitives/backend_sampler_v2.py @@ -123,11 +123,26 @@ def __init__( options: dict | None = None, ): """ + .. deprecated:: 1.4 + The method ``BackendSamplerV2.__init__`` will stop supporting inputs of type + :class:`.BackendV1` in the `backend` parameter in a future release no + earlier than 2.0. :class:`.BackendV1` is deprecated and implementations should + move to :class:`.BackendV2`. + Args: backend: The backend to run the primitive on. options: The options to control the default shots (``default_shots``) and the random seed for the simulator (``seed_simulator``). """ + if not isinstance(backend, BackendV2): + warnings.warn( + "The method `BackendSamplerV2.__init__` will stop supporting inputs of " + f"type `BackendV1` ( {backend} ) in the `backend` parameter in a future " + "release no earlier than 2.0. `BackendV1` is deprecated and implementations " + "should move to `BackendV2`.", + category=DeprecationWarning, + stacklevel=2, + ) self._backend = backend self._options = Options(**options) if options else Options() diff --git a/qiskit/providers/backend_compat.py b/qiskit/providers/backend_compat.py index 2cacf1d9ff33..1e70d7d289d2 100644 --- a/qiskit/providers/backend_compat.py +++ b/qiskit/providers/backend_compat.py @@ -32,12 +32,6 @@ logger = logging.getLogger(__name__) -@deprecate_func( - since="1.4", - removal_timeline="in the 2.0 release", - additional_msg="With the deprecation of `qiskit.providers.models` this utility function " - "is not needed.", -) @deprecate_pulse_arg("defaults") def convert_to_target( configuration: BackendConfiguration, @@ -66,9 +60,19 @@ def convert_to_target( Returns: A ``Target`` instance. """ - return _convert_to_target( - configuration, properties, defaults, custom_name_mapping, add_delay, filter_faulty - ) + # If a deprecated error is raised during the conversion, we should not return the + # deprecation warning to the user,as it is not actionable for them. + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message=".*``qiskit.providers.exceptions.BackendPropertyError``", + module="qiskit", + ) + target = _convert_to_target( + configuration, properties, defaults, custom_name_mapping, add_delay, filter_faulty + ) + return target def _convert_to_target( @@ -323,7 +327,6 @@ def _get_value(prop_dict, prop_name): def qubit_props_list_from_props( properties: BackendProperties, ) -> List[QubitProperties]: - # TODO Remove this function with BackendProperties """Uses BackendProperties to construct and return a list of QubitProperties. """ @@ -440,7 +443,16 @@ def target(self): :rtype: Target """ if self._target is None: + # If a deprecated error is raised during the conversion, + # we should not return the deprecation warning to the user, + # as it is not actionable for them. with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message=".*``qiskit.providers.exceptions.BackendPropertyError``", + module="qiskit", + ) # convert_to_target is deprecated along BackendV2Converter # They both need to be removed at the same time warnings.filterwarnings( @@ -449,7 +461,7 @@ def target(self): message=r".+qiskit\.providers\.backend_compat\.convert_to_target.+", module="qiskit", ) - self._target = convert_to_target( + self._target = _convert_to_target( configuration=self._config, properties=self._properties, defaults=self._defaults, diff --git a/qiskit/providers/basic_provider/basic_simulator.py b/qiskit/providers/basic_provider/basic_simulator.py index dac4bff46781..70382ecbbc89 100644 --- a/qiskit/providers/basic_provider/basic_simulator.py +++ b/qiskit/providers/basic_provider/basic_simulator.py @@ -596,7 +596,6 @@ def _run_job(self, job_id: str, qobj: QasmQobj) -> Result: "time_taken": (end - start), "header": qobj.header.to_dict(), } - return Result.from_dict(result) @deprecate_func( diff --git a/qiskit/providers/exceptions.py b/qiskit/providers/exceptions.py index 3fddacb92fec..b805aa918c56 100644 --- a/qiskit/providers/exceptions.py +++ b/qiskit/providers/exceptions.py @@ -13,6 +13,7 @@ """Exceptions for errors raised while handling Backends and Jobs.""" from qiskit.exceptions import QiskitError +from qiskit.utils import deprecate_func class JobError(QiskitError): @@ -36,10 +37,30 @@ class QiskitBackendNotFoundError(QiskitError): class BackendPropertyError(QiskitError): """Base class for errors raised while looking for a backend property.""" - pass + @deprecate_func( + since="1.4", + removal_timeline="in the 2.0 release", + additional_msg="The models in ``qiskit.providers.models`` and related objects are part " + "of the deprecated `BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires these representations it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=2, + ) + def __init__(self, *message): + super().__init__(*message) class BackendConfigurationError(QiskitError): """Base class for errors raised by the BackendConfiguration.""" - pass + @deprecate_func( + since="1.4", + removal_timeline="in the 2.0 release", + additional_msg="The models in ``qiskit.providers.models`` and related objects are part " + "of the deprecated `BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires these representations it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=2, + ) + def __init__(self, *message): + super().__init__(*message) diff --git a/qiskit/providers/models/backendproperties.py b/qiskit/providers/models/backendproperties.py index 75e7cd18d03a..6ee56590df86 100644 --- a/qiskit/providers/models/backendproperties.py +++ b/qiskit/providers/models/backendproperties.py @@ -34,6 +34,15 @@ class Nduv: value: value. """ + @deprecate_func( + since="1.4", + removal_timeline="in the 2.0 release", + additional_msg="The models in ``qiskit.providers.models`` and related objects are part " + "of the deprecated `BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires these representations it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=2, + ) def __init__(self, date, name, unit, value): """Initialize a new name-date-unit-value object @@ -97,6 +106,15 @@ class GateProperties: _data = {} + @deprecate_func( + since="1.4", + removal_timeline="in the 2.0 release", + additional_msg="The models in ``qiskit.providers.models`` and related objects are part " + "of the deprecated `BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires these representations it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=2, + ) def __init__(self, qubits, gate, parameters, **kwargs): """Initialize a new :class:`GateProperties` object @@ -180,7 +198,7 @@ class BackendProperties: "of the deprecated `BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " "workflow requires these representations it likely relies on deprecated functionality and " "should be updated to use `BackendV2`.", - stacklevel=3, + stacklevel=2, ) def __init__( self, backend_name, backend_version, last_update_date, qubits, gates, general, **kwargs diff --git a/qiskit/providers/models/backendstatus.py b/qiskit/providers/models/backendstatus.py index 5001bffce5ed..14573f123e62 100644 --- a/qiskit/providers/models/backendstatus.py +++ b/qiskit/providers/models/backendstatus.py @@ -14,11 +14,21 @@ import html from qiskit.exceptions import QiskitError +from qiskit.utils import deprecate_func class BackendStatus: """Class representing Backend Status.""" + @deprecate_func( + since="1.4", + removal_timeline="in the 2.0 release", + additional_msg="The models in ``qiskit.providers.models`` and related objects are part " + "of the deprecated `BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires these representations it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=2, + ) def __init__( self, backend_name: str, diff --git a/qiskit/providers/models/jobstatus.py b/qiskit/providers/models/jobstatus.py index 2fc58e437ab9..c1f3f2919025 100644 --- a/qiskit/providers/models/jobstatus.py +++ b/qiskit/providers/models/jobstatus.py @@ -12,6 +12,8 @@ """Class for job status.""" +from qiskit.utils import deprecate_func + class JobStatus: """Model for JobStatus. @@ -24,6 +26,15 @@ class JobStatus: _data = {} + @deprecate_func( + since="1.4", + removal_timeline="in the 2.0 release", + additional_msg="The models in ``qiskit.providers.models`` and related objects are part " + "of the deprecated `BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires these representations it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=2, + ) def __init__(self, job_id, status, status_msg, **kwargs): self._data = {} self.job_id = job_id diff --git a/qiskit/result/result.py b/qiskit/result/result.py index 4a5a928f06d5..c425d2e2cd46 100644 --- a/qiskit/result/result.py +++ b/qiskit/result/result.py @@ -12,6 +12,7 @@ """Model for schema-conformant Results.""" +from collections.abc import Iterable import copy import warnings @@ -25,47 +26,135 @@ from qiskit.qobj.utils import MeasLevel from qiskit.qobj import QobjHeader +_MISSING = object() + class Result: """Model for Results. - Attributes: - backend_name (str): backend name. - backend_version (str): backend version, in the form X.Y.Z. - qobj_id (str): user-generated Qobj id. - job_id (str): unique execution id from the backend. - success (bool): True if complete input qobj executed correctly. (Implies + .. deprecated:: 1.4 + The use of positional arguments in the constructor of :class:`.Result` + is deprecated as of Qiskit 1.4, and will be disabled in Qiskit 2.0. + Please set all arguments using kwarg syntax, i.e: ``Result(backend_name="name", ....)``. + In addition to this, the ``qobj_id`` argument is deprecated and will no longer + be used in Qiskit 2.0. It will, however, still be possible to set ``qobj_id`` as a + generic kwarg, which will land in the metadata field with the other generic kwargs. + + Args: + backend_name (str): (REQUIRED) backend name. + backend_version (str): (REQUIRED) backend version, in the form X.Y.Z. + qobj_id (str): (REQUIRED) user-generated Qobj id. + job_id (str): (REQUIRED) unique execution id from the backend. + success (bool): (REQUIRED) True if complete input qobj executed correctly. (Implies each experiment success) - results (list[ExperimentResult]): corresponding results for array of + results (list[ExperimentResult]): (REQUIRED) corresponding results for array of experiments of the input qobj + date (str): (OPTIONAL) date of the experiment + header(dict): (OPTIONAL)experiment header + kwargs: generic keyword arguments. (OPTIONAL) These will be stored in the metadata field. """ _metadata = {} def __init__( self, - backend_name, - backend_version, - qobj_id, - job_id, - success, - results, + *args, date=None, status=None, header=None, **kwargs, ): + # The following arguments are required. + required_args = { + "backend_name": _MISSING, + "backend_version": _MISSING, + "qobj_id": _MISSING, + "job_id": _MISSING, + "success": _MISSING, + "results": _MISSING, + } + # Step 1: iterate over kwargs. + # An item from required_args might be set as a kwarg, so we must separate + # true kwargs from "required_args" kwargs. + true_kwargs = {} + for key, value in kwargs.items(): + if key in required_args: + required_args[key] = value + else: + true_kwargs[key] = value + # Step 2: iterate over args, which are expected in the order of the index_map below. + index_map = ["backend_name", "backend_version", "qobj_id", "job_id", "success", "results"] + raise_qobj = False + missing_args = [] + for index, name in enumerate(index_map): + try: + value = args[index] + required_args[name] = value + # The use of args is deprecated in 1.4 and will be removed in 2.0. + # Furthermore, qobj_id will be ignored if set as a kwarg in 2.0. + if name == "qobj_id": + warnings.warn( + "The use of positional arguments in `qiskit.result.result.Result.__init__()` " + "is deprecated as of Qiskit 1.4, and will be disabled in Qiskit 2.0. " + "Please set this value using kwarg syntax, " + f"i.e: `Result(...,{name}={name}_value)`. " + "The `qobj_id` argument will no longer be used in Qiskit 2.0, " + "but it will still be possible to " + "set as a kwarg that will land in the metadata field.", + category=DeprecationWarning, + stacklevel=2, + ) + else: + warnings.warn( + "The use of positional arguments in `qiskit.result.result.Result.__init__()` " + "is deprecated as of Qiskit 1.4, and will be disabled in Qiskit 2.0. " + "Please set this value using kwarg syntax, " + f"i.e: `Result(...,{name}={name}_value)`. ", + category=DeprecationWarning, + stacklevel=2, + ) + except IndexError: + if required_args[name] is _MISSING: + missing_args = [ + key for (key, value) in required_args.items() if value is _MISSING + ] + elif name == "qobj_id": + raise_qobj = True + break + + # The deprecation warning should be raised outside of the try-except, + # not to show a confusing trace that points to the IndexError + if len(missing_args) > 1: + raise TypeError( + f"Result.__init__() missing {len(missing_args)} required arguments: {missing_args}" + ) + if len(missing_args) == 1: + raise TypeError(f"Result.__init__() missing a required argument: {missing_args[0]}") + if raise_qobj: + # qobj_id will be ignored if set as a kwarg in 2.0. + warnings.warn( + "The `qobj_id` argument will no longer be used in Qiskit 2.0, " + "but it will still be possible to " + "set as a kwarg that will land in the metadata field.", + category=DeprecationWarning, + stacklevel=2, + ) + self._metadata = {} - self.backend_name = backend_name - self.backend_version = backend_version - self.qobj_id = qobj_id - self.job_id = job_id - self.success = success - self.results = results + self.backend_name = required_args["backend_name"] + self.backend_version = required_args["backend_version"] + self.qobj_id = required_args["qobj_id"] + self.job_id = required_args["job_id"] + self.success = required_args["success"] + self.results = ( + [required_args["results"]] + if not isinstance(required_args["results"], Iterable) + else required_args["results"] + ) self.date = date self.status = status self.header = header - self._metadata.update(kwargs) + self._metadata.update(true_kwargs) def __repr__(self): out = ( diff --git a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py index 7f9012ea1ddb..29d3aaaa5d02 100644 --- a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +++ b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py @@ -357,6 +357,11 @@ def generate_preset_pass_manager( message=".* ``backend_properties`` is deprecated as of Qiskit 1.4", module="qiskit", ) + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message=".*``qiskit.providers.exceptions.BackendPropertyError``", + ) # TODO: This is a temporary usage of deprecated backend_properties in # Target.from_configuration. Probably the logic needs to be restructured # in a more target-centric transpiler diff --git a/qiskit/visualization/gate_map.py b/qiskit/visualization/gate_map.py index 06dc3c66e425..8c2dee0da7cc 100644 --- a/qiskit/visualization/gate_map.py +++ b/qiskit/visualization/gate_map.py @@ -13,6 +13,7 @@ """A module for visualizing device coupling maps""" import math +import warnings from typing import List import numpy as np @@ -21,6 +22,7 @@ from qiskit.exceptions import QiskitError from qiskit.utils import optionals as _optionals +from qiskit.providers import BackendV2 from qiskit.providers.exceptions import BackendPropertyError from qiskit.transpiler.coupling import CouplingMap from .exceptions import VisualizationError @@ -50,6 +52,12 @@ def plot_gate_map( ): """Plots the gate map of a device. + .. deprecated:: 1.4 + The function ``plot_gate_map`` will stop supporting inputs of type + :class:`.BackendV1` in the `backend` parameter in a future release no + earlier than 2.0. :class:`.BackendV1` is deprecated and implementations should + move to :class:`.BackendV2`. + Args: backend (Backend): The backend instance that will be used to plot the device gate map. @@ -92,6 +100,15 @@ def plot_gate_map( plot_gate_map(backend) """ + if not isinstance(backend, BackendV2): + warnings.warn( + "The function `plot_gate_map` will stop supporting inputs of " + f"type `BackendV1` ( {backend} ) in the `backend` parameter in a future " + "release no earlier than 2.0. `BackendV1` is deprecated and implementations " + "should move to `BackendV2`.", + category=DeprecationWarning, + stacklevel=2, + ) qubit_coordinates_map = {} qubit_coordinates_map[5] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]] @@ -1145,6 +1162,12 @@ def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None """Plot the layout of a circuit transpiled for a given target backend. + .. deprecated:: 1.4 + The function ``plot_circuit_layout`` will stop supporting inputs of type + :class:`.BackendV1` in the `backend` parameter in a future release no + earlier than 2.0. :class:`.BackendV1` is deprecated and implementations should + move to :class:`.BackendV2`. + Args: circuit (QuantumCircuit): Input quantum circuit. backend (Backend): Target backend. @@ -1187,6 +1210,17 @@ def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None new_circ_lv3 = transpile(ghz, backend=backend, optimization_level=3) plot_circuit_layout(new_circ_lv3, backend) """ + + if not isinstance(backend, BackendV2): + warnings.warn( + "The function `plot_circuit_layout` will stop supporting inputs of " + f"type `BackendV1` ( {backend} ) in the `backend` parameter in a future " + "release no earlier than 2.0. `BackendV1` is deprecated and implementations " + "should move to `BackendV2`.", + category=DeprecationWarning, + stacklevel=2, + ) + if circuit._layout is None: raise QiskitError("Circuit has no layout. Perhaps it has not been transpiled.") @@ -1254,6 +1288,12 @@ def plot_circuit_layout(circuit, backend, view="virtual", qubit_coordinates=None def plot_error_map(backend, figsize=(15, 12), show_title=True, qubit_coordinates=None): """Plots the error map of a given backend. + .. deprecated:: 1.4 + The function ``plot_error_map`` will stop supporting inputs of type + :class:`.BackendV1` in the `backend` parameter in a future release no + earlier than 2.0. :class:`.BackendV1` is deprecated and implementations should + move to :class:`.BackendV2`. + Args: backend (Backend): Given backend. figsize (tuple): Figure size in inches. @@ -1282,6 +1322,16 @@ def plot_error_map(backend, figsize=(15, 12), show_title=True, qubit_coordinates backend = GenericBackendV2(num_qubits=5) plot_error_map(backend) """ + if not isinstance(backend, BackendV2): + warnings.warn( + "The function `plot_error_map` will stop supporting inputs of " + f"type `BackendV1` ( {backend} ) in the `backend` parameter in a future " + "release no earlier than 2.0. `BackendV1` is deprecated and implementations " + "should move to `BackendV2`.", + category=DeprecationWarning, + stacklevel=2, + ) + import matplotlib import matplotlib.pyplot as plt from matplotlib import gridspec, ticker diff --git a/releasenotes/notes/deprecate-backend-v1-followup-5b51d00ce512bd24.yaml b/releasenotes/notes/deprecate-backend-v1-followup-5b51d00ce512bd24.yaml new file mode 100644 index 000000000000..ddb09510df98 --- /dev/null +++ b/releasenotes/notes/deprecate-backend-v1-followup-5b51d00ce512bd24.yaml @@ -0,0 +1,31 @@ +--- +deprecations_primitives: + - | + Providing inputs of type :class:`.BackendV1` to the ``backend`` argument of + :class:`.BackendSamplerV2` and :class:`.BackendEstimatorV2` is deprecated as of + Qiskit 1.4 and will be removed in Qiskit 2.0. Use an instance of :class:`.BackendV2` + instead. +deprecations_providers: + - | + The error types :class:`.BackendPropertyError` and :class:`.BackendConfigurationError` + have been deprecated in Qiskit 1.4 and will be removed in Qiskit 2.0. These errors are + only used when retrieving items from the deprecated :class:`.BackendProperties` and + :class:`.BackendConfiguration` objects. + - | + The classes :class:`.GateProperties`, :class:`.BackendStatus`, and :class:`qiskit.providers.models.JobStatus`, + which are part of the legacy :class:`.BackendV1` workflow, are now deprecated. + These should have been deprecated in Qiskit 1.2 together with the related elements in :mod:`qiskit.providers.models`. +deprecations_visualization: + - | + Providing inputs of type :class:`.BackendV1` to the ``backend`` argument of + :func:`.plot_gate_map`, :func:`.plot_circuit_layout`, and :func:`.plot_error_map` + are deprecated as of Qiskit 1.4 and will be removed in Qiskit 2.0. + Use an instance of :class:`.BackendV2` instead. +deprecations_misc: + - | + The use of positional arguments in the constructor of :class:`.Result` + is deprecated as of Qiskit 1.4, and will be disabled in Qiskit 2.0. + Please set all arguments using kwarg syntax, i.e: ``Result(backend_name="name", ....)``. + In addition to this, the ``qobj_id`` argument is deprecated and will no longer + be used in Qiskit 2.0. It will, however, still be possible to set ``qobj_id`` as a + generic kwarg, which will land in the metadata field with the other generic kwargs. \ No newline at end of file diff --git a/test/python/primitives/test_backend_estimator_v2.py b/test/python/primitives/test_backend_estimator_v2.py index dd55750c55a0..fbf92f0c2c7f 100644 --- a/test/python/primitives/test_backend_estimator_v2.py +++ b/test/python/primitives/test_backend_estimator_v2.py @@ -147,7 +147,7 @@ def test_estimator_run_v1(self, backend, abelian_grouping): psi1, psi2 = pm.run([psi1, psi2]) with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init estimator = BackendEstimatorV2(backend=backend, options=self._options) estimator.options.abelian_grouping = abelian_grouping # Specify the circuit and observable by indices. @@ -240,7 +240,7 @@ def test_estimator_with_pub_v1(self, backend, abelian_grouping): with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init estimator = BackendEstimatorV2(backend=backend, options=self._options) estimator.options.abelian_grouping = abelian_grouping result4 = estimator.run([pub1, pub2]).result() @@ -272,7 +272,7 @@ def test_estimator_run_no_params_v1(self, backend, abelian_grouping): circuit = pm.run(circuit) with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init est = BackendEstimatorV2(backend=backend, options=self._options) est.options.abelian_grouping = abelian_grouping observable = self.observable.apply_layout(circuit.layout) @@ -455,7 +455,7 @@ def test_run_1qubit_v1(self, backend, abelian_grouping): with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init est = BackendEstimatorV2(backend=backend, options=self._options) est.options.abelian_grouping = abelian_grouping @@ -534,7 +534,7 @@ def test_run_2qubits_v1(self, backend, abelian_grouping): with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init est = BackendEstimatorV2(backend=backend, options=self._options) est.options.abelian_grouping = abelian_grouping op_1 = op.apply_layout(qc.layout) @@ -572,7 +572,7 @@ def test_run_errors_v1(self, backend, abelian_grouping): op2 = SparsePauliOp.from_list([("II", 1)]) with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init est = BackendEstimatorV2(backend=backend, options=self._options) est.options.abelian_grouping = abelian_grouping with self.assertRaises(ValueError): @@ -732,7 +732,7 @@ def test_precision_v1(self, backend, abelian_grouping): """Test for precision""" with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init estimator = BackendEstimatorV2(backend=backend, options=self._options) estimator.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( @@ -778,7 +778,7 @@ def test_diff_precision_v1(self, backend, abelian_grouping): """Test for running different precisions at once""" with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init estimator = BackendEstimatorV2(backend=backend, options=self._options) estimator.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( @@ -868,7 +868,7 @@ def test_job_size_limit_backend_v1(self): param_list = self._rng.random(qc.num_parameters).tolist() with self.assertWarns(DeprecationWarning): # When BackendEstimatorV2 is called with a backend V1, it raises a - # DeprecationWarning from PassManagerConfig.from_backend + # DeprecationWarning from PassManagerConfig.from_backend and its own init estimator = BackendEstimatorV2(backend=backend) with patch.object(backend, "run") as run_mock: estimator.run([(qc, op, param_list)] * k).result() diff --git a/test/python/primitives/test_backend_sampler_v2.py b/test/python/primitives/test_backend_sampler_v2.py index 77830d5c9224..e5e624757466 100644 --- a/test/python/primitives/test_backend_sampler_v2.py +++ b/test/python/primitives/test_backend_sampler_v2.py @@ -170,7 +170,11 @@ def test_sampler_run_v1(self, backend): with self.subTest("single"): bell, _, target = self._cases[1] bell = pm.run(bell) - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) job = sampler.run([bell], shots=self._shots) result = job.result() self.assertIsInstance(result, PrimitiveResult) @@ -183,7 +187,11 @@ def test_sampler_run_v1(self, backend): with self.subTest("single with param"): pqc, param_vals, target = self._cases[2] - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) pqc = pm.run(pqc) params = (param.name for param in pqc.parameters) job = sampler.run([(pqc, {params: param_vals})], shots=self._shots) @@ -198,7 +206,11 @@ def test_sampler_run_v1(self, backend): with self.subTest("multiple"): pqc, param_vals, target = self._cases[2] - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) pqc = pm.run(pqc) params = (param.name for param in pqc.parameters) job = sampler.run( @@ -268,7 +280,11 @@ def test_sampler_run(self, backend): def test_sampler_run_multiple_times_v1(self, backend): """Test run() returns the same results if the same input is given.""" bell, _, _ = self._cases[1] - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, expected_regex="The `generate_preset_pass_manager` function will " @@ -299,7 +315,11 @@ def test_sampler_run_multiple_times(self, backend): def test_sample_run_multiple_circuits_v1(self, backend): """Test run() with multiple circuits.""" bell, _, target = self._cases[1] - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, expected_regex="The `generate_preset_pass_manager` function will " @@ -335,8 +355,11 @@ def test_sampler_run_with_parameterized_circuits_v1(self, backend): with self.assertWarns(DeprecationWarning): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) pqc1, pqc2, pqc3 = pm.run([pqc1, pqc2, pqc3]) - - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run( [(pqc1, param1), (pqc2, param2), (pqc3, param3)], shots=self._shots ).result() @@ -378,7 +401,11 @@ def test_run_1qubit_v1(self, backend): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc, qc2], shots=self._shots).result() self.assertEqual(len(result), 2) for i in range(2): @@ -429,7 +456,11 @@ def test_run_2qubit_v1(self, backend): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc0, qc1, qc2, qc3 = pm.run([qc0, qc1, qc2, qc3]) - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc0, qc1, qc2, qc3], shots=self._shots).result() self.assertEqual(len(result), 4) for i in range(4): @@ -496,7 +527,11 @@ def test_run_single_circuit(self, backend): @combine(backend=BACKENDS_V1) def test_run_single_circuit_v1(self, backend): """Test for single circuit case.""" - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, expected_regex="The `generate_preset_pass_manager` function will " @@ -603,8 +638,11 @@ def test_run_reverse_meas_order_v1(self, backend): ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) - - sampler = BackendSamplerV2(backend=backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend) sampler.options.seed_simulator = self._seed result = sampler.run([(qc, [0, 0]), (qc, [np.pi / 2, 0])], shots=self._shots).result() self.assertEqual(len(result), 2) @@ -682,7 +720,11 @@ def test_run_errors_v1(self, backend): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc1, qc2 = pm.run([qc1, qc2]) - sampler = BackendSamplerV2(backend=backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend) with self.subTest("set parameter values to a non-parameterized circuit"): with self.assertRaises(ValueError): _ = sampler.run([(qc1, [1e2])]).result() @@ -757,7 +799,11 @@ def test_run_empty_parameter_v1(self, backend): ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) with self.subTest("one circuit"): result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) @@ -818,13 +864,21 @@ def test_run_numpy_params_v1(self, backend): target = sampler.run([(qc, params_list)], shots=self._shots).result() with self.subTest("ndarray"): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([(qc, params_array)], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target[0].data.meas) with self.subTest("split a list"): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run( [(qc, params) for params in params_list], shots=self._shots ).result() @@ -912,14 +966,22 @@ def test_run_with_shots_option_v1(self, backend): shots = 100 with self.subTest("run arg"): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([bell], shots=shots).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("default shots"): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) default_shots = sampler.options.default_shots result = sampler.run([bell]).result() self.assertEqual(len(result), 1) @@ -928,7 +990,11 @@ def test_run_with_shots_option_v1(self, backend): with self.subTest("setting default shots"): default_shots = 100 - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) sampler.options.default_shots = default_shots self.assertEqual(sampler.options.default_shots, default_shots) result = sampler.run([bell]).result() @@ -937,21 +1003,33 @@ def test_run_with_shots_option_v1(self, backend): self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) with self.subTest("pub-like"): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([(bell, None, shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("pub"): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([SamplerPub(bell, shots=shots)]).result() self.assertEqual(len(result), 1) self.assertEqual(result[0].data.meas.num_shots, shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots) with self.subTest("multiple pubs"): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) shots1 = 100 shots2 = 200 result = sampler.run( @@ -996,7 +1074,11 @@ def test_run_shots_result_size_v1(self, backend): ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) self.assertLessEqual(result[0].data.meas.num_shots, self._shots) @@ -1022,6 +1104,8 @@ def test_run_level1(self): }, } sampler = BackendSamplerV2(backend=backend, options=options) + # sampler.run will call the custom backend.run implementation + # that returns a deprecation warning result_single = sampler.run([qc]).result() options = { @@ -1033,6 +1117,8 @@ def test_run_level1(self): }, } sampler = BackendSamplerV2(backend=backend, options=options) + # sampler.run will call the custom backend.run implementation + # that returns a deprecation warning result_avg = sampler.run([qc]).result() # Check that averaging the meas_return="single" data matches the @@ -1073,7 +1159,11 @@ def test_primitive_job_status_done_v1(self, backend): ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) job = sampler.run([bell], shots=self._shots) _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) @@ -1126,8 +1216,11 @@ def test_circuit_with_unitary_v1(self, backend): circuit.append(gate, [0]) circuit.measure_all() circuit = pm.run(circuit) - - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({0: self._shots})) @@ -1139,8 +1232,11 @@ def test_circuit_with_unitary_v1(self, backend): circuit.append(gate, [0]) circuit.measure_all() circuit = pm.run(circuit) - - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([circuit], shots=self._shots).result() self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({1: self._shots})) @@ -1301,7 +1397,11 @@ def test_circuit_with_multiple_cregs_v1(self, backend): for title, qc, target in cases: with self.subTest(title): - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(len(result), 1) data = result[0].data @@ -1374,8 +1474,11 @@ def test_circuit_with_aliased_cregs_v1(self, backend): cregs[1]: {0: 5000, 1: 5000}, cregs[2]: {0: 8500, 1: 1500}, } - - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, expected_regex="The `generate_preset_pass_manager` function will " @@ -1395,7 +1498,15 @@ def test_circuit_with_aliased_cregs_v1(self, backend): def test_no_cregs(self, backend): """Test that the sampler works when there are no classical register in the circuit.""" qc = QuantumCircuit(2) - sampler = BackendSamplerV2(backend=backend, options=self._options) + if backend.version == 1: + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) + else: + sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarns(UserWarning): result = sampler.run([qc]).result() @@ -1413,7 +1524,14 @@ def test_empty_creg(self, backend): qc.h(0) qc.measure(0, 0) - sampler = BackendSamplerV2(backend=backend, options=self._options) + if backend.version == 1: + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) + else: + sampler = BackendSamplerV2(backend=backend, options=self._options) result = sampler.run([qc], shots=self._shots).result() self.assertEqual(result[0].data.c1.array.shape, (self._shots, 0)) @@ -1447,7 +1565,11 @@ def test_diff_shots_v1(self, backend): bell, _, target = self._cases[1] bell = pm.run(bell) - sampler = BackendSamplerV2(backend=backend, options=self._options) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="will stop supporting inputs of type `BackendV1`", + ): + sampler = BackendSamplerV2(backend=backend, options=self._options) shots2 = self._shots + 2 target2 = {k: v + 1 for k, v in target.items()} job = sampler.run([(bell, None, self._shots), (bell, None, shots2)]) diff --git a/test/python/providers/test_backendconfiguration.py b/test/python/providers/test_backendconfiguration.py index f3309fda4b40..32df20471d37 100644 --- a/test/python/providers/test_backendconfiguration.py +++ b/test/python/providers/test_backendconfiguration.py @@ -75,14 +75,22 @@ def test_get_channels(self): self.assertEqual(self.config.drive(0), DriveChannel(0)) self.assertEqual(self.config.measure(1), MeasureChannel(1)) self.assertEqual(self.config.acquire(0), AcquireChannel(0)) - with self.assertRaises(BackendConfigurationError): - # Check that an error is raised if the system doesn't have that many qubits - self.assertEqual(self.config.acquire(10), AcquireChannel(10)) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendConfigurationError`` is deprecated ", + ): + with self.assertRaises(BackendConfigurationError): + # Check that an error is raised if the system doesn't have that many qubits + self.assertEqual(self.config.acquire(10), AcquireChannel(10)) with self.assertWarns(DeprecationWarning): self.assertEqual(self.config.control(qubits=[0, 1]), [ControlChannel(0)]) - with self.assertRaises(BackendConfigurationError): - # Check that an error is raised if key not found in self._qubit_channel_map - self.config.control(qubits=(10, 1)) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendConfigurationError`` is deprecated ", + ): + with self.assertRaises(BackendConfigurationError): + # Check that an error is raised if key not found in self._qubit_channel_map + self.config.control(qubits=(10, 1)) def test_get_channel_qubits(self): """Test to get all qubits operated on a given channel.""" @@ -140,9 +148,13 @@ def test_get_qubit_channels(self): ], ) ) - with self.assertRaises(BackendConfigurationError): - # Check that an error is raised if key not found in self._channel_qubit_map - self.config.get_qubit_channels(10) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendConfigurationError`` is deprecated ", + ): + with self.assertRaises(BackendConfigurationError): + # Check that an error is raised if key not found in self._channel_qubit_map + self.config.get_qubit_channels(10) def test_supported_instructions(self): """Test that supported instructions get entered into config dict properly.""" @@ -183,8 +195,12 @@ def test_get_default_rep_delay_and_range(self): def test_get_channel_prefix_index(self): """Test private method to get channel and index.""" self.assertEqual(self.config._get_channel_prefix_index("acquire0"), ("acquire", 0)) - with self.assertRaises(BackendConfigurationError): - self.config._get_channel_prefix_index("acquire") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendConfigurationError`` is deprecated ", + ): + with self.assertRaises(BackendConfigurationError): + self.config._get_channel_prefix_index("acquire") def _test_lists_equal(self, actual, expected): """Test if 2 lists are equal. It returns ``True`` is lists are equal.""" diff --git a/test/python/providers/test_backendproperties.py b/test/python/providers/test_backendproperties.py index ac024973133e..6db6fc214f63 100644 --- a/test/python/providers/test_backendproperties.py +++ b/test/python/providers/test_backendproperties.py @@ -42,8 +42,12 @@ def test_gate_property(self): ) self.assertEqual(self.properties.gate_property("cx"), self.properties._gates["cx"]) - with self.assertRaises(BackendPropertyError): - self.properties.gate_property(self.ref_gate, None, "gate_error") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendPropertyError`` is deprecated ", + ): + with self.assertRaises(BackendPropertyError): + self.properties.gate_property(self.ref_gate, None, "gate_error") def test_gate_error(self): """Test for getting the gate errors.""" @@ -64,9 +68,12 @@ def test_gate_error(self): self.properties.gate_error("cx", [0, 1]), self.properties._gates["cx"][(0, 1)]["gate_error"][0], ) - - with self.assertRaises(BackendPropertyError): - self.properties.gate_error("cx", 0) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendPropertyError`` is deprecated ", + ): + with self.assertRaises(BackendPropertyError): + self.properties.gate_error("cx", 0) def test_gate_length(self): """Test for getting the gate duration.""" @@ -87,8 +94,12 @@ def test_qubit_property(self): ) self.assertEqual(self.properties.qubit_property(0), self.properties._qubits[0]) - with self.assertRaises(BackendPropertyError): - self.properties.qubit_property("T1") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendPropertyError`` is deprecated ", + ): + with self.assertRaises(BackendPropertyError): + self.properties.qubit_property("T1") def test_t1(self): """Test for getting the t1 of given qubit.""" @@ -121,8 +132,12 @@ def test_apply_prefix(self): ) self.assertEqual(self.properties._apply_prefix(71.9500421005539, "ms"), 0.0719500421005539) - with self.assertRaises(BackendPropertyError): - self.properties._apply_prefix(71.9500421005539, "ws") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.exceptions.BackendPropertyError`` is deprecated ", + ): + with self.assertRaises(BackendPropertyError): + self.properties._apply_prefix(71.9500421005539, "ws") def test_operational(self): """Test operation status of a given qubit.""" diff --git a/test/python/providers/test_backendstatus.py b/test/python/providers/test_backendstatus.py index c0cfb7f792a3..dbcd82e81161 100644 --- a/test/python/providers/test_backendstatus.py +++ b/test/python/providers/test_backendstatus.py @@ -21,23 +21,28 @@ class TestBackendConfiguration(QiskitTestCase): """Test the BackendStatus class.""" - def setUp(self): - """Test backend status for one of the fake backends""" - super().setUp() - self.backend_status = BackendStatus("my_backend", "1.0", True, 2, "online") - def test_repr(self): """Test representation methods of BackendStatus""" - self.assertIsInstance(self.backend_status.__repr__(), str) - repr_html = self.backend_status._repr_html_() + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.models.backendstatus.BackendStatus`` is deprecated ", + ): + backend_status = BackendStatus("my_backend", "1.0", True, 2, "online") + + self.assertIsInstance(backend_status.__repr__(), str) + repr_html = backend_status._repr_html_() self.assertIsInstance(repr_html, str) - self.assertIn(self.backend_status.backend_name, repr_html) + self.assertIn(backend_status.backend_name, repr_html) def test_fake_backend_status(self): """Test backend status for one of the fake backends""" with self.assertWarns(DeprecationWarning): fake_backend = Fake5QV1() - backend_status = fake_backend.status() + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="``qiskit.providers.models.backendstatus.BackendStatus`` is deprecated ", + ): + backend_status = fake_backend.status() self.assertIsInstance(backend_status, BackendStatus) diff --git a/test/python/result/test_result.py b/test/python/result/test_result.py index 89539487158c..656220a1ad4e 100644 --- a/test/python/result/test_result.py +++ b/test/python/result/test_result.py @@ -47,7 +47,6 @@ def generate_qiskit_result(self): exp_result_1 = models.ExperimentResult( shots=8, success=True, data=data_1, header=exp_result_header_1 ) - result = Result(results=[exp_result_1], **self.base_result_args) return result @@ -92,7 +91,6 @@ def test_counts_by_name(self): shots=14, success=True, meas_level=2, data=data, header=exp_result_header ) result = Result(results=[exp_result], **self.base_result_args) - self.assertEqual(result.get_counts("a_name"), processed_counts) def test_counts_duplicate_name(self): @@ -240,7 +238,6 @@ def test_marginal_counts_result(self): exp_result_2 = models.ExperimentResult( shots=13, success=True, data=data_2, header=exp_result_header_2 ) - result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args) expected_marginal_counts_1 = {"00": 4, "01": 27, "10": 23} @@ -356,7 +353,6 @@ def test_marginal_counts_result_creg_sizes(self): exp_result = models.ExperimentResult( shots=54, success=True, data=data, header=exp_result_header ) - result = Result(results=[exp_result], **self.base_result_args) expected_marginal_counts = {"0 0": 14, "0 1": 18, "1 0": 13, "1 1": 9} @@ -381,7 +377,6 @@ def test_marginal_counts_result_format(self): exp_result_1 = models.ExperimentResult( shots=54, success=True, data=data_1, header=exp_result_header_1 ) - result = Result(results=[exp_result_1], **self.base_result_args) expected_marginal_counts_1 = { @@ -413,7 +408,6 @@ def test_marginal_counts_inplace_true(self): exp_result_2 = models.ExperimentResult( shots=13, success=True, data=data_2, header=exp_result_header_2 ) - result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args) expected_marginal_counts = {"0": 27, "1": 27} @@ -440,7 +434,6 @@ def test_marginal_counts_inplace_false(self): exp_result_2 = models.ExperimentResult( shots=13, success=True, data=data_2, header=exp_result_header_2 ) - result = Result(results=[exp_result_1, exp_result_2], **self.base_result_args) expected_marginal_counts = {"0": 27, "1": 27} @@ -779,10 +772,43 @@ def test_marginal_counts_no_cregs(self): exp_result_1 = models.ExperimentResult( shots=54, success=True, data=data_1, header=exp_result_header_1 ) - result = Result(results=[exp_result_1], **self.base_result_args) - with self.assertWarns(DeprecationWarning): _ = marginal_counts(result, indices=[0]) marginal_counts_result = marginal_counts(result, indices=[0]) self.assertEqual(marginal_counts_result.get_counts(), {"0": 27, "1": 27}) + + def test_deprecation(self): + """Test that positional arguments are deprecated.""" + memory = [hex(ii) for ii in range(8)] + counts = {m: 1 for m in memory} + data_1 = models.ExperimentResultData(counts=counts, memory=memory) + with self.assertWarns(DeprecationWarning): + exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + exp_result_1 = models.ExperimentResult( + shots=8, success=True, data=data_1, header=exp_result_header_1 + ) + with self.subTest("all positional args"): + # order is: backend_name, backend_version, qobj_id, job_id, success, results + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex=r"The use of positional arguments in " + r"`qiskit.result.result.Result.__init__\(\)` is deprecated as of Qiskit 1.4", + ): + _ = Result("test_backend", "1.0.0", "id-123", "job-123", True, [exp_result_1]) + + with self.subTest("one positional arg"): + result_args = { + "backend_version": "1.0.0", + "qobj_id": "id-123", + "job_id": "job-123", + "success": True, + "results": exp_result_1, + } + # check that even one positional argument raises the deprecation warning + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex=r"The use of positional arguments in " + r"`qiskit.result.result.Result.__init__\(\)` is deprecated as of Qiskit 1.4", + ): + _ = Result("test_backend", **result_args) diff --git a/test/python/transpiler/test_target.py b/test/python/transpiler/test_target.py index cc1ef345cec5..79566cae0c95 100644 --- a/test/python/transpiler/test_target.py +++ b/test/python/transpiler/test_target.py @@ -2120,7 +2120,7 @@ def test_properties_with_durations(self): instruction_durations=durations, dt=config.dt, ) - self.assertEqual(0.5, target["rz"][(0,)].duration) + self.assertEqual(0.5, target["rz"][(0,)].duration) def test_inst_map(self): with self.assertWarns(DeprecationWarning): diff --git a/test/python/visualization/test_gate_map.py b/test/python/visualization/test_gate_map.py index d2d589574103..b33b48125467 100644 --- a/test/python/visualization/test_gate_map.py +++ b/test/python/visualization/test_gate_map.py @@ -56,7 +56,11 @@ def test_plot_gate_map(self, backend): """tests plotting of gate map of a device (20 qubit, 7 qubit, and 5 qubit)""" n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "bit_quantum_computer.png") - fig = plot_gate_map(backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="`plot_gate_map` will stop supporting inputs of type `BackendV1`", + ): + fig = plot_gate_map(backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) @@ -78,7 +82,11 @@ def test_plot_circuit_layout(self, backend): circuit._layout.initial_layout.add_register(qr) n = backend.configuration().n_qubits img_ref = path_to_diagram_reference(str(n) + "_plot_circuit_layout.png") - fig = plot_circuit_layout(circuit, backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="`plot_circuit_layout` will stop supporting inputs of type `BackendV1`", + ): + fig = plot_circuit_layout(circuit, backend) with BytesIO() as img_buffer: fig.savefig(img_buffer, format="png") img_buffer.seek(0) diff --git a/test/utils/base.py b/test/utils/base.py index 133666cfc7ad..7240ede04a16 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -138,6 +138,15 @@ def setUpClass(cls): module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", ) + # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2197 is in a release version + # of Aer. + warnings.filterwarnings( + "ignore", # If "default", it floods the CI output + category=DeprecationWarning, + message=r".*kwarg that will land in the metadata field*", + module="qiskit", + ) + # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2065 is in a release version # of Aer. warnings.filterwarnings( @@ -197,6 +206,18 @@ def setUpClass(cls): module="qiskit.transpiler.passes.scheduling", ) + # The deprecation warning of qobj_id in Result is raised every + # time Aer is used to run a simulation. Remove this filter once + # Aer has transitioned to 2.0. + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message=r"The `qobj_id` argument will no longer be used in Qiskit 2.*0, " + "but it will still be possible to set as a kwarg that will land in " + "the metadata field.", + module="qiskit", + ) + allow_DeprecationWarning_message = [ r"The property ``qiskit\.circuit\.bit\.Bit\.(register|index)`` is deprecated.*", ]