From 9cc2154ac37a6a7f84875fc5cf4931621a6296b8 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 7 Jun 2024 10:42:38 +0200 Subject: [PATCH 001/168] initial commit --- qiskit/providers/backend.py | 2 ++ releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml | 4 ++++ 2 files changed, 6 insertions(+) create mode 100644 releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml diff --git a/qiskit/providers/backend.py b/qiskit/providers/backend.py index 2e551cc311e8..a08622acba21 100644 --- a/qiskit/providers/backend.py +++ b/qiskit/providers/backend.py @@ -23,6 +23,7 @@ from qiskit.providers.provider import Provider from qiskit.providers.models.backendstatus import BackendStatus from qiskit.circuit.gate import Instruction +from qiskit.utils import deprecate_func class Backend: @@ -71,6 +72,7 @@ class BackendV1(Backend, ABC): version = 1 + @deprecate_func(since=1.2, removal_timeline="in the 2.0.0 release") def __init__(self, configuration, provider=None, **fields): """Initialize a backend class diff --git a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml new file mode 100644 index 000000000000..1f5b561e4ecf --- /dev/null +++ b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml @@ -0,0 +1,4 @@ +--- +deprecations_providers: + - | + related to the qiskit.providers module. From 6d8ac9759302161bce96c88b148d093f75679f93 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 21 Jun 2024 12:25:27 +0200 Subject: [PATCH 002/168] reno --- qiskit/providers/backend.py | 11 +++++++++-- releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml | 5 ++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/qiskit/providers/backend.py b/qiskit/providers/backend.py index a08622acba21..cad932f49e70 100644 --- a/qiskit/providers/backend.py +++ b/qiskit/providers/backend.py @@ -44,7 +44,7 @@ class BackendV1(Backend, ABC): This abstract class is to be used for Backend objects. There are several classes of information contained in a Backend. The first are the attributes of the class itself. These should be used to - defined the immutable characteristics of the backend. The ``options`` + define the immutable characteristics of the backend. The ``options`` attribute of the backend is used to contain the dynamic user configurable options of the backend. It should be used more for runtime options that configure how the backend is used. For example, something like a @@ -72,7 +72,14 @@ class BackendV1(Backend, ABC): version = 1 - @deprecate_func(since=1.2, removal_timeline="in the 2.0.0 release") + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="If this backend is only a hardware description, consider constructing a " + "Target. If the provider also provides access for execution, it can construct " + "Primitives. Alternatebly, consider moving to BackendV2 " + "(see https://ibm.biz/qiskit_backendv1-to-v2).", + ) def __init__(self, configuration, provider=None, **fields): """Initialize a backend class diff --git a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml index 1f5b561e4ecf..a7308f428da3 100644 --- a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml +++ b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml @@ -1,4 +1,7 @@ --- deprecations_providers: - | - related to the qiskit.providers module. + BackendV1 is deprecated and it will be removed not earlier than the next major release. + If providers want to explose a backend only as a hardware description, consider constructing a :class:`.Target`. + If the provider also provides access for execution, that can be done via the primitives interfaces. + Alternatebly, if the previous model is prefered, consider moving to :class:`.BackendV2` (see https://ibm.biz/qiskit_backendv1-to-v2). From 5906c3b36e409cb1c4f35ffcc429e84ec220b3ac Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 21 Jun 2024 15:11:58 +0200 Subject: [PATCH 003/168] Apply suggestions from code review --- qiskit/providers/backend.py | 2 +- releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/qiskit/providers/backend.py b/qiskit/providers/backend.py index cad932f49e70..e8b5978398a4 100644 --- a/qiskit/providers/backend.py +++ b/qiskit/providers/backend.py @@ -78,7 +78,7 @@ class BackendV1(Backend, ABC): additional_msg="If this backend is only a hardware description, consider constructing a " "Target. If the provider also provides access for execution, it can construct " "Primitives. Alternatebly, consider moving to BackendV2 " - "(see https://ibm.biz/qiskit_backendv1-to-v2).", + "(see https://qisk.it/backendV1-to-V2).", ) def __init__(self, configuration, provider=None, **fields): """Initialize a backend class diff --git a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml index a7308f428da3..d6d2fdca4c47 100644 --- a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml +++ b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml @@ -4,4 +4,4 @@ deprecations_providers: BackendV1 is deprecated and it will be removed not earlier than the next major release. If providers want to explose a backend only as a hardware description, consider constructing a :class:`.Target`. If the provider also provides access for execution, that can be done via the primitives interfaces. - Alternatebly, if the previous model is prefered, consider moving to :class:`.BackendV2` (see https://ibm.biz/qiskit_backendv1-to-v2). + Alternatebly, if the previous model is prefered, consider moving to :class:`.BackendV2` (see https://qisk.it/backendV1-to-V2). From 2e99d5af4c8f299617b571380e8549014b52371a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 24 Jun 2024 22:06:18 +0200 Subject: [PATCH 004/168] deprecate qobj and assemble --- qiskit/compiler/assembler.py | 8 + qiskit/qobj/common.py | 9 + qiskit/qobj/converters/lo_config.py | 8 + qiskit/qobj/converters/pulse_instruction.py | 9 + qiskit/qobj/pulse_qobj.py | 52 +++ qiskit/qobj/qasm_qobj.py | 52 +++ qiskit/qobj/utils.py | 9 + test/python/qobj/test_pulse_converter.py | 310 ++++++++------ test/python/qobj/test_qobj.py | 427 ++++++++++---------- test/python/qobj/test_qobj_identifiers.py | 3 +- 10 files changed, 548 insertions(+), 339 deletions(-) diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 522e1c503ddf..4417c0666fb4 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -29,6 +29,7 @@ from qiskit.pulse.channels import PulseChannel from qiskit.qobj import QasmQobj, PulseQobj, QobjHeader from qiskit.qobj.utils import MeasLevel, MeasReturnType +from qiskit.utils import deprecate_func logger = logging.getLogger(__name__) @@ -39,6 +40,13 @@ def _log_assembly_time(start_time, end_time): # TODO: parallelize over the experiments (serialize each separately, then add global header/config) +@deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The function assemble is being deprecated " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", +) def assemble( experiments: Union[ QuantumCircuit, diff --git a/qiskit/qobj/common.py b/qiskit/qobj/common.py index 9b219e5ba8d0..f9abb32282b5 100644 --- a/qiskit/qobj/common.py +++ b/qiskit/qobj/common.py @@ -13,6 +13,8 @@ """Module providing definitions of common Qobj classes.""" from types import SimpleNamespace +from qiskit.utils import deprecate_func + class QobjDictField(SimpleNamespace): """A class used to represent a dictionary field in Qobj @@ -21,6 +23,13 @@ class QobjDictField(SimpleNamespace): previously constructed using marshmallow. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QobjDictField subclasses, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, **kwargs): """Instantiate a new Qobj dict field object. diff --git a/qiskit/qobj/converters/lo_config.py b/qiskit/qobj/converters/lo_config.py index e06ff11a8c93..a76df3991f05 100644 --- a/qiskit/qobj/converters/lo_config.py +++ b/qiskit/qobj/converters/lo_config.py @@ -15,6 +15,7 @@ from qiskit.pulse.channels import DriveChannel, MeasureChannel from qiskit.pulse.configuration import LoConfig from qiskit.exceptions import QiskitError +from qiskit.utils import deprecate_func class LoConfigConverter: @@ -23,6 +24,13 @@ class LoConfigConverter: ``get_qubit_los`` and ``get_meas_los`` to align with your backend. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including LoConfigConverter class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__( self, qobj_model, diff --git a/qiskit/qobj/converters/pulse_instruction.py b/qiskit/qobj/converters/pulse_instruction.py index 8f34ee0855ac..45f82a9c7d50 100644 --- a/qiskit/qobj/converters/pulse_instruction.py +++ b/qiskit/qobj/converters/pulse_instruction.py @@ -30,6 +30,7 @@ from qiskit.pulse.schedule import Schedule from qiskit.qobj import QobjMeasurementOption, PulseLibraryItem, PulseQobjInstruction from qiskit.qobj.utils import MeasLevel +from qiskit.utils import deprecate_func class ParametricPulseShapes(Enum): @@ -107,6 +108,14 @@ def _convert_NewInstruction(self, instruction, time_offset): where ``NewInstruction`` must be a class name of Qiskit Pulse instruction. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including InstructionToQobjConverter " + "class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__( self, qobj_model: PulseQobjInstruction, diff --git a/qiskit/qobj/pulse_qobj.py b/qiskit/qobj/pulse_qobj.py index 3552d83ada84..0de59f894dc6 100644 --- a/qiskit/qobj/pulse_qobj.py +++ b/qiskit/qobj/pulse_qobj.py @@ -23,11 +23,20 @@ from qiskit.qobj.common import QobjDictField from qiskit.qobj.common import QobjHeader from qiskit.qobj.common import QobjExperimentHeader +from qiskit.utils import deprecate_func class QobjMeasurementOption: """An individual measurement option.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QobjMeasurementOption " + "class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, name, params=None): """Instantiate a new QobjMeasurementOption object. @@ -89,6 +98,13 @@ class PulseQobjInstruction: "parameters", ] + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including PulseQobjInstruction class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__( self, name, @@ -282,6 +298,13 @@ def _to_complex(value: Union[List[float], complex]) -> complex: class PulseQobjConfig(QobjDictField): """A configuration for a Pulse Qobj.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including PulseQobjConfig class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__( self, meas_level, @@ -383,6 +406,13 @@ class PulseQobjExperiment: experiment as part of a larger Pulse Qobj. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including PulseQobjExperiment class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, instructions, config=None, header=None): """Instantiate a PulseQobjExperiment. @@ -473,6 +503,14 @@ def __eq__(self, other): class PulseQobjExperimentConfig(QobjDictField): """A config for a single Pulse experiment in the qobj.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including PulseQobjExperimentConfig " + "class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, qubit_lo_freq=None, meas_lo_freq=None, **kwargs): """Instantiate a PulseQobjExperimentConfig object. @@ -492,6 +530,13 @@ def __init__(self, qubit_lo_freq=None, meas_lo_freq=None, **kwargs): class PulseLibraryItem: """An item in a pulse library.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including PulseLibraryItem class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, name, samples): """Instantiate a pulse library item. @@ -542,6 +587,13 @@ def __eq__(self, other): class PulseQobj: """A Pulse Qobj.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including PulseQobj class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, qobj_id, config, experiments, header=None): """Instantiate a new Pulse Qobj Object. diff --git a/qiskit/qobj/qasm_qobj.py b/qiskit/qobj/qasm_qobj.py index 88d775b3b773..b9b78bcb4ec1 100644 --- a/qiskit/qobj/qasm_qobj.py +++ b/qiskit/qobj/qasm_qobj.py @@ -18,11 +18,19 @@ from qiskit.circuit.parameterexpression import ParameterExpression from qiskit.qobj.pulse_qobj import PulseQobjInstruction, PulseLibraryItem from qiskit.qobj.common import QobjDictField, QobjHeader +from qiskit.utils import deprecate_func class QasmQobjInstruction: """A class representing a single instruction in an QasmQobj Experiment.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including PulseQobj class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__( self, name, @@ -200,6 +208,13 @@ class QasmQobjExperiment: part of a larger OpenQASM 2 qobj. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QasmQobjExperiment class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, config=None, header=None, instructions=None): """Instantiate a QasmQobjExperiment. @@ -276,6 +291,13 @@ def __eq__(self, other): class QasmQobjConfig(SimpleNamespace): """A configuration for an OpenQASM 2 Qobj.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QasmQobjConfig class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__( self, shots=None, @@ -410,6 +432,14 @@ class QasmQobjExperimentHeader(QobjDictField): class QasmQobjExperimentConfig(QobjDictField): """Configuration for a single OpenQASM 2 experiment in the qobj.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QasmQobjExperimentConfig " + "class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, calibrations=None, qubit_lo_freq=None, meas_lo_freq=None, **kwargs): """ Args: @@ -446,6 +476,14 @@ class QasmExperimentCalibrations: GateCalibrations. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QasmExperimentCalibrations " + "class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, gates): """ Initialize a container for calibrations. @@ -486,6 +524,13 @@ class GateCalibration: """Each calibration specifies a unique gate by name, qubits and params, and contains the Pulse instructions to implement it.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including GateCalibration class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, name, qubits, params, instructions): """ Initialize a single gate calibration. Instructions may reference waveforms which should be @@ -541,6 +586,13 @@ def from_dict(cls, data): class QasmQobj: """An OpenQASM 2 Qobj.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QasmQobj class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def __init__(self, qobj_id=None, config=None, experiments=None, header=None): """Instantiate a new OpenQASM 2 Qobj Object. diff --git a/qiskit/qobj/utils.py b/qiskit/qobj/utils.py index a689fc01e7e7..1d3b6bd84300 100644 --- a/qiskit/qobj/utils.py +++ b/qiskit/qobj/utils.py @@ -14,7 +14,16 @@ from enum import Enum, IntEnum +from qiskit.utils import deprecate_func + +@deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The full Qobj module is being deprecated, including QobjType class, " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", +) class QobjType(str, Enum): """Qobj.type allowed values.""" diff --git a/test/python/qobj/test_pulse_converter.py b/test/python/qobj/test_pulse_converter.py index cacbde2cd8b5..528d87244fe8 100644 --- a/test/python/qobj/test_pulse_converter.py +++ b/test/python/qobj/test_pulse_converter.py @@ -56,29 +56,33 @@ class TestInstructionToQobjConverter(QiskitTestCase): def test_drive_instruction(self): """Test converted qobj from Play.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) - instruction = Play(Waveform(np.arange(0, 0.01), name="linear"), DriveChannel(0)) - valid_qobj = PulseQobjInstruction(name="linear", ch="d0", t0=0) - self.assertEqual(converter(0, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + instruction = Play(Waveform(np.arange(0, 0.01), name="linear"), DriveChannel(0)) + valid_qobj = PulseQobjInstruction(name="linear", ch="d0", t0=0) + self.assertEqual(converter(0, instruction), valid_qobj) def test_gaussian_pulse_instruction(self): """Test that parametric pulses are correctly converted to PulseQobjInstructions.""" amp = 0.3 angle = -0.7 - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) instruction = Play(Gaussian(duration=25, sigma=15, amp=amp, angle=angle), DriveChannel(0)) - valid_qobj = PulseQobjInstruction( - name="parametric_pulse", - pulse_shape="gaussian", - ch="d0", - t0=0, - parameters={"duration": 25, "sigma": 15, "amp": amp * np.exp(1j * angle)}, - ) - self.assertEqual(converter(0, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + valid_qobj = PulseQobjInstruction( + name="parametric_pulse", + pulse_shape="gaussian", + ch="d0", + t0=0, + parameters={"duration": 25, "sigma": 15, "amp": amp * np.exp(1j * angle)}, + ) + self.assertEqual(converter(0, instruction), valid_qobj) def test_gaussian_square_pulse_instruction(self): """Test that parametric pulses are correctly converted to PulseQobjInstructions.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) amp = 0.7 angle = -0.6 instruction = Play( @@ -86,110 +90,129 @@ def test_gaussian_square_pulse_instruction(self): MeasureChannel(1), ) - valid_qobj = PulseQobjInstruction( - name="parametric_pulse", - pulse_shape="gaussian_square", - ch="m1", - t0=10, - parameters={ - "duration": 1500, - "sigma": 15, - "amp": amp * np.exp(1j * angle), - "width": 1300, - }, - ) - self.assertEqual(converter(10, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + valid_qobj = PulseQobjInstruction( + name="parametric_pulse", + pulse_shape="gaussian_square", + ch="m1", + t0=10, + parameters={ + "duration": 1500, + "sigma": 15, + "amp": amp * np.exp(1j * angle), + "width": 1300, + }, + ) + self.assertEqual(converter(10, instruction), valid_qobj) def test_constant_pulse_instruction(self): """Test that parametric pulses are correctly converted to PulseQobjInstructions.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) instruction = Play(Constant(duration=25, amp=1, angle=np.pi), ControlChannel(2)) - valid_qobj = PulseQobjInstruction( - name="parametric_pulse", - pulse_shape="constant", - ch="u2", - t0=20, - parameters={"duration": 25, "amp": 1 * np.exp(1j * np.pi)}, - ) - self.assertEqual(converter(20, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + valid_qobj = PulseQobjInstruction( + name="parametric_pulse", + pulse_shape="constant", + ch="u2", + t0=20, + parameters={"duration": 25, "amp": 1 * np.exp(1j * np.pi)}, + ) + self.assertEqual(converter(20, instruction), valid_qobj) def test_drag_pulse_instruction(self): """Test that parametric pulses are correctly converted to PulseQobjInstructions.""" amp = 0.7 angle = -0.6 - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) instruction = Play( Drag(duration=25, sigma=15, amp=amp, angle=angle, beta=0.5), DriveChannel(0) ) - valid_qobj = PulseQobjInstruction( - name="parametric_pulse", - pulse_shape="drag", - ch="d0", - t0=30, - parameters={"duration": 25, "sigma": 15, "amp": amp * np.exp(1j * angle), "beta": 0.5}, - ) - self.assertEqual(converter(30, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + valid_qobj = PulseQobjInstruction( + name="parametric_pulse", + pulse_shape="drag", + ch="d0", + t0=30, + parameters={ + "duration": 25, + "sigma": 15, + "amp": amp * np.exp(1j * angle), + "beta": 0.5, + }, + ) + self.assertEqual(converter(30, instruction), valid_qobj) def test_frame_change(self): """Test converted qobj from ShiftPhase.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) - valid_qobj = PulseQobjInstruction(name="fc", ch="d0", t0=0, phase=0.1) - instruction = ShiftPhase(0.1, DriveChannel(0)) - self.assertEqual(converter(0, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + valid_qobj = PulseQobjInstruction(name="fc", ch="d0", t0=0, phase=0.1) + instruction = ShiftPhase(0.1, DriveChannel(0)) + self.assertEqual(converter(0, instruction), valid_qobj) def test_set_phase(self): """Test converted qobj from ShiftPhase.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) - instruction = SetPhase(3.14, DriveChannel(0)) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + instruction = SetPhase(3.14, DriveChannel(0)) - valid_qobj = PulseQobjInstruction(name="setp", ch="d0", t0=0, phase=3.14) + valid_qobj = PulseQobjInstruction(name="setp", ch="d0", t0=0, phase=3.14) - self.assertEqual(converter(0, instruction), valid_qobj) + self.assertEqual(converter(0, instruction), valid_qobj) def test_set_frequency(self): """Test converted qobj from SetFrequency.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) - instruction = SetFrequency(8.0e9, DriveChannel(0)) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + instruction = SetFrequency(8.0e9, DriveChannel(0)) - valid_qobj = PulseQobjInstruction(name="setf", ch="d0", t0=0, frequency=8.0) + valid_qobj = PulseQobjInstruction(name="setf", ch="d0", t0=0, frequency=8.0) - self.assertEqual(converter(0, instruction), valid_qobj) + self.assertEqual(converter(0, instruction), valid_qobj) def test_shift_frequency(self): """Test converted qobj from ShiftFrequency.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) - instruction = ShiftFrequency(8.0e9, DriveChannel(0)) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + instruction = ShiftFrequency(8.0e9, DriveChannel(0)) - valid_qobj = PulseQobjInstruction(name="shiftf", ch="d0", t0=0, frequency=8.0) + valid_qobj = PulseQobjInstruction(name="shiftf", ch="d0", t0=0, frequency=8.0) - self.assertEqual(converter(0, instruction), valid_qobj) + self.assertEqual(converter(0, instruction), valid_qobj) def test_acquire(self): """Test converted qobj from AcquireInstruction.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) instruction = Acquire(10, AcquireChannel(0), MemorySlot(0), RegisterSlot(0)) - valid_qobj = PulseQobjInstruction( - name="acquire", t0=0, duration=10, qubits=[0], memory_slot=[0], register_slot=[0] - ) - self.assertEqual(converter(0, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + valid_qobj = PulseQobjInstruction( + name="acquire", t0=0, duration=10, qubits=[0], memory_slot=[0], register_slot=[0] + ) + self.assertEqual(converter(0, instruction), valid_qobj) # without register instruction = Acquire(10, AcquireChannel(0), MemorySlot(0)) - valid_qobj = PulseQobjInstruction( - name="acquire", t0=0, duration=10, qubits=[0], memory_slot=[0] - ) - self.assertEqual(converter(0, instruction), valid_qobj) + with self.assertWarns(DeprecationWarning): + valid_qobj = PulseQobjInstruction( + name="acquire", t0=0, duration=10, qubits=[0], memory_slot=[0] + ) + self.assertEqual(converter(0, instruction), valid_qobj) def test_snapshot(self): """Test converted qobj from Snapshot.""" - converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) + with self.assertWarns(DeprecationWarning): + converter = InstructionToQobjConverter(PulseQobjInstruction, meas_level=2) instruction = Snapshot(label="label", snapshot_type="type") - valid_qobj = PulseQobjInstruction(name="snapshot", t0=0, label="label", type="type") + with self.assertWarns(DeprecationWarning): + valid_qobj = PulseQobjInstruction(name="snapshot", t0=0, label="label", type="type") - self.assertEqual(converter(0, instruction), valid_qobj) + self.assertEqual(converter(0, instruction), valid_qobj) class TestQobjToInstructionConverter(QiskitTestCase): @@ -198,9 +221,10 @@ class TestQobjToInstructionConverter(QiskitTestCase): def setUp(self): super().setUp() self.linear = Waveform(np.arange(0, 0.01), name="linear") - self.pulse_library = [ - PulseLibraryItem(name=self.linear.name, samples=self.linear.samples.tolist()) - ] + with self.assertWarns(DeprecationWarning): + self.pulse_library = [ + PulseLibraryItem(name=self.linear.name, samples=self.linear.samples.tolist()) + ] self.converter = QobjToInstructionConverter(self.pulse_library, buffer=0) self.num_qubits = 2 @@ -208,7 +232,8 @@ def setUp(self): def test_drive_instruction(self): """Test converted qobj from PulseInstruction.""" instruction = Play(self.linear, DriveChannel(0)) - qobj = PulseQobjInstruction(name="linear", ch="d0", t0=10) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="linear", ch="d0", t0=10) converted_instruction = self.converter(qobj) self.assertEqual(converted_instruction.instructions[0][-1], instruction) @@ -218,14 +243,15 @@ def test_parametric_pulses(self): Gaussian(duration=25, sigma=15, amp=0.5, angle=np.pi / 2, name="pulse1"), DriveChannel(0), ) - qobj = PulseQobjInstruction( - name="parametric_pulse", - label="pulse1", - pulse_shape="gaussian", - ch="d0", - t0=0, - parameters={"duration": 25, "sigma": 15, "amp": 0.5j}, - ) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction( + name="parametric_pulse", + label="pulse1", + pulse_shape="gaussian", + ch="d0", + t0=0, + parameters={"duration": 25, "sigma": 15, "amp": 0.5j}, + ) converted_instruction = self.converter(qobj) self.assertEqual(converted_instruction.start_time, 0) self.assertEqual(converted_instruction.duration, 25) @@ -238,19 +264,21 @@ def test_parametric_pulses_no_label(self): short_pulse_id = hashlib.md5(base_str.encode("utf-8")).hexdigest()[:4] pulse_name = f"gaussian_{short_pulse_id}" - qobj = PulseQobjInstruction( - name="parametric_pulse", - pulse_shape="gaussian", - ch="d0", - t0=0, - parameters={"duration": 25, "sigma": 15, "amp": -0.5 + 0.2j}, - ) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction( + name="parametric_pulse", + pulse_shape="gaussian", + ch="d0", + t0=0, + parameters={"duration": 25, "sigma": 15, "amp": -0.5 + 0.2j}, + ) converted_instruction = self.converter(qobj) self.assertEqual(converted_instruction.instructions[0][-1].pulse.name, pulse_name) def test_frame_change(self): """Test converted qobj from ShiftPhase.""" - qobj = PulseQobjInstruction(name="fc", ch="m0", t0=0, phase=0.1) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="fc", ch="m0", t0=0, phase=0.1) converted_instruction = self.converter(qobj) instruction = ShiftPhase(0.1, MeasureChannel(0)) @@ -263,7 +291,8 @@ def test_parameterized_frame_change(self): instruction = ShiftPhase(4.0, MeasureChannel(0)) shifted = instruction << 10 - qobj = PulseQobjInstruction(name="fc", ch="m0", t0=10, phase="P1*2") + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="fc", ch="m0", t0=10, phase="P1*2") converted_instruction = self.converter(qobj) self.assertIsInstance(converted_instruction, Schedule) @@ -277,7 +306,8 @@ def test_parameterized_frame_change(self): def test_set_phase(self): """Test converted qobj from SetPhase.""" - qobj = PulseQobjInstruction(name="setp", ch="m0", t0=0, phase=3.14) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="setp", ch="m0", t0=0, phase=3.14) converted_instruction = self.converter(qobj) instruction = SetPhase(3.14, MeasureChannel(0)) @@ -287,7 +317,8 @@ def test_set_phase(self): def test_parameterized_set_phase(self): """Test converted qobj from SetPhase, with parameterized phase.""" - qobj = PulseQobjInstruction(name="setp", ch="m0", t0=0, phase="p/2") + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="setp", ch="m0", t0=0, phase="p/2") converted_instruction = self.converter(qobj) self.assertIsInstance(converted_instruction, Schedule) @@ -303,7 +334,8 @@ def test_set_frequency(self): """Test converted qobj from SetFrequency.""" instruction = SetFrequency(8.0e9, DriveChannel(0)) - qobj = PulseQobjInstruction(name="setf", ch="d0", t0=0, frequency=8.0) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="setf", ch="d0", t0=0, frequency=8.0) converted_instruction = self.converter(qobj) self.assertEqual(converted_instruction.start_time, 0) @@ -313,7 +345,8 @@ def test_set_frequency(self): def test_parameterized_set_frequency(self): """Test converted qobj from SetFrequency, when passing a parameterized frequency.""" - qobj = PulseQobjInstruction(name="setf", ch="d0", t0=2, frequency="f") + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="setf", ch="d0", t0=2, frequency="f") self.assertTrue("frequency" in qobj.to_dict()) converted_instruction = self.converter(qobj) @@ -332,7 +365,8 @@ def test_shift_frequency(self): """Test converted qobj from ShiftFrequency.""" instruction = ShiftFrequency(8.0e9, DriveChannel(0)) - qobj = PulseQobjInstruction(name="shiftf", ch="d0", t0=0, frequency=8.0) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="shiftf", ch="d0", t0=0, frequency=8.0) converted_instruction = self.converter(qobj) self.assertEqual(converted_instruction.start_time, 0) @@ -342,9 +376,8 @@ def test_shift_frequency(self): def test_parameterized_shift_frequency(self): """Test converted qobj from ShiftFrequency, with a parameterized frequency.""" - instruction = ShiftFrequency(8.0e9, DriveChannel(0)) - - qobj = PulseQobjInstruction(name="shiftf", ch="d0", t0=1, frequency="f / 1000") + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="shiftf", ch="d0", t0=1, frequency="f / 1000") self.assertTrue("frequency" in qobj.to_dict()) converted_instruction = self.converter(qobj) @@ -363,7 +396,8 @@ def test_delay(self): """Test converted qobj from Delay.""" instruction = Delay(10, DriveChannel(0)) - qobj = PulseQobjInstruction(name="delay", ch="d0", t0=0, duration=10) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="delay", ch="d0", t0=0, duration=10) converted_instruction = self.converter(qobj) self.assertTrue("delay" in qobj.to_dict().values()) @@ -382,17 +416,19 @@ def test_acquire(self): kernel=Kernel(name="test_kern", test_params="test"), discriminator=Discriminator(name="test_disc", test_params=1.0), ) - - qobj = PulseQobjInstruction( - name="acquire", - t0=0, - duration=10, - qubits=[0, 1], - memory_slot=[0, 1], - register_slot=[0, 1], - kernels=[QobjMeasurementOption(name="test_kern", params={"test_params": "test"})], - discriminators=[QobjMeasurementOption(name="test_disc", params={"test_params": 1.0})], - ) + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction( + name="acquire", + t0=0, + duration=10, + qubits=[0, 1], + memory_slot=[0, 1], + register_slot=[0, 1], + kernels=[QobjMeasurementOption(name="test_kern", params={"test_params": "test"})], + discriminators=[ + QobjMeasurementOption(name="test_disc", params={"test_params": 1.0}) + ], + ) converted_instruction = self.converter(qobj) self.assertEqual(converted_instruction.start_time, 0) @@ -408,7 +444,8 @@ def test_snapshot(self): instruction = Snapshot(label="label", snapshot_type="type") shifted = instruction << 10 - qobj = PulseQobjInstruction(name="snapshot", t0=10, label="label", type="type") + with self.assertWarns(DeprecationWarning): + qobj = PulseQobjInstruction(name="snapshot", t0=10, label="label", type="type") converted_instruction = self.converter(qobj) self.assertEqual(converted_instruction.start_time, shifted.start_time) @@ -417,17 +454,22 @@ def test_snapshot(self): def test_instruction_name_collision(self): """Avoid command name collision of pulse library items.""" - pulse_library_from_backend_x = [ - PulseLibraryItem(name="pulse123", samples=[0.1, 0.1, 0.1]), - PulseLibraryItem(name="pulse456", samples=[0.3, 0.3, 0.3]), - ] + with self.assertWarns(DeprecationWarning): + pulse_library_from_backend_x = [ + PulseLibraryItem(name="pulse123", samples=[0.1, 0.1, 0.1]), + PulseLibraryItem(name="pulse456", samples=[0.3, 0.3, 0.3]), + ] converter_of_backend_x = QobjToInstructionConverter(pulse_library_from_backend_x, buffer=0) - pulse_library_from_backend_y = [PulseLibraryItem(name="pulse123", samples=[0.2, 0.2, 0.2])] + with self.assertWarns(DeprecationWarning): + pulse_library_from_backend_y = [ + PulseLibraryItem(name="pulse123", samples=[0.2, 0.2, 0.2]) + ] converter_of_backend_y = QobjToInstructionConverter(pulse_library_from_backend_y, buffer=0) - qobj1 = PulseQobjInstruction(name="pulse123", qubits=[0], t0=0, ch="d0") - qobj2 = PulseQobjInstruction(name="pulse456", qubits=[0], t0=0, ch="d0") + with self.assertWarns(DeprecationWarning): + qobj1 = PulseQobjInstruction(name="pulse123", qubits=[0], t0=0, ch="d0") + qobj2 = PulseQobjInstruction(name="pulse456", qubits=[0], t0=0, ch="d0") sched_out_x = converter_of_backend_x(qobj1) sched_out_y = converter_of_backend_y(qobj1) @@ -446,21 +488,23 @@ class TestLoConverter(QiskitTestCase): def test_qubit_los(self): """Test qubit channel configuration.""" user_lo_config = LoConfig({DriveChannel(0): 1.3e9}) - converter = LoConfigConverter( - PulseQobjExperimentConfig, [1.2e9], [3.4e9], [(0.0, 5e9)], [(0.0, 5e9)] - ) - - valid_qobj = PulseQobjExperimentConfig(qubit_lo_freq=[1.3]) + with self.assertWarns(DeprecationWarning): + converter = LoConfigConverter( + PulseQobjExperimentConfig, [1.2e9], [3.4e9], [(0.0, 5e9)], [(0.0, 5e9)] + ) + valid_qobj = PulseQobjExperimentConfig(qubit_lo_freq=[1.3]) - self.assertEqual(converter(user_lo_config), valid_qobj) + with self.assertWarns(DeprecationWarning): + self.assertEqual(converter(user_lo_config), valid_qobj) def test_meas_los(self): """Test measurement channel configuration.""" user_lo_config = LoConfig({MeasureChannel(0): 3.5e9}) - converter = LoConfigConverter( - PulseQobjExperimentConfig, [1.2e9], [3.4e9], [(0.0, 5e9)], [(0.0, 5e9)] - ) + with self.assertWarns(DeprecationWarning): + converter = LoConfigConverter( + PulseQobjExperimentConfig, [1.2e9], [3.4e9], [(0.0, 5e9)], [(0.0, 5e9)] + ) - valid_qobj = PulseQobjExperimentConfig(meas_lo_freq=[3.5]) + valid_qobj = PulseQobjExperimentConfig(meas_lo_freq=[3.5]) - self.assertEqual(converter(user_lo_config), valid_qobj) + self.assertEqual(converter(user_lo_config), valid_qobj) diff --git a/test/python/qobj/test_qobj.py b/test/python/qobj/test_qobj.py index c0b96a1bda5e..ae59d6de00a5 100644 --- a/test/python/qobj/test_qobj.py +++ b/test/python/qobj/test_qobj.py @@ -41,19 +41,20 @@ class TestQASMQobj(QiskitTestCase): def setUp(self): super().setUp() - self.valid_qobj = QasmQobj( - qobj_id="12345", - header=QobjHeader(), - config=QasmQobjConfig(shots=1024, memory_slots=2), - experiments=[ - QasmQobjExperiment( - instructions=[ - QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), - QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), - ] - ) - ], - ) + with self.assertWarns(DeprecationWarning): + self.valid_qobj = QasmQobj( + qobj_id="12345", + header=QobjHeader(), + config=QasmQobjConfig(shots=1024, memory_slots=2), + experiments=[ + QasmQobjExperiment( + instructions=[ + QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), + QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), + ] + ) + ], + ) self.valid_dict = { "qobj_id": "12345", @@ -70,55 +71,59 @@ def setUp(self): } ], } - - self.bad_qobj = copy.deepcopy(self.valid_qobj) + with self.assertWarns(DeprecationWarning): + self.bad_qobj = copy.deepcopy(self.valid_qobj) self.bad_qobj.experiments = [] def test_from_dict_per_class(self): """Test Qobj and its subclass representations given a dictionary.""" - test_parameters = { - QasmQobj: (self.valid_qobj, self.valid_dict), - QasmQobjConfig: ( - QasmQobjConfig(shots=1, memory_slots=2), - {"shots": 1, "memory_slots": 2}, - ), - QasmQobjExperiment: ( - QasmQobjExperiment( - instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])] + with self.assertWarns(DeprecationWarning): + test_parameters = { + QasmQobj: (self.valid_qobj, self.valid_dict), + QasmQobjConfig: ( + QasmQobjConfig(shots=1, memory_slots=2), + {"shots": 1, "memory_slots": 2}, ), - {"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]}, - ), - QasmQobjInstruction: ( - QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), - {"name": "u1", "qubits": [1], "params": [0.4]}, - ), - } + QasmQobjExperiment: ( + QasmQobjExperiment( + instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])] + ), + {"instructions": [{"name": "u1", "qubits": [1], "params": [0.4]}]}, + ), + QasmQobjInstruction: ( + QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), + {"name": "u1", "qubits": [1], "params": [0.4]}, + ), + } for qobj_class, (qobj_item, expected_dict) in test_parameters.items(): with self.subTest(msg=str(qobj_class)): - self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict)) + with self.assertWarns(DeprecationWarning): + qobj = qobj_class.from_dict(expected_dict) + self.assertEqual(qobj_item, qobj) def test_snapshot_instruction_to_dict(self): """Test snapshot instruction to dict.""" - valid_qobj = QasmQobj( - qobj_id="12345", - header=QobjHeader(), - config=QasmQobjConfig(shots=1024, memory_slots=2), - experiments=[ - QasmQobjExperiment( - instructions=[ - QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), - QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), - QasmQobjInstruction( - name="snapshot", - qubits=[1], - snapshot_type="statevector", - label="my_snap", - ), - ] - ) - ], - ) + with self.assertWarns(DeprecationWarning): + valid_qobj = QasmQobj( + qobj_id="12345", + header=QobjHeader(), + config=QasmQobjConfig(shots=1024, memory_slots=2), + experiments=[ + QasmQobjExperiment( + instructions=[ + QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), + QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), + QasmQobjInstruction( + name="snapshot", + qubits=[1], + snapshot_type="statevector", + label="my_snap", + ), + ] + ) + ], + ) res = valid_qobj.to_dict() expected_dict = { "qobj_id": "12345", @@ -147,25 +152,26 @@ def test_snapshot_instruction_to_dict(self): def test_snapshot_instruction_from_dict(self): """Test snapshot instruction from dict.""" - expected_qobj = QasmQobj( - qobj_id="12345", - header=QobjHeader(), - config=QasmQobjConfig(shots=1024, memory_slots=2), - experiments=[ - QasmQobjExperiment( - instructions=[ - QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), - QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), - QasmQobjInstruction( - name="snapshot", - qubits=[1], - snapshot_type="statevector", - label="my_snap", - ), - ] - ) - ], - ) + with self.assertWarns(DeprecationWarning): + expected_qobj = QasmQobj( + qobj_id="12345", + header=QobjHeader(), + config=QasmQobjConfig(shots=1024, memory_slots=2), + experiments=[ + QasmQobjExperiment( + instructions=[ + QasmQobjInstruction(name="u1", qubits=[1], params=[0.4]), + QasmQobjInstruction(name="u2", qubits=[1], params=[0.4, 0.2]), + QasmQobjInstruction( + name="snapshot", + qubits=[1], + snapshot_type="statevector", + label="my_snap", + ), + ] + ) + ], + ) qobj_dict = { "qobj_id": "12345", "type": "QASM", @@ -187,7 +193,9 @@ def test_snapshot_instruction_from_dict(self): } ], } - self.assertEqual(expected_qobj, QasmQobj.from_dict(qobj_dict)) + with self.assertWarns(DeprecationWarning): + qobj = QasmQobj.from_dict(qobj_dict) + self.assertEqual(expected_qobj, qobj) def test_change_qobj_after_compile(self): """Test modifying Qobj parameters after compile.""" @@ -202,7 +210,8 @@ def test_change_qobj_after_compile(self): qc1.measure(qr, cr) qc2.measure(qr, cr) circuits = [qc1, qc2] - qobj1 = assemble(circuits, shots=1024, seed=88) + with self.assertWarns(DeprecationWarning): + qobj1 = assemble(circuits, shots=1024, seed=88) qobj1.experiments[0].config.shots = 50 qobj1.experiments[1].config.shots = 1 self.assertTrue(qobj1.experiments[0].config.shots == 50) @@ -211,27 +220,28 @@ def test_change_qobj_after_compile(self): def test_gate_calibrations_to_dict(self): """Test gate calibrations to dict.""" - - pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])] - valid_qobj = QasmQobj( - qobj_id="12345", - header=QobjHeader(), - config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library), - experiments=[ - QasmQobjExperiment( - instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])], - config=QasmQobjConfig( - calibrations=QasmExperimentCalibrations( - gates=[ - GateCalibration( - name="u1", qubits=[1], params=[0.4], instructions=[] - ) - ] - ) - ), - ) - ], - ) + with self.assertWarns(DeprecationWarning): + pulse_library = [PulseLibraryItem(name="test", samples=[1j, 1j])] + with self.assertWarns(DeprecationWarning): + valid_qobj = QasmQobj( + qobj_id="12345", + header=QobjHeader(), + config=QasmQobjConfig(shots=1024, memory_slots=2, pulse_library=pulse_library), + experiments=[ + QasmQobjExperiment( + instructions=[QasmQobjInstruction(name="u1", qubits=[1], params=[0.4])], + config=QasmQobjConfig( + calibrations=QasmExperimentCalibrations( + gates=[ + GateCalibration( + name="u1", qubits=[1], params=[0.4], instructions=[] + ) + ] + ) + ), + ) + ], + ) res = valid_qobj.to_dict() expected_dict = { "qobj_id": "12345", @@ -265,48 +275,51 @@ class TestPulseQobj(QiskitTestCase): def setUp(self): super().setUp() - self.valid_qobj = PulseQobj( - qobj_id="12345", - header=QobjHeader(), - config=PulseQobjConfig( - shots=1024, - memory_slots=2, - meas_level=1, - memory_slot_size=8192, - meas_return="avg", - pulse_library=[ - PulseLibraryItem(name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j]) + with self.assertWarns(DeprecationWarning): + self.valid_qobj = PulseQobj( + qobj_id="12345", + header=QobjHeader(), + config=PulseQobjConfig( + shots=1024, + memory_slots=2, + meas_level=1, + memory_slot_size=8192, + meas_return="avg", + pulse_library=[ + PulseLibraryItem( + name="pulse0", samples=[0.0 + 0.0j, 0.5 + 0.0j, 0.0 + 0.0j] + ) + ], + qubit_lo_freq=[4.9], + meas_lo_freq=[6.9], + rep_time=1000, + ), + experiments=[ + PulseQobjExperiment( + instructions=[ + PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), + PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57), + PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0), + PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"), + PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14), + PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0), + PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0), + PulseQobjInstruction( + name="acquire", + t0=15, + duration=5, + qubits=[0], + memory_slot=[0], + kernels=[ + QobjMeasurementOption( + name="boxcar", params={"start_window": 0, "stop_window": 5} + ) + ], + ), + ] + ) ], - qubit_lo_freq=[4.9], - meas_lo_freq=[6.9], - rep_time=1000, - ), - experiments=[ - PulseQobjExperiment( - instructions=[ - PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), - PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=1.57), - PulseQobjInstruction(name="fc", t0=5, ch="d0", phase=0.0), - PulseQobjInstruction(name="fc", t0=5, ch="d0", phase="P1"), - PulseQobjInstruction(name="setp", t0=10, ch="d0", phase=3.14), - PulseQobjInstruction(name="setf", t0=10, ch="d0", frequency=8.0), - PulseQobjInstruction(name="shiftf", t0=10, ch="d0", frequency=4.0), - PulseQobjInstruction( - name="acquire", - t0=15, - duration=5, - qubits=[0], - memory_slot=[0], - kernels=[ - QobjMeasurementOption( - name="boxcar", params={"start_window": 0, "stop_window": 5} - ) - ], - ), - ] - ) - ], - ) + ) self.valid_dict = { "qobj_id": "12345", "type": "PULSE", @@ -350,87 +363,91 @@ def setUp(self): def test_from_dict_per_class(self): """Test converting to Qobj and its subclass representations given a dictionary.""" - test_parameters = { - PulseQobj: (self.valid_qobj, self.valid_dict), - PulseQobjConfig: ( - PulseQobjConfig( - meas_level=1, - memory_slot_size=8192, - meas_return="avg", - pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])], - qubit_lo_freq=[4.9], - meas_lo_freq=[6.9], - rep_time=1000, + with self.assertWarns(DeprecationWarning): + test_parameters = { + PulseQobj: (self.valid_qobj, self.valid_dict), + PulseQobjConfig: ( + PulseQobjConfig( + meas_level=1, + memory_slot_size=8192, + meas_return="avg", + pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])], + qubit_lo_freq=[4.9], + meas_lo_freq=[6.9], + rep_time=1000, + ), + { + "meas_level": 1, + "memory_slot_size": 8192, + "meas_return": "avg", + "pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}], + "qubit_lo_freq": [4.9], + "meas_lo_freq": [6.9], + "rep_time": 1000, + }, ), - { - "meas_level": 1, - "memory_slot_size": 8192, - "meas_return": "avg", - "pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}], - "qubit_lo_freq": [4.9], - "meas_lo_freq": [6.9], - "rep_time": 1000, - }, - ), - PulseLibraryItem: ( - PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]), - {"name": "pulse0", "samples": [0.1 + 0j]}, - ), - PulseQobjExperiment: ( - PulseQobjExperiment( - instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")] + PulseLibraryItem: ( + PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]), + {"name": "pulse0", "samples": [0.1 + 0j]}, ), - {"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]}, - ), - PulseQobjInstruction: ( - PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), - {"name": "pulse0", "t0": 0, "ch": "d0"}, - ), - } + PulseQobjExperiment: ( + PulseQobjExperiment( + instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")] + ), + {"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]}, + ), + PulseQobjInstruction: ( + PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), + {"name": "pulse0", "t0": 0, "ch": "d0"}, + ), + } for qobj_class, (qobj_item, expected_dict) in test_parameters.items(): with self.subTest(msg=str(qobj_class)): - self.assertEqual(qobj_item, qobj_class.from_dict(expected_dict)) + with self.assertWarns(DeprecationWarning): + qobj = qobj_class.from_dict(expected_dict) + self.assertEqual(qobj_item, qobj) def test_to_dict_per_class(self): """Test converting from Qobj and its subclass representations given a dictionary.""" - test_parameters = { - PulseQobj: (self.valid_qobj, self.valid_dict), - PulseQobjConfig: ( - PulseQobjConfig( - meas_level=1, - memory_slot_size=8192, - meas_return="avg", - pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])], - qubit_lo_freq=[4.9], - meas_lo_freq=[6.9], - rep_time=1000, + with self.assertWarns(DeprecationWarning): + test_parameters = { + PulseQobj: (self.valid_qobj, self.valid_dict), + PulseQobjConfig: ( + PulseQobjConfig( + meas_level=1, + memory_slot_size=8192, + meas_return="avg", + pulse_library=[PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j])], + qubit_lo_freq=[4.9], + meas_lo_freq=[6.9], + rep_time=1000, + ), + { + "meas_level": 1, + "memory_slot_size": 8192, + "meas_return": "avg", + "pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}], + "qubit_lo_freq": [4.9], + "meas_lo_freq": [6.9], + "rep_time": 1000, + }, ), - { - "meas_level": 1, - "memory_slot_size": 8192, - "meas_return": "avg", - "pulse_library": [{"name": "pulse0", "samples": [0.1 + 0j]}], - "qubit_lo_freq": [4.9], - "meas_lo_freq": [6.9], - "rep_time": 1000, - }, - ), - PulseLibraryItem: ( - PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]), - {"name": "pulse0", "samples": [0.1 + 0j]}, - ), - PulseQobjExperiment: ( - PulseQobjExperiment( - instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")] + PulseLibraryItem: ( + PulseLibraryItem(name="pulse0", samples=[0.1 + 0.0j]), + {"name": "pulse0", "samples": [0.1 + 0j]}, ), - {"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]}, - ), - PulseQobjInstruction: ( - PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), - {"name": "pulse0", "t0": 0, "ch": "d0"}, - ), - } + PulseQobjExperiment: ( + PulseQobjExperiment( + instructions=[PulseQobjInstruction(name="pulse0", t0=0, ch="d0")] + ), + {"instructions": [{"name": "pulse0", "t0": 0, "ch": "d0"}]}, + ), + PulseQobjInstruction: ( + PulseQobjInstruction(name="pulse0", t0=0, ch="d0"), + {"name": "pulse0", "t0": 0, "ch": "d0"}, + ), + } for qobj_class, (qobj_item, expected_dict) in test_parameters.items(): with self.subTest(msg=str(qobj_class)): diff --git a/test/python/qobj/test_qobj_identifiers.py b/test/python/qobj/test_qobj_identifiers.py index d319aa4611de..84eb58a1d782 100644 --- a/test/python/qobj/test_qobj_identifiers.py +++ b/test/python/qobj/test_qobj_identifiers.py @@ -36,7 +36,8 @@ def setUp(self): self.circuits = [qc] def test_qobj_identifiers(self): - qobj = assemble(self.circuits) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circuits) exp = qobj.experiments[0] self.assertIn(self.qr_name, (x[0] for x in exp.header.qubit_labels)) self.assertIn(self.cr_name, (x[0] for x in exp.header.clbit_labels)) From 76e6dd598401756632bf388ab62f01c1caa2a0cf Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 24 Jun 2024 22:12:51 +0200 Subject: [PATCH 005/168] reno --- releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml diff --git a/releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml b/releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml new file mode 100644 index 000000000000..8817020e742a --- /dev/null +++ b/releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml @@ -0,0 +1,4 @@ +--- +deprecations_providers: + - | + With the deprecation of BackendV1, the Qobj structure is not necessary and it is deprecated. Hence, the related tools such as the function assemble are also deprecated. From a3610f5935c3534eec30e7aa444f326b090a388a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 10:15:05 +0200 Subject: [PATCH 006/168] first attempt on Fake1QV2 --- test/python/transpiler/test_1q.py | 53 +++++++++++++++++++++++++++---- 1 file changed, 47 insertions(+), 6 deletions(-) diff --git a/test/python/transpiler/test_1q.py b/test/python/transpiler/test_1q.py index 50bdc7b24643..293c7448ad8d 100644 --- a/test/python/transpiler/test_1q.py +++ b/test/python/transpiler/test_1q.py @@ -16,12 +16,16 @@ from qiskit import QuantumCircuit from qiskit.compiler import transpile -from qiskit.providers.fake_provider import Fake1Q +from qiskit.providers.fake_provider import Fake1Q, GenericBackendV2 from qiskit.providers.basic_provider import BasicSimulator from qiskit.transpiler import TranspilerError from test import combine # pylint: disable=wrong-import-order from test import QiskitTestCase # pylint: disable=wrong-import-order +Fake1QV2 = GenericBackendV2( + num_qubits=1, basis_gates=["u1", "u2", "u3", "cx"], coupling_map=None, dtm=1.3333, seed=42 +) + def emptycircuit(): """Empty circuit""" @@ -45,31 +49,50 @@ class Test1QFailing(QiskitTestCase): circuit=[circuit_3516], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should fail", - name="{circuit.__name__}_level{level}_fail", + name="{circuit.__name__}_level{level}_fail_v1", ) def test(self, circuit, level): - """All the levels with all the 1Q backend""" + """All the levels with all the 1Q backendV1""" with self.assertRaises(TranspilerError): transpile(circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42) +@ddt +class Test1QV2Failing(QiskitTestCase): + """1QV2 tests that should fail.""" + + @combine( + circuit=[circuit_3516], + level=[0, 1, 2, 3], + dsc="Transpiling {circuit.__name__} at level {level} should fail", + name="{circuit.__name__}_level{level}_fail_v2", + ) + def test(self, circuit, level): + """All the levels with all the 1Q backendV2""" + with self.assertRaises(TranspilerError): + transpile(circuit(), backend=Fake1QV2, optimization_level=level, seed_transpiler=42) + + @ddt class Test1QWorking(QiskitTestCase): - """1Q tests that should work.""" + """1QV1 tests that should work.""" @combine( circuit=[emptycircuit], level=[0, 1, 2, 3], dsc="Transpiling {circuit.__name__} at level {level} should work", - name="{circuit.__name__}_level{level}_valid", + name="{circuit.__name__}_level{level}_valid_v1", ) def test_device(self, circuit, level): - """All the levels with all the 1Q backend""" + """All the levels with all the 1Q backendV1""" result = transpile( circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42 ) self.assertIsInstance(result, QuantumCircuit) + +@ddt +class TestBasicSimulatorWorking(QiskitTestCase): @combine( circuit=[circuit_3516], level=[0, 1, 2, 3], @@ -81,3 +104,21 @@ def test_simulator(self, circuit, level): backend = BasicSimulator() result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42) self.assertIsInstance(result, QuantumCircuit) + + +@ddt +class Test1QV2Working(QiskitTestCase): + """1QV2 tests that should work.""" + + @combine( + circuit=[emptycircuit], + level=[0, 1, 2, 3], + dsc="Transpiling {circuit.__name__} at level {level} should work", + name="{circuit.__name__}_level{level}_valid_v2", + ) + def test_device(self, circuit, level): + """All the levels with all the 1Q backendV2""" + result = transpile( + circuit(), backend=Fake1QV2, optimization_level=level, seed_transpiler=42 + ) + self.assertIsInstance(result, QuantumCircuit) From 7c7930913dd155ca0776cbf2fdfc6ed7062ad67c Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 10:27:58 +0200 Subject: [PATCH 007/168] deprecate Fake1Q --- qiskit/providers/fake_provider/fake_1q.py | 6 ++++++ test/python/transpiler/test_1q.py | 12 ++++++++---- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/qiskit/providers/fake_provider/fake_1q.py b/qiskit/providers/fake_provider/fake_1q.py index 09959620bc92..34d581031464 100644 --- a/qiskit/providers/fake_provider/fake_1q.py +++ b/qiskit/providers/fake_provider/fake_1q.py @@ -18,11 +18,17 @@ from qiskit.providers.models.backendproperties import BackendProperties, Gate, Nduv from .fake_backend import FakeBackend +from ...utils import deprecate_func class Fake1Q(FakeBackend): """A fake 1Q backend.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="Fake backendV1 are deprecated in favor of GenericBackendV2", + ) def __init__(self): """ 0 diff --git a/test/python/transpiler/test_1q.py b/test/python/transpiler/test_1q.py index 293c7448ad8d..f726f4ac0b52 100644 --- a/test/python/transpiler/test_1q.py +++ b/test/python/transpiler/test_1q.py @@ -54,7 +54,8 @@ class Test1QFailing(QiskitTestCase): def test(self, circuit, level): """All the levels with all the 1Q backendV1""" with self.assertRaises(TranspilerError): - transpile(circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42) + with self.assertWarns(DeprecationWarning): + transpile(circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42) @ddt @@ -85,14 +86,17 @@ class Test1QWorking(QiskitTestCase): ) def test_device(self, circuit, level): """All the levels with all the 1Q backendV1""" - result = transpile( - circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42 - ) + with self.assertWarns(DeprecationWarning): + result = transpile( + circuit(), backend=Fake1Q(), optimization_level=level, seed_transpiler=42 + ) self.assertIsInstance(result, QuantumCircuit) @ddt class TestBasicSimulatorWorking(QiskitTestCase): + """Test with a simulator backend""" + @combine( circuit=[circuit_3516], level=[0, 1, 2, 3], From a5a6d7288428506b183ad9088e5ce24fb125e91b Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 10:30:38 +0200 Subject: [PATCH 008/168] Fake1QV2 should not have two-qubit gates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- test/python/transpiler/test_1q.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/python/transpiler/test_1q.py b/test/python/transpiler/test_1q.py index f726f4ac0b52..13379f410c34 100644 --- a/test/python/transpiler/test_1q.py +++ b/test/python/transpiler/test_1q.py @@ -23,7 +23,7 @@ from test import QiskitTestCase # pylint: disable=wrong-import-order Fake1QV2 = GenericBackendV2( - num_qubits=1, basis_gates=["u1", "u2", "u3", "cx"], coupling_map=None, dtm=1.3333, seed=42 + num_qubits=1, basis_gates=["u1", "u2", "u3"], coupling_map=None, dtm=1.3333, seed=42 ) @@ -95,7 +95,7 @@ def test_device(self, circuit, level): @ddt class TestBasicSimulatorWorking(QiskitTestCase): - """Test with a simulator backend""" + """All the levels with a simulator backend""" @combine( circuit=[circuit_3516], From 70113d0a274b68679e94e871217bc98da25455ed Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 19:08:47 +0200 Subject: [PATCH 009/168] test.python.circuit.test_parameters.TestParameters --- qiskit/providers/fake_provider/fake_1q.py | 6 --- .../providers/fake_provider/fake_backend.py | 7 ++- test/python/circuit/test_parameters.py | 45 ++++++++++++++++++- 3 files changed, 49 insertions(+), 9 deletions(-) diff --git a/qiskit/providers/fake_provider/fake_1q.py b/qiskit/providers/fake_provider/fake_1q.py index 34d581031464..09959620bc92 100644 --- a/qiskit/providers/fake_provider/fake_1q.py +++ b/qiskit/providers/fake_provider/fake_1q.py @@ -18,17 +18,11 @@ from qiskit.providers.models.backendproperties import BackendProperties, Gate, Nduv from .fake_backend import FakeBackend -from ...utils import deprecate_func class Fake1Q(FakeBackend): """A fake 1Q backend.""" - @deprecate_func( - since="1.2", - removal_timeline="in the 2.0 release", - additional_msg="Fake backendV1 are deprecated in favor of GenericBackendV2", - ) def __init__(self): """ 0 diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 4a638f315574..725688515757 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -23,7 +23,7 @@ from qiskit.providers import BackendV1 from qiskit import pulse from qiskit.exceptions import QiskitError -from qiskit.utils import optionals as _optionals +from qiskit.utils import optionals as _optionals, deprecate_func from qiskit.providers import basic_provider @@ -39,6 +39,11 @@ def __init__(self, token="123456", url="https://"): class FakeBackend(BackendV1): """This is a dummy backend just for testing purposes.""" + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="Fake backends using BackendV1 are deprecated in favor of GenericBackendV2", + ) def __init__(self, configuration, time_alive=10): """FakeBackend initializer. diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index f580416eccf5..294afbb18d42 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -31,7 +31,7 @@ from qiskit.compiler import assemble, transpile from qiskit import pulse from qiskit.quantum_info import Operator -from qiskit.providers.fake_provider import Fake5QV1 +from qiskit.providers.fake_provider import Fake5QV1, GenericBackendV2 from qiskit.providers.basic_provider import BasicSimulator from qiskit.utils import parallel_map from test import QiskitTestCase, combine # pylint: disable=wrong-import-order @@ -1038,6 +1038,26 @@ def test_transpiling_multiple_parameterized_circuits(self): self.assertTrue(len(job.result().results), 2) + @data(0, 1, 2, 3) + def test_transpile_across_optimization_levelsV1(self, opt_level): + """Verify parameterized circuits can be transpiled with all default pass managers. + To remove once Fake5QV1 gets removed""" + + qc = QuantumCircuit(5, 5) + + theta = Parameter("theta") + phi = Parameter("phi") + + qc.rx(theta, 0) + qc.x(0) + for i in range(5 - 1): + qc.rxx(phi, i, i + 1) + + qc.measure(range(5 - 1), range(5 - 1)) + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() + transpile(qc, backend, optimization_level=opt_level) + @data(0, 1, 2, 3) def test_transpile_across_optimization_levels(self, opt_level): """Verify parameterized circuits can be transpiled with all default pass managers.""" @@ -1054,7 +1074,28 @@ def test_transpile_across_optimization_levels(self, opt_level): qc.measure(range(5 - 1), range(5 - 1)) - transpile(qc, Fake5QV1(), optimization_level=opt_level) + transpile( + qc, + GenericBackendV2( + num_qubits=5, + coupling_map=[ + [0, 1], + [1, 0], + [1, 2], + [2, 1], + [0, 2], + [2, 0], + [2, 3], + [3, 2], + [3, 4], + [4, 3], + [2, 4], + [4, 2], + ], + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + ), + optimization_level=opt_level, + ) def test_repeated_gates_to_dag_and_back(self): """Verify circuits with repeated parameterized gates can be converted From ca7eba8c87912624588b14cf5d410d21666bfb56 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 20:38:04 +0200 Subject: [PATCH 010/168] test.python.providers.fake_provider.test_fake_backends.FakeBackendsTest --- test/python/circuit/test_parameters.py | 1 - .../fake_provider/test_fake_backends.py | 34 ++++++++++++++++++- 2 files changed, 33 insertions(+), 2 deletions(-) diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index 294afbb18d42..f72bc8acaab0 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -1092,7 +1092,6 @@ def test_transpile_across_optimization_levels(self, opt_level): [2, 4], [4, 2], ], - basis_gates=["id", "rz", "sx", "x", "cx", "reset"], ), optimization_level=opt_level, ) diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index c12be3584fc2..2342d66c7272 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -35,10 +35,42 @@ def get_test_circuit(): class FakeBackendsTest(QiskitTestCase): """fake backends test.""" + @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") + def test_fake_backends_get_kwargs_v1(self): + """Fake backends honor kwargs passed. + To remove once Fake5QV1 gets removed""" + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() + + qc = QuantumCircuit(2) + qc.x(range(0, 2)) + qc.measure_all() + + trans_qc = transpile(qc, backend) + raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() + + self.assertEqual(sum(raw_counts.values()), 1000) + @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backends_get_kwargs(self): """Fake backends honor kwargs passed.""" - backend = Fake5QV1() + backend = GenericBackendV2( + num_qubits=5, + coupling_map=[ + [0, 1], + [1, 0], + [1, 2], + [2, 1], + [0, 2], + [2, 0], + [2, 3], + [3, 2], + [3, 4], + [4, 3], + [2, 4], + [4, 2], + ], + ) qc = QuantumCircuit(2) qc.x(range(0, 2)) From 43cfcb0665976f8dc8027d3be302c0ef5c1cca3a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 21:25:58 +0200 Subject: [PATCH 011/168] test.python.providers.test_fake_backends.TestFakeBackends --- test/python/providers/test_backendstatus.py | 3 +- test/python/providers/test_fake_backends.py | 51 +++++++++++++-------- 2 files changed, 35 insertions(+), 19 deletions(-) diff --git a/test/python/providers/test_backendstatus.py b/test/python/providers/test_backendstatus.py index 8372108408ac..2cfa31791de3 100644 --- a/test/python/providers/test_backendstatus.py +++ b/test/python/providers/test_backendstatus.py @@ -35,7 +35,8 @@ def test_repr(self): def test_fake_backend_status(self): """Test backend status for one of the fake backends""" - fake_backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + fake_backend = Fake5QV1() backend_status = fake_backend.status() self.assertIsInstance(backend_status, BackendStatus) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index d5c5507b3b8e..258a6be7a2ed 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -17,6 +17,7 @@ import itertools import operator import unittest +import warnings from test import combine from ddt import ddt, data @@ -77,7 +78,8 @@ from qiskit.transpiler.coupling import CouplingMap from test.utils.base import QiskitTestCase # pylint: disable=wrong-import-order -BACKENDS = [Fake5QV1(), Fake20QV1(), Fake7QPulseV1(), Fake27QPulseV1(), Fake127QPulseV1()] +with warnings.catch_warnings(): + BACKENDS = [Fake5QV1(), Fake20QV1(), Fake7QPulseV1(), Fake27QPulseV1(), Fake127QPulseV1()] BACKENDS_V2 = [] for n in [5, 7, 16, 20, 27, 65, 127]: @@ -187,7 +189,7 @@ def test_to_dict_configuration(self, backend): self.assertIsInstance(configuration.to_dict(), dict) - @data(BACKENDS) + @data(*BACKENDS) def test_defaults_to_dict(self, backend): if hasattr(backend, "defaults"): defaults = backend.defaults() @@ -204,7 +206,8 @@ def test_defaults_to_dict(self, backend): self.skipTest(f"Backend {backend} does not have defaults") def test_delay_circuit(self): - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.configuration().timing_constraints = { "acquire_alignment": 1, "granularity": 1, @@ -221,7 +224,8 @@ def test_delay_circuit(self): @data(0, 1, 2, 3) def test_converter(self, opt_level): - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() backend_v2 = BackendV2Converter(backend) self.assertIsInstance(backend_v2, BackendV2) res = transpile(self.circuit, backend_v2, optimization_level=opt_level) @@ -232,7 +236,8 @@ def test_converter(self, opt_level): self.assertEqual(max_count, "11") def test_converter_delay_circuit(self): - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.configuration().timing_constraints = { "acquire_alignment": 1, "granularity": 1, @@ -251,8 +256,8 @@ def test_converter_delay_circuit(self): def test_converter_with_missing_gate_property(self): """Test converting to V2 model with irregular backend data.""" - backend = FakeOpenPulse2Q() - + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() # The backend includes pulse calibration definition for U2, but its property is gone. # Note that u2 is a basis gate of this device. # Since gate property is not provided, the gate broadcasts to all qubits as ideal instruction. @@ -516,7 +521,8 @@ def __init__(self, num_ctrl_qubits, ctrl_state=None): def test_filter_faulty_qubits_backend_v2_converter(self): """Test faulty qubits in v2 conversion.""" - backend = Fake127QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake127QPulseV1() # Get properties dict to make it easier to work with the properties API # is difficult to edit because of the multiple layers of nesting and # different object types @@ -537,7 +543,8 @@ def test_filter_faulty_qubits_backend_v2_converter(self): def test_filter_faulty_qubits_backend_v2_converter_with_delay(self): """Test faulty qubits in v2 conversion.""" - backend = Fake127QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake127QPulseV1() # Get properties dict to make it easier to work with the properties API # is difficult to edit because of the multiple layers of nesting and # different object types @@ -579,14 +586,16 @@ def test_backend_v2_converter_without_delay(self): (4, 2), (4, 3), } - - backend = BackendV2Converter(backend=Fake5QV1(), filter_faulty=True, add_delay=False) + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() + backend = BackendV2Converter(backend=backend, filter_faulty=True, add_delay=False) self.assertEqual(backend.target.qargs, expected) def test_backend_v2_converter_with_meaningless_gate_config(self): """Test backend with broken gate config can be converted only with properties data.""" - backend_v1 = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend_v1 = Fake5QV1() backend_v1.configuration().gates = [ GateConfig(name="NotValidGate", parameters=[], qasm_def="not_valid_gate") ] @@ -603,7 +612,8 @@ def test_backend_v2_converter_with_meaningless_gate_config(self): def test_filter_faulty_qubits_and_gates_backend_v2_converter(self): """Test faulty gates and qubits.""" - backend = Fake127QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake127QPulseV1() # Get properties dict to make it easier to work with the properties API # is difficult to edit because of the multiple layers of nesting and # different object types @@ -646,7 +656,8 @@ def test_filter_faulty_qubits_and_gates_backend_v2_converter(self): def test_filter_faulty_gates_v2_converter(self): """Test just faulty gates in conversion.""" - backend = Fake127QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake127QPulseV1() # Get properties dict to make it easier to work with the properties API # is difficult to edit because of the multiple layers of nesting and # different object types @@ -680,14 +691,16 @@ def test_filter_faulty_gates_v2_converter(self): def test_filter_faulty_no_faults_v2_converter(self): """Test that faulty qubit filtering does nothing with all operational qubits and gates.""" - backend = Fake127QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake127QPulseV1() v2_backend = BackendV2Converter(backend, filter_faulty=True) for i in range(v2_backend.num_qubits): self.assertIn((i,), v2_backend.target.qargs) @data(0, 1, 2, 3) def test_faulty_full_path_transpile_connected_cmap(self, opt_level): - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() non_operational_gate = { "date": datetime.datetime.now(datetime.timezone.utc), "name": "operational", @@ -710,7 +723,8 @@ def test_faulty_full_path_transpile_connected_cmap(self, opt_level): self.assertNotIn((0, 1), connections) def test_convert_to_target_control_flow(self): - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() properties = backend.properties() configuration = backend.configuration() configuration.supported_instructions = [ @@ -734,7 +748,8 @@ def test_convert_to_target_control_flow(self): self.assertTrue(target.instruction_supported("switch_case", ())) def test_convert_unrelated_supported_instructions(self): - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() properties = backend.properties() configuration = backend.configuration() configuration.supported_instructions = [ From 535f1332515f6365194d759b199365df8d5e6256 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 21:35:49 +0200 Subject: [PATCH 012/168] test.python.result.test_mitigators --- test/python/result/test_mitigators.py | 30 ++++++++++++++++++--------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/test/python/result/test_mitigators.py b/test/python/result/test_mitigators.py index 3b3e83bce009..8112089b6ad6 100644 --- a/test/python/result/test_mitigators.py +++ b/test/python/result/test_mitigators.py @@ -119,8 +119,8 @@ def counts_data(circuit, assignment_matrices, shots=1024): def test_mitigation_improvement(self): """Test whether readout mitigation led to more accurate results""" shots = 1024 - assignment_matrices = self.assignment_matrices() - num_qubits = len(assignment_matrices) + with self.assertWarns(DeprecationWarning): + assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, circuit_name, num_qubits = self.ghz_3_circuit() counts_ideal, counts_noise, probs_noise = self.counts_data( @@ -156,7 +156,8 @@ def test_expectation_improvement(self): """Test whether readout mitigation led to more accurate results and that its standard deviation is increased""" shots = 1024 - assignment_matrices = self.assignment_matrices() + with self.assertWarns(DeprecationWarning): + assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) num_qubits = len(assignment_matrices) diagonals = [] @@ -198,7 +199,8 @@ def test_expectation_improvement(self): def test_clbits_parameter(self): """Test whether the clbits parameter is handled correctly""" shots = 10000 - assignment_matrices = self.assignment_matrices() + with self.assertWarns(DeprecationWarning): + assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) @@ -233,7 +235,8 @@ def test_clbits_parameter(self): def test_qubits_parameter(self): """Test whether the qubits parameter is handled correctly""" shots = 10000 - assignment_matrices = self.assignment_matrices() + with self.assertWarns(DeprecationWarning): + assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) @@ -281,7 +284,8 @@ def test_qubits_parameter(self): def test_repeated_qubits_parameter(self): """Tests the order of mitigated qubits.""" shots = 10000 - assignment_matrices = self.assignment_matrices() + with self.assertWarns(DeprecationWarning): + assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[0, 1, 2]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) @@ -319,7 +323,8 @@ def test_qubits_subset_parameter(self): """Tests mitigation on a subset of the initial set of qubits.""" shots = 10000 - assignment_matrices = self.assignment_matrices() + with self.assertWarns(DeprecationWarning): + assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices, qubits=[2, 4, 6]) circuit, _, _ = self.first_qubit_h_3_circuit() counts_ideal, counts_noise, _ = self.counts_data(circuit, assignment_matrices, shots) @@ -364,7 +369,8 @@ def test_qubits_subset_parameter(self): def test_from_backend(self): """Test whether a local mitigator can be created directly from backend properties""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() num_qubits = len(backend.properties().qubits) probs = TestReadoutMitigation.rng.random((num_qubits, 2)) for qubit_idx, qubit_prop in enumerate(backend.properties().qubits): @@ -422,7 +428,9 @@ def test_error_handling(self): def test_expectation_value_endian(self): """Test that endian for expval is little.""" - mitigators = self.mitigators(self.assignment_matrices()) + with self.assertWarns(DeprecationWarning): + assignment_matrices = self.assignment_matrices() + mitigators = self.mitigators(assignment_matrices) counts = Counts({"10": 3, "11": 24, "00": 74, "01": 923}) for mitigator in mitigators: expval, _ = mitigator.expectation_value(counts, diagonal="IZ", qubits=[0, 1]) @@ -449,7 +457,9 @@ class TestLocalReadoutMitigation(QiskitTestCase): def test_assignment_matrix(self): """Tests that the local mitigator generates the full assignment matrix correctly""" qubits = [7, 2, 3] - assignment_matrices = LocalReadoutMitigator(backend=Fake5QV1())._assignment_mats[0:3] + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() + assignment_matrices = LocalReadoutMitigator(backend=backend)._assignment_mats[0:3] expected_assignment_matrix = np.kron( np.kron(assignment_matrices[2], assignment_matrices[1]), assignment_matrices[0] ) From 7a265bb38deb14f98579c7e6ece6da4f5a2103ac Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 21:40:17 +0200 Subject: [PATCH 013/168] test.python.transpiler.test_preset_passmanagers --- .../transpiler/test_preset_passmanagers.py | 31 +++++++++++++------ 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/test/python/transpiler/test_preset_passmanagers.py b/test/python/transpiler/test_preset_passmanagers.py index ee85dc34ffd6..2d67348f9fd0 100644 --- a/test/python/transpiler/test_preset_passmanagers.py +++ b/test/python/transpiler/test_preset_passmanagers.py @@ -222,7 +222,9 @@ def test_alignment_constraints_called_with_by_default(self, level): circuit.h(q[0]) circuit.cz(q[0], q[1]) with unittest.mock.patch("qiskit.transpiler.passes.TimeUnitConversion.run") as mock: - transpile(circuit, backend=Fake20QV1(), optimization_level=level) + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() + transpile(circuit, backend=backend, optimization_level=level) mock.assert_not_called() @combine(level=[0, 1, 2, 3], name="level{level}") @@ -236,12 +238,15 @@ def test_alignment_constraints_called_with_delay_in_circuit(self, level): with unittest.mock.patch( "qiskit.transpiler.passes.TimeUnitConversion.run", return_value=circuit_to_dag(circuit) ) as mock: - transpile(circuit, backend=Fake20QV1(), optimization_level=level) + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() + transpile(circuit, backend=backend, optimization_level=level) mock.assert_called_once() def test_unroll_only_if_not_gates_in_basis(self): """Test that the list of passes _unroll only runs if a gate is not in the basis.""" - qcomp = Fake5QV1() + with self.assertWarns(DeprecationWarning): + qcomp = Fake5QV1() qv_circuit = QuantumVolume(3) gates_in_basis_true_count = 0 collect_2q_blocks_count = 0 @@ -782,7 +787,8 @@ def test_layout_2503(self, level): 19: ancilla[16], } - backend = Fake20QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) @@ -1038,7 +1044,8 @@ def test_trivial_layout(self, level): expected_layouts = [trivial_layout, trivial_layout] - backend = Fake20QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @@ -1071,7 +1078,8 @@ def test_initial_layout(self, level): 18: qr[9], } - backend = Fake20QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() result = transpile( qc, backend, optimization_level=level, initial_layout=initial_layout, seed_transpiler=42 ) @@ -1151,7 +1159,8 @@ def test_optimization_condition(self, level): cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.cx(0, 1).c_if(cr, 1) - backend = Fake20QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() circ = transpile(qc, backend, optimization_level=level) self.assertIsInstance(circ, QuantumCircuit) @@ -1215,8 +1224,9 @@ class TestGeneratePresetPassManagers(QiskitTestCase): @data(0, 1, 2, 3) def test_with_backend(self, optimization_level): """Test a passmanager is constructed when only a backend and optimization level.""" - target = Fake20QV1() - pm = generate_preset_pass_manager(optimization_level, target) + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() + pm = generate_preset_pass_manager(optimization_level, backend) self.assertIsInstance(pm, PassManager) @data(0, 1, 2, 3) @@ -1569,7 +1579,8 @@ def test_invalid_methods_raise_on_control_flow(self, optimization_level): def test_unsupported_basis_gates_raise(self, optimization_level): """Test that trying to transpile a control-flow circuit for a backend that doesn't support the necessary operations in its `basis_gates` will raise a sensible error.""" - backend = Fake20QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() qc = QuantumCircuit(1, 1) with qc.for_loop((0,)): From eea59aa9e5d7c3446d75b9e7ede1752a23081f9a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 21:42:18 +0200 Subject: [PATCH 014/168] test.python.transpiler.test_target --- test/python/transpiler/test_target.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/python/transpiler/test_target.py b/test/python/transpiler/test_target.py index f63ed5061cc7..928cd09c8dd1 100644 --- a/test/python/transpiler/test_target.py +++ b/test/python/transpiler/test_target.py @@ -1937,7 +1937,8 @@ def test_basis_gates_coupling_map(self): self.assertEqual({(0, 1), (1, 2), (2, 0)}, target["cx"].keys()) def test_properties(self): - fake_backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + fake_backend = Fake5QV1() config = fake_backend.configuration() properties = fake_backend.properties() target = Target.from_configuration( @@ -1950,7 +1951,8 @@ def test_properties(self): self.assertEqual(0, target["rz"][(0,)].duration) def test_properties_with_durations(self): - fake_backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + fake_backend = Fake5QV1() config = fake_backend.configuration() properties = fake_backend.properties() durations = InstructionDurations([("rz", 0, 0.5)], dt=1.0) @@ -1965,7 +1967,8 @@ def test_properties_with_durations(self): self.assertEqual(0.5, target["rz"][(0,)].duration) def test_inst_map(self): - fake_backend = Fake7QPulseV1() + with self.assertWarns(DeprecationWarning): + fake_backend = Fake7QPulseV1() config = fake_backend.configuration() properties = fake_backend.properties() defaults = fake_backend.defaults() @@ -1986,7 +1989,8 @@ def test_inst_map(self): self.assertEqual(target.acquire_alignment, constraints.acquire_alignment) def test_concurrent_measurements(self): - fake_backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + fake_backend = Fake5QV1() config = fake_backend.configuration() target = Target.from_configuration( basis_gates=config.basis_gates, From b2ed530fd2754f4af5169aaa73beeab394e1c80d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:02:31 +0200 Subject: [PATCH 015/168] test.python.transpiler.test_unitary_synthesis --- .../transpiler/test_unitary_synthesis.py | 39 ++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/test/python/transpiler/test_unitary_synthesis.py b/test/python/transpiler/test_unitary_synthesis.py index 0f4423426a8a..43acd4ef67af 100644 --- a/test/python/transpiler/test_unitary_synthesis.py +++ b/test/python/transpiler/test_unitary_synthesis.py @@ -148,7 +148,8 @@ def test_two_qubit_synthesis_to_directional_cx_from_gate_errors(self): """Verify two qubit unitaries are synthesized to match basis gates.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap(conf.coupling_map) @@ -182,7 +183,8 @@ def test_swap_synthesis_to_directional_cx(self): """Verify two qubit unitaries are synthesized to match basis gates.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap(conf.coupling_map) @@ -218,7 +220,8 @@ def test_two_qubit_synthesis_to_directional_cx_multiple_registers(self): across multiple registers.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr0 = QuantumRegister(1) qr1 = QuantumRegister(1) @@ -253,7 +256,8 @@ def test_two_qubit_synthesis_to_directional_cx_from_coupling_map(self): """Verify natural cx direction is used when specified in coupling map.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) @@ -296,7 +300,8 @@ def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_none(se when natural_direction is None.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) @@ -339,7 +344,8 @@ def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_false(s when natural_direction is None.""" # TODO: should make check more explicit e.g. explicitly set gate # direction in test instead of using specific fake backend - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) @@ -379,7 +385,8 @@ def test_two_qubit_synthesis_to_directional_cx_from_coupling_map_natural_false(s def test_two_qubit_synthesis_not_pulse_optimal(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr = QuantumRegister(2) qc = QuantumCircuit(qr) @@ -415,7 +422,8 @@ def test_two_qubit_synthesis_not_pulse_optimal(self): def test_two_qubit_pulse_optimal_true_raises(self): """Verify raises if pulse optimal==True but cx is not in the backend basis.""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() # this assumes iswawp pulse optimal decomposition doesn't exist conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] @@ -438,7 +446,8 @@ def test_two_qubit_pulse_optimal_true_raises(self): def test_two_qubit_natural_direction_true_duration_fallback(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" # this assumes iswawp pulse optimal decomposition doesn't exist - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() # conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) @@ -462,7 +471,8 @@ def test_two_qubit_natural_direction_true_duration_fallback(self): def test_two_qubit_natural_direction_true_gate_length_raises(self): """Verify not attempting pulse optimal decomposition when pulse_optimize==False.""" # this assumes iswawp pulse optimal decomposition doesn't exist - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() for _, nduv in backend.properties()._gates["cx"].items(): nduv["gate_length"] = (4e-7, nduv["gate_length"][1]) @@ -485,7 +495,8 @@ def test_two_qubit_natural_direction_true_gate_length_raises(self): def test_two_qubit_pulse_optimal_none_optimal(self): """Verify pulse optimal decomposition when pulse_optimize==None.""" # this assumes iswawp pulse optimal decomposition doesn't exist - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() qr = QuantumRegister(2) coupling_map = CouplingMap([[0, 1], [1, 2], [1, 3], [3, 4]]) @@ -512,7 +523,8 @@ def test_two_qubit_pulse_optimal_none_no_raise(self): """Verify pulse optimal decomposition when pulse_optimize==None doesn't raise when pulse optimal decomposition unknown.""" # this assumes iswawp pulse optimal decomposition doesn't exist - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() conf = backend.configuration() conf.basis_gates = [gate if gate != "cx" else "iswap" for gate in conf.basis_gates] qr = QuantumRegister(2) @@ -662,7 +674,8 @@ def test_coupling_map_unequal_durations(self, opt): qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() tqc = transpile( circ, backend=backend, From 8cabdc19c88315cbf0cd4c47fbb25f1a77122b6f Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:04:40 +0200 Subject: [PATCH 016/168] test.python.transpiler.test_vf2_layout --- test/python/transpiler/test_vf2_layout.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/python/transpiler/test_vf2_layout.py b/test/python/transpiler/test_vf2_layout.py index 716e49d35009..6d170ee9a13e 100644 --- a/test/python/transpiler/test_vf2_layout.py +++ b/test/python/transpiler/test_vf2_layout.py @@ -629,7 +629,8 @@ def test_no_properties(self): def test_with_properties(self): """Test it finds the least noise perfect layout with no properties.""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.x(qr) @@ -643,7 +644,8 @@ def test_with_properties(self): def test_max_trials_exceeded(self): """Test it exits when max_trials is reached.""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.x(qr) @@ -663,7 +665,8 @@ def test_max_trials_exceeded(self): def test_time_limit_exceeded(self): """Test the pass stops after time_limit is reached.""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr = QuantumRegister(2) qc = QuantumCircuit(qr) qc.x(qr) @@ -706,7 +709,8 @@ def test_reasonable_limits_for_simple_layouts(self): def test_no_limits_with_negative(self): """Test that we're not enforcing a trial limit if set to negative.""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qc = QuantumCircuit(3) qc.h(0) cmap = CouplingMap(backend.configuration().coupling_map) From 52f950c1292728457ed51c8128275a8cfb0a16f7 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:08:45 +0200 Subject: [PATCH 017/168] test.python.transpiler.test_vf2_post_layout --- .../python/transpiler/test_vf2_post_layout.py | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/test/python/transpiler/test_vf2_post_layout.py b/test/python/transpiler/test_vf2_post_layout.py index 3df2fefcc73b..e97ed279a8d8 100644 --- a/test/python/transpiler/test_vf2_post_layout.py +++ b/test/python/transpiler/test_vf2_post_layout.py @@ -102,8 +102,9 @@ def test_no_backend_properties(self): def test_empty_circuit(self): """Test no solution found for empty circuit""" + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qc = QuantumCircuit(2, 2) - backend = Fake5QV1() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) @@ -128,9 +129,10 @@ def test_empty_circuit_v2(self): def test_skip_3q_circuit(self): """Test that the pass is a no-op on circuits with >2q gates.""" + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qc = QuantumCircuit(3) qc.ccx(0, 1, 2) - backend = Fake5QV1() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) @@ -141,10 +143,11 @@ def test_skip_3q_circuit(self): def test_skip_3q_circuit_control_flow(self): """Test that the pass is a no-op on circuits with >2q gates.""" + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qc = QuantumCircuit(3) with qc.for_loop((1,)): qc.ccx(0, 1, 2) - backend = Fake5QV1() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props) @@ -182,7 +185,8 @@ def test_skip_3q_circuit_control_flow_v2(self): def test_best_mapping_ghz_state_full_device_multiple_qregs(self): """Test best mappings with multiple registers""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) @@ -207,7 +211,8 @@ def test_2q_circuit_5q_backend(self): 0 - 1 qr1 - qr0 """ - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) @@ -227,7 +232,8 @@ def test_2q_circuit_5q_backend_controlflow(self): 0 - 1 qr1 - qr0 """ - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() circuit = QuantumCircuit(2, 1) with circuit.for_loop((1,)): @@ -253,7 +259,8 @@ def test_2q_circuit_5q_backend_max_trials(self): qr1 - qr0 """ max_trials = 11 - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) @@ -564,8 +571,10 @@ def test_no_backend_properties(self): def test_empty_circuit(self): """Test no solution found for empty circuit""" + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() + qc = QuantumCircuit(2, 2) - backend = Fake5QV1() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False) @@ -593,9 +602,11 @@ def test_empty_circuit_v2(self): def test_skip_3q_circuit(self): """Test that the pass is a no-op on circuits with >2q gates.""" + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() + qc = QuantumCircuit(3) qc.ccx(0, 1, 2) - backend = Fake5QV1() cmap = CouplingMap(backend.configuration().coupling_map) props = backend.properties() vf2_pass = VF2PostLayout(coupling_map=cmap, properties=props, strict_direction=False) @@ -624,7 +635,8 @@ def test_skip_3q_circuit_v2(self): def test_best_mapping_ghz_state_full_device_multiple_qregs(self): """Test best mappings with multiple registers""" - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr_a = QuantumRegister(2) qr_b = QuantumRegister(3) qc = QuantumCircuit(qr_a, qr_b) @@ -651,7 +663,8 @@ def test_2q_circuit_5q_backend(self): 0 - 1 qr1 - qr0 """ - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) From 1659babf7aec576bff32094a65311e6918ff9829 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:11:41 +0200 Subject: [PATCH 018/168] test/python/visualization/test_circuit_latex --- test/python/visualization/test_circuit_latex.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/test/python/visualization/test_circuit_latex.py b/test/python/visualization/test_circuit_latex.py index 5490648fd6bf..1be7ad7ce051 100644 --- a/test/python/visualization/test_circuit_latex.py +++ b/test/python/visualization/test_circuit_latex.py @@ -480,11 +480,15 @@ def test_partial_layout(self): """Tests partial_layout See: https://github.com/Qiskit/qiskit-terra/issues/4757""" filename = self._get_resource_path("test_latex_partial_layout.tex") + + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() + circuit = QuantumCircuit(3) circuit.h(1) transpiled = transpile( circuit, - backend=Fake5QV1(), + backend=backend, optimization_level=0, initial_layout=[1, 2, 0], seed_transpiler=0, From 9dc496a9391bf2c2fbfc1ba35cdf8c3ee05d0c83 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:31:18 +0200 Subject: [PATCH 019/168] test.python.transpiler.test_sabre_layout --- test/python/transpiler/test_sabre_layout.py | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/test/python/transpiler/test_sabre_layout.py b/test/python/transpiler/test_sabre_layout.py index 0a7b977162a3..2a4ed78dd815 100644 --- a/test/python/transpiler/test_sabre_layout.py +++ b/test/python/transpiler/test_sabre_layout.py @@ -195,7 +195,9 @@ def test_layout_with_classical_bits(self): rz(0) q4835[1]; """ ) - res = transpile(qc, Fake27QPulseV1(), layout_method="sabre", seed_transpiler=1234) + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() + res = transpile(qc, backend, layout_method="sabre", seed_transpiler=1234) self.assertIsInstance(res, QuantumCircuit) layout = res._layout.initial_layout self.assertEqual( @@ -245,9 +247,12 @@ def test_layout_many_search_trials(self): barrier q18585[5],q18585[2],q18585[8],q18585[3],q18585[6]; """ ) + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() + res = transpile( qc, - Fake27QPulseV1(), + backend, layout_method="sabre", routing_method="stochastic", seed_transpiler=12345, From 3bafa4766aa5bc98b19120aa1fb2999ff881f527 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:32:24 +0200 Subject: [PATCH 020/168] test.python.transpiler.test_sabre_layout --- test/python/transpiler/test_pulse_gate_pass.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index a11d4c4a6b53..e98edf3b0f4b 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -244,7 +244,8 @@ def test_transpile_with_parameterized_custom_gate(self): def test_transpile_with_multiple_circuits(self): """Test transpile with multiple circuits with custom gate.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) From 429718e929ec40c6ef5206680b2c4d23868cdb23 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:42:59 +0200 Subject: [PATCH 021/168] test.python.transpiler.test_pulse_gate_pass --- .../python/transpiler/test_pulse_gate_pass.py | 58 ++++++++++++++----- 1 file changed, 42 insertions(+), 16 deletions(-) diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index e98edf3b0f4b..ebd42f82bada 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -56,7 +56,8 @@ def setUp(self): def test_transpile_with_bare_backend(self): """Test transpile without custom calibrations.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() # Remove timing constraints to avoid triggering # scheduling passes. backend.configuration().timing_constraints = {} @@ -96,7 +97,8 @@ def test_transpile_with_backend_target(self): def test_transpile_with_custom_basis_gate(self): """Test transpile with custom calibrations.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) backend.defaults().instruction_schedule_map.add("sx", (1,), self.custom_sx_q1) # Remove timing constraints to avoid triggering @@ -122,10 +124,12 @@ def test_transpile_with_custom_basis_gate(self): def test_transpile_with_custom_basis_gate_in_target(self): """Test transpile with custom calibrations.""" + with self.assertWarns(DeprecationWarning): + backend_pulse = Fake27QPulseV1() target = GenericBackendV2( num_qubits=5, coupling_map=BOGOTA_CMAP, - calibrate_instructions=Fake27QPulseV1().defaults().instruction_schedule_map, + calibrate_instructions=backend_pulse.defaults().instruction_schedule_map, ).target target["sx"][(0,)].calibration = self.custom_sx_q0 @@ -150,12 +154,16 @@ def test_transpile_with_custom_basis_gate_in_target(self): def test_transpile_with_instmap(self): """Test providing instruction schedule map.""" - instmap = Fake27QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() + + instmap = backend.defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) # Inst map is renewed - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() # Remove timing constraints to avoid triggering # scheduling passes. backend.configuration().timing_constraints = {} @@ -179,7 +187,8 @@ def test_transpile_with_instmap(self): def test_transpile_with_custom_gate(self): """Test providing non-basis gate.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) @@ -215,7 +224,8 @@ def test_transpile_with_custom_gate(self): def test_transpile_with_parameterized_custom_gate(self): """Test providing non-basis gate, which is kept parameterized throughout transpile.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) @@ -275,7 +285,8 @@ def test_transpile_with_multiple_circuits(self): def test_multiple_instructions_with_different_parameters(self): """Test adding many instruction with different parameter binding.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] ) @@ -309,7 +320,8 @@ def test_multiple_instructions_with_different_parameters(self): def test_transpile_with_different_qubit(self): """Test transpile with qubit without custom gate.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) # Remove timing constraints to avoid triggering # scheduling passes. @@ -330,16 +342,20 @@ def test_transpile_with_both_instmap_and_empty_target(self, opt_level): Test case from Qiskit/qiskit-terra/#9489 """ - instmap = Fake27QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() + instmap = backend.defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) instmap.add("cx", (0, 1), self.custom_cx_q01) + with self.assertWarns(DeprecationWarning): + backend_pulse = Fake27QPulseV1() # This doesn't have custom schedule definition target = GenericBackendV2( num_qubits=5, coupling_map=BOGOTA_CMAP, - calibrate_instructions=Fake27QPulseV1().defaults().instruction_schedule_map, + calibrate_instructions=backend_pulse.defaults().instruction_schedule_map, seed=42, ).target @@ -372,7 +388,10 @@ def test_transpile_with_instmap_with_v2backend(self, opt_level): Test case from Qiskit/qiskit-terra/#9489 """ - instmap = Fake27QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() + + instmap = backend.defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) instmap.add("cx", (0, 1), self.custom_cx_q01) @@ -381,9 +400,12 @@ def test_transpile_with_instmap_with_v2backend(self, opt_level): qc.append(random_unitary(4, seed=123), [0, 1]) qc.measure_all() + with self.assertWarns(DeprecationWarning): + backend_pulse = Fake27QPulseV1() + backend = GenericBackendV2( num_qubits=5, - calibrate_instructions=Fake27QPulseV1().defaults().instruction_schedule_map, + calibrate_instructions=backend_pulse.defaults().instruction_schedule_map, seed=42, ) @@ -417,8 +439,9 @@ def test_transpile_with_instmap_with_v2backend_with_custom_gate(self, opt_level) """ with pulse.build(name="custom") as rabi12: pulse.play(pulse.Constant(100, 0.4), pulse.DriveChannel(0)) - - instmap = Fake27QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() + instmap = backend.defaults().instruction_schedule_map instmap.add("rabi12", (0,), rabi12) gate = circuit.Gate("rabi12", 1, []) @@ -458,7 +481,10 @@ def test_transpile_with_instmap_not_mutate_backend(self): ) original_sx0 = backend.target["sx"][(0,)].calibration - instmap = Fake27QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend_pulse = Fake27QPulseV1() + + instmap = backend_pulse.defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) qc = circuit.QuantumCircuit(1) From 8498188408d0a47fdb54e4e3403662586cbb54cf Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:45:48 +0200 Subject: [PATCH 022/168] test.python.scheduler.test_basic_scheduler.TestBasicSchedule --- test/python/scheduler/test_basic_scheduler.py | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/test/python/scheduler/test_basic_scheduler.py b/test/python/scheduler/test_basic_scheduler.py index 16ec00927c67..98363880b14b 100644 --- a/test/python/scheduler/test_basic_scheduler.py +++ b/test/python/scheduler/test_basic_scheduler.py @@ -46,14 +46,16 @@ class TestBasicSchedule(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() self.inst_map = self.backend.defaults().instruction_schedule_map def test_unavailable_defaults(self): """Test backend with unavailable defaults.""" qr = QuantumRegister(1) qc = QuantumCircuit(qr) - backend = FakeBackend(None) + with self.assertWarns(DeprecationWarning): + backend = FakeBackend(None) backend.defaults = backend.configuration self.assertRaises(QiskitError, lambda: schedule(qc, backend)) @@ -252,7 +254,8 @@ def test_3q_schedule(self): # ┌──────┴───┴──────┐ └───────────────┘ ┌─┴─┐┌─────────────────┐ # q0_2: ┤ U2(0.778,0.122) ├───────────────────┤ X ├┤ U2(0.778,0.122) ├ # └─────────────────┘ └───┘└─────────────────┘ - backend = FakeOpenPulse3Q() + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse3Q() inst_map = backend.defaults().instruction_schedule_map q = QuantumRegister(3) c = ClassicalRegister(3) @@ -416,9 +419,13 @@ def test_subset_calibrated_measurements(self): meas_scheds.append(meas) qc.add_calibration("measure", [qubit], meas) - meas = macros.measure([1], FakeOpenPulse3Q()) + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse3Q() + meas = macros.measure([1], backend) meas = meas.exclude(channels=[AcquireChannel(0), AcquireChannel(2)]) - sched = schedule(qc, FakeOpenPulse3Q()) + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse3Q() + sched = schedule(qc, backend) expected = Schedule(meas_scheds[0], meas_scheds[1], meas) self.assertEqual(sched.instructions, expected.instructions) From 6c2014928da4950b47cb0814e46c5b7d4111e235 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:47:25 +0200 Subject: [PATCH 023/168] test.python.pulse.test_transforms --- test/python/pulse/test_transforms.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/python/pulse/test_transforms.py b/test/python/pulse/test_transforms.py index 5918a6e6993d..c16405cff4d1 100644 --- a/test/python/pulse/test_transforms.py +++ b/test/python/pulse/test_transforms.py @@ -46,7 +46,8 @@ class TestAlignMeasures(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.inst_map = self.backend.defaults().instruction_schedule_map self.short_pulse = pulse.Waveform( @@ -202,7 +203,8 @@ class TestAddImplicitAcquires(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.short_pulse = pulse.Waveform( samples=np.array([0.02739068], dtype=np.complex128), name="p0" From 1fb783380284376d3159e7ec1907f7c3634d9ba7 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:49:08 +0200 Subject: [PATCH 024/168] test.python.pulse.test_schedule --- test/python/pulse/test_schedule.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/python/pulse/test_schedule.py b/test/python/pulse/test_schedule.py index 40d637887ed0..5e5676e7c2d9 100644 --- a/test/python/pulse/test_schedule.py +++ b/test/python/pulse/test_schedule.py @@ -61,7 +61,8 @@ def linear(duration, slope, intercept): return slope * x + intercept self.linear = linear - self.config = FakeOpenPulse2Q().configuration() + with self.assertWarns(DeprecationWarning): + self.config = FakeOpenPulse2Q().configuration() class TestScheduleBuilding(BaseTestSchedule): From c8004142af75cf80b7e7ff4549639025c98a7499 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:51:46 +0200 Subject: [PATCH 025/168] test.python.pulse.test_macros --- test/python/pulse/test_macros.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/test/python/pulse/test_macros.py b/test/python/pulse/test_macros.py index 05937c88982d..ee83038c7ed0 100644 --- a/test/python/pulse/test_macros.py +++ b/test/python/pulse/test_macros.py @@ -33,9 +33,11 @@ class TestMeasure(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() + self.backend_v1 = Fake27QPulseV1() + self.inst_map = self.backend.defaults().instruction_schedule_map - self.backend_v1 = Fake27QPulseV1() self.backend_v2 = GenericBackendV2( num_qubits=27, calibrate_instructions=self.backend_v1.defaults().instruction_schedule_map, @@ -171,7 +173,9 @@ def test_output_with_measure_v1_and_measure_v2_sched_with_qubit_mem_slots(self): def test_output_with_measure_v1_and_measure_v2_sched_with_meas_map(self): """Test make outputs of measure_v1 and measure_v2 with custom meas_map as list and dict consistent.""" - num_qubits_list_measure_v1 = list(range(Fake27QPulseV1().configuration().num_qubits)) + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() + num_qubits_list_measure_v1 = list(range(backend.configuration().num_qubits)) num_qubits_list_measure_v2 = list(range(self.backend_v2.num_qubits)) sched_with_meas_map_list_v1 = macros.measure( qubits=[0], backend=self.backend_v1, meas_map=[num_qubits_list_measure_v1] @@ -210,7 +214,8 @@ class TestMeasureAll(QiskitTestCase): def setUp(self): super().setUp() - self.backend_v1 = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend_v1 = FakeOpenPulse2Q() self.inst_map = self.backend_v1.defaults().instruction_schedule_map self.backend_v2 = GenericBackendV2( num_qubits=2, From da77a153d42537e5be128ea85fcdbcc6744efb1b Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 22:55:52 +0200 Subject: [PATCH 026/168] test.python.pulse.test_instruction_schedule_map --- .../pulse/test_instruction_schedule_map.py | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/test/python/pulse/test_instruction_schedule_map.py b/test/python/pulse/test_instruction_schedule_map.py index 67628ba845ae..cb0cb6307ebc 100644 --- a/test/python/pulse/test_instruction_schedule_map.py +++ b/test/python/pulse/test_instruction_schedule_map.py @@ -100,7 +100,9 @@ def test_has(self): def test_has_from_mock(self): """Test `has` and `assert_has` from mock data.""" - inst_map = FakeOpenPulse2Q().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() + inst_map = backend.defaults().instruction_schedule_map self.assertTrue(inst_map.has("u1", [0])) self.assertTrue(inst_map.has("cx", (0, 1))) self.assertTrue(inst_map.has("u3", 0)) @@ -229,7 +231,9 @@ def test_has_gate(self): def test_has_from_mock_gate(self): """Test `has` and `assert_has` from mock data.""" - inst_map = FakeOpenPulse2Q().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() + inst_map = backend.defaults().instruction_schedule_map self.assertTrue(inst_map.has(U1Gate(0), [0])) self.assertTrue(inst_map.has(CXGate(), (0, 1))) self.assertTrue(inst_map.has(U3Gate(0, 0, 0), 0)) @@ -530,14 +534,18 @@ def test_callable_sched1(par_b): def test_two_instmaps_equal(self): """Test eq method when two instmaps are identical.""" - instmap1 = Fake7QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() + instmap1 = backend.defaults().instruction_schedule_map instmap2 = copy.deepcopy(instmap1) self.assertEqual(instmap1, instmap2) def test_two_instmaps_different(self): """Test eq method when two instmaps are not identical.""" - instmap1 = Fake7QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() + instmap1 = backend.defaults().instruction_schedule_map instmap2 = copy.deepcopy(instmap1) # override one of instruction @@ -547,7 +555,9 @@ def test_two_instmaps_different(self): def test_instmap_picklable(self): """Test if instmap can be pickled.""" - instmap = Fake7QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() + instmap = backend.defaults().instruction_schedule_map ser_obj = pickle.dumps(instmap) deser_instmap = pickle.loads(ser_obj) @@ -561,7 +571,9 @@ def test_instmap_picklable_with_arguments(self): in which arguments are provided by users in the form of python dict key object that is not picklable. """ - instmap = Fake7QPulseV1().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() + instmap = backend.defaults().instruction_schedule_map param1 = Parameter("P1") param2 = Parameter("P2") @@ -581,14 +593,18 @@ def test_instmap_picklable_with_arguments(self): def test_check_backend_provider_cals(self): """Test if schedules provided by backend provider is distinguishable.""" - instmap = FakeOpenPulse2Q().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() + instmap = backend.defaults().instruction_schedule_map publisher = instmap.get("u1", (0,), P0=0).metadata["publisher"] self.assertEqual(publisher, CalibrationPublisher.BACKEND_PROVIDER) def test_check_user_cals(self): """Test if schedules provided by user is distinguishable.""" - instmap = FakeOpenPulse2Q().defaults().instruction_schedule_map + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() + instmap = backend.defaults().instruction_schedule_map test_u1 = Schedule() test_u1 += ShiftPhase(Parameter("P0"), DriveChannel(0)) @@ -600,7 +616,8 @@ def test_check_user_cals(self): def test_has_custom_gate(self): """Test method to check custom gate.""" - backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() instmap = backend.defaults().instruction_schedule_map self.assertFalse(instmap.has_custom_gate()) From 40e2e69e0d0555bf3e346ee7fceb99e848d8bcd4 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 23:00:04 +0200 Subject: [PATCH 027/168] test.python.pulse.test_block --- test/python/pulse/test_block.py | 3 ++- test/python/pulse/test_builder.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/test/python/pulse/test_block.py b/test/python/pulse/test_block.py index 3af2d0b510d1..c6a2c2384f64 100644 --- a/test/python/pulse/test_block.py +++ b/test/python/pulse/test_block.py @@ -28,7 +28,8 @@ class BaseTestBlock(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() self.test_waveform0 = pulse.Constant(100, 0.1) self.test_waveform1 = pulse.Constant(200, 0.1) diff --git a/test/python/pulse/test_builder.py b/test/python/pulse/test_builder.py index cf029d5d98c2..0a54a9556880 100644 --- a/test/python/pulse/test_builder.py +++ b/test/python/pulse/test_builder.py @@ -30,7 +30,8 @@ class TestBuilder(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() self.configuration = self.backend.configuration() self.defaults = self.backend.defaults() self.inst_map = self.defaults.instruction_schedule_map @@ -689,7 +690,8 @@ def test_measure_all(self): self.assertScheduleEqual(schedule, reference) - backend = Fake127QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake127QPulseV1() num_qubits = backend.configuration().num_qubits with pulse.build(backend) as schedule: regs = pulse.measure_all() From ddef3200405c9c63459faa8e3feefce0817153ec Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 25 Jun 2024 23:10:11 +0200 Subject: [PATCH 028/168] test.python.circuit.test_scheduled_circuit --- test/python/circuit/test_scheduled_circuit.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index ec4bc72ffd06..fec0c58d624e 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -33,8 +33,9 @@ class TestScheduledCircuit(QiskitTestCase): def setUp(self): super().setUp() - self.backend_with_dt = Fake27QPulseV1() - self.backend_without_dt = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + self.backend_with_dt = Fake27QPulseV1() + self.backend_without_dt = Fake27QPulseV1() delattr(self.backend_without_dt.configuration(), "dt") # Remove timing constraints from the backends (alignment values, # granularity and min_length), so that these values will default From 847b92032dd535b4eb0bab38c9abac2938280c95 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 08:27:18 +0200 Subject: [PATCH 029/168] test.python.transpiler.test_calibrationbuilder --- .../transpiler/test_calibrationbuilder.py | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/test/python/transpiler/test_calibrationbuilder.py b/test/python/transpiler/test_calibrationbuilder.py index bc64d954a429..cb7293049ef5 100644 --- a/test/python/transpiler/test_calibrationbuilder.py +++ b/test/python/transpiler/test_calibrationbuilder.py @@ -266,7 +266,8 @@ def build_reverse( @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_cr_pulse_stretch(self, theta: float): """Test that cross resonance pulse durations are computed correctly.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: @@ -279,7 +280,8 @@ def test_rzx_calibration_cr_pulse_stretch(self, theta: float): @data(-np.pi / 4, 0.1, np.pi / 4, np.pi / 2, np.pi) def test_rzx_calibration_rotary_pulse_stretch(self, theta: float): """Test that rotary pulse durations are computed correctly.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) with builder.build() as test_sched: @@ -296,8 +298,8 @@ def test_raise(self): qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) dag = circuit_to_dag(qc) - - backend = Fake7QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() # The error is raised when calibrations in multi-qubit # gates are not detected. # We force this by removing the 'cx' entries from the @@ -322,7 +324,8 @@ def test_ecr_cx_forward(self): qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) @@ -347,7 +350,8 @@ def test_ecr_cx_reverse(self): qc = circuit.QuantumCircuit(2) qc.rzx(theta, 1, 0) - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilder(inst_map) test_qc = PassManager(_pass).run(qc) @@ -434,7 +438,8 @@ def test_ecr_cx_forward(self): qc = circuit.QuantumCircuit(2) qc.rzx(theta, 0, 1) - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() inst_map = backend.defaults().instruction_schedule_map _pass = RZXCalibrationBuilderNoEcho(inst_map) From 2a9cbe8ed2b7796a5de661572651899d0ce97957 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 08:52:47 +0200 Subject: [PATCH 030/168] test.python.providers.test_backendconfiguration --- .../python/providers/test_backendconfiguration.py | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/test/python/providers/test_backendconfiguration.py b/test/python/providers/test_backendconfiguration.py index 5ba727fd660d..1fc5a6bb3e12 100644 --- a/test/python/providers/test_backendconfiguration.py +++ b/test/python/providers/test_backendconfiguration.py @@ -26,7 +26,8 @@ class TestBackendConfiguration(QiskitTestCase): def setUp(self): super().setUp() - backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() self.config = backend.configuration() def test_simple_config(self): @@ -60,7 +61,8 @@ def test_hamiltonian(self): {k: var * 1e-9 for k, var in ref_vars.items()}, ) # 3Q doesn't offer a hamiltonian -- test that we get a reasonable response - backend_3q = FakeOpenPulse3Q() + with self.assertWarns(DeprecationWarning): + backend_3q = FakeOpenPulse3Q() self.assertEqual(backend_3q.configuration().hamiltonian, None) def test_get_channels(self): @@ -80,7 +82,8 @@ def test_get_channel_qubits(self): """Test to get all qubits operated on a given channel.""" self.assertEqual(self.config.get_channel_qubits(channel=DriveChannel(0)), [0]) self.assertEqual(self.config.get_channel_qubits(channel=ControlChannel(0)), [0, 1]) - backend_3q = FakeOpenPulse3Q() + with self.assertWarns(DeprecationWarning): + backend_3q = FakeOpenPulse3Q() self.assertEqual(backend_3q.configuration().get_channel_qubits(ControlChannel(2)), [2, 1]) self.assertEqual(backend_3q.configuration().get_channel_qubits(ControlChannel(1)), [1, 0]) with self.assertRaises(BackendConfigurationError): @@ -107,7 +110,8 @@ def test_get_qubit_channels(self): ], ) ) - backend_3q = FakeOpenPulse3Q() + with self.assertWarns(DeprecationWarning): + backend_3q = FakeOpenPulse3Q() self.assertTrue( self._test_lists_equal( actual=backend_3q.configuration().get_qubit_channels(1), @@ -178,7 +182,8 @@ def test_deepcopy(self): def test_u_channel_lo_scale(self): """Ensure that u_channel_lo scale is a complex number""" - valencia_conf = Fake27QPulseV1().configuration() + with self.assertWarns(DeprecationWarning): + valencia_conf = Fake27QPulseV1().configuration() self.assertTrue(isinstance(valencia_conf.u_channel_lo[0][0].scale, complex)) def test_processor_type(self): From 783b426f587516b6735c9c2296eb1e02a9142324 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 12:35:00 +0200 Subject: [PATCH 031/168] test.python.compiler.test_transpiler --- test/python/compiler/test_transpiler.py | 80 +++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 4 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 77b63a3098bc..c14d720e54cb 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1511,7 +1511,8 @@ def test_scheduling_timing_constraints(self): """Test that scheduling-related loose transpile constraints work with both BackendV1 and BackendV2.""" - backend_v1 = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend_v1 = Fake27QPulseV1() backend_v2 = BackendV2Converter(backend_v1) # the original timing constraints are granularity = min_length = 16 timing_constraints = TimingConstraints(granularity=32, min_length=64) @@ -1546,7 +1547,8 @@ def test_scheduling_instruction_constraints(self): """Test that scheduling-related loose transpile constraints work with both BackendV1 and BackendV2.""" - backend_v1 = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend_v1 = Fake27QPulseV1() backend_v2 = BackendV2Converter(backend_v1) qc = QuantumCircuit(2) qc.h(0) @@ -2068,6 +2070,21 @@ def test_transpile_annotated_ops(self, opt_level): self.assertEqual(Operator(qc), Operator(transpiled)) self.assertEqual(Operator(qc), Operator(expected)) + @combine(opt_level=[0, 1, 2, 3]) + def test_transpile_annotated_ops_with_backend_v1(self, opt_level): + """Test transpilation of circuits with annotated operations given a backend. + Remove once Fake20QV1 is removed.""" + qc = QuantumCircuit(3) + qc.append(AnnotatedOperation(SGate(), InverseModifier()), [0]) + qc.append(AnnotatedOperation(XGate(), ControlModifier(1)), [1, 2]) + qc.append(AnnotatedOperation(HGate(), PowerModifier(3)), [2]) + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() + transpiled = transpile( + qc, optimization_level=opt_level, backend=backend, seed_transpiler=42 + ) + self.assertLessEqual(set(transpiled.count_ops().keys()), {"u1", "u2", "u3", "cx"}) + @combine(opt_level=[0, 1, 2, 3]) def test_transpile_annotated_ops_with_backend(self, opt_level): """Test transpilation of circuits with annotated operations given a backend.""" @@ -2075,7 +2092,59 @@ def test_transpile_annotated_ops_with_backend(self, opt_level): qc.append(AnnotatedOperation(SGate(), InverseModifier()), [0]) qc.append(AnnotatedOperation(XGate(), ControlModifier(1)), [1, 2]) qc.append(AnnotatedOperation(HGate(), PowerModifier(3)), [2]) - backend = Fake20QV1() + + backend = GenericBackendV2( + num_qubits=20, + coupling_map=[ + [0, 1], + [1, 0], + [1, 2], + [1, 6], + [2, 1], + [2, 3], + [3, 2], + [3, 4], + [3, 8], + [4, 3], + [5, 6], + [5, 10], + [6, 1], + [6, 5], + [6, 7], + [7, 6], + [7, 8], + [7, 12], + [8, 3], + [8, 7], + [8, 9], + [9, 8], + [9, 14], + [10, 5], + [10, 11], + [11, 10], + [11, 12], + [11, 16], + [12, 7], + [12, 11], + [12, 13], + [13, 12], + [13, 14], + [13, 18], + [14, 9], + [14, 13], + [15, 16], + [16, 11], + [16, 15], + [16, 17], + [17, 16], + [17, 18], + [18, 13], + [18, 17], + [18, 19], + [19, 18], + ], + basis_gates=["id", "u1", "u2", "u3", "cx"], + ) transpiled = transpile( qc, optimization_level=opt_level, backend=backend, seed_transpiler=42 ) @@ -2383,9 +2452,12 @@ def test_qpy_roundtrip_standalone_var_target(self, optimization_level): @data(0, 1, 2, 3) def test_qasm3_output(self, optimization_level): """Test that the output of a transpiled circuit can be dumped into OpenQASM 3.""" + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() + transpiled = transpile( self._regular_circuit(), - backend=Fake20QV1(), + backend=backend, optimization_level=optimization_level, seed_transpiler=2022_10_17, ) From 798d06baff288041132ed776a3030dc4782a17c0 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 12:44:17 +0200 Subject: [PATCH 032/168] test.python.transpiler.test_passmanager_run --- .../python/transpiler/test_passmanager_run.py | 112 +++++++++++++++++- 1 file changed, 107 insertions(+), 5 deletions(-) diff --git a/test/python/transpiler/test_passmanager_run.py b/test/python/transpiler/test_passmanager_run.py index caf6af2aaf67..969dbc6bd951 100644 --- a/test/python/transpiler/test_passmanager_run.py +++ b/test/python/transpiler/test_passmanager_run.py @@ -15,7 +15,7 @@ from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import CXGate from qiskit.transpiler.preset_passmanagers import level_1_pass_manager -from qiskit.providers.fake_provider import Fake20QV1 +from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import Layout, PassManager from qiskit.transpiler.passmanager_config import PassManagerConfig from test import QiskitTestCase # pylint: disable=wrong-import-order @@ -83,12 +83,63 @@ def test_default_pass_manager_single(self): circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) - coupling_map = Fake20QV1().configuration().coupling_map + coupling_map = [ + [0, 1], + [1, 0], + [1, 2], + [1, 6], + [2, 1], + [2, 3], + [3, 2], + [3, 4], + [3, 8], + [4, 3], + [5, 6], + [5, 10], + [6, 1], + [6, 5], + [6, 7], + [7, 6], + [7, 8], + [7, 12], + [8, 3], + [8, 7], + [8, 9], + [9, 8], + [9, 14], + [10, 5], + [10, 11], + [11, 10], + [11, 12], + [11, 16], + [12, 7], + [12, 11], + [12, 13], + [13, 12], + [13, 14], + [13, 18], + [14, 9], + [14, 13], + [15, 16], + [16, 11], + [16, 15], + [16, 17], + [17, 16], + [17, 18], + [18, 13], + [18, 17], + [18, 19], + [19, 18], + ] + + backend = GenericBackendV2( + num_qubits=20, coupling_map=coupling_map, basis_gates=["id", "u1", "u2", "u3", "cx"] + ) initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( - Fake20QV1(), + backend, initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) @@ -133,12 +184,63 @@ def test_default_pass_manager_two(self): circuit2.cx(qr[0], qr[1]) circuit2.cx(qr[2], qr[3]) - coupling_map = Fake20QV1().configuration().coupling_map + coupling_map = [ + [0, 1], + [1, 0], + [1, 2], + [1, 6], + [2, 1], + [2, 3], + [3, 2], + [3, 4], + [3, 8], + [4, 3], + [5, 6], + [5, 10], + [6, 1], + [6, 5], + [6, 7], + [7, 6], + [7, 8], + [7, 12], + [8, 3], + [8, 7], + [8, 9], + [9, 8], + [9, 14], + [10, 5], + [10, 11], + [11, 10], + [11, 12], + [11, 16], + [12, 7], + [12, 11], + [12, 13], + [13, 12], + [13, 14], + [13, 18], + [14, 9], + [14, 13], + [15, 16], + [16, 11], + [16, 15], + [16, 17], + [17, 16], + [17, 18], + [18, 13], + [18, 17], + [18, 19], + [19, 18], + ] initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] + backend = GenericBackendV2( + num_qubits=20, coupling_map=coupling_map, basis_gates=["id", "u1", "u2", "u3", "cx"] + ) + pass_manager = level_1_pass_manager( PassManagerConfig.from_backend( - Fake20QV1(), + backend=backend, initial_layout=Layout.from_qubit_list(initial_layout), seed_transpiler=42, ) From 77bf474ffb4f16ea7c043e35d40ec8307eb06c67 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 12:46:25 +0200 Subject: [PATCH 033/168] test.python.transpiler.test_passmanager_config.TestPassManagerConfig.test_from_backend_and_user --- .../transpiler/test_passmanager_config.py | 76 ++++++++++++++++++- 1 file changed, 75 insertions(+), 1 deletion(-) diff --git a/test/python/transpiler/test_passmanager_config.py b/test/python/transpiler/test_passmanager_config.py index 01ec7ebf133a..7e653c18e5e2 100644 --- a/test/python/transpiler/test_passmanager_config.py +++ b/test/python/transpiler/test_passmanager_config.py @@ -51,11 +51,13 @@ def test_invalid_backend(self): with self.assertRaises(AttributeError): PassManagerConfig.from_backend(Backend()) - def test_from_backend_and_user(self): + def test_from_backend_and_user_v1(self): """Test from_backend() with a backend and user options. `FakeMelbourne` is used in this testcase. This backend does not have `defaults` attribute and thus not provide an instruction schedule map. + + REMOVE AFTER Fake20QV1 GETS REMOVED. """ qr = QuantumRegister(4, "qr") initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] @@ -72,6 +74,78 @@ def test_from_backend_and_user(self): ) self.assertEqual(config.initial_layout, initial_layout) + def test_from_backend_and_user(self): + """Test from_backend() with a backend and user options. + + `FakeMelbourne` is used in this testcase. This backend does not have + `defaults` attribute and thus not provide an instruction schedule map. + """ + qr = QuantumRegister(4, "qr") + initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] + + backend = GenericBackendV2( + num_qubits=20, + coupling_map=[ + [0, 1], + [1, 0], + [1, 2], + [1, 6], + [2, 1], + [2, 3], + [3, 2], + [3, 4], + [3, 8], + [4, 3], + [5, 6], + [5, 10], + [6, 1], + [6, 5], + [6, 7], + [7, 6], + [7, 8], + [7, 12], + [8, 3], + [8, 7], + [8, 9], + [9, 8], + [9, 14], + [10, 5], + [10, 11], + [11, 10], + [11, 12], + [11, 16], + [12, 7], + [12, 11], + [12, 13], + [13, 12], + [13, 14], + [13, 18], + [14, 9], + [14, 13], + [15, 16], + [16, 11], + [16, 15], + [16, 17], + [17, 16], + [17, 18], + [18, 13], + [18, 17], + [18, 19], + [19, 18], + ], + basis_gates=["id", "u1", "u2", "u3", "cx"], + ) + config = PassManagerConfig.from_backend( + backend, basis_gates=["user_gate"], initial_layout=initial_layout + ) + self.assertEqual(config.basis_gates, ["user_gate"]) + self.assertNotEqual(config.basis_gates, backend.configuration().basis_gates) + self.assertIsNone(config.inst_map) + self.assertEqual( + str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map)) + ) + self.assertEqual(config.initial_layout, initial_layout) + def test_from_backendv1_inst_map_is_none(self): """Test that from_backend() works with backend that has defaults defined as None.""" backend = Fake27QPulseV1() From 5dfacd36beb908eb94fdf69e9a7fcb04d506d1be Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 13:06:54 +0200 Subject: [PATCH 034/168] test.python.transpiler.test_passmanager_config --- .../transpiler/test_passmanager_config.py | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/test/python/transpiler/test_passmanager_config.py b/test/python/transpiler/test_passmanager_config.py index 7e653c18e5e2..344428158dc3 100644 --- a/test/python/transpiler/test_passmanager_config.py +++ b/test/python/transpiler/test_passmanager_config.py @@ -30,7 +30,8 @@ def test_config_from_backend(self): `Fake27QPulseV1` is used in this testcase. This backend has `defaults` attribute that contains an instruction schedule map. """ - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() config = PassManagerConfig.from_backend(backend) self.assertEqual(config.basis_gates, backend.configuration().basis_gates) self.assertEqual(config.inst_map, backend.defaults().instruction_schedule_map) @@ -62,7 +63,8 @@ def test_from_backend_and_user_v1(self): qr = QuantumRegister(4, "qr") initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] - backend = Fake20QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() config = PassManagerConfig.from_backend( backend, basis_gates=["user_gate"], initial_layout=initial_layout ) @@ -134,21 +136,21 @@ def test_from_backend_and_user(self): [19, 18], ], basis_gates=["id", "u1", "u2", "u3", "cx"], + calibrate_instructions=None, ) config = PassManagerConfig.from_backend( backend, basis_gates=["user_gate"], initial_layout=initial_layout ) self.assertEqual(config.basis_gates, ["user_gate"]) - self.assertNotEqual(config.basis_gates, backend.configuration().basis_gates) - self.assertIsNone(config.inst_map) - self.assertEqual( - str(config.coupling_map), str(CouplingMap(backend.configuration().coupling_map)) - ) + self.assertNotEqual(config.basis_gates, backend.operation_names) + self.assertEqual(config.inst_map.instructions, []) + self.assertEqual(str(config.coupling_map), str(CouplingMap(backend.coupling_map))) self.assertEqual(config.initial_layout, initial_layout) def test_from_backendv1_inst_map_is_none(self): """Test that from_backend() works with backend that has defaults defined as None.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() backend.defaults = lambda: None config = PassManagerConfig.from_backend(backend) self.assertIsInstance(config, PassManagerConfig) @@ -156,8 +158,9 @@ def test_from_backendv1_inst_map_is_none(self): def test_invalid_user_option(self): """Test from_backend() with an invalid user option.""" + backend = GenericBackendV2(num_qubits=20) with self.assertRaises(TypeError): - PassManagerConfig.from_backend(Fake20QV1(), invalid_option=None) + PassManagerConfig.from_backend(backend, invalid_option=None) def test_str(self): """Test string output.""" From d892be3b3b77b7bc3c6ec83e4f1b23cff8387969 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 13:46:16 +0200 Subject: [PATCH 035/168] test.python.primitives.test_backend_estimator.TestBackendEstimator --- .../primitives/test_backend_estimator.py | 20 +++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index 9725b865b4c4..ce9adada0f3b 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -297,8 +297,10 @@ def max_circuits(self): self.assertEqual(run_mock.call_count, 10) def test_job_size_limit_v1(self): - """Test BackendEstimator respects job size limit""" - backend = Fake7QPulseV1() + """Test BackendEstimator respects job size limit + REMOVE ONCE Fake7QPulseV1 GETS REMOVED""" + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() config = backend.configuration() config.max_experiments = 1 backend._configuration = config @@ -314,8 +316,10 @@ def test_job_size_limit_v1(self): self.assertEqual(run_mock.call_count, 10) def test_no_max_circuits(self): - """Test BackendEstimator works with BackendV1 and no max_experiments set.""" - backend = Fake7QPulseV1() + """Test BackendEstimator works with BackendV1 and no max_experiments set. + REMOVE ONCE Fake7QPulseV1 GETS REMOVED""" + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() config = backend.configuration() del config.max_experiments backend._configuration = config @@ -352,7 +356,9 @@ def callback(msg): bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) + estimator = BackendEstimator( + backend=GenericBackendV2(num_qubits=5, seed=42), bound_pass_manager=bound_pass + ) _ = estimator.run(qc, op).result() expected = [ "bound_pass_manager", @@ -372,7 +378,9 @@ def callback(msg): # pylint: disable=function-redefined bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) + estimator = BackendEstimator( + backend=GenericBackendV2(num_qubits=5, seed=42), bound_pass_manager=bound_pass + ) _ = estimator.run([qc, qc], [op, op]).result() expected = [ "bound_pass_manager", From 2170a9783a6b486e63ed556f3d1bdb459070a8f2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 14:23:51 +0200 Subject: [PATCH 036/168] test.python.circuit.test_scheduled_circuit.TestScheduledCircuit.test_schedule_circuit_when_backend_tells_dt --- qiskit/compiler/assembler.py | 8 +++++++ test/python/circuit/test_scheduled_circuit.py | 22 +++++++++++-------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 522e1c503ddf..aa8dd0559ab9 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -29,6 +29,7 @@ from qiskit.pulse.channels import PulseChannel from qiskit.qobj import QasmQobj, PulseQobj, QobjHeader from qiskit.qobj.utils import MeasLevel, MeasReturnType +from qiskit.utils import deprecate_func logger = logging.getLogger(__name__) @@ -39,6 +40,13 @@ def _log_assembly_time(start_time, end_time): # TODO: parallelize over the experiments (serialize each separately, then add global header/config) +@deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The function assemble is being deprecated " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that the provider is using a backend based on the deprecated BackendV1 class.", +) def assemble( experiments: Union[ QuantumCircuit, diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index fec0c58d624e..3b407e0f7939 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -53,25 +53,29 @@ def test_schedule_circuit_when_backend_tells_dt(self): qc = QuantumCircuit(2) qc.delay(0.1, 0, unit="ms") # 450000[dt] qc.delay(100, 0, unit="ns") # 450[dt] - qc.h(0) # 160[dt] - qc.h(1) # 160[dt] - sc = transpile(qc, self.backend_with_dt, scheduling_method="alap", layout_method="trivial") - self.assertEqual(sc.duration, 450546) + qc.h(0) # 195[dt] + qc.h(1) # 210[dt] + + backend = GenericBackendV2(27, calibrate_instructions=True, seed=42) + + sc = transpile(qc, backend, scheduling_method="alap", layout_method="trivial") + self.assertEqual(sc.duration, 451096) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") - self.assertEqual(sc.data[0].operation.duration, 450450) + self.assertEqual(sc.data[0].operation.duration, 450900) self.assertEqual(sc.data[0].operation.unit, "dt") self.assertEqual(sc.data[1].operation.name, "rz") self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") - self.assertEqual(sc.data[4].operation.duration, 450450) + self.assertEqual(sc.data[4].operation.duration, 450928) self.assertEqual(sc.data[4].operation.unit, "dt") - qobj = assemble(sc, self.backend_with_dt) + with self.assertWarns(DeprecationWarning): + qobj = assemble(sc, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") - self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450450) + self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450900) self.assertEqual(qobj.experiments[0].instructions[4].name, "delay") - self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450450) + self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450928) def test_schedule_circuit_when_transpile_option_tells_dt(self): """dt is known to transpiler by transpile option""" From a21ee828f763eb917a312c7def3d52c017f2a82b Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 19:37:17 +0200 Subject: [PATCH 037/168] test.python.circuit.test_scheduled_circuit --- test/python/circuit/test_scheduled_circuit.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index 3b407e0f7939..fd321d00498a 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -51,7 +51,7 @@ def setUp(self): def test_schedule_circuit_when_backend_tells_dt(self): """dt is known to transpiler by backend""" qc = QuantumCircuit(2) - qc.delay(0.1, 0, unit="ms") # 450000[dt] + qc.delay(0.1, 0, unit="ms") # 450450[dt] qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) # 195[dt] qc.h(1) # 210[dt] @@ -124,7 +124,7 @@ def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): self.assertEqual(sc.data[4].operation.name, "delay") self.assertAlmostEqual(sc.data[4].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[4].operation.unit, "s") - with self.assertRaises(QiskitError): + with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): assemble(sc, self.backend_without_dt) def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self): @@ -382,7 +382,8 @@ def test_transpile_and_assemble_delay_circuit_for_simulator(self): qc.delay(100, 0, "ns") circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled - qobj = assemble(circ, self.simulator_backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7) @@ -394,7 +395,8 @@ def test_transpile_and_assemble_t1_circuit_for_simulator(self): qc.measure(0, 0) circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled - qobj = assemble(circ, self.simulator_backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertAlmostEqual(qobj.experiments[0].instructions[1].params[0], 1e-7) @@ -420,7 +422,8 @@ def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween qc.measure(0, 0) circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) - qobj = assemble(circ, self.backend_with_dt) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertEqual(qobj.experiments[0].instructions[1].params[0], 450) @@ -445,7 +448,7 @@ def test_fail_to_assemble_circuits_with_unbounded_parameters(self): qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = transpile(qc, self.backend_with_dt) - with self.assertRaises(QiskitError): + with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): assemble(qc, self.backend_with_dt) @data("asap", "alap") From 21540a59196e2c9e51bbe41648fb7f8312d5bcd2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 26 Jun 2024 22:23:34 +0200 Subject: [PATCH 038/168] test.python.transpiler.test_vf2_layout --- test/python/transpiler/test_vf2_layout.py | 26 ++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/test/python/transpiler/test_vf2_layout.py b/test/python/transpiler/test_vf2_layout.py index 6d170ee9a13e..4e4844f5f701 100644 --- a/test/python/transpiler/test_vf2_layout.py +++ b/test/python/transpiler/test_vf2_layout.py @@ -688,9 +688,11 @@ def test_time_limit_exceeded(self): self.assertEqual(set(property_set["layout"].get_physical_bits()), {2, 0}) - def test_reasonable_limits_for_simple_layouts(self): - """Test that the default trials is set to a reasonable number.""" - backend = Fake127QPulseV1() + def test_reasonable_limits_for_simple_layouts_v1(self): + """Test that the default trials is set to a reasonable number. + REMOVE ONCE Fake127QPulseV1 IS GONE""" + with self.assertWarns(DeprecationWarning): + backend = Fake127QPulseV1() qc = QuantumCircuit(5) qc.cx(2, 3) qc.cx(0, 1) @@ -707,6 +709,24 @@ def test_reasonable_limits_for_simple_layouts(self): ) self.assertEqual(set(property_set["layout"].get_physical_bits()), {57, 58, 61, 62, 0}) + def test_reasonable_limits_for_simple_layouts(self): + """Test that the default trials is set to a reasonable number.""" + backend = GenericBackendV2(27, calibrate_instructions=True, seed=42) + qc = QuantumCircuit(5) + qc.cx(2, 3) + qc.cx(0, 1) + + # Run without any limits set + vf2_pass = VF2Layout(target=backend.target, seed=42) + property_set = {} + with self.assertLogs("qiskit.transpiler.passes.layout.vf2_layout", level="DEBUG") as cm: + vf2_pass(qc, property_set) + self.assertIn( + "DEBUG:qiskit.transpiler.passes.layout.vf2_layout:Trial 717 is >= configured max trials 717", + cm.output, + ) + self.assertEqual(set(property_set["layout"].get_physical_bits()), {16, 24, 6, 7, 0}) + def test_no_limits_with_negative(self): """Test that we're not enforcing a trial limit if set to negative.""" with self.assertWarns(DeprecationWarning): From a39842550b6aa2a80905d2c3c9d23c956e2071d3 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 27 Jun 2024 16:19:55 +0200 Subject: [PATCH 039/168] shallow deprecation of assemble --- qiskit/assembler/assemble_circuits.py | 142 +++++++++++------- qiskit/circuit/instruction.py | 17 ++- qiskit/compiler/assembler.py | 85 +++++++++-- .../basic_provider/basic_simulator.py | 4 +- qiskit/qobj/common.py | 2 +- qiskit/result/models.py | 5 +- qiskit/result/result.py | 4 +- 7 files changed, 186 insertions(+), 73 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index a3d9b6bbb549..13187089d631 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -12,6 +12,7 @@ """Assemble function for converting a list of circuits into a qobj.""" import copy +import warnings from collections import defaultdict from typing import Dict, List, Optional, Tuple @@ -35,6 +36,7 @@ QobjHeader, ) from qiskit.utils.parallel import parallel_map +from qiskit.utils import deprecate_func PulseLibrary = Dict[str, List[complex]] @@ -87,20 +89,24 @@ def _assemble_circuit( metadata = circuit.metadata if metadata is None: metadata = {} - header = QobjExperimentHeader( - qubit_labels=qubit_labels, - n_qubits=num_qubits, - qreg_sizes=qreg_sizes, - clbit_labels=clbit_labels, - memory_slots=memory_slots, - creg_sizes=creg_sizes, - name=circuit.name, - global_phase=float(circuit.global_phase), - metadata=metadata, - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + header = QobjExperimentHeader( + qubit_labels=qubit_labels, + n_qubits=num_qubits, + qreg_sizes=qreg_sizes, + clbit_labels=clbit_labels, + memory_slots=memory_slots, + creg_sizes=creg_sizes, + name=circuit.name, + global_phase=float(circuit.global_phase), + metadata=metadata, + ) # TODO: why do we need n_qubits and memory_slots in both the header and the config - config = QasmQobjExperimentConfig(n_qubits=num_qubits, memory_slots=memory_slots) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + config = QasmQobjExperimentConfig(n_qubits=num_qubits, memory_slots=memory_slots) calibrations, pulse_library = _assemble_pulse_gates(circuit, run_config) if calibrations: config.calibrations = calibrations @@ -118,7 +124,7 @@ def _assemble_circuit( instructions = [] for op_context in circuit.data: - instruction = op_context.operation.assemble() + instruction = op_context.operation._assemble() # Add register attributes to the instruction qargs = op_context.qubits @@ -166,10 +172,12 @@ def _assemble_circuit( del instruction._condition instructions.append(instruction) - return ( - QasmQobjExperiment(instructions=instructions, header=header, config=config), - pulse_library, - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + return ( + QasmQobjExperiment(instructions=instructions, header=header, config=config), + pulse_library, + ) def _assemble_pulse_gates( @@ -299,41 +307,9 @@ def _configure_experiment_los( return experiments -def assemble_circuits( +def _assemble_circuits( circuits: List[QuantumCircuit], run_config: RunConfig, qobj_id: int, qobj_header: QobjHeader ) -> QasmQobj: - """Assembles a list of circuits into a qobj that can be run on the backend. - - Args: - circuits: circuit(s) to assemble - run_config: configuration of the runtime environment - qobj_id: identifier for the generated qobj - qobj_header: header to pass to the results - - Returns: - The qobj to be run on the backends - - Examples: - - .. code-block:: python - - from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit - from qiskit.assembler import assemble_circuits - from qiskit.assembler.run_config import RunConfig - # Build a circuit to convert into a Qobj - q = QuantumRegister(2) - c = ClassicalRegister(2) - qc = QuantumCircuit(q, c) - qc.h(q[0]) - qc.cx(q[0], q[1]) - qc.measure(q, c) - # Assemble a Qobj from the input circuit - qobj = assemble_circuits(circuits=[qc], - qobj_id="custom-id", - qobj_header=[], - run_config=RunConfig(shots=2000, memory=True, init_qubits=True)) - """ - # assemble the circuit experiments experiments_and_pulse_libs = parallel_map(_assemble_circuit, circuits, [run_config]) experiments = [] pulse_library = {} @@ -346,10 +322,16 @@ def assemble_circuits( experiments, calibrations = _extract_common_calibrations(experiments) # configure LO freqs per circuit - lo_converter = converters.LoConfigConverter(QasmQobjExperimentConfig, **run_config.to_dict()) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + lo_converter = converters.LoConfigConverter( + QasmQobjExperimentConfig, **run_config.to_dict() + ) experiments = _configure_experiment_los(experiments, lo_converter, run_config) - qobj_config = QasmQobjConfig() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + qobj_config = QasmQobjConfig() if run_config: qobj_config_dict = run_config.to_dict() @@ -379,7 +361,9 @@ def assemble_circuits( if m_los: qobj_config_dict["meas_lo_freq"] = [freq / 1e9 for freq in m_los] - qobj_config = QasmQobjConfig(**qobj_config_dict) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + qobj_config = QasmQobjConfig(**qobj_config_dict) qubit_sizes = [] memory_slot_sizes = [] @@ -402,7 +386,53 @@ def assemble_circuits( if calibrations and calibrations.gates: qobj_config.calibrations = calibrations + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + return QasmQobj( + qobj_id=qobj_id, config=qobj_config, experiments=experiments, header=qobj_header + ) - return QasmQobj( - qobj_id=qobj_id, config=qobj_config, experiments=experiments, header=qobj_header - ) + +@deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The function assemble_circuits is being deprecated " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", +) +def assemble_circuits( + circuits: List[QuantumCircuit], run_config: RunConfig, qobj_id: int, qobj_header: QobjHeader +) -> QasmQobj: + """Assembles a list of circuits into a qobj that can be run on the backend. + + Args: + circuits: circuit(s) to assemble + run_config: configuration of the runtime environment + qobj_id: identifier for the generated qobj + qobj_header: header to pass to the results + + Returns: + The qobj to be run on the backends + + Examples: + + .. code-block:: python + + from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit + from qiskit.assembler import assemble_circuits + from qiskit.assembler.run_config import RunConfig + # Build a circuit to convert into a Qobj + q = QuantumRegister(2) + c = ClassicalRegister(2) + qc = QuantumCircuit(q, c) + qc.h(q[0]) + qc.cx(q[0], q[1]) + qc.measure(q, c) + # Assemble a Qobj from the input circuit + qobj = assemble_circuits(circuits=[qc], + qobj_id="custom-id", + qobj_header=[], + run_config=RunConfig(shots=2000, memory=True, init_qubits=True)) + """ + # assemble the circuit experiments + return _assemble_circuits(circuits, run_config, qobj_id, qobj_header) diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index 1b5fca3f738b..2e1ae9ae7235 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -34,6 +34,7 @@ from __future__ import annotations import copy +import warnings from itertools import zip_longest import math from typing import List, Type @@ -47,7 +48,7 @@ from qiskit.circuit.operation import Operation from qiskit.circuit.annotated_operation import AnnotatedOperation, InverseModifier - +from qiskit.utils import deprecate_func _CUTOFF_PRECISION = 1e-10 @@ -358,9 +359,21 @@ def unit(self, unit): """Set the time unit of duration.""" self._unit = unit + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The method assemble is being deprecated " + "as it is not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) def assemble(self): """Assemble a QasmQobjInstruction""" - instruction = QasmQobjInstruction(name=self.name) + return self._assemble() + + def _assemble(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + instruction = QasmQobjInstruction(name=self.name) # Evaluate parameters if self.params: params = [x.evalf(x) if hasattr(x, "evalf") else x for x in self.params] diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 4417c0666fb4..3b6b22e11b86 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -20,7 +20,7 @@ import numpy as np -from qiskit.assembler import assemble_circuits, assemble_schedules +from qiskit.assembler import assemble_schedules from qiskit.assembler.run_config import RunConfig from qiskit.circuit import Parameter, QuantumCircuit, Qubit from qiskit.exceptions import QiskitError @@ -30,6 +30,7 @@ from qiskit.qobj import QasmQobj, PulseQobj, QobjHeader from qiskit.qobj.utils import MeasLevel, MeasReturnType from qiskit.utils import deprecate_func +from qiskit.assembler.assemble_circuits import _assemble_circuits logger = logging.getLogger(__name__) @@ -89,7 +90,7 @@ def assemble( to create ``Qobj`` "experiments". It further annotates the experiment payload with header and configurations. - NOTE: Backend.options is not used within assemble. The required values + NOTE: ``Backend.options`` is not used within assemble. The required values (previously given by backend.set_options) should be manually extracted from options and supplied directly when calling. @@ -161,27 +162,91 @@ def assemble( Raises: QiskitError: if the input cannot be interpreted as either circuits or schedules """ - start_time = time() - experiments = experiments if isinstance(experiments, list) else [experiments] - pulse_qobj = any(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments) - qobj_id, qobj_header, run_config_common_dict = _parse_common_args( + return _assemble( + experiments, backend, qobj_id, qobj_header, shots, memory, seed_simulator, - init_qubits, - rep_delay, qubit_lo_freq, meas_lo_freq, qubit_lo_range, meas_lo_range, schedule_los, - pulse_qobj=pulse_qobj, + meas_level, + meas_return, + meas_map, + memory_slot_size, + rep_time, + rep_delay, + parameter_binds, + parametric_pulses, + init_qubits, **run_config, ) + +def _assemble( + experiments: Union[ + QuantumCircuit, + List[QuantumCircuit], + Schedule, + List[Schedule], + ScheduleBlock, + List[ScheduleBlock], + ], + backend: Optional[Backend] = None, + qobj_id: Optional[str] = None, + qobj_header: Optional[Union[QobjHeader, Dict]] = None, + shots: Optional[int] = None, + memory: Optional[bool] = False, + seed_simulator: Optional[int] = None, + qubit_lo_freq: Optional[List[float]] = None, + meas_lo_freq: Optional[List[float]] = None, + qubit_lo_range: Optional[List[float]] = None, + meas_lo_range: Optional[List[float]] = None, + schedule_los: Optional[ + Union[ + List[Union[Dict[PulseChannel, float], LoConfig]], + Union[Dict[PulseChannel, float], LoConfig], + ] + ] = None, + meas_level: Union[int, MeasLevel] = MeasLevel.CLASSIFIED, + meas_return: Union[str, MeasReturnType] = MeasReturnType.AVERAGE, + meas_map: Optional[List[List[Qubit]]] = None, + memory_slot_size: int = 100, + rep_time: Optional[int] = None, + rep_delay: Optional[float] = None, + parameter_binds: Optional[List[Dict[Parameter, float]]] = None, + parametric_pulses: Optional[List[str]] = None, + init_qubits: bool = True, + **run_config: Dict, +) -> Union[QasmQobj, PulseQobj]: + start_time = time() + experiments = experiments if isinstance(experiments, list) else [experiments] + pulse_qobj = any(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + qobj_id, qobj_header, run_config_common_dict = _parse_common_args( + backend, + qobj_id, + qobj_header, + shots, + memory, + seed_simulator, + init_qubits, + rep_delay, + qubit_lo_freq, + meas_lo_freq, + qubit_lo_range, + meas_lo_range, + schedule_los, + pulse_qobj=pulse_qobj, + **run_config, + ) + # assemble either circuits or schedules if all(isinstance(exp, QuantumCircuit) for exp in experiments): run_config = _parse_circuit_args( @@ -199,7 +264,7 @@ def assemble( ) end_time = time() _log_assembly_time(start_time, end_time) - return assemble_circuits( + return _assemble_circuits( circuits=bound_experiments, qobj_id=qobj_id, qobj_header=qobj_header, diff --git a/qiskit/providers/basic_provider/basic_simulator.py b/qiskit/providers/basic_provider/basic_simulator.py index 9971bf36725c..1d1205294677 100644 --- a/qiskit/providers/basic_provider/basic_simulator.py +++ b/qiskit/providers/basic_provider/basic_simulator.py @@ -525,7 +525,7 @@ def run( } """ # TODO: replace assemble with new run flow - from qiskit.compiler import assemble + from qiskit.compiler.assembler import _assemble out_options = {} for key, value in backend_options.items(): @@ -535,7 +535,7 @@ def run( ) else: out_options[key] = value - qobj = assemble(run_input, self, **out_options) + qobj = _assemble(run_input, self, **out_options) qobj_options = qobj.config self._set_options(qobj_config=qobj_options, backend_options=backend_options) job_id = str(uuid.uuid4()) diff --git a/qiskit/qobj/common.py b/qiskit/qobj/common.py index f9abb32282b5..9a3fdd4e20e2 100644 --- a/qiskit/qobj/common.py +++ b/qiskit/qobj/common.py @@ -26,7 +26,7 @@ class QobjDictField(SimpleNamespace): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QobjDictField subclasses, " + additional_msg="The full Qobj module is being deprecated, including QobjDictField's subclasses, " "as they are not necessary for BackendV2. If user still need Qobj, that probably " "means that they are using a backend based on the deprecated BackendV1 class.", ) diff --git a/qiskit/result/models.py b/qiskit/result/models.py index 83d9e4e78d5f..3eabbdd2f14f 100644 --- a/qiskit/result/models.py +++ b/qiskit/result/models.py @@ -13,6 +13,7 @@ """Schema and helper models for schema-conformant Results.""" import copy +import warnings from qiskit.qobj.utils import MeasReturnType, MeasLevel from qiskit.qobj import QobjExperimentHeader @@ -223,7 +224,9 @@ def from_dict(cls, data): in_data = copy.copy(data) data_obj = ExperimentResultData.from_dict(in_data.pop("data")) if "header" in in_data: - in_data["header"] = QobjExperimentHeader.from_dict(in_data.pop("header")) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + in_data["header"] = QobjExperimentHeader.from_dict(in_data.pop("header")) shots = in_data.pop("shots") success = in_data.pop("success") diff --git a/qiskit/result/result.py b/qiskit/result/result.py index 7df365785166..1f8519c4b469 100644 --- a/qiskit/result/result.py +++ b/qiskit/result/result.py @@ -125,7 +125,9 @@ def from_dict(cls, data): in_data = copy.copy(data) in_data["results"] = [ExperimentResult.from_dict(x) for x in in_data.pop("results")] if in_data.get("header") is not None: - in_data["header"] = QobjHeader.from_dict(in_data.pop("header")) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + in_data["header"] = QobjHeader.from_dict(in_data.pop("header")) return cls(**in_data) def data(self, experiment=None): From 6d96cc8a6d3d317eb33045f9deffd79db9ff90da Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 27 Jun 2024 16:42:30 +0200 Subject: [PATCH 040/168] test.python.compiler.test_disassembler --- qiskit/assembler/disassemble.py | 8 ++ test/benchmarks/assembler.py | 2 + test/python/compiler/test_disassembler.py | 134 +++++++++++++--------- 3 files changed, 90 insertions(+), 54 deletions(-) diff --git a/qiskit/assembler/disassemble.py b/qiskit/assembler/disassemble.py index 127bbd35eb26..8f296a42d9bf 100644 --- a/qiskit/assembler/disassemble.py +++ b/qiskit/assembler/disassemble.py @@ -23,6 +23,7 @@ from qiskit.qobj import PulseQobjInstruction from qiskit.qobj.converters import QobjToInstructionConverter +from qiskit.utils import deprecate_func # A ``CircuitModule`` is a representation of a circuit execution on the backend. # It is currently a list of quantum circuits to execute, a run Qobj dictionary @@ -37,6 +38,13 @@ PulseModule = NewType("PulseModule", Tuple[List[pulse.Schedule], Dict[str, Any], Dict[str, Any]]) +@deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The function disassemble is being deprecated " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", +) def disassemble(qobj) -> Union[CircuitModule, PulseModule]: """Disassemble a qobj and return the circuits or pulse schedules, run_config, and user header. diff --git a/test/benchmarks/assembler.py b/test/benchmarks/assembler.py index 3899c05e92bb..03d349088c86 100644 --- a/test/benchmarks/assembler.py +++ b/test/benchmarks/assembler.py @@ -46,4 +46,6 @@ def setup(self, n_qubits, depth, number_of_circuits): self.qobj = assemble(self.circuits) def time_disassemble_circuit(self, _, __, ___): + # TODO: QObj is getting deprecated. Remove once that happens + # https://github.com/Qiskit/qiskit/pull/12649 disassemble(self.qobj) diff --git a/test/python/compiler/test_disassembler.py b/test/python/compiler/test_disassembler.py index e575c021adca..0525b54e2107 100644 --- a/test/python/compiler/test_disassembler.py +++ b/test/python/compiler/test_disassembler.py @@ -10,7 +10,9 @@ # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. -"""Assembler Test.""" +"""Assembler Test. +FULLY REMOVE ONCE Qobj, assemble AND disassemble ARE REMOVED. +""" import unittest @@ -55,14 +57,15 @@ def test_disassemble_single_circuit(self): qubit_lo_freq = [5e9, 5e9] meas_lo_freq = [6.7e9, 6.7e9] - qobj = assemble( - circ, - shots=2000, - memory=True, - qubit_lo_freq=qubit_lo_freq, - meas_lo_freq=meas_lo_freq, - ) - circuits, run_config_out, headers = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + circ, + shots=2000, + memory=True, + qubit_lo_freq=qubit_lo_freq, + meas_lo_freq=meas_lo_freq, + ) + circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) @@ -91,8 +94,9 @@ def test_disassemble_multiple_circuits(self): circ1.cx(qr1[0], qr1[2]) circ1.measure(qr1, qc1) - qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6) - circuits, run_config_out, headers = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble([circ0, circ1], shots=100, memory=False, seed=6) + circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 3) self.assertEqual(run_config_out.memory_slots, 3) @@ -113,8 +117,9 @@ def test_disassemble_no_run_config(self): circ.cx(qr[0], qr[1]) circ.measure(qr, qc) - qobj = assemble(circ) - circuits, run_config_out, headers = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ) + circuits, run_config_out, headers = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) @@ -128,8 +133,9 @@ def test_disassemble_initialize(self): circ = QuantumCircuit(q, name="circ") circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:]) - qobj = assemble(circ) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 0) @@ -142,8 +148,9 @@ def test_disassemble_isometry(self): q = QuantumRegister(2, name="q") circ = QuantumCircuit(q, name="circ") circ.append(Isometry(qi.random_unitary(4).data, 0, 0), circ.qubits) - qobj = assemble(circ) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 0) @@ -166,8 +173,9 @@ def test_opaque_instruction(self): c = ClassicalRegister(4, name="c") circ = QuantumCircuit(q, c, name="circ") circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]]) - qobj = assemble(circ) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 6) self.assertEqual(run_config_out.memory_slots, 4) @@ -184,8 +192,9 @@ def test_circuit_with_conditionals(self): qc.measure(qr[0], cr1) # Measure not required for a later conditional qc.measure(qr[1], cr2[1]) # Measure required for a later conditional qc.h(qr[1]).c_if(cr2, 3) - qobj = assemble(qc) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 3) @@ -199,8 +208,9 @@ def test_circuit_with_simple_conditional(self): cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr, 1) - qobj = assemble(qc) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 1) self.assertEqual(run_config_out.memory_slots, 1) @@ -219,8 +229,10 @@ def test_circuit_with_single_bit_conditions(self): cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[0], 1) - qobj = assemble(qc) - circuits, run_config_out, header = disassemble(qobj) + + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, len(qr)) self.assertEqual(run_config_out.memory_slots, len(cr)) @@ -234,8 +246,9 @@ def test_circuit_with_mcx(self): cr = ClassicalRegister(5) qc = QuantumCircuit(qr, cr) qc.mcx([0, 1, 2], 4) - qobj = assemble(qc) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 5) self.assertEqual(run_config_out.memory_slots, 5) @@ -257,8 +270,9 @@ def test_multiple_conditionals_multiple_registers(self): qc.cx(qr[1], qr[0]).c_if(cr3, 14) qc.ccx(qr[0], qr[2], qr[1]).c_if(cr4, 1) qc.h(qr).c_if(cr1, 3) - qobj = assemble(qc) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 3) self.assertEqual(run_config_out.memory_slots, 15) @@ -272,8 +286,9 @@ def test_circuit_with_bit_conditional_1(self): cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) qc.h(qr[0]).c_if(cr[1], True) - qobj = assemble(qc) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 2) @@ -290,8 +305,9 @@ def test_circuit_with_bit_conditional_2(self): qc.h(qr[0]).c_if(cr1[1], False) qc.h(qr[1]).c_if(cr[0], True) qc.cx(qr[0], qr[1]).c_if(cr1[0], False) - qobj = assemble(qc) - circuits, run_config_out, header = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) + circuits, run_config_out, header = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.n_qubits, 2) self.assertEqual(run_config_out.memory_slots, 4) @@ -330,8 +346,9 @@ def test_single_circuit_calibrations(self): qc.add_calibration("h", [0], h_sched) qc.add_calibration(RXGate(np.pi), [0], x180) - qobj = assemble(qc, FakeOpenPulse2Q()) - output_circuits, _, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc, FakeOpenPulse2Q()) + output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual([qc], output_circuits) @@ -344,11 +361,12 @@ def test_parametric_pulse_circuit_calibrations(self): qc.h(0) qc.add_calibration("h", [0], h_sched) - backend = FakeOpenPulse2Q() - backend.configuration().parametric_pulses = ["drag"] + with self.assertWarns(DeprecationWarning): + backend = FakeOpenPulse2Q() + backend.configuration().parametric_pulses = ["drag"] - qobj = assemble(qc, backend) - output_circuits, _, _ = disassemble(qobj) + qobj = assemble(qc, backend) + output_circuits, _, _ = disassemble(qobj) out_qc = output_circuits[0] self.assertCircuitCalibrationsEqual([qc], output_circuits) @@ -377,8 +395,9 @@ def test_multi_circuit_uncommon_calibrations(self): qc_1.h(0) circuits = [qc_0, qc_1] - qobj = assemble(circuits, FakeOpenPulse2Q()) - output_circuits, _, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circuits, FakeOpenPulse2Q()) + output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual(circuits, output_circuits) @@ -398,8 +417,9 @@ def test_multi_circuit_common_calibrations(self): qc_1.add_calibration(RXGate(np.pi), [1], sched) circuits = [qc_0, qc_1] - qobj = assemble(circuits, FakeOpenPulse2Q()) - output_circuits, _, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circuits, FakeOpenPulse2Q()) + output_circuits, _, _ = disassemble(qobj) self.assertCircuitCalibrationsEqual(circuits, output_circuits) @@ -413,8 +433,9 @@ def test_single_circuit_delay_calibrations(self): qc.add_calibration("test", [0], test_sched) - qobj = assemble(qc, FakeOpenPulse2Q()) - output_circuits, _, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc, FakeOpenPulse2Q()) + output_circuits, _, _ = disassemble(qobj) self.assertEqual(len(qc.calibrations), len(output_circuits[0].calibrations)) self.assertEqual(qc.calibrations.keys(), output_circuits[0].calibrations.keys()) @@ -436,7 +457,8 @@ class TestPulseScheduleDisassembler(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"] @@ -456,8 +478,9 @@ def test_disassemble_single_schedule(self): pulse.play(pulse.library.Constant(8, 0.1), d1) pulse.measure_all() - qobj = assemble(sched, backend=self.backend, shots=2000) - scheds, run_config_out, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(sched, backend=self.backend, shots=2000) + scheds, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) @@ -498,8 +521,9 @@ def test_disassemble_multiple_schedules(self): pulse.play(pulse.library.Constant(8, 0.4), d1) pulse.measure_all() - qobj = assemble([sched0, sched1], backend=self.backend, shots=2000) - scheds, run_config_out, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble([sched0, sched1], backend=self.backend, shots=2000) + scheds, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.memory_slots, 2) self.assertEqual(run_config_out.shots, 2000) @@ -518,8 +542,9 @@ def test_disassemble_parametric_pulses(self): pulse.play(pulse.library.GaussianSquare(10, 1.0, 2.0, 3), d0) pulse.play(pulse.library.Drag(10, 1.0, 2.0, 0.1), d0) - qobj = assemble(sched, backend=self.backend, shots=2000) - scheds, _, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble(sched, backend=self.backend, shots=2000) + scheds, _, _ = disassemble(qobj) self.assertEqual(scheds[0], target_qobj_transform(sched)) def test_disassemble_schedule_los(self): @@ -536,8 +561,9 @@ def test_disassemble_schedule_los(self): {d0: 4.5e9, d1: 5e9, m0: 6e9, m1: 7e9}, {d0: 5e9, d1: 4.5e9, m0: 7e9, m1: 6e9}, ] - qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los) - _, run_config_out, _ = disassemble(qobj) + with self.assertWarns(DeprecationWarning): + qobj = assemble([sched0, sched1], backend=self.backend, schedule_los=schedule_los) + _, run_config_out, _ = disassemble(qobj) run_config_out = RunConfig(**run_config_out) self.assertEqual(run_config_out.schedule_los, schedule_los) From e0a39995a091e9ca8314132cc7cc4f14b96d289a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 28 Jun 2024 12:39:12 +0200 Subject: [PATCH 041/168] fakebackend pulse --- qiskit/providers/fake_provider/fake_backend.py | 3 +++ qiskit/providers/models/pulsedefaults.py | 11 +++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 4a638f315574..5523d123e073 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -120,6 +120,9 @@ def properties(self): @classmethod def _default_options(cls): + # with warnings.catch_warnings(): + # Remove this + # warnings.simplefilter("ignore", category=DeprecationWarning) if _optionals.HAS_AER: from qiskit_aer import QasmSimulator diff --git a/qiskit/providers/models/pulsedefaults.py b/qiskit/providers/models/pulsedefaults.py index 7c1864bad9ee..4edfc5f2c065 100644 --- a/qiskit/providers/models/pulsedefaults.py +++ b/qiskit/providers/models/pulsedefaults.py @@ -12,6 +12,7 @@ """Model and schema for pulse defaults.""" +import warnings from typing import Any, Dict, List from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap, PulseQobjDef @@ -282,10 +283,12 @@ def from_dict(cls, data): in_data = {} for key, value in data.items(): if key in schema: - if isinstance(value, list): - in_data[key] = list(map(schema[key].from_dict, value)) - else: - in_data[key] = schema[key].from_dict(value) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + if isinstance(value, list): + in_data[key] = list(map(schema[key].from_dict, value)) + else: + in_data[key] = schema[key].from_dict(value) else: in_data[key] = value From 79f67c2fb7ad1eac7801fd01d08461548b7be309 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 28 Jun 2024 13:20:35 +0200 Subject: [PATCH 042/168] test.python.circuit.test_parameters --- test/python/circuit/test_parameters.py | 53 ++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 8 deletions(-) diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index f580416eccf5..d977aa30089f 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -793,7 +793,8 @@ def test_circuit_generation(self): theta_list = numpy.linspace(0, numpy.pi, 20) for theta_i in theta_list: circs.append(qc_aer.assign_parameters({theta: theta_i})) - qobj = assemble(circs) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circs) for index, theta_i in enumerate(theta_list): res = float(qobj.experiments[index].instructions[0].params[0]) self.assertTrue(math.isclose(res, theta_i), f"{res} != {theta_i}") @@ -980,8 +981,9 @@ def test_parameter_equality_to_expression(self, ptype): self.assertEqual(hash(x1), hash(x1_expr)) self.assertEqual(hash(x2), hash(x2_expr)) - def test_binding_parameterized_circuits_built_in_multiproc(self): - """Verify subcircuits built in a subprocess can still be bound.""" + def test_binding_parameterized_circuits_built_in_multiproc_(self): + """Verify subcircuits built in a subprocess can still be bound. + REMOVE this test once assemble is REMOVED""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2429 num_processes = 4 @@ -1001,11 +1003,12 @@ def test_binding_parameterized_circuits_built_in_multiproc(self): parameter_values = [{x: 1.0 for x in parameters}] - qobj = assemble( - circuit, - backend=BasicSimulator(), - parameter_binds=parameter_values, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + circuit, + backend=BasicSimulator(), + parameter_binds=parameter_values, + ) self.assertEqual(len(qobj.experiments), 1) self.assertEqual(len(qobj.experiments[0].instructions), 4) @@ -1018,6 +1021,40 @@ def test_binding_parameterized_circuits_built_in_multiproc(self): ) ) + def test_binding_parameterized_circuits_built_in_multiproc(self): + """Verify subcircuits built in a subprocess can still be bound. + REMOVE this test once assemble is REMOVED""" + # ref: https://github.com/Qiskit/qiskit-terra/issues/2429 + + num_processes = 4 + + qr = QuantumRegister(3) + cr = ClassicalRegister(3) + + circuit = QuantumCircuit(qr, cr) + parameters = [Parameter(f"x{i}") for i in range(num_processes)] + + results = parallel_map( + _construct_circuit, parameters, task_args=(qr,), num_processes=num_processes + ) + + for qc in results: + circuit.compose(qc, inplace=True) + + parameter_values = {x: 1.0 for x in parameters} + + bind_circuit = circuit.assign_parameters(parameter_values) + + self.assertEqual(len(bind_circuit.data), 4) + self.assertTrue( + all( + len(inst.operation.params) == 1 + and isinstance(inst.operation.params[0], float) + and float(inst.operation.params[0]) == 1 + for inst in bind_circuit.data + ) + ) + def test_transpiling_multiple_parameterized_circuits(self): """Verify several parameterized circuits can be transpiled at once.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2864 From 2bba185b99ae1fbaeccd8540a609f2671bf4ddc1 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 28 Jun 2024 17:26:52 +0200 Subject: [PATCH 043/168] PulseQobjInstruction is used by GenericBackendV2 --- .../fake_provider/generic_backend_v2.py | 47 +++++++++++-------- test/python/circuit/test_diagonal_gate.py | 12 +++-- test/python/circuit/test_hamiltonian_gate.py | 6 ++- 3 files changed, 39 insertions(+), 26 deletions(-) diff --git a/qiskit/providers/fake_provider/generic_backend_v2.py b/qiskit/providers/fake_provider/generic_backend_v2.py index 214754080e57..f20ac772eac1 100644 --- a/qiskit/providers/fake_provider/generic_backend_v2.py +++ b/qiskit/providers/fake_provider/generic_backend_v2.py @@ -253,27 +253,36 @@ def _get_calibration_sequence( # Note that the calibration pulses are different for # 1q gates vs 2q gates vs measurement instructions. if inst == "measure": - sequence = [ - PulseQobjInstruction( - name="acquire", - duration=1792, - t0=0, - qubits=qargs, - memory_slot=qargs, - ) - ] + [PulseQobjInstruction(name=pulse_library[1].name, ch=f"m{i}", t0=0) for i in qargs] - return sequence - if num_qubits == 1: + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + # TODO move away from deprecated PulseQobjInstruction + sequence = [ + PulseQobjInstruction( + name="acquire", + duration=1792, + t0=0, + qubits=qargs, + memory_slot=qargs, + ) + ] + [ + PulseQobjInstruction(name=pulse_library[1].name, ch=f"m{i}", t0=0) + for i in qargs + ] + return sequence + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + # TODO: move away from deprecated PulseQobjInstruction + if num_qubits == 1: + return [ + PulseQobjInstruction(name="fc", ch=f"u{qargs[0]}", t0=0, phase="-P0"), + PulseQobjInstruction(name=pulse_library[0].name, ch=f"d{qargs[0]}", t0=0), + ] return [ - PulseQobjInstruction(name="fc", ch=f"u{qargs[0]}", t0=0, phase="-P0"), - PulseQobjInstruction(name=pulse_library[0].name, ch=f"d{qargs[0]}", t0=0), + PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[0]}", t0=0), + PulseQobjInstruction(name=pulse_library[2].name, ch=f"u{qargs[0]}", t0=0), + PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[1]}", t0=0), + PulseQobjInstruction(name="fc", ch=f"d{qargs[1]}", t0=0, phase=2.1), ] - return [ - PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[0]}", t0=0), - PulseQobjInstruction(name=pulse_library[2].name, ch=f"u{qargs[0]}", t0=0), - PulseQobjInstruction(name=pulse_library[1].name, ch=f"d{qargs[1]}", t0=0), - PulseQobjInstruction(name="fc", ch=f"d{qargs[1]}", t0=0, phase=2.1), - ] def _generate_calibration_defaults(self) -> PulseDefaults: """Generate pulse calibration defaults as specified with `self._calibrate_instructions`. diff --git a/test/python/circuit/test_diagonal_gate.py b/test/python/circuit/test_diagonal_gate.py index 57a5d5966c7e..de8d53e12d3b 100644 --- a/test/python/circuit/test_diagonal_gate.py +++ b/test/python/circuit/test_diagonal_gate.py @@ -75,11 +75,13 @@ def test_npcomplex_params_conversion(self): all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) - qobj = assemble(qc) - params = qobj.experiments[0].instructions[0].params - self.assertTrue( - all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) - ) + with self.assertWarns(DeprecationWarning): + # REMOVE this assertion (not the full test) once ASSEMBLE is removed. + qobj = assemble(qc) + params = qobj.experiments[0].instructions[0].params + self.assertTrue( + all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) + ) def _get_diag_gate_matrix(diag): diff --git a/test/python/circuit/test_hamiltonian_gate.py b/test/python/circuit/test_hamiltonian_gate.py index 46aee007b158..60fb1e9a90a9 100644 --- a/test/python/circuit/test_hamiltonian_gate.py +++ b/test/python/circuit/test_hamiltonian_gate.py @@ -131,7 +131,8 @@ def test_3q_hamiltonian(self): np.testing.assert_almost_equal(dnode.op.to_matrix(), 1j * matrix.data) def test_qobj_with_hamiltonian(self): - """test qobj output with hamiltonian""" + """test qobj output with hamiltonian + REMOVE once Qobj gets removed""" qr = QuantumRegister(4) qc = QuantumCircuit(qr) qc.rx(np.pi / 4, qr[0]) @@ -141,7 +142,8 @@ def test_qobj_with_hamiltonian(self): qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) qc = qc.assign_parameters({theta: np.pi / 2}) - qobj = qiskit.compiler.assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "hamiltonian") # Also test label From b809acebfea83d9a13ff08087f976268bf2a13c0 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 28 Jun 2024 20:00:41 +0200 Subject: [PATCH 044/168] test.python.scheduler.test_basic_scheduler --- .../fake_provider/fake_openpulse_2q.py | 299 ++++++------ .../fake_provider/fake_openpulse_3q.py | 442 +++++++++--------- .../transpiler/test_preset_passmanagers.py | 14 +- 3 files changed, 385 insertions(+), 370 deletions(-) diff --git a/qiskit/providers/fake_provider/fake_openpulse_2q.py b/qiskit/providers/fake_provider/fake_openpulse_2q.py index caa0f53e7a38..f2b5b02f5229 100644 --- a/qiskit/providers/fake_provider/fake_openpulse_2q.py +++ b/qiskit/providers/fake_provider/fake_openpulse_2q.py @@ -14,6 +14,7 @@ Fake backend supporting OpenPulse. """ import datetime +import warnings from qiskit.providers.models import ( GateConfig, @@ -126,152 +127,158 @@ def __init__(self): description="A fake test backend with pulse defaults", ) - self._defaults = PulseDefaults.from_dict( - { - "qubit_freq_est": [4.9, 5.0], - "meas_freq_est": [6.5, 6.6], - "buffer": 10, - "pulse_library": [ - {"name": "x90p_d0", "samples": 2 * [0.1 + 0j]}, - {"name": "x90p_d1", "samples": 2 * [0.1 + 0j]}, - {"name": "x90m_d0", "samples": 2 * [-0.1 + 0j]}, - {"name": "x90m_d1", "samples": 2 * [-0.1 + 0j]}, - {"name": "y90p_d0", "samples": 2 * [0.1j]}, - {"name": "y90p_d1", "samples": 2 * [0.1j]}, - {"name": "xp_d0", "samples": 2 * [0.2 + 0j]}, - {"name": "ym_d0", "samples": 2 * [-0.2j]}, - {"name": "cr90p_u0", "samples": 9 * [0.1 + 0j]}, - {"name": "cr90m_u0", "samples": 9 * [-0.1 + 0j]}, - {"name": "measure_m0", "samples": 10 * [0.1 + 0j]}, - {"name": "measure_m1", "samples": 10 * [0.1 + 0j]}, - ], - "cmd_def": [ - Command.from_dict( - { - "name": "u1", - "qubits": [0], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase="-P0" - ).to_dict() - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u1", - "qubits": [1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d1", t0=0, phase="-P0" - ).to_dict() - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u2", - "qubits": [0], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase="-P1" - ).to_dict(), - PulseQobjInstruction(name="y90p_d0", ch="d0", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d0", t0=2, phase="-P0" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u2", - "qubits": [1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d1", t0=0, phase="-P1" - ).to_dict(), - PulseQobjInstruction(name="y90p_d1", ch="d1", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d1", t0=2, phase="-P0" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u3", - "qubits": [0], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase="-P2" - ).to_dict(), - PulseQobjInstruction(name="x90p_d0", ch="d0", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d0", t0=2, phase="-P0" - ).to_dict(), - PulseQobjInstruction(name="x90m_d0", ch="d0", t0=2).to_dict(), - PulseQobjInstruction( - name="fc", ch="d0", t0=4, phase="-P1" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u3", - "qubits": [1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d1", t0=0, phase="-P2" - ).to_dict(), - PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d1", t0=2, phase="-P0" - ).to_dict(), - PulseQobjInstruction(name="x90m_d1", ch="d1", t0=2).to_dict(), - PulseQobjInstruction( - name="fc", ch="d1", t0=4, phase="-P1" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "cx", - "qubits": [0, 1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase=1.57 - ).to_dict(), - PulseQobjInstruction(name="ym_d0", ch="d0", t0=0).to_dict(), - PulseQobjInstruction(name="xp_d0", ch="d0", t0=11).to_dict(), - PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), - PulseQobjInstruction(name="cr90p_u0", ch="u0", t0=2).to_dict(), - PulseQobjInstruction(name="cr90m_u0", ch="u0", t0=13).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "measure", - "qubits": [0, 1], - "sequence": [ - PulseQobjInstruction(name="measure_m0", ch="m0", t0=0).to_dict(), - PulseQobjInstruction(name="measure_m1", ch="m1", t0=0).to_dict(), - PulseQobjInstruction( - name="acquire", - duration=10, - t0=0, - qubits=[0, 1], - memory_slot=[0, 1], - ).to_dict(), - ], - } - ).to_dict(), - ], - } - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + self._defaults = PulseDefaults.from_dict( + { + "qubit_freq_est": [4.9, 5.0], + "meas_freq_est": [6.5, 6.6], + "buffer": 10, + "pulse_library": [ + {"name": "x90p_d0", "samples": 2 * [0.1 + 0j]}, + {"name": "x90p_d1", "samples": 2 * [0.1 + 0j]}, + {"name": "x90m_d0", "samples": 2 * [-0.1 + 0j]}, + {"name": "x90m_d1", "samples": 2 * [-0.1 + 0j]}, + {"name": "y90p_d0", "samples": 2 * [0.1j]}, + {"name": "y90p_d1", "samples": 2 * [0.1j]}, + {"name": "xp_d0", "samples": 2 * [0.2 + 0j]}, + {"name": "ym_d0", "samples": 2 * [-0.2j]}, + {"name": "cr90p_u0", "samples": 9 * [0.1 + 0j]}, + {"name": "cr90m_u0", "samples": 9 * [-0.1 + 0j]}, + {"name": "measure_m0", "samples": 10 * [0.1 + 0j]}, + {"name": "measure_m1", "samples": 10 * [0.1 + 0j]}, + ], + "cmd_def": [ + Command.from_dict( + { + "name": "u1", + "qubits": [0], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase="-P0" + ).to_dict() + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u1", + "qubits": [1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d1", t0=0, phase="-P0" + ).to_dict() + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u2", + "qubits": [0], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase="-P1" + ).to_dict(), + PulseQobjInstruction(name="y90p_d0", ch="d0", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d0", t0=2, phase="-P0" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u2", + "qubits": [1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d1", t0=0, phase="-P1" + ).to_dict(), + PulseQobjInstruction(name="y90p_d1", ch="d1", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d1", t0=2, phase="-P0" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u3", + "qubits": [0], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase="-P2" + ).to_dict(), + PulseQobjInstruction(name="x90p_d0", ch="d0", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d0", t0=2, phase="-P0" + ).to_dict(), + PulseQobjInstruction(name="x90m_d0", ch="d0", t0=2).to_dict(), + PulseQobjInstruction( + name="fc", ch="d0", t0=4, phase="-P1" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u3", + "qubits": [1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d1", t0=0, phase="-P2" + ).to_dict(), + PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d1", t0=2, phase="-P0" + ).to_dict(), + PulseQobjInstruction(name="x90m_d1", ch="d1", t0=2).to_dict(), + PulseQobjInstruction( + name="fc", ch="d1", t0=4, phase="-P1" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "cx", + "qubits": [0, 1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase=1.57 + ).to_dict(), + PulseQobjInstruction(name="ym_d0", ch="d0", t0=0).to_dict(), + PulseQobjInstruction(name="xp_d0", ch="d0", t0=11).to_dict(), + PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), + PulseQobjInstruction(name="cr90p_u0", ch="u0", t0=2).to_dict(), + PulseQobjInstruction(name="cr90m_u0", ch="u0", t0=13).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "measure", + "qubits": [0, 1], + "sequence": [ + PulseQobjInstruction( + name="measure_m0", ch="m0", t0=0 + ).to_dict(), + PulseQobjInstruction( + name="measure_m1", ch="m1", t0=0 + ).to_dict(), + PulseQobjInstruction( + name="acquire", + duration=10, + t0=0, + qubits=[0, 1], + memory_slot=[0, 1], + ).to_dict(), + ], + } + ).to_dict(), + ], + } + ) mock_time = datetime.datetime.now() dt = 1.3333 diff --git a/qiskit/providers/fake_provider/fake_openpulse_3q.py b/qiskit/providers/fake_provider/fake_openpulse_3q.py index 8d2529a68a2a..161fc5fbb4d4 100644 --- a/qiskit/providers/fake_provider/fake_openpulse_3q.py +++ b/qiskit/providers/fake_provider/fake_openpulse_3q.py @@ -13,6 +13,7 @@ """ Fake backend supporting OpenPulse. """ +import warnings from qiskit.providers.models import ( GateConfig, @@ -109,223 +110,230 @@ def __init__(self): }, }, ) - - self._defaults = PulseDefaults.from_dict( - { - "qubit_freq_est": [4.9, 5.0, 4.8], - "meas_freq_est": [6.5, 6.6, 6.4], - "buffer": 10, - "pulse_library": [ - {"name": "x90p_d0", "samples": 2 * [0.1 + 0j]}, - {"name": "x90p_d1", "samples": 2 * [0.1 + 0j]}, - {"name": "x90p_d2", "samples": 2 * [0.1 + 0j]}, - {"name": "x90m_d0", "samples": 2 * [-0.1 + 0j]}, - {"name": "x90m_d1", "samples": 2 * [-0.1 + 0j]}, - {"name": "x90m_d2", "samples": 2 * [-0.1 + 0j]}, - {"name": "y90p_d0", "samples": 2 * [0.1j]}, - {"name": "y90p_d1", "samples": 2 * [0.1j]}, - {"name": "y90p_d2", "samples": 2 * [0.1j]}, - {"name": "xp_d0", "samples": 2 * [0.2 + 0j]}, - {"name": "ym_d0", "samples": 2 * [-0.2j]}, - {"name": "xp_d1", "samples": 2 * [0.2 + 0j]}, - {"name": "ym_d1", "samples": 2 * [-0.2j]}, - {"name": "cr90p_u0", "samples": 9 * [0.1 + 0j]}, - {"name": "cr90m_u0", "samples": 9 * [-0.1 + 0j]}, - {"name": "cr90p_u1", "samples": 9 * [0.1 + 0j]}, - {"name": "cr90m_u1", "samples": 9 * [-0.1 + 0j]}, - {"name": "measure_m0", "samples": 10 * [0.1 + 0j]}, - {"name": "measure_m1", "samples": 10 * [0.1 + 0j]}, - {"name": "measure_m2", "samples": 10 * [0.1 + 0j]}, - ], - "cmd_def": [ - Command.from_dict( - { - "name": "u1", - "qubits": [0], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase="-P0" - ).to_dict() - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u1", - "qubits": [1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d1", t0=0, phase="-P0" - ).to_dict() - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u1", - "qubits": [2], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d2", t0=0, phase="-P0" - ).to_dict() - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u2", - "qubits": [0], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase="-P1" - ).to_dict(), - PulseQobjInstruction(name="y90p_d0", ch="d0", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d0", t0=2, phase="-P0" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u2", - "qubits": [1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d1", t0=0, phase="-P1" - ).to_dict(), - PulseQobjInstruction(name="y90p_d1", ch="d1", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d1", t0=2, phase="-P0" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u2", - "qubits": [2], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d2", t0=0, phase="-P1" - ).to_dict(), - PulseQobjInstruction(name="y90p_d2", ch="d2", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d2", t0=2, phase="-P0" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u3", - "qubits": [0], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase="-P2" - ).to_dict(), - PulseQobjInstruction(name="x90p_d0", ch="d0", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d0", t0=2, phase="-P0" - ).to_dict(), - PulseQobjInstruction(name="x90m_d0", ch="d0", t0=2).to_dict(), - PulseQobjInstruction( - name="fc", ch="d0", t0=4, phase="-P1" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u3", - "qubits": [1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d1", t0=0, phase="-P2" - ).to_dict(), - PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d1", t0=2, phase="-P0" - ).to_dict(), - PulseQobjInstruction(name="x90m_d1", ch="d1", t0=2).to_dict(), - PulseQobjInstruction( - name="fc", ch="d1", t0=4, phase="-P1" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "u3", - "qubits": [2], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d2", t0=0, phase="-P2" - ).to_dict(), - PulseQobjInstruction(name="x90p_d2", ch="d2", t0=0).to_dict(), - PulseQobjInstruction( - name="fc", ch="d2", t0=2, phase="-P0" - ).to_dict(), - PulseQobjInstruction(name="x90m_d2", ch="d2", t0=2).to_dict(), - PulseQobjInstruction( - name="fc", ch="d2", t0=4, phase="-P1" - ).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "cx", - "qubits": [0, 1], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d0", t0=0, phase=1.57 - ).to_dict(), - PulseQobjInstruction(name="ym_d0", ch="d0", t0=0).to_dict(), - PulseQobjInstruction(name="xp_d0", ch="d0", t0=11).to_dict(), - PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), - PulseQobjInstruction(name="cr90p_u0", ch="u0", t0=2).to_dict(), - PulseQobjInstruction(name="cr90m_u0", ch="u0", t0=13).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "cx", - "qubits": [1, 2], - "sequence": [ - PulseQobjInstruction( - name="fc", ch="d1", t0=0, phase=1.57 - ).to_dict(), - PulseQobjInstruction(name="ym_d1", ch="d1", t0=0).to_dict(), - PulseQobjInstruction(name="xp_d1", ch="d1", t0=11).to_dict(), - PulseQobjInstruction(name="x90p_d2", ch="d2", t0=0).to_dict(), - PulseQobjInstruction(name="cr90p_u1", ch="u1", t0=2).to_dict(), - PulseQobjInstruction(name="cr90m_u1", ch="u1", t0=13).to_dict(), - ], - } - ).to_dict(), - Command.from_dict( - { - "name": "measure", - "qubits": [0, 1, 2], - "sequence": [ - PulseQobjInstruction(name="measure_m0", ch="m0", t0=0).to_dict(), - PulseQobjInstruction(name="measure_m1", ch="m1", t0=0).to_dict(), - PulseQobjInstruction(name="measure_m2", ch="m2", t0=0).to_dict(), - PulseQobjInstruction( - name="acquire", - duration=10, - t0=0, - qubits=[0, 1, 2], - memory_slot=[0, 1, 2], - ).to_dict(), - ], - } - ).to_dict(), - ], - } - ) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=DeprecationWarning) + self._defaults = PulseDefaults.from_dict( + { + "qubit_freq_est": [4.9, 5.0, 4.8], + "meas_freq_est": [6.5, 6.6, 6.4], + "buffer": 10, + "pulse_library": [ + {"name": "x90p_d0", "samples": 2 * [0.1 + 0j]}, + {"name": "x90p_d1", "samples": 2 * [0.1 + 0j]}, + {"name": "x90p_d2", "samples": 2 * [0.1 + 0j]}, + {"name": "x90m_d0", "samples": 2 * [-0.1 + 0j]}, + {"name": "x90m_d1", "samples": 2 * [-0.1 + 0j]}, + {"name": "x90m_d2", "samples": 2 * [-0.1 + 0j]}, + {"name": "y90p_d0", "samples": 2 * [0.1j]}, + {"name": "y90p_d1", "samples": 2 * [0.1j]}, + {"name": "y90p_d2", "samples": 2 * [0.1j]}, + {"name": "xp_d0", "samples": 2 * [0.2 + 0j]}, + {"name": "ym_d0", "samples": 2 * [-0.2j]}, + {"name": "xp_d1", "samples": 2 * [0.2 + 0j]}, + {"name": "ym_d1", "samples": 2 * [-0.2j]}, + {"name": "cr90p_u0", "samples": 9 * [0.1 + 0j]}, + {"name": "cr90m_u0", "samples": 9 * [-0.1 + 0j]}, + {"name": "cr90p_u1", "samples": 9 * [0.1 + 0j]}, + {"name": "cr90m_u1", "samples": 9 * [-0.1 + 0j]}, + {"name": "measure_m0", "samples": 10 * [0.1 + 0j]}, + {"name": "measure_m1", "samples": 10 * [0.1 + 0j]}, + {"name": "measure_m2", "samples": 10 * [0.1 + 0j]}, + ], + "cmd_def": [ + Command.from_dict( + { + "name": "u1", + "qubits": [0], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase="-P0" + ).to_dict() + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u1", + "qubits": [1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d1", t0=0, phase="-P0" + ).to_dict() + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u1", + "qubits": [2], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d2", t0=0, phase="-P0" + ).to_dict() + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u2", + "qubits": [0], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase="-P1" + ).to_dict(), + PulseQobjInstruction(name="y90p_d0", ch="d0", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d0", t0=2, phase="-P0" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u2", + "qubits": [1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d1", t0=0, phase="-P1" + ).to_dict(), + PulseQobjInstruction(name="y90p_d1", ch="d1", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d1", t0=2, phase="-P0" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u2", + "qubits": [2], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d2", t0=0, phase="-P1" + ).to_dict(), + PulseQobjInstruction(name="y90p_d2", ch="d2", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d2", t0=2, phase="-P0" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u3", + "qubits": [0], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase="-P2" + ).to_dict(), + PulseQobjInstruction(name="x90p_d0", ch="d0", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d0", t0=2, phase="-P0" + ).to_dict(), + PulseQobjInstruction(name="x90m_d0", ch="d0", t0=2).to_dict(), + PulseQobjInstruction( + name="fc", ch="d0", t0=4, phase="-P1" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u3", + "qubits": [1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d1", t0=0, phase="-P2" + ).to_dict(), + PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d1", t0=2, phase="-P0" + ).to_dict(), + PulseQobjInstruction(name="x90m_d1", ch="d1", t0=2).to_dict(), + PulseQobjInstruction( + name="fc", ch="d1", t0=4, phase="-P1" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "u3", + "qubits": [2], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d2", t0=0, phase="-P2" + ).to_dict(), + PulseQobjInstruction(name="x90p_d2", ch="d2", t0=0).to_dict(), + PulseQobjInstruction( + name="fc", ch="d2", t0=2, phase="-P0" + ).to_dict(), + PulseQobjInstruction(name="x90m_d2", ch="d2", t0=2).to_dict(), + PulseQobjInstruction( + name="fc", ch="d2", t0=4, phase="-P1" + ).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "cx", + "qubits": [0, 1], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d0", t0=0, phase=1.57 + ).to_dict(), + PulseQobjInstruction(name="ym_d0", ch="d0", t0=0).to_dict(), + PulseQobjInstruction(name="xp_d0", ch="d0", t0=11).to_dict(), + PulseQobjInstruction(name="x90p_d1", ch="d1", t0=0).to_dict(), + PulseQobjInstruction(name="cr90p_u0", ch="u0", t0=2).to_dict(), + PulseQobjInstruction(name="cr90m_u0", ch="u0", t0=13).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "cx", + "qubits": [1, 2], + "sequence": [ + PulseQobjInstruction( + name="fc", ch="d1", t0=0, phase=1.57 + ).to_dict(), + PulseQobjInstruction(name="ym_d1", ch="d1", t0=0).to_dict(), + PulseQobjInstruction(name="xp_d1", ch="d1", t0=11).to_dict(), + PulseQobjInstruction(name="x90p_d2", ch="d2", t0=0).to_dict(), + PulseQobjInstruction(name="cr90p_u1", ch="u1", t0=2).to_dict(), + PulseQobjInstruction(name="cr90m_u1", ch="u1", t0=13).to_dict(), + ], + } + ).to_dict(), + Command.from_dict( + { + "name": "measure", + "qubits": [0, 1, 2], + "sequence": [ + PulseQobjInstruction( + name="measure_m0", ch="m0", t0=0 + ).to_dict(), + PulseQobjInstruction( + name="measure_m1", ch="m1", t0=0 + ).to_dict(), + PulseQobjInstruction( + name="measure_m2", ch="m2", t0=0 + ).to_dict(), + PulseQobjInstruction( + name="acquire", + duration=10, + t0=0, + qubits=[0, 1, 2], + memory_slot=[0, 1, 2], + ).to_dict(), + ], + } + ).to_dict(), + ], + } + ) super().__init__(configuration) def defaults(self): # pylint: disable=missing-function-docstring diff --git a/test/python/transpiler/test_preset_passmanagers.py b/test/python/transpiler/test_preset_passmanagers.py index ee85dc34ffd6..32d39304b44e 100644 --- a/test/python/transpiler/test_preset_passmanagers.py +++ b/test/python/transpiler/test_preset_passmanagers.py @@ -21,7 +21,7 @@ from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister from qiskit.circuit import Qubit, Gate, ControlFlowOp, ForLoopOp -from qiskit.compiler import transpile, assemble +from qiskit.compiler import transpile from qiskit.transpiler import CouplingMap, Layout, PassManager, TranspilerError, Target from qiskit.circuit.library import U2Gate, U3Gate, QuantumVolume, CXGate, CZGate, XGate from qiskit.transpiler.passes import ( @@ -684,15 +684,15 @@ def test_layout_1711(self, level): } backend = GenericBackendV2(num_qubits=16, coupling_map=RUESCHLIKON_CMAP, seed=42) qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) - qobj = assemble(qc_b) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) - compiled_ops = qobj.experiments[0].instructions - for operation in compiled_ops: - if operation.name == "cx": - self.assertIn(tuple(operation.qubits), backend.coupling_map) - self.assertIn(operation.qubits, [[15, 0], [15, 2]]) + for inst in qc_b.data: + if inst.operation.name == "cx": + self.assertIn( + tuple(qc_b.find_bit(bit).index for bit in inst.qubits), backend.coupling_map + ) + self.assertIn([qc_b.find_bit(bit).index for bit in inst.qubits], [[15, 0], [15, 2]]) @data(0, 1, 2, 3) def test_layout_2532(self, level): From e5c5b43d1e9b97c33093a1d42a767c92aa65deb0 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 28 Jun 2024 20:26:29 +0200 Subject: [PATCH 045/168] test.python.result.test_result --- test/python/result/test_result.py | 150 +++++++++++++++++++----------- 1 file changed, 95 insertions(+), 55 deletions(-) diff --git a/test/python/result/test_result.py b/test/python/result/test_result.py index ff1f4cbf29a0..89539487158c 100644 --- a/test/python/result/test_result.py +++ b/test/python/result/test_result.py @@ -42,7 +42,8 @@ def generate_qiskit_result(self): memory = [hex(ii) for ii in range(8)] counts = {m: 1 for m in memory} data_1 = models.ExperimentResultData(counts=counts, memory=memory) - exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + 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 ) @@ -67,9 +68,10 @@ def test_counts_header(self): raw_counts = {"0x0": 4, "0x2": 10} processed_counts = {"0 0 00": 4, "0 0 10": 10} data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader( - creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 - ) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader( + creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 + ) exp_result = models.ExperimentResult( shots=14, success=True, meas_level=2, data=data, header=exp_result_header ) @@ -82,9 +84,10 @@ def test_counts_by_name(self): raw_counts = {"0x0": 4, "0x2": 10} processed_counts = {"0 0 00": 4, "0 0 10": 10} data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader( - creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4, name="a_name" - ) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader( + creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4, name="a_name" + ) exp_result = models.ExperimentResult( shots=14, success=True, meas_level=2, data=data, header=exp_result_header ) @@ -95,7 +98,8 @@ def test_counts_by_name(self): def test_counts_duplicate_name(self): """Test results containing multiple entries of a single name will warn.""" data = models.ExperimentResultData(counts={}) - exp_result_header = QobjExperimentHeader(name="foo") + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader(name="foo") exp_result = models.ExperimentResult( shots=14, success=True, data=data, header=exp_result_header ) @@ -108,9 +112,10 @@ def test_result_repr(self): """Test that repr is constructed correctly for a results object.""" raw_counts = {"0x0": 4, "0x2": 10} data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader( - creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 - ) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader( + creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 + ) exp_result = models.ExperimentResult( shots=14, success=True, meas_level=2, data=data, header=exp_result_header ) @@ -137,7 +142,8 @@ def test_multiple_circuits_counts(self): raw_counts_1 = {"0x0": 5, "0x3": 12, "0x5": 9, "0xD": 6, "0xE": 2} processed_counts_1 = {"0000": 5, "0011": 12, "0101": 9, "1101": 6, "1110": 2} data_1 = models.ExperimentResultData(counts=raw_counts_1) - exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result_1 = models.ExperimentResult( shots=14, success=True, meas_level=2, data=data_1, header=exp_result_header_1 ) @@ -145,7 +151,8 @@ def test_multiple_circuits_counts(self): raw_counts_2 = {"0x1": 0, "0x4": 3, "0x6": 6, "0xA": 1, "0xB": 2} processed_counts_2 = {"0001": 0, "0100": 3, "0110": 6, "1010": 1, "1011": 2} data_2 = models.ExperimentResultData(counts=raw_counts_2) - exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result_2 = models.ExperimentResult( shots=14, success=True, meas_level=2, data=data_2, header=exp_result_header_2 ) @@ -153,7 +160,8 @@ def test_multiple_circuits_counts(self): raw_counts_3 = {"0xC": 27, "0xF": 20} processed_counts_3 = {"1100": 27, "1111": 20} data_3 = models.ExperimentResultData(counts=raw_counts_3) - exp_result_header_3 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header_3 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result_3 = models.ExperimentResult( shots=14, success=True, meas_level=2, data=data_3, header=exp_result_header_3 ) @@ -172,7 +180,8 @@ def test_marginal_counts(self): """Test that counts are marginalized correctly.""" raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result = models.ExperimentResult( shots=54, success=True, data=data, header=exp_result_header ) @@ -186,7 +195,8 @@ def test_marginal_distribution(self): """Test that counts are marginalized correctly.""" raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result = models.ExperimentResult( shots=54, success=True, data=data, header=exp_result_header ) @@ -200,7 +210,10 @@ def test_marginal_distribution(self): self.assertEqual(marginal_distribution(result.get_counts(), [1, 0]), expected_reverse) # test with register spacing, bitstrings are in form of "00 00" for register split data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 2], ["c1", 2]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader( + creg_sizes=[["c0", 2], ["c1", 2]], memory_slots=4 + ) exp_result = models.ExperimentResult( shots=54, success=True, data=data, header=exp_result_header ) @@ -214,14 +227,16 @@ def test_marginal_counts_result(self): """Test that a Result object containing counts marginalizes correctly.""" raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} data_1 = models.ExperimentResultData(counts=raw_counts_1) - exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result_1 = models.ExperimentResult( shots=54, success=True, data=data_1, header=exp_result_header_1 ) raw_counts_2 = {"0x2": 5, "0x3": 8} data_2 = models.ExperimentResultData(counts=raw_counts_2) - exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2) + with self.assertWarns(DeprecationWarning): + exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2) exp_result_2 = models.ExperimentResult( shots=13, success=True, data=data_2, header=exp_result_header_2 ) @@ -240,14 +255,20 @@ def test_marginal_counts_result(self): "1110": 8, } - self.assertEqual(marginal_counts(result, [0, 1]).get_counts(0), expected_marginal_counts_1) - self.assertEqual(marginal_counts(result, [0]).get_counts(1), expected_marginal_counts_2) - self.assertEqual(marginal_counts(result, None).get_counts(0), expected_marginal_counts_none) + with self.assertWarns(DeprecationWarning): + self.assertEqual( + marginal_counts(result, [0, 1]).get_counts(0), expected_marginal_counts_1 + ) + self.assertEqual(marginal_counts(result, [0]).get_counts(1), expected_marginal_counts_2) + self.assertEqual( + marginal_counts(result, None).get_counts(0), expected_marginal_counts_none + ) def test_marginal_counts_result_memory(self): """Test that a Result object containing memory marginalizes correctly.""" result = self.generate_qiskit_result() - marginal_result = marginal_counts(result, indices=[0]) + with self.assertWarns(DeprecationWarning): + marginal_result = marginal_counts(result, indices=[0]) marginal_memory = marginal_result.results[0].data.memory self.assertEqual(marginal_memory, [hex(ii % 2) for ii in range(8)]) @@ -255,7 +276,8 @@ def test_marginal_counts_result_memory_nonzero_indices(self): """Test that a Result object containing memory marginalizes correctly.""" result = self.generate_qiskit_result() index = 2 - marginal_result = marginal_counts(result, indices=[index]) + with self.assertWarns(DeprecationWarning): + marginal_result = marginal_counts(result, indices=[index]) marginal_memory = marginal_result.results[0].data.memory mask = 1 << index expected = [hex((ii & mask) >> index) for ii in range(8)] @@ -266,7 +288,8 @@ def test_marginal_counts_result_memory_indices_None(self): result = self.generate_qiskit_result() memory = "should not be touched" result.results[0].data.memory = memory - marginal_result = marginal_counts(result, indices=None) + with self.assertWarns(DeprecationWarning): + marginal_result = marginal_counts(result, indices=None) marginal_memory = marginal_result.results[0].data.memory self.assertEqual(marginal_memory, memory) @@ -297,17 +320,20 @@ def test_marginal_counts_result_marginalize_memory(self): self.assertTrue(hasattr(marginal_result.results[0].data, "memory")) result = self.generate_qiskit_result() - marginal_result = marginal_counts( - result, indices=[0], inplace=False, marginalize_memory=False - ) + with self.assertWarns(DeprecationWarning): + marginal_result = marginal_counts( + result, indices=[0], inplace=False, marginalize_memory=False + ) self.assertFalse(hasattr(marginal_result.results[0].data, "memory")) - marginal_result = marginal_counts( - result, indices=[0], inplace=False, marginalize_memory=None - ) + with self.assertWarns(DeprecationWarning): + marginal_result = marginal_counts( + result, indices=[0], inplace=False, marginalize_memory=None + ) self.assertTrue(hasattr(marginal_result.results[0].data, "memory")) - marginal_result = marginal_counts( - result, indices=[0], inplace=False, marginalize_memory=True - ) + with self.assertWarns(DeprecationWarning): + marginal_result = marginal_counts( + result, indices=[0], inplace=False, marginalize_memory=True + ) self.assertTrue(hasattr(marginal_result.results[0].data, "memory")) def test_marginal_counts_result_inplace(self): @@ -323,7 +349,10 @@ def test_marginal_counts_result_creg_sizes(self): """Test that marginal_counts with Result input properly changes creg_sizes.""" raw_counts = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader(creg_sizes=[["c0", 1], ["c1", 3]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader( + creg_sizes=[["c0", 1], ["c1", 3]], memory_slots=4 + ) exp_result = models.ExperimentResult( shots=54, success=True, data=data, header=exp_result_header ) @@ -333,7 +362,8 @@ def test_marginal_counts_result_creg_sizes(self): expected_marginal_counts = {"0 0": 14, "0 1": 18, "1 0": 13, "1 1": 9} expected_creg_sizes = [["c0", 1], ["c1", 1]] expected_memory_slots = 2 - marginal_counts_result = marginal_counts(result, [0, 2]) + with self.assertWarns(DeprecationWarning): + marginal_counts_result = marginal_counts(result, [0, 2]) self.assertEqual(marginal_counts_result.results[0].header.creg_sizes, expected_creg_sizes) self.assertEqual( marginal_counts_result.results[0].header.memory_slots, expected_memory_slots @@ -344,9 +374,10 @@ def test_marginal_counts_result_format(self): """Test that marginal_counts with format_marginal true properly formats output.""" raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0x12": 8} data_1 = models.ExperimentResultData(counts=raw_counts_1) - exp_result_header_1 = QobjExperimentHeader( - creg_sizes=[["c0", 2], ["c1", 3]], memory_slots=5 - ) + with self.assertWarns(DeprecationWarning): + exp_result_header_1 = QobjExperimentHeader( + creg_sizes=[["c0", 2], ["c1", 3]], memory_slots=5 + ) exp_result_1 = models.ExperimentResult( shots=54, success=True, data=data_1, header=exp_result_header_1 ) @@ -369,14 +400,16 @@ def test_marginal_counts_inplace_true(self): """Test marginal_counts(Result, inplace = True)""" raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} data_1 = models.ExperimentResultData(counts=raw_counts_1) - exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result_1 = models.ExperimentResult( shots=54, success=True, data=data_1, header=exp_result_header_1 ) raw_counts_2 = {"0x2": 5, "0x3": 8} data_2 = models.ExperimentResultData(counts=raw_counts_2) - exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2) + with self.assertWarns(DeprecationWarning): + exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2) exp_result_2 = models.ExperimentResult( shots=13, success=True, data=data_2, header=exp_result_header_2 ) @@ -394,14 +427,16 @@ def test_marginal_counts_inplace_false(self): """Test marginal_counts(Result, inplace=False)""" raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0xE": 8} data_1 = models.ExperimentResultData(counts=raw_counts_1) - exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) + with self.assertWarns(DeprecationWarning): + exp_result_header_1 = QobjExperimentHeader(creg_sizes=[["c0", 4]], memory_slots=4) exp_result_1 = models.ExperimentResult( shots=54, success=True, data=data_1, header=exp_result_header_1 ) raw_counts_2 = {"0x2": 5, "0x3": 8} data_2 = models.ExperimentResultData(counts=raw_counts_2) - exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2) + with self.assertWarns(DeprecationWarning): + exp_result_header_2 = QobjExperimentHeader(creg_sizes=[["c0", 2]], memory_slots=2) exp_result_2 = models.ExperimentResult( shots=13, success=True, data=data_2, header=exp_result_header_2 ) @@ -410,9 +445,10 @@ def test_marginal_counts_inplace_false(self): expected_marginal_counts = {"0": 27, "1": 27} - self.assertEqual( - marginal_counts(result, [0], inplace=False).get_counts(0), expected_marginal_counts - ) + with self.assertWarns(DeprecationWarning): + self.assertEqual( + marginal_counts(result, [0], inplace=False).get_counts(0), expected_marginal_counts + ) self.assertNotEqual(result.get_counts(0), expected_marginal_counts) def test_marginal_counts_with_dict(self): @@ -465,9 +501,10 @@ def test_memory_counts_header(self): "0 0 10", ] data = models.ExperimentResultData(memory=raw_memory) - exp_result_header = QobjExperimentHeader( - creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 - ) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader( + creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4 + ) exp_result = models.ExperimentResult( shots=14, success=True, meas_level=2, memory=True, data=data, header=exp_result_header ) @@ -703,9 +740,10 @@ def test_counts_name_out(self): """Test that fails when get_count is called with a nonexistent name.""" raw_counts = {"0x0": 4, "0x2": 10} data = models.ExperimentResultData(counts=raw_counts) - exp_result_header = QobjExperimentHeader( - creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4, name="a_name" - ) + with self.assertWarns(DeprecationWarning): + exp_result_header = QobjExperimentHeader( + creg_sizes=[["c0", 2], ["c0", 1], ["c1", 1]], memory_slots=4, name="a_name" + ) exp_result = models.ExperimentResult( shots=14, success=True, meas_level=2, data=data, header=exp_result_header ) @@ -736,13 +774,15 @@ def test_marginal_counts_no_cregs(self): """Test that marginal_counts without cregs See qiskit-terra/6430.""" raw_counts_1 = {"0x0": 4, "0x1": 7, "0x2": 10, "0x6": 5, "0x9": 11, "0xD": 9, "0x12": 8} data_1 = models.ExperimentResultData(counts=raw_counts_1) - exp_result_header_1 = QobjExperimentHeader(memory_slots=5) + with self.assertWarns(DeprecationWarning): + exp_result_header_1 = QobjExperimentHeader(memory_slots=5) 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) - _ = marginal_counts(result, indices=[0]) - marginal_counts_result = marginal_counts(result, indices=[0]) + 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}) From 7edd883ba39113e738ce0a97f841610339052aa3 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 28 Jun 2024 20:31:25 +0200 Subject: [PATCH 046/168] test.python.pulse.test_calibration_entries --- test/python/pulse/test_calibration_entries.py | 168 +++++++++--------- 1 file changed, 87 insertions(+), 81 deletions(-) diff --git a/test/python/pulse/test_calibration_entries.py b/test/python/pulse/test_calibration_entries.py index 20e6773d2fd2..cc31789ef683 100644 --- a/test/python/pulse/test_calibration_entries.py +++ b/test/python/pulse/test_calibration_entries.py @@ -281,29 +281,31 @@ class TestPulseQobj(QiskitTestCase): def setUp(self): super().setUp() - self.converter = QobjToInstructionConverter( - pulse_library=[ - PulseLibraryItem(name="waveform", samples=[0.3, 0.1, 0.2, 0.2, 0.3]), - ] - ) + with self.assertWarns(DeprecationWarning): + self.converter = QobjToInstructionConverter( + pulse_library=[ + PulseLibraryItem(name="waveform", samples=[0.3, 0.1, 0.2, 0.2, 0.3]), + ] + ) def test_add_qobj(self): """Basic test PulseQobj format.""" - serialized_program = [ - PulseQobjInstruction( - name="parametric_pulse", - t0=0, - ch="d0", - label="TestPulse", - pulse_shape="constant", - parameters={"amp": 0.1 + 0j, "duration": 10}, - ), - PulseQobjInstruction( - name="waveform", - t0=20, - ch="d0", - ), - ] + with self.assertWarns(DeprecationWarning): + serialized_program = [ + PulseQobjInstruction( + name="parametric_pulse", + t0=0, + ch="d0", + label="TestPulse", + pulse_shape="constant", + parameters={"amp": 0.1 + 0j, "duration": 10}, + ), + PulseQobjInstruction( + name="waveform", + t0=20, + ch="d0", + ), + ] entry = PulseQobjDef(converter=self.converter, name="my_gate") entry.define(serialized_program) @@ -328,13 +330,14 @@ def test_add_qobj(self): def test_missing_waveform(self): """Test incomplete Qobj should raise warning and calibration returns None.""" - serialized_program = [ - PulseQobjInstruction( - name="waveform_123456", - t0=20, - ch="d0", - ), - ] + with self.assertWarns(DeprecationWarning): + serialized_program = [ + PulseQobjInstruction( + name="waveform_123456", + t0=20, + ch="d0", + ), + ] entry = PulseQobjDef(converter=self.converter, name="my_gate") entry.define(serialized_program) @@ -355,22 +358,23 @@ def test_parameterized_qobj(self): Note that pulse parameter cannot be parameterized by convention. """ - serialized_program = [ - PulseQobjInstruction( - name="parametric_pulse", - t0=0, - ch="d0", - label="TestPulse", - pulse_shape="constant", - parameters={"amp": 0.1, "duration": 10}, - ), - PulseQobjInstruction( - name="fc", - t0=0, - ch="d0", - phase="P1", - ), - ] + with self.assertWarns(DeprecationWarning): + serialized_program = [ + PulseQobjInstruction( + name="parametric_pulse", + t0=0, + ch="d0", + label="TestPulse", + pulse_shape="constant", + parameters={"amp": 0.1, "duration": 10}, + ), + PulseQobjInstruction( + name="fc", + t0=0, + ch="d0", + phase="P1", + ), + ] entry = PulseQobjDef(converter=self.converter, name="my_gate") entry.define(serialized_program) @@ -395,27 +399,27 @@ def test_parameterized_qobj(self): def test_equality(self): """Test equality evaluation between the pulse qobj entries.""" - serialized_program1 = [ - PulseQobjInstruction( - name="parametric_pulse", - t0=0, - ch="d0", - label="TestPulse", - pulse_shape="constant", - parameters={"amp": 0.1, "duration": 10}, - ) - ] - - serialized_program2 = [ - PulseQobjInstruction( - name="parametric_pulse", - t0=0, - ch="d0", - label="TestPulse", - pulse_shape="constant", - parameters={"amp": 0.2, "duration": 10}, - ) - ] + with self.assertWarns(DeprecationWarning): + serialized_program1 = [ + PulseQobjInstruction( + name="parametric_pulse", + t0=0, + ch="d0", + label="TestPulse", + pulse_shape="constant", + parameters={"amp": 0.1, "duration": 10}, + ) + ] + serialized_program2 = [ + PulseQobjInstruction( + name="parametric_pulse", + t0=0, + ch="d0", + label="TestPulse", + pulse_shape="constant", + parameters={"amp": 0.2, "duration": 10}, + ) + ] entry1 = PulseQobjDef(name="my_gate1") entry1.define(serialized_program1) @@ -435,16 +439,17 @@ def test_equality_with_schedule(self): Because the pulse qobj entry is a subclass of the schedule entry, these instances can be compared by the generated definition, i.e. Schedule. """ - serialized_program = [ - PulseQobjInstruction( - name="parametric_pulse", - t0=0, - ch="d0", - label="TestPulse", - pulse_shape="constant", - parameters={"amp": 0.1, "duration": 10}, - ) - ] + with self.assertWarns(DeprecationWarning): + serialized_program = [ + PulseQobjInstruction( + name="parametric_pulse", + t0=0, + ch="d0", + label="TestPulse", + pulse_shape="constant", + parameters={"amp": 0.1, "duration": 10}, + ) + ] entry1 = PulseQobjDef(name="qobj_entry") entry1.define(serialized_program) @@ -470,13 +475,14 @@ def test_calibration_missing_waveform(self): In this situation, parsed calibration data must become None, instead of raising an error. """ - serialized_program = [ - PulseQobjInstruction( - name="SomeMissingPulse", - t0=0, - ch="d0", - ) - ] + with self.assertWarns(DeprecationWarning): + serialized_program = [ + PulseQobjInstruction( + name="SomeMissingPulse", + t0=0, + ch="d0", + ) + ] entry = PulseQobjDef(name="qobj_entry") entry.define(serialized_program) From b5e8b2871e4e41667f1b48114854ffeffa87cbc9 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 28 Jun 2024 22:17:09 +0200 Subject: [PATCH 047/168] test.python.compiler.test_assembler --- test/python/compiler/test_assembler.py | 977 ++++++++++++++----------- 1 file changed, 542 insertions(+), 435 deletions(-) diff --git a/test/python/compiler/test_assembler.py b/test/python/compiler/test_assembler.py index 1a6e5b6b8fe5..ff1f86f228db 100644 --- a/test/python/compiler/test_assembler.py +++ b/test/python/compiler/test_assembler.py @@ -80,7 +80,8 @@ def setUp(self): def test_assemble_single_circuit(self): """Test assembling a single circuit.""" - qobj = assemble(self.circ, shots=2000, memory=True) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, shots=2000, memory=True) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 2000) @@ -105,7 +106,8 @@ def test_assemble_multiple_circuits(self): circ1.cx(qr1[0], qr1[2]) circ1.measure(qr1, qc1) - qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6) + with self.assertWarns(DeprecationWarning): + qobj = assemble([circ0, circ1], shots=100, memory=False, seed_simulator=6) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.seed_simulator, 6) @@ -116,29 +118,34 @@ def test_assemble_multiple_circuits(self): def test_assemble_no_run_config(self): """Test assembling with no run_config, relying on default.""" - qobj = assemble(self.circ) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 1024) def test_shots_greater_than_max_shots(self): """Test assembling with shots greater than max shots""" - self.assertRaises(QiskitError, assemble, self.backend, shots=1024000) + with self.assertWarns(DeprecationWarning): + self.assertRaises(QiskitError, assemble, self.backend, shots=1024000) def test_shots_not_of_type_int(self): """Test assembling with shots having type other than int""" - self.assertRaises(QiskitError, assemble, self.backend, shots="1024") + with self.assertWarns(DeprecationWarning): + self.assertRaises(QiskitError, assemble, self.backend, shots="1024") def test_shots_of_type_numpy_int64(self): """Test assembling with shots having type numpy.int64""" - qobj = assemble(self.circ, shots=np.int64(2048)) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, shots=np.int64(2048)) self.assertEqual(qobj.config.shots, 2048) def test_default_shots_greater_than_max_shots(self): """Test assembling with default shots greater than max shots""" self.backend_config.max_shots = 5 - qobj = assemble(self.circ, self.backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, self.backend) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.shots, 5) @@ -149,7 +156,8 @@ def test_assemble_initialize(self): circ = QuantumCircuit(q, name="circ") circ.initialize([1 / np.sqrt(2), 0, 0, 1 / np.sqrt(2)], q[:]) - qobj = assemble(circ) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.experiments[0].instructions[0].name, "initialize") @@ -159,14 +167,16 @@ def test_assemble_initialize(self): def test_assemble_meas_level_meas_return(self): """Test assembling a circuit schedule with `meas_level`.""" - qobj = assemble(self.circ, meas_level=1, meas_return="single") + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, meas_level=1, meas_return="single") self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.meas_level, 1) self.assertEqual(qobj.config.meas_return, "single") # no meas_level set - qobj = assemble(self.circ) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.config.meas_level, 2) @@ -181,12 +191,14 @@ def test_assemble_backend_rep_delays(self): # dynamic rep rates off setattr(self.backend_config, "dynamic_reprate_enabled", False) - qobj = assemble(self.circ, self.backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, self.backend) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # dynamic rep rates on setattr(self.backend_config, "dynamic_reprate_enabled", True) - qobj = assemble(self.circ, self.backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, self.backend) self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6) def test_assemble_user_rep_time_delay(self): @@ -198,22 +210,26 @@ def test_assemble_user_rep_time_delay(self): # dynamic rep rates off (no default so shouldn't be in qobj config) setattr(self.backend_config, "dynamic_reprate_enabled", False) - qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # turn on dynamic rep rates, rep_delay should be set setattr(self.backend_config, "dynamic_reprate_enabled", True) - qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, self.backend, rep_delay=rep_delay) self.assertEqual(qobj.config.rep_delay, 2.2) # test ``rep_delay=0`` - qobj = assemble(self.circ, self.backend, rep_delay=0) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, self.backend, rep_delay=0) self.assertEqual(qobj.config.rep_delay, 0) # use ``rep_delay`` outside of ``rep_delay_range``` rep_delay_large = 5.0e-6 - with self.assertRaises(QiskitError): - assemble(self.circ, self.backend, rep_delay=rep_delay_large) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + assemble(self.circ, self.backend, rep_delay=rep_delay_large) def test_assemble_opaque_inst(self): """Test opaque instruction is assembled as-is""" @@ -223,7 +239,8 @@ def test_assemble_opaque_inst(self): circ = QuantumCircuit(q, c, name="circ") circ.append(opaque_inst, [q[0], q[2], q[5], q[3]], [c[3], c[0]]) - qobj = assemble(circ) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(len(qobj.experiments[0].instructions), 1) @@ -245,7 +262,8 @@ def test_assemble_unroll_parametervector(self): qc.assign_parameters({pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}) - qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}]) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc, parameter_binds=[{pv1: [0.1, 0.2, 0.3], pv2: [0.4, 0.5, 0.6]}]) self.assertIsInstance(qobj, QasmQobj) self.assertEqual(qobj.experiments[0].instructions[0].params[0], 0.100000000000000) @@ -267,7 +285,8 @@ def test_measure_to_registers_when_conditionals(self): qc.measure(qr[1], cr2[1]) # Measure required for a later conditional qc.h(qr[1]).c_if(cr2, 3) - qobj = assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) first_measure, second_measure = ( op for op in qobj.experiments[0].instructions if op.name == "measure" @@ -286,7 +305,8 @@ def test_convert_to_bfunc_plus_conditional(self): qc.h(qr[0]).c_if(cr, 1) - qobj = assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) bfunc_op, h_op = qobj.experiments[0].instructions @@ -306,7 +326,8 @@ def test_convert_to_bfunc_plus_conditional_onebit(self): qc.h(qr[0]).c_if(cr[2], 1) - qobj = assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) inst_set = qobj.experiments[0].instructions [bfunc_op, h_op] = inst_set @@ -331,7 +352,8 @@ def test_resize_value_to_register(self): qc.h(qr[0]).c_if(cr2, 2) - qobj = assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) bfunc_op, h_op = qobj.experiments[0].instructions @@ -363,23 +385,24 @@ def test_assemble_circuits_raises_for_bind_circuit_mismatch(self): full_bind_args = {"parameter_binds": [{x: 1, y: 1}, {x: 0, y: 0}]} inconsistent_bind_args = {"parameter_binds": [{x: 1}, {x: 0, y: 0}]} - # Raise when parameters passed for non-parametric circuit - self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args) + with self.assertWarns(DeprecationWarning): + # Raise when parameters passed for non-parametric circuit + self.assertRaises(QiskitError, assemble, full_bound_circ, **partial_bind_args) - # Raise when no parameters passed for parametric circuit - self.assertRaises(QiskitError, assemble, partial_param_circ) - self.assertRaises(QiskitError, assemble, full_param_circ) + # Raise when no parameters passed for parametric circuit + self.assertRaises(QiskitError, assemble, partial_param_circ) + self.assertRaises(QiskitError, assemble, full_param_circ) - # Raise when circuit has more parameters than run_config - self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args) + # Raise when circuit has more parameters than run_config + self.assertRaises(QiskitError, assemble, full_param_circ, **partial_bind_args) - # Raise when not all circuits have all parameters - self.assertRaises( - QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args - ) + # Raise when not all circuits have all parameters + self.assertRaises( + QiskitError, assemble, [full_param_circ, partial_param_circ], **full_bind_args + ) - # Raise when not all binds have all circuit params - self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args) + # Raise when not all binds have all circuit params + self.assertRaises(QiskitError, assemble, full_param_circ, **inconsistent_bind_args) def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self): """Verify assemble_circuits raises for invalid binds for circuit including @@ -395,11 +418,13 @@ def test_assemble_circuits_rases_for_bind_mismatch_over_expressions(self): partial_bind_args = {"parameter_binds": [{x: 1}, {x: 0}]} - # Raise when no parameters passed for parametric circuit - self.assertRaises(QiskitError, assemble, expr_circ) + with self.assertWarns(DeprecationWarning): + # Raise when no parameters passed for parametric circuit + self.assertRaises(QiskitError, assemble, expr_circ) - # Raise when circuit has more parameters than run_config - self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args) + with self.assertWarns(DeprecationWarning): + # Raise when circuit has more parameters than run_config + self.assertRaises(QiskitError, assemble, expr_circ, **partial_bind_args) def test_assemble_circuits_binds_parameters(self): """Verify assemble_circuits applies parameter bindings and output circuits are bound.""" @@ -422,7 +447,8 @@ def test_assemble_circuits_binds_parameters(self): bind_args = {"parameter_binds": [{x: 0, y: 0}, {x: 1, y: 0}, {x: 1, y: 1}]} - qobj = assemble([qc1, qc2, qc3], **bind_args) + with self.assertWarns(DeprecationWarning): + qobj = assemble([qc1, qc2, qc3], **bind_args) self.assertEqual(len(qobj.experiments), 9) self.assertEqual( @@ -451,17 +477,20 @@ def _qobj_inst_params(expt_no, inst_no): def test_init_qubits_default(self): """Check that the init_qubits=None assemble option is passed on to the qobj.""" - qobj = assemble(self.circ) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_true(self): """Check that the init_qubits=True assemble option is passed on to the qobj.""" - qobj = assemble(self.circ, init_qubits=True) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, init_qubits=True) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_false(self): """Check that the init_qubits=False assemble option is passed on to the qobj.""" - qobj = assemble(self.circ, init_qubits=False) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, init_qubits=False) self.assertEqual(qobj.config.init_qubits, False) def test_circuit_with_global_phase(self): @@ -471,7 +500,8 @@ def test_circuit_with_global_phase(self): circ.cx(0, 1) circ.measure_all() circ.global_phase = 0.3 * np.pi - qobj = assemble([circ, self.circ]) + with self.assertWarns(DeprecationWarning): + qobj = assemble([circ, self.circ]) self.assertEqual(getattr(qobj.experiments[1].header, "global_phase"), 0) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0.3 * np.pi) @@ -493,10 +523,12 @@ def _define(self): gate = TestGate() circ = QuantumCircuit(1) circ.append(gate, [0]) - qobj = assemble([circ]) + with self.assertWarns(DeprecationWarning): + qobj = assemble([circ]) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), 0) circ.global_phase = np.pi / 2 - qobj = assemble([circ]) + with self.assertWarns(DeprecationWarning): + qobj = assemble([circ]) self.assertEqual(getattr(qobj.experiments[0].header, "global_phase"), np.pi / 2) def test_pulse_gates_single_circ(self): @@ -518,7 +550,8 @@ def test_pulse_gates_single_circ(self): circ.add_calibration(RxGate(3.14), [0], x180) circ.add_calibration(RxGate(3.14), [1], x180) - qobj = assemble(circ, FakeOpenPulse2Q()) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, FakeOpenPulse2Q()) # Only one circuit, so everything is stored at the job level cals = qobj.config.calibrations lib = qobj.config.pulse_library @@ -539,7 +572,8 @@ def test_custom_pulse_gates_single_circ(self): circ.add_calibration("h", [0], custom_h_schedule) - qobj = assemble(circ, FakeOpenPulse2Q()) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, FakeOpenPulse2Q()) lib = qobj.config.pulse_library self.assertEqual(len(lib), 1) np.testing.assert_almost_equal( @@ -559,7 +593,8 @@ def test_pulse_gates_with_parameteric_pulses(self): backend = FakeOpenPulse2Q() backend.configuration().parametric_pulses = ["drag"] - qobj = assemble(circ, backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, backend) self.assertFalse(hasattr(qobj.config, "pulse_library")) self.assertTrue(hasattr(qobj.config, "calibrations")) @@ -577,7 +612,8 @@ def test_pulse_gates_multiple_circuits(self): circ2 = QuantumCircuit(2) circ2.h(0) - qobj = assemble([circ, circ2], FakeOpenPulse2Q()) + with self.assertWarns(DeprecationWarning): + qobj = assemble([circ, circ2], FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.pulse_library), 1) self.assertEqual(len(qobj.experiments[0].config.calibrations.gates), 2) self.assertFalse(hasattr(qobj.config, "calibrations")) @@ -598,7 +634,8 @@ def test_pulse_gates_common_cals(self): circ2.h(0) circ2.add_calibration(RxGate(3.14), [1], dummy_sched) - qobj = assemble([circ, circ2], FakeOpenPulse2Q()) + with self.assertWarns(DeprecationWarning): + qobj = assemble([circ, circ2], FakeOpenPulse2Q()) # Identical pulses are only added once self.assertEqual(len(qobj.config.pulse_library), 1) # Identical calibrations are only added once @@ -611,7 +648,8 @@ def test_pulse_gates_common_cals(self): def test_assemble_adds_circuit_metadata_to_experiment_header(self): """Verify that any circuit metadata is added to the experiment header.""" circ = QuantumCircuit(2, metadata={"experiment_type": "gst", "execution_number": "1234"}) - qobj = assemble(circ, shots=100, memory=False, seed_simulator=6) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, shots=100, memory=False, seed_simulator=6) self.assertEqual( qobj.experiments[0].header.metadata, {"experiment_type": "gst", "execution_number": "1234"}, @@ -623,7 +661,8 @@ def test_pulse_gates_delay_only(self): circ.append(Gate("test", 1, []), [0]) test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0)) circ.add_calibration("test", [0], test_sched) - qobj = assemble(circ, FakeOpenPulse2Q()) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2) self.assertEqual( qobj.config.calibrations.gates[0].instructions[1].to_dict(), @@ -633,12 +672,13 @@ def test_pulse_gates_delay_only(self): def test_job_qubit_meas_los_no_range(self): """Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ out any lo range.""" - qobj = assemble( - self.circ, - backend=self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.circ, + backend=self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + ) # convert to ghz qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] @@ -653,73 +693,79 @@ def test_job_lo_errors(self): meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq] # lo range not a nested list - with self.assertRaises(QiskitError): - assemble( - self.circ, - backend=self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - qubit_lo_range=[4.995e9 for i in range(self.num_qubits)], - meas_lo_range=meas_lo_range, - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + assemble( + self.circ, + backend=self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + qubit_lo_range=[4.995e9 for i in range(self.num_qubits)], + meas_lo_range=meas_lo_range, + ) # qubit lo range inner list not 2d - with self.assertRaises(QiskitError): - assemble( - self.circ, - backend=self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - qubit_lo_range=qubit_lo_range, - meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + assemble( + self.circ, + backend=self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + qubit_lo_range=qubit_lo_range, + meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], + ) # meas lo range inner list not 2d - with self.assertRaises(QiskitError): - assemble( - self.circ, - backend=self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - qubit_lo_range=qubit_lo_range, - meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + assemble( + self.circ, + backend=self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + qubit_lo_range=qubit_lo_range, + meas_lo_range=[[6.695e9] for i in range(self.num_qubits)], + ) # qubit lo out of range - with self.assertRaises(QiskitError): - assemble( - self.circ, - backend=self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)], - meas_lo_range=meas_lo_range, - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + assemble( + self.circ, + backend=self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + qubit_lo_range=[[5.005e9, 5.010e9] for i in range(self.num_qubits)], + meas_lo_range=meas_lo_range, + ) # meas lo out of range - with self.assertRaises(QiskitError): - assemble( - self.circ, - backend=self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - qubit_lo_range=qubit_lo_range, - meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)], - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + assemble( + self.circ, + backend=self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + qubit_lo_range=qubit_lo_range, + meas_lo_range=[[6.705e9, 6.710e9] for i in range(self.num_qubits)], + ) def test_job_qubit_meas_los_w_range(self): """Test that adding job qubit/meas lo freq lists are assembled into the qobj.config, w/ lo ranges input. Verify that lo ranges do not enter into the config.""" qubit_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_qubit_lo_freq] meas_lo_range = [[freq - 5e6, freq + 5e6] for freq in self.default_meas_lo_freq] - qobj = assemble( - self.circ, - backend=self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - qubit_lo_range=qubit_lo_range, - meas_lo_range=meas_lo_range, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.circ, + backend=self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + qubit_lo_range=qubit_lo_range, + meas_lo_range=meas_lo_range, + ) # convert to ghz qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] @@ -731,13 +777,14 @@ def test_job_qubit_meas_los_w_range(self): def test_assemble_single_circ_single_lo_config(self): """Test assembling a single circuit, with a single experiment level lo config.""" - qobj = assemble( - self.circ, - self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=self.user_lo_config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.circ, + self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=self.user_lo_config, + ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) @@ -746,13 +793,14 @@ def test_assemble_single_circ_single_lo_config(self): def test_assemble_single_circ_single_lo_config_dict(self): """Test assembling a single circuit, with a single experiment level lo config supplied as dictionary.""" - qobj = assemble( - self.circ, - self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=self.user_lo_config_dict, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.circ, + self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=self.user_lo_config_dict, + ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) @@ -769,13 +817,14 @@ def test_assemble_single_circ_multi_lo_config(self): pulse.MeasureChannel(3): 6.1e9, } user_lo_config2 = pulse.LoConfig(user_lo_config_dict2) - qobj = assemble( - self.circ, - self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[self.user_lo_config, user_lo_config2], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.circ, + self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[self.user_lo_config, user_lo_config2], + ) qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] @@ -800,13 +849,14 @@ def test_assemble_multi_circ_multi_lo_config(self): pulse.MeasureChannel(3): 6.1e9, } user_lo_config2 = pulse.LoConfig(user_lo_config_dict2) - qobj = assemble( - [self.circ, self.circ], - self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[self.user_lo_config, user_lo_config2], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + [self.circ, self.circ], + self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[self.user_lo_config, user_lo_config2], + ) qubit_lo_freq_ghz = [freq / 1e9 for freq in self.default_qubit_lo_freq] meas_lo_freq_ghz = [freq / 1e9 for freq in self.default_meas_lo_freq] @@ -824,13 +874,14 @@ def test_assemble_multi_circ_multi_lo_config(self): def test_assemble_multi_circ_single_lo_config(self): """Test assembling multiple circuits, with a single experiment level lo config (should override job level).""" - qobj = assemble( - [self.circ, self.circ], - self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=self.user_lo_config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + [self.circ, self.circ], + self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=self.user_lo_config, + ) self.assertListEqual(qobj.config.qubit_lo_freq, [5.55, 5, 5, 4.91, 5]) self.assertListEqual(qobj.config.meas_lo_freq, [6.64, 6.7, 6.7, 6.7, 6.1]) @@ -840,14 +891,15 @@ def test_assemble_multi_circ_wrong_number_of_multi_lo_configs(self): """Test assembling circuits, with a different number of experiment level lo configs (n:m setup). """ - with self.assertRaises(QiskitError): - assemble( - [self.circ, self.circ, self.circ], - self.backend, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[self.user_lo_config, self.user_lo_config], - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + assemble( + [self.circ, self.circ, self.circ], + self.backend, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[self.user_lo_config, self.user_lo_config], + ) def test_assemble_circ_lo_config_errors(self): """Test that lo config errors are raised properly if experiment level los are provided and @@ -867,7 +919,8 @@ def test_assemble_circ_lo_config_errors(self): pulse.MeasureChannel(4): 7e9, } - qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.circ, self.backend, schedule_los=full_lo_config_dict) self.assertListEqual(qobj.config.qubit_lo_freq, [4.85, 4.9, 4.95, 5, 5.05]) self.assertListEqual(qobj.config.meas_lo_freq, [6.8, 6.85, 6.9, 6.95, 7]) @@ -876,14 +929,16 @@ def test_assemble_circ_lo_config_errors(self): # no defaults and missing experiment level drive lo raises missing_drive_lo_config_dict = copy.deepcopy(full_lo_config_dict) missing_drive_lo_config_dict.pop(pulse.DriveChannel(0)) - with self.assertRaises(QiskitError): - qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + qobj = assemble(self.circ, self.backend, schedule_los=missing_drive_lo_config_dict) # no defaults and missing experiment level meas lo raises missing_meas_lo_config_dict = copy.deepcopy(full_lo_config_dict) missing_meas_lo_config_dict.pop(pulse.MeasureChannel(0)) - with self.assertRaises(QiskitError): - qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + qobj = assemble(self.circ, self.backend, schedule_los=missing_meas_lo_config_dict) # verify lo ranges are checked at experiment level lo_values = list(full_lo_config_dict.values()) @@ -892,24 +947,26 @@ def test_assemble_circ_lo_config_errors(self): # out of range drive lo full_lo_config_dict[pulse.DriveChannel(0)] -= 5.5e6 - with self.assertRaises(QiskitError): - qobj = assemble( - self.circ, - self.backend, - qubit_lo_range=qubit_lo_range, - schedule_los=full_lo_config_dict, - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + qobj = assemble( + self.circ, + self.backend, + qubit_lo_range=qubit_lo_range, + schedule_los=full_lo_config_dict, + ) full_lo_config_dict[pulse.DriveChannel(0)] += 5.5e6 # reset drive value # out of range meas lo full_lo_config_dict[pulse.MeasureChannel(0)] += 5.5e6 - with self.assertRaises(QiskitError): - qobj = assemble( - self.circ, - self.backend, - meas_lo_range=meas_lo_range, - schedule_los=full_lo_config_dict, - ) + with self.assertWarns(DeprecationWarning): + with self.assertRaises(QiskitError): + qobj = assemble( + self.circ, + self.backend, + meas_lo_range=meas_lo_range, + schedule_los=full_lo_config_dict, + ) class TestPulseAssembler(QiskitTestCase): @@ -945,13 +1002,14 @@ def setUp(self): def test_assemble_adds_schedule_metadata_to_experiment_header(self): """Verify that any circuit metadata is added to the experiment header.""" self.schedule.metadata = {"experiment_type": "gst", "execution_number": "1234"} - qobj = assemble( - self.schedule, - shots=100, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + shots=100, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[], + ) self.assertEqual( qobj.experiments[0].header.metadata, {"experiment_type": "gst", "execution_number": "1234"}, @@ -969,14 +1027,15 @@ def test_assemble_sample_pulse(self): schedule += pulse.Play( pulse.Waveform([0.5] * 16, name="test0"), pulse.DriveChannel(0), name="test1" ) - qobj = assemble( - schedule, - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[], - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[], + **self.config, + ) test_dict = qobj.to_dict() experiment = test_dict["experiments"][0] @@ -994,14 +1053,15 @@ def test_assemble_sample_pulse(self): def test_assemble_single_schedule_without_lo_config(self): """Test assembling a single schedule, no lo config.""" - qobj = assemble( - self.schedule, - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[], - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[], + **self.config, + ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) @@ -1010,13 +1070,14 @@ def test_assemble_single_schedule_without_lo_config(self): def test_assemble_multi_schedules_without_lo_config(self): """Test assembling schedules, no lo config.""" - qobj = assemble( - [self.schedule, self.schedule], - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + [self.schedule, self.schedule], + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + **self.config, + ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) @@ -1025,14 +1086,15 @@ def test_assemble_multi_schedules_without_lo_config(self): def test_assemble_single_schedule_with_lo_config(self): """Test assembling a single schedule, with a single lo config.""" - qobj = assemble( - self.schedule, - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=self.user_lo_config, - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=self.user_lo_config, + **self.config, + ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0]) @@ -1041,14 +1103,15 @@ def test_assemble_single_schedule_with_lo_config(self): def test_assemble_single_schedule_with_lo_config_dict(self): """Test assembling a single schedule, with a single lo config supplied as dictionary.""" - qobj = assemble( - self.schedule, - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=self.user_lo_config_dict, - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=self.user_lo_config_dict, + **self.config, + ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.91, 5.0]) @@ -1057,14 +1120,15 @@ def test_assemble_single_schedule_with_lo_config_dict(self): def test_assemble_single_schedule_with_multi_lo_configs(self): """Test assembling a single schedule, with multiple lo configs (frequency sweep).""" - qobj = assemble( - self.schedule, - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[self.user_lo_config, self.user_lo_config], - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[self.user_lo_config, self.user_lo_config], + **self.config, + ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) @@ -1074,14 +1138,15 @@ def test_assemble_single_schedule_with_multi_lo_configs(self): def test_assemble_multi_schedules_with_multi_lo_configs(self): """Test assembling schedules, with the same number of lo configs (n:n setup).""" - qobj = assemble( - [self.schedule, self.schedule], - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[self.user_lo_config, self.user_lo_config], - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + [self.schedule, self.schedule], + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[self.user_lo_config, self.user_lo_config], + **self.config, + ) test_dict = qobj.to_dict() self.assertListEqual(test_dict["config"]["qubit_lo_freq"], [4.9, 5.0]) @@ -1092,14 +1157,15 @@ def test_assemble_multi_schedules_with_multi_lo_configs(self): def test_assemble_multi_schedules_with_wrong_number_of_multi_lo_configs(self): """Test assembling schedules, with a different number of lo configs (n:m setup).""" with self.assertRaises(QiskitError): - assemble( - [self.schedule, self.schedule, self.schedule], - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[self.user_lo_config, self.user_lo_config], - **self.config, - ) + with self.assertWarns(DeprecationWarning): + assemble( + [self.schedule, self.schedule, self.schedule], + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[self.user_lo_config, self.user_lo_config], + **self.config, + ) def test_assemble_meas_map(self): """Test assembling a single schedule, no lo config.""" @@ -1107,20 +1173,22 @@ def test_assemble_meas_map(self): schedule = schedule.insert(5, Acquire(5, AcquireChannel(0), MemorySlot(0))) schedule = schedule.insert(5, Acquire(5, AcquireChannel(1), MemorySlot(1))) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0], [1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0], [1]], + ) self.assertIsInstance(qobj, PulseQobj) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1, 2]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1, 2]], + ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_memory_slots(self): @@ -1132,12 +1200,13 @@ def test_assemble_memory_slots(self): 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0], [1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0], [1]], + ) self.assertEqual(qobj.config.memory_slots, n_memoryslots) # this should be in experimental header as well @@ -1153,13 +1222,13 @@ def test_assemble_memory_slots(self): 5, self.backend_config.acquire(0), mem_slot=pulse.MemorySlot(n_memoryslots - 1) ), ) - - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0], [1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0], [1]], + ) self.assertEqual(qobj.config.memory_slots, n_memoryslots) # this should be in experimental header as well @@ -1176,12 +1245,13 @@ def test_assemble_memory_slots_for_schedules(self): ) schedules.append(schedule) - qobj = assemble( - schedules, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0], [1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedules, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0], [1]], + ) self.assertEqual(qobj.config.memory_slots, max(n_memoryslots)) self.assertEqual(qobj.experiments[0].header.memory_slots, n_memoryslots[0]) @@ -1198,14 +1268,15 @@ def test_pulse_name_conflicts(self): 1, Play(name_conflict_pulse, self.backend_config.drive(1)) ) - qobj = assemble( - self.schedule, - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[], - **self.config, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[], + **self.config, + ) self.assertNotEqual(qobj.config.pulse_library[0].name, qobj.config.pulse_library[1].name) @@ -1222,9 +1293,12 @@ def test_pulse_name_conflicts_in_other_schedule(self): sched += measure(qubits=[0], backend=backend) << 100 schedules.append(sched) - qobj = assemble( - schedules, qubit_lo_freq=defaults.qubit_freq_est, meas_lo_freq=defaults.meas_freq_est - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedules, + qubit_lo_freq=defaults.qubit_freq_est, + meas_lo_freq=defaults.meas_freq_est, + ) # two user pulses and one measurement pulse should be contained self.assertEqual(len(qobj.config.pulse_library), 3) @@ -1233,7 +1307,9 @@ def test_assemble_with_delay(self): """Test that delay instruction is not ignored in assembly.""" delay_schedule = pulse.Delay(10, self.backend_config.drive(0)) delay_schedule += self.schedule - delay_qobj = assemble(delay_schedule, self.backend) + + with self.assertWarns(DeprecationWarning): + delay_qobj = assemble(delay_schedule, self.backend) self.assertEqual(delay_qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(delay_qobj.experiments[0].instructions[0].duration, 10) @@ -1258,7 +1334,8 @@ def test_delay_removed_on_acq_ch(self): sched2 += delay1 sched2 += self.schedule # includes ``Acquire`` instr - delay_qobj = assemble([sched0, sched1, sched2], self.backend) + with self.assertWarns(DeprecationWarning): + delay_qobj = assemble([sched0, sched1, sched2], self.backend) # check that no delay instrs occur on acquire channels is_acq_delay = False @@ -1279,15 +1356,16 @@ def test_delay_removed_on_acq_ch(self): def test_assemble_schedule_enum(self): """Test assembling a schedule with enum input values to assemble.""" - qobj = assemble( - self.schedule, - qobj_header=self.header, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - schedule_los=[], - meas_level=MeasLevel.CLASSIFIED, - meas_return=MeasReturnType.AVERAGE, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qobj_header=self.header, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + schedule_los=[], + meas_level=MeasLevel.CLASSIFIED, + meas_return=MeasReturnType.AVERAGE, + ) test_dict = qobj.to_dict() self.assertEqual(test_dict["config"]["meas_return"], "avg") @@ -1319,7 +1397,8 @@ def test_assemble_parametric(self): "gaussian_square", "constant", ] - qobj = assemble(sched, backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(sched, backend) self.assertEqual(qobj.config.pulse_library, []) qobj_insts = qobj.experiments[0].instructions @@ -1361,7 +1440,8 @@ def test_assemble_parametric_unsupported(self): backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = ["something_extra"] - qobj = assemble(sched, backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(sched, backend) self.assertNotEqual(qobj.config.pulse_library, []) qobj_insts = qobj.experiments[0].instructions @@ -1379,7 +1459,8 @@ def test_assemble_parametric_pulse_kwarg_with_backend_setting(self): qc.add_calibration("x", (0,), x_q0) - qobj = assemble(qc, backend, parametric_pulses=["gaussian"]) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc, backend, parametric_pulses=["gaussian"]) self.assertEqual(qobj.config.parametric_pulses, ["gaussian"]) def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self): @@ -1394,22 +1475,26 @@ def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self): qc.add_calibration("x", (0,), x_q0) - qobj = assemble(qc, backend, parametric_pulses=[]) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc, backend, parametric_pulses=[]) self.assertEqual(qobj.config.parametric_pulses, []) def test_init_qubits_default(self): """Check that the init_qubits=None assemble option is passed on to the qobj.""" - qobj = assemble(self.schedule, self.backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_true(self): """Check that the init_qubits=True assemble option is passed on to the qobj.""" - qobj = assemble(self.schedule, self.backend, init_qubits=True) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.schedule, self.backend, init_qubits=True) self.assertEqual(qobj.config.init_qubits, True) def test_init_qubits_false(self): """Check that the init_qubits=False assemble option is passed on to the qobj.""" - qobj = assemble(self.schedule, self.backend, init_qubits=False) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.schedule, self.backend, init_qubits=False) self.assertEqual(qobj.config.init_qubits, False) def test_assemble_backend_rep_times_delays(self): @@ -1423,14 +1508,15 @@ def test_assemble_backend_rep_times_delays(self): setattr(self.backend_config, "default_rep_delay", default_rep_delay) # dynamic rep rates off - qobj = assemble(self.schedule, self.backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) # dynamic rep rates on setattr(self.backend_config, "dynamic_reprate_enabled", True) # RuntimeWarning bc ``rep_time`` is specified`` when dynamic rep rates not enabled - with self.assertWarns(RuntimeWarning): + with self.assertWarns(DeprecationWarning): qobj = assemble(self.schedule, self.backend) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, default_rep_delay * 1e6) @@ -1445,7 +1531,7 @@ def test_assemble_user_rep_time_delay(self): # dynamic rep rates off # RuntimeWarning bc using ``rep_delay`` when dynamic rep rates off - with self.assertWarns(RuntimeWarning): + with self.assertWarns(DeprecationWarning): qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) @@ -1454,7 +1540,7 @@ def test_assemble_user_rep_time_delay(self): # RuntimeWarning bc using ``rep_time`` when dynamic rep rates are enabled del self.config["rep_delay"] setattr(self.backend_config, "dynamic_reprate_enabled", True) - with self.assertWarns(RuntimeWarning): + with self.assertWarns(DeprecationWarning): qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_time * 1e6)) self.assertEqual(hasattr(qobj.config, "rep_delay"), False) @@ -1466,19 +1552,21 @@ def test_assemble_user_rep_time_delay(self): setattr(self.backend_config, "rep_delay_range", [0, 3.0e-6]) setattr(self.backend_config, "default_rep_delay", 2.2e-6) del self.config["rep_time"] - qobj = assemble(self.schedule, self.backend, **self.config) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, 2.2) # use qobj ``default_rep_delay`` self.config["rep_delay"] = 1.5e-6 - qobj = assemble(self.schedule, self.backend, **self.config) + with self.assertWarns(DeprecationWarning): + qobj = assemble(self.schedule, self.backend, **self.config) self.assertEqual(qobj.config.rep_time, int(rep_times[0] * 1e6)) self.assertEqual(qobj.config.rep_delay, 1.5) # use ``rep_delay`` outside of ``rep_delay_range self.config["rep_delay"] = 5.0e-6 - with self.assertRaises(QiskitError): + with self.assertRaises(DeprecationWarning): assemble(self.schedule, self.backend, **self.config) def test_assemble_with_individual_discriminators(self): @@ -1494,12 +1582,13 @@ def test_assemble_with_individual_discriminators(self): Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two), ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1]], + ) qobj_discriminators = qobj.experiments[0].instructions[0].discriminators self.assertEqual(len(qobj_discriminators), 2) @@ -1520,12 +1609,13 @@ def test_assemble_with_single_discriminators(self): Acquire(5, AcquireChannel(1), MemorySlot(1)), ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1]], + ) qobj_discriminators = qobj.experiments[0].instructions[0].discriminators self.assertEqual(len(qobj_discriminators), 1) @@ -1543,7 +1633,7 @@ def test_assemble_with_unequal_discriminators(self): schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), discriminator=disc_two) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) - with self.assertRaises(QiskitError): + with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, @@ -1564,12 +1654,13 @@ def test_assemble_with_individual_kernels(self): Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two), ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1]], + ) qobj_kernels = qobj.experiments[0].instructions[0].kernels self.assertEqual(len(qobj_kernels), 2) @@ -1590,12 +1681,13 @@ def test_assemble_with_single_kernels(self): Acquire(5, AcquireChannel(1), MemorySlot(1)), ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1]], + ) qobj_kernels = qobj.experiments[0].instructions[0].kernels self.assertEqual(len(qobj_kernels), 1) @@ -1613,7 +1705,7 @@ def test_assemble_with_unequal_kernels(self): schedule += Acquire(5, AcquireChannel(1), MemorySlot(1), kernel=disc_two) schedule += Acquire(5, AcquireChannel(2), MemorySlot(2)) - with self.assertRaises(QiskitError): + with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): assemble( schedule, qubit_lo_freq=self.default_qubit_lo_freq, @@ -1624,7 +1716,8 @@ def test_assemble_with_unequal_kernels(self): def test_assemble_single_instruction(self): """Test assembling schedules, no lo config.""" inst = pulse.Play(pulse.Constant(100, 1.0), pulse.DriveChannel(0)) - self.assertIsInstance(assemble(inst, self.backend), PulseQobj) + with self.assertWarns(DeprecationWarning): + self.assertIsInstance(assemble(inst, self.backend), PulseQobj) def test_assemble_overlapping_time(self): """Test that assembly errors when qubits are measured in overlapping time.""" @@ -1636,12 +1729,13 @@ def test_assemble_overlapping_time(self): Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1, ) with self.assertRaises(QiskitError): - assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1]], - ) + with self.assertWarns(DeprecationWarning): + assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1]], + ) def test_assemble_meas_map_vs_insts(self): """Test that assembly errors when the qubits are measured in overlapping time @@ -1653,12 +1747,13 @@ def test_assemble_meas_map_vs_insts(self): schedule += Acquire(5, AcquireChannel(3), MemorySlot(3)) << 2 with self.assertRaises(QiskitError): - assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0], [1, 2], [3]], - ) + with self.assertWarns(DeprecationWarning): + assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0], [1, 2], [3]], + ) def test_assemble_non_overlapping_time_single_meas_map(self): """Test that assembly works when qubits are measured in non-overlapping @@ -1670,12 +1765,13 @@ def test_assemble_non_overlapping_time_single_meas_map(self): schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 5, ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1]], + ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_disjoint_time(self): @@ -1687,12 +1783,13 @@ def test_assemble_disjoint_time(self): schedule = schedule.append( Acquire(5, AcquireChannel(1), MemorySlot(1)) << 1, ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 2], [1, 3]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 2], [1, 3]], + ) self.assertIsInstance(qobj, PulseQobj) def test_assemble_valid_qubits(self): @@ -1708,12 +1805,13 @@ def test_assemble_valid_qubits(self): schedule = schedule.append( Acquire(5, AcquireChannel(3), MemorySlot(3)), ) - qobj = assemble( - schedule, - qubit_lo_freq=self.default_qubit_lo_freq, - meas_lo_freq=self.default_meas_lo_freq, - meas_map=[[0, 1, 2], [3]], - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + schedule, + qubit_lo_freq=self.default_qubit_lo_freq, + meas_lo_freq=self.default_meas_lo_freq, + meas_map=[[0, 1, 2], [3]], + ) self.assertIsInstance(qobj, PulseQobj) @@ -1746,24 +1844,26 @@ def setUp(self): def test_defaults(self): """Test defaults work.""" - qobj = assemble( - self.schedule, - qubit_lo_freq=self.qubit_lo_freq, - meas_lo_freq=self.meas_lo_freq, - qubit_lo_range=self.qubit_lo_range, - meas_lo_range=self.meas_lo_range, - schedule_los=self.schedule_los, - meas_map=self.meas_map, - memory_slots=self.memory_slots, - rep_time=self.rep_time, - rep_delay=self.rep_delay, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qubit_lo_freq=self.qubit_lo_freq, + meas_lo_freq=self.meas_lo_freq, + qubit_lo_range=self.qubit_lo_range, + meas_lo_range=self.meas_lo_range, + schedule_los=self.schedule_los, + meas_map=self.meas_map, + memory_slots=self.memory_slots, + rep_time=self.rep_time, + rep_delay=self.rep_delay, + ) self.assertIsInstance(qobj, PulseQobj) def test_missing_qubit_lo_freq(self): """Test error raised if qubit_lo_freq missing.""" - with self.assertRaises(QiskitError): + with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): + assemble( self.schedule, qubit_lo_freq=None, @@ -1779,7 +1879,7 @@ def test_missing_qubit_lo_freq(self): def test_missing_meas_lo_freq(self): """Test error raised if meas_lo_freq missing.""" - with self.assertRaises(QiskitError): + with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): assemble( self.schedule, qubit_lo_freq=self.qubit_lo_freq, @@ -1794,74 +1894,78 @@ def test_missing_meas_lo_freq(self): def test_missing_memory_slots(self): """Test error is not raised if memory_slots are missing.""" - qobj = assemble( - self.schedule, - qubit_lo_freq=self.qubit_lo_freq, - meas_lo_freq=self.meas_lo_freq, - qubit_lo_range=self.qubit_lo_range, - meas_lo_range=self.meas_lo_range, - schedule_los=self.schedule_los, - meas_map=self.meas_map, - memory_slots=None, - rep_time=self.rep_time, - rep_delay=self.rep_delay, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qubit_lo_freq=self.qubit_lo_freq, + meas_lo_freq=self.meas_lo_freq, + qubit_lo_range=self.qubit_lo_range, + meas_lo_range=self.meas_lo_range, + schedule_los=self.schedule_los, + meas_map=self.meas_map, + memory_slots=None, + rep_time=self.rep_time, + rep_delay=self.rep_delay, + ) self.assertIsInstance(qobj, PulseQobj) def test_missing_rep_time_and_delay(self): """Test qobj is valid if rep_time and rep_delay are missing.""" - qobj = assemble( - self.schedule, - qubit_lo_freq=self.qubit_lo_freq, - meas_lo_freq=self.meas_lo_freq, - qubit_lo_range=self.qubit_lo_range, - meas_lo_range=self.meas_lo_range, - schedule_los=self.schedule_los, - meas_map=self.meas_map, - memory_slots=None, - rep_time=None, - rep_delay=None, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qubit_lo_freq=self.qubit_lo_freq, + meas_lo_freq=self.meas_lo_freq, + qubit_lo_range=self.qubit_lo_range, + meas_lo_range=self.meas_lo_range, + schedule_los=self.schedule_los, + meas_map=self.meas_map, + memory_slots=None, + rep_time=None, + rep_delay=None, + ) self.assertEqual(hasattr(qobj, "rep_time"), False) self.assertEqual(hasattr(qobj, "rep_delay"), False) def test_missing_meas_map(self): """Test that assembly still works if meas_map is missing.""" - qobj = assemble( - self.schedule, - qubit_lo_freq=self.qubit_lo_freq, - meas_lo_freq=self.meas_lo_freq, - qubit_lo_range=self.qubit_lo_range, - meas_lo_range=self.meas_lo_range, - schedule_los=self.schedule_los, - meas_map=None, - memory_slots=self.memory_slots, - rep_time=self.rep_time, - rep_delay=self.rep_delay, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qubit_lo_freq=self.qubit_lo_freq, + meas_lo_freq=self.meas_lo_freq, + qubit_lo_range=self.qubit_lo_range, + meas_lo_range=self.meas_lo_range, + schedule_los=self.schedule_los, + meas_map=None, + memory_slots=self.memory_slots, + rep_time=self.rep_time, + rep_delay=self.rep_delay, + ) self.assertIsInstance(qobj, PulseQobj) def test_missing_lo_ranges(self): """Test that assembly still works if lo_ranges are missing.""" - qobj = assemble( - self.schedule, - qubit_lo_freq=self.qubit_lo_freq, - meas_lo_freq=self.meas_lo_freq, - qubit_lo_range=None, - meas_lo_range=None, - schedule_los=self.schedule_los, - meas_map=self.meas_map, - memory_slots=self.memory_slots, - rep_time=self.rep_time, - rep_delay=self.rep_delay, - ) + with self.assertWarns(DeprecationWarning): + qobj = assemble( + self.schedule, + qubit_lo_freq=self.qubit_lo_freq, + meas_lo_freq=self.meas_lo_freq, + qubit_lo_range=None, + meas_lo_range=None, + schedule_los=self.schedule_los, + meas_map=self.meas_map, + memory_slots=self.memory_slots, + rep_time=self.rep_time, + rep_delay=self.rep_delay, + ) self.assertIsInstance(qobj, PulseQobj) def test_unsupported_meas_level(self): """Test that assembly raises an error if meas_level is not supported""" backend = FakeOpenPulse2Q() backend.configuration().meas_levels = [1, 2] - with self.assertRaises(QiskitError): + with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): assemble( self.schedule, backend, @@ -1890,10 +1994,12 @@ def test_single_and_deprecated_acquire_styles(self): deprecated_style_schedule += Acquire(1200, AcquireChannel(i), MemorySlot(i)) # The Qobj IDs will be different - n_qobj = assemble(new_style_schedule, backend) + with self.assertWarns(DeprecationWarning): + n_qobj = assemble(new_style_schedule, backend) n_qobj.qobj_id = None n_qobj.experiments[0].header.name = None - d_qobj = assemble(deprecated_style_schedule, backend) + with self.assertWarns(DeprecationWarning): + d_qobj = assemble(deprecated_style_schedule, backend) d_qobj.qobj_id = None d_qobj.experiments[0].header.name = None self.assertEqual(n_qobj, d_qobj) @@ -1924,7 +2030,8 @@ def setUp(self): def assertAssembleLog(self, log_msg): """Runs assemble and checks for logs containing specified message""" - assemble(self.circuit, shots=2000, memory=True) + with self.assertWarns(DeprecationWarning): + assemble(self.circuit, shots=2000, memory=True) self.output.seek(0) # Filter unrelated log lines output_lines = self.output.readlines() From a2ee3b3689cf2b53f0f67ba0ffd472687a2dccf3 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 08:29:29 +0200 Subject: [PATCH 048/168] test.python.transpiler.test_star_prerouting --- test/python/transpiler/test_star_prerouting.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/test/python/transpiler/test_star_prerouting.py b/test/python/transpiler/test_star_prerouting.py index ddc8096eefd7..c09d4a717a28 100644 --- a/test/python/transpiler/test_star_prerouting.py +++ b/test/python/transpiler/test_star_prerouting.py @@ -15,6 +15,8 @@ """Test the StarPreRouting pass""" import unittest +import warnings + from test import QiskitTestCase import ddt @@ -258,8 +260,11 @@ def test_100q_grid_full_path(self, opt_level): ) pm.init += StarPreRouting() result = pm.run(qc) - counts_before = AerSimulator().run(qc).result().get_counts() - counts_after = AerSimulator().run(result).result().get_counts() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` + warnings.simplefilter("ignore", category=DeprecationWarning) + counts_before = AerSimulator().run(qc).result().get_counts() + counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) def test_10q_bv_no_barrier(self): @@ -298,8 +303,11 @@ def test_100q_grid_full_path_no_barrier(self, opt_level): ) pm.init += StarPreRouting() result = pm.run(qc) - counts_before = AerSimulator().run(qc).result().get_counts() - counts_after = AerSimulator().run(result).result().get_counts() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` + warnings.simplefilter("ignore", category=DeprecationWarning) + counts_before = AerSimulator().run(qc).result().get_counts() + counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) def test_hadamard_ordering(self): From 8a56629bff59adb3154d7b7fa7a4d8cefd268bdc Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 10:41:20 +0200 Subject: [PATCH 049/168] test.python.pulse.test_instruction_schedule_map --- test/python/pulse/test_instruction_schedule_map.py | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/test/python/pulse/test_instruction_schedule_map.py b/test/python/pulse/test_instruction_schedule_map.py index 67628ba845ae..3ef2ccaa38e5 100644 --- a/test/python/pulse/test_instruction_schedule_map.py +++ b/test/python/pulse/test_instruction_schedule_map.py @@ -305,12 +305,13 @@ def test_pop_gate(self): def test_sequenced_parameterized_schedule(self): """Test parameterized schedule consists of multiple instruction.""" - converter = QobjToInstructionConverter([], buffer=0) - qobjs = [ - PulseQobjInstruction(name="fc", ch="d0", t0=10, phase="P1"), - PulseQobjInstruction(name="fc", ch="d0", t0=20, phase="P2"), - PulseQobjInstruction(name="fc", ch="d0", t0=30, phase="P3"), - ] + with self.assertWarns(DeprecationWarning): + converter = QobjToInstructionConverter([], buffer=0) + qobjs = [ + PulseQobjInstruction(name="fc", ch="d0", t0=10, phase="P1"), + PulseQobjInstruction(name="fc", ch="d0", t0=20, phase="P2"), + PulseQobjInstruction(name="fc", ch="d0", t0=30, phase="P3"), + ] converted_instruction = [converter(qobj) for qobj in qobjs] inst_map = InstructionScheduleMap() From 249ccb7b0f7c17ddd77385185c0981c8ecb79ea1 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 10:45:42 +0200 Subject: [PATCH 050/168] test.python.providers.basic_provider.test_basic_simulator --- qiskit/assembler/assemble_circuits.py | 17 ++++++++++------- .../basic_provider/test_basic_simulator.py | 3 +-- 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index 13187089d631..6c6aa37fc602 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -157,13 +157,16 @@ def _assemble_circuit( ] conditional_reg_idx = memory_slots + max_conditional_idx - conversion_bfunc = QasmQobjInstruction( - name="bfunc", - mask="0x%X" % mask, # pylint: disable=consider-using-f-string - relation="==", - val="0x%X" % val, # pylint: disable=consider-using-f-string - register=conditional_reg_idx, - ) + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using _assemble + warnings.simplefilter("ignore", category=DeprecationWarning) + conversion_bfunc = QasmQobjInstruction( + name="bfunc", + mask="0x%X" % mask, # pylint: disable=consider-using-f-string + relation="==", + val="0x%X" % val, # pylint: disable=consider-using-f-string + register=conditional_reg_idx, + ) instructions.append(conversion_bfunc) instruction.conditional = conditional_reg_idx max_conditional_idx += 1 diff --git a/test/python/providers/basic_provider/test_basic_simulator.py b/test/python/providers/basic_provider/test_basic_simulator.py index 282b23c1b2a5..57dd67dfd3c3 100644 --- a/test/python/providers/basic_provider/test_basic_simulator.py +++ b/test/python/providers/basic_provider/test_basic_simulator.py @@ -17,7 +17,7 @@ import numpy as np from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister -from qiskit.compiler import transpile, assemble +from qiskit.compiler import transpile from qiskit.providers.basic_provider import BasicSimulator from qiskit.qasm2 import dumps from test import QiskitTestCase # pylint: disable=wrong-import-order @@ -47,7 +47,6 @@ def setUp(self): qcirc = QuantumCircuit.from_qasm_file(qasm_filename) qcirc.name = "test" self.transpiled_circuit = transpile(qcirc, backend=self.backend) - self.qobj = assemble(self.transpiled_circuit, shots=1000, seed_simulator=self.seed) def test_basic_simulator_single_shot(self): """Test single shot run.""" From e48d295ec3f49afb1a22404668c87edbaacc4b35 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 10:53:14 +0200 Subject: [PATCH 051/168] test.python.primitives.test_backend_sampler_v2 --- qiskit/primitives/backend_estimator.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index 8446c870b1fd..a41deca6e801 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -15,6 +15,7 @@ from __future__ import annotations +import warnings from collections.abc import Sequence from itertools import accumulate @@ -67,14 +68,17 @@ def _run_circuits( max_circuits = backend.max_circuits else: raise RuntimeError("Backend version not supported") - if max_circuits: - jobs = [ - backend.run(circuits[pos : pos + max_circuits], **run_options) - for pos in range(0, len(circuits), max_circuits) - ] - result = [x.result() for x in jobs] - else: - result = [backend.run(circuits, **run_options).result()] + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + if max_circuits: + jobs = [ + backend.run(circuits[pos : pos + max_circuits], **run_options) + for pos in range(0, len(circuits), max_circuits) + ] + result = [x.result() for x in jobs] + else: + result = [backend.run(circuits, **run_options).result()] return result, metadata From 50a350a73da93aaaee5bdd430d232a2696854272 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 10:55:15 +0200 Subject: [PATCH 052/168] test.python.compiler.test_disassembler --- test/python/compiler/test_disassembler.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/python/compiler/test_disassembler.py b/test/python/compiler/test_disassembler.py index 0525b54e2107..e5d0fd73a79c 100644 --- a/test/python/compiler/test_disassembler.py +++ b/test/python/compiler/test_disassembler.py @@ -457,8 +457,7 @@ class TestPulseScheduleDisassembler(QiskitTestCase): def setUp(self): super().setUp() - with self.assertWarns(DeprecationWarning): - self.backend = FakeOpenPulse2Q() + self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"] From fefb2946ad3db444833317ce57e84e00ae3df959 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 15:07:08 +0200 Subject: [PATCH 053/168] test.python.compiler.test_compiler --- test/python/compiler/test_compiler.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/python/compiler/test_compiler.py b/test/python/compiler/test_compiler.py index 7ebfe1f13343..1479fde88cec 100644 --- a/test/python/compiler/test_compiler.py +++ b/test/python/compiler/test_compiler.py @@ -197,7 +197,8 @@ def test_parallel_compile(self): qc.cx(qr[0], qr[k]) qc.measure(qr[5], cr[0]) qlist = [qc for k in range(10)] - qobj = assemble(transpile(qlist, backend=backend)) + with self.assertWarns(DeprecationWarning): + qobj = assemble(transpile(qlist, backend=backend)) self.assertEqual(len(qobj.experiments), 10) def test_no_conflict_backend_passmanager(self): @@ -240,7 +241,8 @@ def test_compile_single_qubit(self): circuit2 = transpile( circuit, backend=None, coupling_map=cmap, basis_gates=["u2"], initial_layout=layout ) - qobj = assemble(circuit2) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circuit2) compiled_instruction = qobj.experiments[0].instructions[0] @@ -504,7 +506,8 @@ def test_yzy_zyz_cases(self): circ1.cx(qr[0], qr[1]) circ1.rz(0.7, qr[1]) circ1.rx(1.570796, qr[1]) - qobj1 = assemble(transpile(circ1, backend)) + with self.assertWarns(DeprecationWarning): + qobj1 = assemble(transpile(circ1, backend)) self.assertIsInstance(qobj1, QasmQobj) circ2 = QuantumCircuit(qr) @@ -512,7 +515,8 @@ def test_yzy_zyz_cases(self): circ2.h(qr[0]) circ2.s(qr[0]) circ2.h(qr[0]) - qobj2 = assemble(transpile(circ2, backend)) + with self.assertWarns(DeprecationWarning): + qobj2 = assemble(transpile(circ2, backend)) self.assertIsInstance(qobj2, QasmQobj) From da38a7240b59db87475acfd973bf8474a3b53564 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 15:09:58 +0200 Subject: [PATCH 054/168] test.python.circuit.test_scheduled_circuit --- test/python/circuit/test_scheduled_circuit.py | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index ec4bc72ffd06..c3b3158d7b85 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -66,11 +66,6 @@ def test_schedule_circuit_when_backend_tells_dt(self): self.assertEqual(sc.data[4].operation.name, "delay") self.assertEqual(sc.data[4].operation.duration, 450450) self.assertEqual(sc.data[4].operation.unit, "dt") - qobj = assemble(sc, self.backend_with_dt) - self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") - self.assertEqual(qobj.experiments[0].instructions[0].params[0], 450450) - self.assertEqual(qobj.experiments[0].instructions[4].name, "delay") - self.assertEqual(qobj.experiments[0].instructions[4].params[0], 450450) def test_schedule_circuit_when_transpile_option_tells_dt(self): """dt is known to transpiler by transpile option""" @@ -119,7 +114,7 @@ def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): self.assertEqual(sc.data[4].operation.name, "delay") self.assertAlmostEqual(sc.data[4].operation.duration, 1.0e-4 + 1.0e-7) self.assertEqual(sc.data[4].operation.unit, "s") - with self.assertRaises(QiskitError): + with self.assertRaises(DeprecationWarning): assemble(sc, self.backend_without_dt) def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self): @@ -377,7 +372,8 @@ def test_transpile_and_assemble_delay_circuit_for_simulator(self): qc.delay(100, 0, "ns") circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled - qobj = assemble(circ, self.simulator_backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[0].name, "delay") self.assertEqual(qobj.experiments[0].instructions[0].params[0], 1e-7) @@ -389,7 +385,8 @@ def test_transpile_and_assemble_t1_circuit_for_simulator(self): qc.measure(0, 0) circ = transpile(qc, self.simulator_backend) self.assertEqual(circ.duration, None) # not scheduled - qobj = assemble(circ, self.simulator_backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, self.simulator_backend) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertAlmostEqual(qobj.experiments[0].instructions[1].params[0], 1e-7) @@ -415,7 +412,8 @@ def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween qc.measure(0, 0) circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) - qobj = assemble(circ, self.backend_with_dt) + with self.assertWarns(DeprecationWarning): + qobj = assemble(circ, self.backend_with_dt) self.assertEqual(qobj.experiments[0].instructions[1].name, "delay") self.assertEqual(qobj.experiments[0].instructions[1].params[0], 450) @@ -440,7 +438,7 @@ def test_fail_to_assemble_circuits_with_unbounded_parameters(self): qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = transpile(qc, self.backend_with_dt) - with self.assertRaises(QiskitError): + with self.assertRaises(DeprecationWarning): assemble(qc, self.backend_with_dt) @data("asap", "alap") From a4180087ab7b7734c126fe8319d0e18249d73e69 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 15:18:47 +0200 Subject: [PATCH 055/168] test.python.providers.test_fake_backends --- test/python/providers/test_fake_backends.py | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index d5c5507b3b8e..76d96c946028 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -17,6 +17,7 @@ import itertools import operator import unittest +import warnings from test import combine from ddt import ddt, data @@ -112,7 +113,10 @@ def test_circuit_on_fake_backend_v2(self, backend, optimization_level): ), seed_simulator=42, ) - result = job.result() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") @@ -134,7 +138,10 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): ), seed_simulator=42, ) - result = job.result() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") @@ -142,7 +149,8 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): def test_qobj_failure(self): backend = BACKENDS[-1] tqc = transpile(self.circuit, backend) - qobj = assemble(tqc, backend) + with self.assertWarns(DeprecationWarning): + qobj = assemble(tqc, backend) with self.assertRaises(QiskitError): backend.run(qobj) @@ -226,7 +234,10 @@ def test_converter(self, opt_level): self.assertIsInstance(backend_v2, BackendV2) res = transpile(self.circuit, backend_v2, optimization_level=opt_level) job = backend_v2.run(res) - result = job.result() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") From a3f0c795835408ae00cdde903104dbe0de662f33 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 17:53:52 +0200 Subject: [PATCH 056/168] test.python.circuit.test_unitary --- test/python/circuit/test_initializer.py | 3 ++- test/python/circuit/test_unitary.py | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/test/python/circuit/test_initializer.py b/test/python/circuit/test_initializer.py index 122a4e4afe9a..a37c51f48184 100644 --- a/test/python/circuit/test_initializer.py +++ b/test/python/circuit/test_initializer.py @@ -481,7 +481,8 @@ def test_init(self): all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) ) - qobj = assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = assemble(qc) params = qobj.experiments[0].instructions[0].params self.assertTrue( all(isinstance(p, complex) and not isinstance(p, np.number) for p in params) diff --git a/test/python/circuit/test_unitary.py b/test/python/circuit/test_unitary.py index c5c9344ad7ed..63edbdaffbf9 100644 --- a/test/python/circuit/test_unitary.py +++ b/test/python/circuit/test_unitary.py @@ -168,7 +168,8 @@ def test_qobj_with_unitary_matrix(self): uni = UnitaryGate(matrix) qc.append(uni, [qr[0], qr[1], qr[3]]) qc.cx(qr[3], qr[2]) - qobj = qiskit.compiler.assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[1] self.assertEqual(instr.name, "unitary") assert_allclose(numpy.array(instr.params[0]).astype(numpy.complex64), matrix) @@ -197,7 +198,8 @@ def test_labeled_unitary(self): matrix = numpy.kron(sigmax, sigmay) uni = UnitaryGate(matrix, label="xy") qc.append(uni, [qr[0], qr[1]]) - qobj = qiskit.compiler.assemble(qc) + with self.assertWarns(DeprecationWarning): + qobj = qiskit.compiler.assemble(qc) instr = qobj.experiments[0].instructions[0] self.assertEqual(instr.name, "unitary") self.assertEqual(instr.label, "xy") From 2c99f288ec451c1b4a40a3bb04dba8954dd62d22 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 18:23:23 +0200 Subject: [PATCH 057/168] test.python.transpiler.test_sabre_swap --- test/python/compiler/test_transpiler.py | 6 +++++- test/python/transpiler/test_sabre_swap.py | 12 ++++++++---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 77b63a3098bc..72f813ae6dfd 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -17,6 +17,7 @@ import math import os import sys +import warnings from logging import StreamHandler, getLogger from unittest.mock import patch import numpy as np @@ -2638,7 +2639,10 @@ def test_parallel_dispatch(self, opt_level): tqc = transpile( qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242 ) - result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: self.assertTrue(math.isclose(count["00000"], 500, rel_tol=0.1)) diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index b1effdae7d8b..e403627c3daa 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -15,6 +15,8 @@ import unittest import itertools +import warnings + import ddt import numpy.random @@ -278,10 +280,12 @@ def test_no_infinite_loop(self, method): from qiskit_aer import Aer - with self.assertWarns(DeprecationWarning): - sim = Aer.get_backend("aer_simulator") - in_results = sim.run(qc, shots=4096).result().get_counts() - out_results = sim.run(routed, shots=4096).result().get_counts() + sim = Aer.get_backend("aer_simulator") + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + in_results = sim.run(qc, shots=4096).result().get_counts() + out_results = sim.run(routed, shots=4096).result().get_counts() self.assertEqual(set(in_results), set(out_results)) def test_classical_condition(self): From 51244030e904e16198298314d0f22e38177486a9 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 18:25:24 +0200 Subject: [PATCH 058/168] test.python.providers.fake_provider.test_fake_backends --- .../providers/fake_provider/test_fake_backends.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index c12be3584fc2..b2c8b6532ab2 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -13,6 +13,7 @@ """Test of generated fake backends.""" import math import unittest +import warnings from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.providers.fake_provider import Fake5QV1, GenericBackendV2 @@ -45,7 +46,10 @@ def test_fake_backends_get_kwargs(self): qc.measure_all() trans_qc = transpile(qc, backend) - raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @@ -57,6 +61,9 @@ def test_fake_backend_v2_noise_model_always_present(self): qc = QuantumCircuit(1) qc.x(0) qc.measure_all() - res = backend.run(qc, shots=1000).result().get_counts() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.simplefilter("ignore", category=DeprecationWarning) + res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000}) From 884d3942a2e6d9bc4463f7e28a2e406f107193b9 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 1 Jul 2024 19:08:47 +0200 Subject: [PATCH 059/168] Aer using Provider ABC --- .../fake_provider/test_generic_backend_v2.py | 7 ++++++- test/python/transpiler/test_sabre_swap.py | 12 ++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/test/python/providers/fake_provider/test_generic_backend_v2.py b/test/python/providers/fake_provider/test_generic_backend_v2.py index cd7c611b2212..fd11b8a2eab6 100644 --- a/test/python/providers/fake_provider/test_generic_backend_v2.py +++ b/test/python/providers/fake_provider/test_generic_backend_v2.py @@ -13,6 +13,7 @@ """ Test of GenericBackendV2 backend""" import math +import warnings from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, transpile from qiskit.providers.fake_provider import GenericBackendV2 @@ -116,7 +117,11 @@ def test_run(self): backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"]) tqc = transpile(qc, backend=backend, optimization_level=3, seed_transpiler=42) - result = backend.run(tqc, seed_simulator=42, shots=1000).result() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using Provider ABC + # https://github.com/Qiskit/qiskit-aer/pull/2184 + warnings.simplefilter("ignore", category=DeprecationWarning) + result = backend.run(tqc, seed_simulator=42, shots=1000).result() counts = result.get_counts() self.assertTrue(math.isclose(counts["00000"], 500, rel_tol=0.1)) diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index e403627c3daa..74932767f9e2 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -275,15 +275,19 @@ def test_no_infinite_loop(self, method): # Assert that the same keys are produced by a simulation - this is a test that the inserted # swaps route the qubits correctly. - if not optionals.HAS_AER: - return + with warnings.catch_warnings(): + # TODO remove Aer stops using Provider Qiskit class + warnings.simplefilter("ignore", category=DeprecationWarning) + if not optionals.HAS_AER: + return from qiskit_aer import Aer - sim = Aer.get_backend("aer_simulator") with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField + # TODO remove this catch once Aer stops using QobjDictField and Provider ABC + # https://github.com/Qiskit/qiskit-aer/pull/2184 warnings.simplefilter("ignore", category=DeprecationWarning) + sim = Aer.get_backend("aer_simulator") in_results = sim.run(qc, shots=4096).result().get_counts() out_results = sim.run(routed, shots=4096).result().get_counts() self.assertEqual(set(in_results), set(out_results)) From ada3d38935897c53058ab732d6c48ade0165a65f Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 2 Jul 2024 11:17:57 +0200 Subject: [PATCH 060/168] aer warnings --- qiskit/providers/fake_provider/fake_backend.py | 5 ++++- test/python/providers/test_fake_backends.py | 16 ++++++++-------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 5523d123e073..0de65b09622d 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -58,7 +58,10 @@ def _setup_sim(self): self.sim = AerSimulator() if self.properties(): - noise_model = NoiseModel.from_backend(self) + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops Treating CircuitInstruction as an iterable + warnings.simplefilter("ignore", category=DeprecationWarning) + noise_model = NoiseModel.from_backend(self) self.sim.set_options(noise_model=noise_model) # Update fake backend default options too to avoid overwriting # it when run() is called diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 76d96c946028..a5e67e4025ee 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -105,17 +105,17 @@ def setUpClass(cls): optimization_level=[0, 1, 2, 3], ) def test_circuit_on_fake_backend_v2(self, backend, optimization_level): - if not optionals.HAS_AER and backend.num_qubits > 20: - self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") - job = backend.run( - transpile( - self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level - ), - seed_simulator=42, - ) with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField warnings.simplefilter("ignore", category=DeprecationWarning) + if not optionals.HAS_AER and backend.num_qubits > 20: + self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") + job = backend.run( + transpile( + self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level + ), + seed_simulator=42, + ) result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] From 593fabb60906eed51a1d2744d78a8b9204935f45 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 2 Jul 2024 17:08:29 +0200 Subject: [PATCH 061/168] reno --- qiskit/providers/fake_provider/fake_backend.py | 3 --- .../notes/deprecate_assemble-67486b4d0a8d4f96.yaml | 10 ++++++++++ releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml | 4 ---- 3 files changed, 10 insertions(+), 7 deletions(-) create mode 100644 releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml delete mode 100644 releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 0de65b09622d..5fbd0de5da61 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -123,9 +123,6 @@ def properties(self): @classmethod def _default_options(cls): - # with warnings.catch_warnings(): - # Remove this - # warnings.simplefilter("ignore", category=DeprecationWarning) if _optionals.HAS_AER: from qiskit_aer import QasmSimulator diff --git a/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml b/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml new file mode 100644 index 000000000000..3c99d84ce84d --- /dev/null +++ b/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml @@ -0,0 +1,10 @@ +--- +deprecations_providers: + - | + The structures related to Qobj are now deprecated. Interacting with remote backends should be done via QPY or + OpenQASM instead. +deprecations_transpiler: + - | + The function `assemble` is now deprecated as the Oobj structure is not needed any more. The function was used, + among other things, to create a Qobj. It was also used for binding parameter and that functionality is now + fully covered by :meth:`.assign_parameters`. diff --git a/releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml b/releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml deleted file mode 100644 index 8817020e742a..000000000000 --- a/releasenotes/notes/qobj_assemble-f745a12fd88ba9fb.yaml +++ /dev/null @@ -1,4 +0,0 @@ ---- -deprecations_providers: - - | - With the deprecation of BackendV1, the Qobj structure is not necessary and it is deprecated. Hence, the related tools such as the function assemble are also deprecated. From 1d781b0129ad2fce826253b2bc6bc45fcf0f24f6 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 3 Jul 2024 11:02:42 +0200 Subject: [PATCH 062/168] another pass on reno --- releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml b/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml index 3c99d84ce84d..94044a361bb9 100644 --- a/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml +++ b/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml @@ -5,6 +5,6 @@ deprecations_providers: OpenQASM instead. deprecations_transpiler: - | - The function `assemble` is now deprecated as the Oobj structure is not needed any more. The function was used, + The function `assemble` is now deprecated as the Qobj structure is not needed any more. The function was used, among other things, to create a Qobj. It was also used for binding parameter and that functionality is now - fully covered by :meth:`.assign_parameters`. + fully covered by :meth:`~.QuantumCircuit.assign_parameters`. From 621e72ad3b84d5949bb4a5b8f0de879aea46e028 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 3 Jul 2024 14:45:59 +0200 Subject: [PATCH 063/168] test.python.pulse --- qiskit/assembler/assemble_circuits.py | 4 ++-- qiskit/providers/fake_provider/fake_backend.py | 18 +++++++++++++----- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index 6c6aa37fc602..4e2439ca525b 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -326,14 +326,14 @@ def _assemble_circuits( # configure LO freqs per circuit with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # warnings.simplefilter("ignore", category=DeprecationWarning) lo_converter = converters.LoConfigConverter( QasmQobjExperimentConfig, **run_config.to_dict() ) experiments = _configure_experiment_los(experiments, lo_converter, run_config) with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # warnings.simplefilter("ignore", category=DeprecationWarning) qobj_config = QasmQobjConfig() if run_config: qobj_config_dict = run_config.to_dict() diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 5fbd0de5da61..240c8e343edf 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -123,12 +123,20 @@ def properties(self): @classmethod def _default_options(cls): - if _optionals.HAS_AER: - from qiskit_aer import QasmSimulator + with warnings.catch_warnings(): + # Remove once https://github.com/Qiskit/qiskit-aer/issues/2178 gets closed. + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + module="qiskit", + message=".+abstract Provider and ProviderV1.+", + ) + if _optionals.HAS_AER: + from qiskit_aer import QasmSimulator - return QasmSimulator._default_options() - else: - return basic_provider.BasicSimulator._default_options() + return QasmSimulator._default_options() + else: + return basic_provider.BasicSimulator._default_options() def run(self, run_input, **kwargs): """Main job in simulator""" From 3898c7705c321998a2b6ba10368c392357fc8d2a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 3 Jul 2024 15:11:07 +0200 Subject: [PATCH 064/168] test.python.compiler.test_compiler --- qiskit/assembler/assemble_circuits.py | 4 ++-- qiskit/result/result.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index 4e2439ca525b..3a8a84bfc431 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -326,14 +326,14 @@ def _assemble_circuits( # configure LO freqs per circuit with warnings.catch_warnings(): - # warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") lo_converter = converters.LoConfigConverter( QasmQobjExperimentConfig, **run_config.to_dict() ) experiments = _configure_experiment_los(experiments, lo_converter, run_config) with warnings.catch_warnings(): - # warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") qobj_config = QasmQobjConfig() if run_config: qobj_config_dict = run_config.to_dict() diff --git a/qiskit/result/result.py b/qiskit/result/result.py index 1f8519c4b469..4a5a928f06d5 100644 --- a/qiskit/result/result.py +++ b/qiskit/result/result.py @@ -126,7 +126,7 @@ def from_dict(cls, data): in_data["results"] = [ExperimentResult.from_dict(x) for x in in_data.pop("results")] if in_data.get("header") is not None: with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") in_data["header"] = QobjHeader.from_dict(in_data.pop("header")) return cls(**in_data) From c2f2fdb3de97a6f5a44c8a6ba73442e75f99b106 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 3 Jul 2024 16:05:02 +0200 Subject: [PATCH 065/168] add module to fiterwarning --- qiskit/assembler/assemble_circuits.py | 19 ++++++++++++------- qiskit/circuit/instruction.py | 3 ++- qiskit/compiler/assembler.py | 3 ++- qiskit/primitives/backend_estimator.py | 2 +- .../providers/fake_provider/fake_backend.py | 2 +- .../fake_provider/fake_openpulse_2q.py | 3 ++- .../fake_provider/fake_openpulse_3q.py | 3 ++- .../fake_provider/generic_backend_v2.py | 10 +++++----- qiskit/providers/models/pulsedefaults.py | 5 +++-- qiskit/result/models.py | 3 ++- test/python/compiler/test_transpiler.py | 2 +- .../fake_provider/test_fake_backends.py | 9 +++++---- .../fake_provider/test_generic_backend_v2.py | 2 +- test/python/providers/test_fake_backends.py | 18 +++++++++--------- test/python/transpiler/test_sabre_swap.py | 4 ++-- .../python/transpiler/test_star_prerouting.py | 4 ++-- 16 files changed, 52 insertions(+), 40 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index 3a8a84bfc431..a8d7a78cfc4c 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -90,7 +90,8 @@ def _assemble_circuit( if metadata is None: metadata = {} with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QobjExperimentHeader is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") header = QobjExperimentHeader( qubit_labels=qubit_labels, n_qubits=num_qubits, @@ -105,7 +106,8 @@ def _assemble_circuit( # TODO: why do we need n_qubits and memory_slots in both the header and the config with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QasmQobjExperimentConfig is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") config = QasmQobjExperimentConfig(n_qubits=num_qubits, memory_slots=memory_slots) calibrations, pulse_library = _assemble_pulse_gates(circuit, run_config) if calibrations: @@ -158,8 +160,8 @@ def _assemble_circuit( conditional_reg_idx = memory_slots + max_conditional_idx with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using _assemble - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QasmQobjInstruction is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") conversion_bfunc = QasmQobjInstruction( name="bfunc", mask="0x%X" % mask, # pylint: disable=consider-using-f-string @@ -176,7 +178,8 @@ def _assemble_circuit( instructions.append(instruction) with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QasmQobjExperiment is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") return ( QasmQobjExperiment(instructions=instructions, header=header, config=config), pulse_library, @@ -365,7 +368,8 @@ def _assemble_circuits( qobj_config_dict["meas_lo_freq"] = [freq / 1e9 for freq in m_los] with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QasmQobjConfig is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") qobj_config = QasmQobjConfig(**qobj_config_dict) qubit_sizes = [] @@ -390,7 +394,8 @@ def _assemble_circuits( if calibrations and calibrations.gates: qobj_config.calibrations = calibrations with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QasmQobj is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") return QasmQobj( qobj_id=qobj_id, config=qobj_config, experiments=experiments, header=qobj_header ) diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index 2e1ae9ae7235..30796fa08ad2 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -372,7 +372,8 @@ def assemble(self): def _assemble(self): with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QasmQobjInstruction is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") instruction = QasmQobjInstruction(name=self.name) # Evaluate parameters if self.params: diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 3b6b22e11b86..0446735a5089 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -228,7 +228,8 @@ def _assemble( experiments = experiments if isinstance(experiments, list) else [experiments] pulse_qobj = any(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments) with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The Qobj is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") qobj_id, qobj_header, run_config_common_dict = _parse_common_args( backend, qobj_id, diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index a41deca6e801..4f237396d2b2 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -70,7 +70,7 @@ def _run_circuits( raise RuntimeError("Backend version not supported") with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") if max_circuits: jobs = [ backend.run(circuits[pos : pos + max_circuits], **run_options) diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 240c8e343edf..0256cbc9e17c 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -60,7 +60,7 @@ def _setup_sim(self): if self.properties(): with warnings.catch_warnings(): # TODO remove this catch once Aer stops Treating CircuitInstruction as an iterable - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") noise_model = NoiseModel.from_backend(self) self.sim.set_options(noise_model=noise_model) # Update fake backend default options too to avoid overwriting diff --git a/qiskit/providers/fake_provider/fake_openpulse_2q.py b/qiskit/providers/fake_provider/fake_openpulse_2q.py index f2b5b02f5229..c76f4e048828 100644 --- a/qiskit/providers/fake_provider/fake_openpulse_2q.py +++ b/qiskit/providers/fake_provider/fake_openpulse_2q.py @@ -128,7 +128,8 @@ def __init__(self): ) with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class PulseQobjInstruction is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") self._defaults = PulseDefaults.from_dict( { "qubit_freq_est": [4.9, 5.0], diff --git a/qiskit/providers/fake_provider/fake_openpulse_3q.py b/qiskit/providers/fake_provider/fake_openpulse_3q.py index 161fc5fbb4d4..36b66847dad4 100644 --- a/qiskit/providers/fake_provider/fake_openpulse_3q.py +++ b/qiskit/providers/fake_provider/fake_openpulse_3q.py @@ -111,7 +111,8 @@ def __init__(self): }, ) with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class PulseQobjInstruction is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") self._defaults = PulseDefaults.from_dict( { "qubit_freq_est": [4.9, 5.0, 4.8], diff --git a/qiskit/providers/fake_provider/generic_backend_v2.py b/qiskit/providers/fake_provider/generic_backend_v2.py index f20ac772eac1..595e075dd44b 100644 --- a/qiskit/providers/fake_provider/generic_backend_v2.py +++ b/qiskit/providers/fake_provider/generic_backend_v2.py @@ -254,8 +254,8 @@ def _get_calibration_sequence( # 1q gates vs 2q gates vs measurement instructions. if inst == "measure": with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) - # TODO move away from deprecated PulseQobjInstruction + # The class PulseQobjInstruction is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") sequence = [ PulseQobjInstruction( name="acquire", @@ -268,10 +268,10 @@ def _get_calibration_sequence( PulseQobjInstruction(name=pulse_library[1].name, ch=f"m{i}", t0=0) for i in qargs ] - return sequence + return sequence with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) - # TODO: move away from deprecated PulseQobjInstruction + # The class PulseQobjInstruction is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") if num_qubits == 1: return [ PulseQobjInstruction(name="fc", ch=f"u{qargs[0]}", t0=0, phase="-P0"), diff --git a/qiskit/providers/models/pulsedefaults.py b/qiskit/providers/models/pulsedefaults.py index 4edfc5f2c065..fcd11c26ec29 100644 --- a/qiskit/providers/models/pulsedefaults.py +++ b/qiskit/providers/models/pulsedefaults.py @@ -272,7 +272,7 @@ def from_dict(cls, data): PulseDefaults: The PulseDefaults from the input dictionary. """ schema = { - "pulse_library": PulseLibraryItem, + "pulse_library": PulseLibraryItem, # The class PulseLibraryItem` is deprecated "cmd_def": Command, "meas_kernel": MeasurementKernel, "discriminator": Discriminator, @@ -284,7 +284,8 @@ def from_dict(cls, data): for key, value in data.items(): if key in schema: with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class PulseLibraryItem` is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") if isinstance(value, list): in_data[key] = list(map(schema[key].from_dict, value)) else: diff --git a/qiskit/result/models.py b/qiskit/result/models.py index 3eabbdd2f14f..93a1954ac7f4 100644 --- a/qiskit/result/models.py +++ b/qiskit/result/models.py @@ -225,7 +225,8 @@ def from_dict(cls, data): data_obj = ExperimentResultData.from_dict(in_data.pop("data")) if "header" in in_data: with warnings.catch_warnings(): - warnings.simplefilter("ignore", category=DeprecationWarning) + # The class QobjExperimentHeader is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") in_data["header"] = QobjExperimentHeader.from_dict(in_data.pop("header")) shots = in_data.pop("shots") success = in_data.pop("success") diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 72f813ae6dfd..a1bfae10ee47 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -2641,7 +2641,7 @@ def test_parallel_dispatch(self, opt_level): ) with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index b2c8b6532ab2..7318fc2bc05a 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -48,7 +48,7 @@ def test_fake_backends_get_kwargs(self): trans_qc = transpile(qc, backend) with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @@ -62,8 +62,9 @@ def test_fake_backend_v2_noise_model_always_present(self): qc.x(0) qc.measure_all() with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.simplefilter("ignore", category=DeprecationWarning) - res = backend.run(qc, shots=1000).result().get_counts() + with warnings.catch_warnings(): + # TODO remove this catch once Aer stops using QobjDictField + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000}) diff --git a/test/python/providers/fake_provider/test_generic_backend_v2.py b/test/python/providers/fake_provider/test_generic_backend_v2.py index fd11b8a2eab6..8a19f62aee95 100644 --- a/test/python/providers/fake_provider/test_generic_backend_v2.py +++ b/test/python/providers/fake_provider/test_generic_backend_v2.py @@ -120,7 +120,7 @@ def test_run(self): with warnings.catch_warnings(): # TODO remove this catch once Aer stops using Provider ABC # https://github.com/Qiskit/qiskit-aer/pull/2184 - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") result = backend.run(tqc, seed_simulator=42, shots=1000).result() counts = result.get_counts() diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index a5e67e4025ee..49771deef568 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -107,7 +107,7 @@ def setUpClass(cls): def test_circuit_on_fake_backend_v2(self, backend, optimization_level): with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") if not optionals.HAS_AER and backend.num_qubits > 20: self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") job = backend.run( @@ -132,15 +132,15 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): self.skipTest( f"Unable to run fake_backend {backend.configuration().backend_name} without qiskit-aer" ) - job = backend.run( - transpile( - self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level - ), - seed_simulator=42, - ) with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + job = backend.run( + transpile( + self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level + ), + seed_simulator=42, + ) result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] @@ -236,7 +236,7 @@ def test_converter(self, opt_level): job = backend_v2.run(res) with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index 74932767f9e2..5273e2a17089 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -277,7 +277,7 @@ def test_no_infinite_loop(self, method): # swaps route the qubits correctly. with warnings.catch_warnings(): # TODO remove Aer stops using Provider Qiskit class - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") if not optionals.HAS_AER: return @@ -286,7 +286,7 @@ def test_no_infinite_loop(self, method): with warnings.catch_warnings(): # TODO remove this catch once Aer stops using QobjDictField and Provider ABC # https://github.com/Qiskit/qiskit-aer/pull/2184 - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") sim = Aer.get_backend("aer_simulator") in_results = sim.run(qc, shots=4096).result().get_counts() out_results = sim.run(routed, shots=4096).result().get_counts() diff --git a/test/python/transpiler/test_star_prerouting.py b/test/python/transpiler/test_star_prerouting.py index c09d4a717a28..aeac559e2b9c 100644 --- a/test/python/transpiler/test_star_prerouting.py +++ b/test/python/transpiler/test_star_prerouting.py @@ -262,7 +262,7 @@ def test_100q_grid_full_path(self, opt_level): result = pm.run(qc) with warnings.catch_warnings(): # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") counts_before = AerSimulator().run(qc).result().get_counts() counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) @@ -305,7 +305,7 @@ def test_100q_grid_full_path_no_barrier(self, opt_level): result = pm.run(qc) with warnings.catch_warnings(): # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` - warnings.simplefilter("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") counts_before = AerSimulator().run(qc).result().get_counts() counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) From 82032bc011b319a324c76b6baf7ba4115234a90d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 4 Jul 2024 11:38:44 +0200 Subject: [PATCH 066/168] test.python.compiler.test_transpiler --- qiskit/compiler/assembler.py | 53 ++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 0446735a5089..68edde7f7e6f 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -227,26 +227,23 @@ def _assemble( start_time = time() experiments = experiments if isinstance(experiments, list) else [experiments] pulse_qobj = any(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments) - with warnings.catch_warnings(): - # The Qobj is deprecated - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - qobj_id, qobj_header, run_config_common_dict = _parse_common_args( - backend, - qobj_id, - qobj_header, - shots, - memory, - seed_simulator, - init_qubits, - rep_delay, - qubit_lo_freq, - meas_lo_freq, - qubit_lo_range, - meas_lo_range, - schedule_los, - pulse_qobj=pulse_qobj, - **run_config, - ) + qobj_id, qobj_header, run_config_common_dict = _parse_common_args( + backend, + qobj_id, + qobj_header, + shots, + memory, + seed_simulator, + init_qubits, + rep_delay, + qubit_lo_freq, + meas_lo_freq, + qubit_lo_range, + meas_lo_range, + schedule_los, + pulse_qobj=pulse_qobj, + **run_config, + ) # assemble either circuits or schedules if all(isinstance(exp, QuantumCircuit) for exp in experiments): @@ -265,12 +262,16 @@ def _assemble( ) end_time = time() _log_assembly_time(start_time, end_time) - return _assemble_circuits( - circuits=bound_experiments, - qobj_id=qobj_id, - qobj_header=qobj_header, - run_config=run_config, - ) + with warnings.catch_warnings(): + # The Qobj is deprecated + # warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + warnings.filterwarnings("ignore", category=DeprecationWarning) + return _assemble_circuits( + circuits=bound_experiments, + qobj_id=qobj_id, + qobj_header=qobj_header, + run_config=run_config, + ) elif all(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments): run_config = _parse_pulse_args( From 963b1ae12337d675241b8dd6a58f963a23a93a3c Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 4 Jul 2024 12:45:05 +0200 Subject: [PATCH 067/168] fixing obscure expcetion handleing for comparison --- qiskit/compiler/assembler.py | 37 +++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 17 deletions(-) diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 68edde7f7e6f..eb1697fd4e07 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -227,23 +227,26 @@ def _assemble( start_time = time() experiments = experiments if isinstance(experiments, list) else [experiments] pulse_qobj = any(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments) - qobj_id, qobj_header, run_config_common_dict = _parse_common_args( - backend, - qobj_id, - qobj_header, - shots, - memory, - seed_simulator, - init_qubits, - rep_delay, - qubit_lo_freq, - meas_lo_freq, - qubit_lo_range, - meas_lo_range, - schedule_los, - pulse_qobj=pulse_qobj, - **run_config, - ) + with warnings.catch_warnings(): + # The Qobj is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + qobj_id, qobj_header, run_config_common_dict = _parse_common_args( + backend, + qobj_id, + qobj_header, + shots, + memory, + seed_simulator, + init_qubits, + rep_delay, + qubit_lo_freq, + meas_lo_freq, + qubit_lo_range, + meas_lo_range, + schedule_los, + pulse_qobj=pulse_qobj, + **run_config, + ) # assemble either circuits or schedules if all(isinstance(exp, QuantumCircuit) for exp in experiments): From 8f6714d1097ed1cba2274c738525054d0b70c5e4 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 11 Jul 2024 13:20:50 +0200 Subject: [PATCH 068/168] test.python.transpiler.test_stochastic_swap test.python.transpiler.test_sabre_swap --- test/python/transpiler/test_sabre_swap.py | 12 ++++++------ test/python/transpiler/test_stochastic_swap.py | 11 ++++++----- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index 5273e2a17089..792b55971e5a 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -26,7 +26,7 @@ from qiskit.circuit.random import random_circuit from qiskit.compiler.transpiler import transpile from qiskit.converters import circuit_to_dag, dag_to_circuit -from qiskit.providers.fake_provider import Fake27QPulseV1, GenericBackendV2 +from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler.passes import SabreSwap, TrivialLayout, CheckMap from qiskit.transpiler import CouplingMap, Layout, PassManager, Target, TranspilerError from qiskit import ClassicalRegister, QuantumRegister, QuantumCircuit @@ -1335,11 +1335,11 @@ class TestSabreSwapRandomCircuitValidOutput(QiskitTestCase): @classmethod def setUpClass(cls): super().setUpClass() - cls.backend = Fake27QPulseV1() - cls.backend.configuration().coupling_map = MUMBAI_CMAP - cls.backend.configuration().basis_gates += ["for_loop", "while_loop", "if_else"] - cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map} - cls.basis_gates = set(cls.backend.configuration().basis_gates) + cls.backend = GenericBackendV2( + num_qubits=27, calibrate_instructions=True, control_flow=True, coupling_map=MUMBAI_CMAP + ) + cls.coupling_edge_set = {tuple(x) for x in cls.backend.coupling_map} + cls.basis_gates = set(cls.backend.operation_names) def assert_valid_circuit(self, transpiled): """Assert circuit complies with constraints of backend.""" diff --git a/test/python/transpiler/test_stochastic_swap.py b/test/python/transpiler/test_stochastic_swap.py index 8c96150ae8ff..f04427e835bd 100644 --- a/test/python/transpiler/test_stochastic_swap.py +++ b/test/python/transpiler/test_stochastic_swap.py @@ -24,7 +24,7 @@ from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.transpiler.passes.utils import CheckMap from qiskit.circuit.random import random_circuit -from qiskit.providers.fake_provider import Fake27QPulseV1, GenericBackendV2 +from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.compiler.transpiler import transpile from qiskit.circuit import ControlFlowOp, Clbit, CASE_DEFAULT from qiskit.circuit.classical import expr, types @@ -1488,10 +1488,11 @@ class TestStochasticSwapRandomCircuitValidOutput(QiskitTestCase): @classmethod def setUpClass(cls): super().setUpClass() - cls.backend = Fake27QPulseV1() - cls.backend.configuration().basis_gates += ["for_loop", "while_loop", "if_else"] - cls.coupling_edge_set = {tuple(x) for x in cls.backend.configuration().coupling_map} - cls.basis_gates = set(cls.backend.configuration().basis_gates) + cls.backend = GenericBackendV2( + num_qubits=27, calibrate_instructions=True, control_flow=True + ) + cls.coupling_edge_set = {tuple(x) for x in cls.backend.coupling_map} + cls.basis_gates = set(cls.backend.operation_names) def assert_valid_circuit(self, transpiled): """Assert circuit complies with constraints of backend.""" From a921073e9cb1d53389b2e1cc2fd854aea51f3610 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 11 Jul 2024 13:49:45 +0200 Subject: [PATCH 069/168] test.python.transpiler.test_echo_rzx_weyl_decomposition --- test/python/transpiler/test_echo_rzx_weyl_decomposition.py | 7 ++++++- test/python/transpiler/test_sabre_swap.py | 6 +++++- test/python/transpiler/test_stochastic_swap.py | 2 +- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/test/python/transpiler/test_echo_rzx_weyl_decomposition.py b/test/python/transpiler/test_echo_rzx_weyl_decomposition.py index c4efffc977f4..8f876dd261d7 100644 --- a/test/python/transpiler/test_echo_rzx_weyl_decomposition.py +++ b/test/python/transpiler/test_echo_rzx_weyl_decomposition.py @@ -32,7 +32,12 @@ class TestEchoRZXWeylDecomposition(QiskitTestCase): def setUp(self): super().setUp() - self.backend = Fake27QPulseV1() + # TODO once https://github.com/Qiskit/qiskit/issues/12759 is fixed, replace with + # backend = GenericBackendV2(num_qubits=27, calibrate_instructions=True, + # control_flow=True, seed=42) + # self.inst_map = backend.instruction_schedule_map + with self.assertWarns(DeprecationWarning): + self.backend = Fake27QPulseV1() self.inst_map = self.backend.defaults().instruction_schedule_map def assertRZXgates(self, unitary_circuit, after): diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index 792b55971e5a..0ab954fd3412 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -1336,7 +1336,11 @@ class TestSabreSwapRandomCircuitValidOutput(QiskitTestCase): def setUpClass(cls): super().setUpClass() cls.backend = GenericBackendV2( - num_qubits=27, calibrate_instructions=True, control_flow=True, coupling_map=MUMBAI_CMAP + num_qubits=27, + calibrate_instructions=True, + control_flow=True, + coupling_map=MUMBAI_CMAP, + seed=42, ) cls.coupling_edge_set = {tuple(x) for x in cls.backend.coupling_map} cls.basis_gates = set(cls.backend.operation_names) diff --git a/test/python/transpiler/test_stochastic_swap.py b/test/python/transpiler/test_stochastic_swap.py index f04427e835bd..4843bac8baf5 100644 --- a/test/python/transpiler/test_stochastic_swap.py +++ b/test/python/transpiler/test_stochastic_swap.py @@ -1489,7 +1489,7 @@ class TestStochasticSwapRandomCircuitValidOutput(QiskitTestCase): def setUpClass(cls): super().setUpClass() cls.backend = GenericBackendV2( - num_qubits=27, calibrate_instructions=True, control_flow=True + num_qubits=27, calibrate_instructions=True, control_flow=True, seed=42 ) cls.coupling_edge_set = {tuple(x) for x in cls.backend.coupling_map} cls.basis_gates = set(cls.backend.operation_names) From 31a03e177913954b7849241f83f57631f20f0407 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 11 Jul 2024 15:28:29 +0200 Subject: [PATCH 070/168] test.python.transpiler.test_instruction_durations --- test/python/transpiler/test_instruction_durations.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/python/transpiler/test_instruction_durations.py b/test/python/transpiler/test_instruction_durations.py index ba37f6cd65e4..de68fbadf86a 100644 --- a/test/python/transpiler/test_instruction_durations.py +++ b/test/python/transpiler/test_instruction_durations.py @@ -36,14 +36,18 @@ def test_fail_if_invalid_dict_is_supplied_when_construction(self): InstructionDurations(invalid_dic) def test_from_backend_for_backend_with_dt(self): - backend = Fake27QPulseV1() + # Remove context once https://github.com/Qiskit/qiskit/issues/12760 is fixed + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() gate = self._find_gate_with_length(backend) durations = InstructionDurations.from_backend(backend) self.assertGreater(durations.dt, 0) self.assertGreater(durations.get(gate, 0), 0) def test_from_backend_for_backend_without_dt(self): - backend = Fake27QPulseV1() + # Remove context once https://github.com/Qiskit/qiskit/issues/12760 is fixed + with self.assertWarns(DeprecationWarning): + backend = Fake27QPulseV1() delattr(backend.configuration(), "dt") gate = self._find_gate_with_length(backend) durations = InstructionDurations.from_backend(backend) From 226a98b93a3d5faa34a62b6ade67a162f070e561 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 11 Jul 2024 15:51:36 +0200 Subject: [PATCH 071/168] test.python.providers.test_backendproperties --- test/python/providers/test_backendproperties.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/test/python/providers/test_backendproperties.py b/test/python/providers/test_backendproperties.py index b1455bd9a320..ac024973133e 100644 --- a/test/python/providers/test_backendproperties.py +++ b/test/python/providers/test_backendproperties.py @@ -22,12 +22,13 @@ class BackendpropertiesTestCase(QiskitTestCase): """Test usability methods of backend.properties().""" - backend = Fake5QV1() - backend_name = "fake_ourense" + # TODO the full file can be removed once BackendV1 is removed, since it is the + # only one with backend.properties() def setUp(self): super().setUp() - self.backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + self.backend = Fake5QV1() self.properties = self.backend.properties() self.ref_gate = next( g for g in self.backend.configuration().basis_gates if g not in ["id", "rz"] From 9dc293bf868fcc8e2e7902b3d6f0f73956354b68 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 11 Jul 2024 15:55:58 +0200 Subject: [PATCH 072/168] test.python.qpy.test_circuit_load_from_qpy --- test/python/qpy/test_circuit_load_from_qpy.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/python/qpy/test_circuit_load_from_qpy.py b/test/python/qpy/test_circuit_load_from_qpy.py index a050a70cac5f..774920699e1e 100644 --- a/test/python/qpy/test_circuit_load_from_qpy.py +++ b/test/python/qpy/test_circuit_load_from_qpy.py @@ -61,8 +61,10 @@ class TestCalibrationPasses(QpyCircuitTestCase): def setUp(self): super().setUp() - # This backend provides CX(0,1) with native ECR direction. - self.inst_map = Fake27QPulseV1().defaults().instruction_schedule_map + # TODO remove context once https://github.com/Qiskit/qiskit/issues/12759 is fixed + with self.assertWarns(DeprecationWarning): + # This backend provides CX(0,1) with native ECR direction. + self.inst_map = Fake27QPulseV1().defaults().instruction_schedule_map @data(0.1, 0.7, 1.5) def test_rzx_calibration(self, angle): From c20b11bf6b8eb605903392e78ee95f5da0c47455 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 10:42:56 +0200 Subject: [PATCH 073/168] test.python.providers.test_pulse_defaults --- test/python/providers/test_pulse_defaults.py | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/test/python/providers/test_pulse_defaults.py b/test/python/providers/test_pulse_defaults.py index 33fe9ecbad65..0facf9a9ce25 100644 --- a/test/python/providers/test_pulse_defaults.py +++ b/test/python/providers/test_pulse_defaults.py @@ -17,7 +17,7 @@ import numpy as np -from qiskit.providers.fake_provider import FakeOpenPulse2Q +from qiskit.providers.fake_provider import FakeOpenPulse2Q, GenericBackendV2 from test import QiskitTestCase # pylint: disable=wrong-import-order @@ -26,8 +26,13 @@ class TestPulseDefaults(QiskitTestCase): def setUp(self): super().setUp() - self.defs = FakeOpenPulse2Q().defaults() - self.inst_map = self.defs.instruction_schedule_map + with self.assertWarns(DeprecationWarning): + # BackendV2 does not have defaults + self.defs = FakeOpenPulse2Q().defaults() + backend = GenericBackendV2( + 27, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + ) + self.inst_map = backend.instruction_schedule_map def test_buffer(self): """Test getting the buffer value.""" From 283471b93f5bd26233bdfca4c68510baf9ac7eb6 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 10:45:38 +0200 Subject: [PATCH 074/168] test.python.primitives.test_backend_sampler_v2 --- test/python/primitives/test_backend_sampler_v2.py | 7 +++---- test/python/providers/test_pulse_defaults.py | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/test/python/primitives/test_backend_sampler_v2.py b/test/python/primitives/test_backend_sampler_v2.py index b03818846c82..632ed1984d2d 100644 --- a/test/python/primitives/test_backend_sampler_v2.py +++ b/test/python/primitives/test_backend_sampler_v2.py @@ -714,10 +714,9 @@ def max_circuits(self): def test_job_size_limit_backend_v1(self): """Test BackendSamplerV2 respects backend's job size limit.""" - backend = Fake7QPulseV1() - config = backend.configuration() - config.max_experiments = 1 - backend._configuration = config + backend = GenericBackendV2( + 2, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + ) qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) diff --git a/test/python/providers/test_pulse_defaults.py b/test/python/providers/test_pulse_defaults.py index 0facf9a9ce25..18f849255917 100644 --- a/test/python/providers/test_pulse_defaults.py +++ b/test/python/providers/test_pulse_defaults.py @@ -30,7 +30,7 @@ def setUp(self): # BackendV2 does not have defaults self.defs = FakeOpenPulse2Q().defaults() backend = GenericBackendV2( - 27, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + 2, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 ) self.inst_map = backend.instruction_schedule_map From 5ec7f9f6f67ed7fe5bacad8b22e2a545ccb99c44 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 10:49:13 +0200 Subject: [PATCH 075/168] test.python.primitives.test_backend_sampler --- .../python/primitives/test_backend_sampler.py | 22 +++++++++++++------ 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index 8d1a3e2aab2b..c8e644f2be3b 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -322,10 +322,9 @@ def max_circuits(self): def test_primitive_job_size_limit_backend_v1(self): """Test primitive respects backend's job size limit.""" - backend = Fake7QPulseV1() - config = backend.configuration() - config.max_experiments = 1 - backend._configuration = config + backend = GenericBackendV2( + 7, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + ) qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) @@ -362,12 +361,15 @@ def test_circuit_with_dynamic_circuit(self): def test_sequential_run(self): """Test sequential run.""" + backend = GenericBackendV2( + 7, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + ) qc = QuantumCircuit(1) qc.measure_all() qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=Fake7QPulseV1()) + sampler = BackendSampler(backend=backend) result = sampler.run([qc]).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) result2 = sampler.run([qc2]).result() @@ -407,7 +409,10 @@ def callback(msg): bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - sampler = BackendSampler(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) + backend = GenericBackendV2( + 7, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + ) + sampler = BackendSampler(backend=backend, bound_pass_manager=bound_pass) _ = sampler.run([self._circuit[0]]).result() expected = [ "bound_pass_manager", @@ -427,7 +432,10 @@ def callback(msg): # pylint: disable=function-redefined bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - sampler = BackendSampler(backend=Fake7QPulseV1(), bound_pass_manager=bound_pass) + backend = GenericBackendV2( + 7, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + ) + sampler = BackendSampler(backend=backend, bound_pass_manager=bound_pass) _ = sampler.run([self._circuit[0], self._circuit[0]]).result() expected = [ "bound_pass_manager", From dc8f2374ff4b2aaacbfdf2341003e95bb49679e0 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 10:57:26 +0200 Subject: [PATCH 076/168] test.python.compiler.test_scheduler --- test/python/compiler/test_scheduler.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/test/python/compiler/test_scheduler.py b/test/python/compiler/test_scheduler.py index 62e0af596ba4..ad9b14b24c4a 100644 --- a/test/python/compiler/test_scheduler.py +++ b/test/python/compiler/test_scheduler.py @@ -15,7 +15,7 @@ from qiskit.circuit import QuantumRegister, ClassicalRegister, QuantumCircuit from qiskit.exceptions import QiskitError from qiskit.pulse import InstructionScheduleMap, Schedule -from qiskit.providers.fake_provider import FakeOpenPulse3Q +from qiskit.providers.fake_provider import FakeOpenPulse3Q, GenericBackendV2 from qiskit.compiler.scheduler import schedule from test import QiskitTestCase # pylint: disable=wrong-import-order @@ -37,9 +37,9 @@ def setUp(self): self.circ2.cx(qr2[0], qr2[1]) self.circ2.measure(qr2, cr2) - self.backend = FakeOpenPulse3Q() - self.backend_config = self.backend.configuration() - self.num_qubits = self.backend_config.n_qubits + self.backend = GenericBackendV2( + 3, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 + ) def test_instruction_map_and_backend_not_supplied(self): """Test instruction map and backend not supplied.""" @@ -51,6 +51,8 @@ def test_instruction_map_and_backend_not_supplied(self): def test_instruction_map_and_backend_defaults_unavailable(self): """Test backend defaults unavailable when backend is provided, but instruction map is not.""" + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse3Q() self.backend._defaults = None with self.assertRaisesRegex( QiskitError, r"The backend defaults are unavailable. The backend may not support pulse." From df530caf512a8693e1bef80f5c1e0d3c62e9bc38 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 11:06:12 +0200 Subject: [PATCH 077/168] test/python/compiler/test_scheduler.py --- test/python/compiler/test_scheduler.py | 1 + 1 file changed, 1 insertion(+) diff --git a/test/python/compiler/test_scheduler.py b/test/python/compiler/test_scheduler.py index ad9b14b24c4a..ae7957c90010 100644 --- a/test/python/compiler/test_scheduler.py +++ b/test/python/compiler/test_scheduler.py @@ -51,6 +51,7 @@ def test_instruction_map_and_backend_not_supplied(self): def test_instruction_map_and_backend_defaults_unavailable(self): """Test backend defaults unavailable when backend is provided, but instruction map is not.""" + # TODO remove the test once BackendV1 is removed, since BackendV2 does not have defaults with self.assertWarns(DeprecationWarning): self.backend = FakeOpenPulse3Q() self.backend._defaults = None From 105848fa4476d29a690102757c6eae89682e5279 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 11:06:32 +0200 Subject: [PATCH 078/168] test.python.compiler.test_disassembler --- test/python/compiler/test_disassembler.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/python/compiler/test_disassembler.py b/test/python/compiler/test_disassembler.py index e5d0fd73a79c..0525b54e2107 100644 --- a/test/python/compiler/test_disassembler.py +++ b/test/python/compiler/test_disassembler.py @@ -457,7 +457,8 @@ class TestPulseScheduleDisassembler(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() self.backend_config.parametric_pulses = ["constant", "gaussian", "gaussian_square", "drag"] From 386d8939e9b71ec1b6fa79088fe970591db3e28d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 11:13:16 +0200 Subject: [PATCH 079/168] test.python.compiler.test_assembler --- test/python/compiler/test_assembler.py | 48 ++++++++++++++++++++------ 1 file changed, 37 insertions(+), 11 deletions(-) diff --git a/test/python/compiler/test_assembler.py b/test/python/compiler/test_assembler.py index ff1f86f228db..fdd23edd53f3 100644 --- a/test/python/compiler/test_assembler.py +++ b/test/python/compiler/test_assembler.py @@ -63,7 +63,9 @@ def setUp(self): self.circ.cx(qr[0], qr[1]) self.circ.measure(qr, cr) - self.backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + self.backend = Fake5QV1() self.backend_config = self.backend.configuration() self.num_qubits = self.backend_config.n_qubits @@ -551,6 +553,7 @@ def test_pulse_gates_single_circ(self): circ.add_calibration(RxGate(3.14), [1], x180) with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble(circ, FakeOpenPulse2Q()) # Only one circuit, so everything is stored at the job level cals = qobj.config.calibrations @@ -573,6 +576,7 @@ def test_custom_pulse_gates_single_circ(self): circ.add_calibration("h", [0], custom_h_schedule) with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble(circ, FakeOpenPulse2Q()) lib = qobj.config.pulse_library self.assertEqual(len(lib), 1) @@ -591,7 +595,9 @@ def test_pulse_gates_with_parameteric_pulses(self): circ.h(0) circ.add_calibration("h", [0], custom_h_schedule) - backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = FakeOpenPulse2Q() backend.configuration().parametric_pulses = ["drag"] with self.assertWarns(DeprecationWarning): qobj = assemble(circ, backend) @@ -635,6 +641,7 @@ def test_pulse_gates_common_cals(self): circ2.add_calibration(RxGate(3.14), [1], dummy_sched) with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble([circ, circ2], FakeOpenPulse2Q()) # Identical pulses are only added once self.assertEqual(len(qobj.config.pulse_library), 1) @@ -662,6 +669,7 @@ def test_pulse_gates_delay_only(self): test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0)) circ.add_calibration("test", [0], test_sched) with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble(circ, FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2) self.assertEqual( @@ -974,7 +982,9 @@ class TestPulseAssembler(QiskitTestCase): def setUp(self): super().setUp() - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() test_pulse = pulse.Waveform( @@ -1282,7 +1292,9 @@ def test_pulse_name_conflicts(self): def test_pulse_name_conflicts_in_other_schedule(self): """Test two pulses with the same name in different schedule can be resolved.""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = Fake27QPulseV1() defaults = backend.defaults() schedules = [] @@ -1390,7 +1402,9 @@ def test_assemble_parametric(self): ) << sched.duration ) - backend = FakeOpenPulse3Q() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = [ "gaussian", "drag", @@ -1437,7 +1451,9 @@ def test_assemble_parametric_unsupported(self): ) sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2)) - backend = FakeOpenPulse3Q() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = ["something_extra"] with self.assertWarns(DeprecationWarning): @@ -1449,7 +1465,9 @@ def test_assemble_parametric_unsupported(self): def test_assemble_parametric_pulse_kwarg_with_backend_setting(self): """Test that parametric pulses respect the kwarg over backend""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = Fake27QPulseV1() qc = QuantumCircuit(1, 1) qc.x(0) @@ -1465,7 +1483,9 @@ def test_assemble_parametric_pulse_kwarg_with_backend_setting(self): def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self): """Test that parametric pulses respect the kwarg as empty list over backend""" - backend = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = Fake27QPulseV1() qc = QuantumCircuit(1, 1) qc.x(0) @@ -1822,7 +1842,9 @@ def setUp(self): super().setUp() self.schedule = pulse.Schedule(name="fake_experiment") - self.backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.defaults = self.backend.defaults() self.qubit_lo_freq = list(self.defaults.qubit_freq_est) @@ -1963,7 +1985,9 @@ def test_missing_lo_ranges(self): def test_unsupported_meas_level(self): """Test that assembly raises an error if meas_level is not supported""" - backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = FakeOpenPulse2Q() backend.configuration().meas_levels = [1, 2] with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): assemble( @@ -1983,7 +2007,9 @@ def test_unsupported_meas_level(self): def test_single_and_deprecated_acquire_styles(self): """Test that acquires are identically combined with Acquires that take a single channel.""" - backend = FakeOpenPulse2Q() + with self.assertWarns(DeprecationWarning): + # Ignorable, because assemble and BackendV1 are deprecated + backend = FakeOpenPulse2Q() new_style_schedule = Schedule() acq_dur = 1200 for i in range(2): From 0ce73df0d7345f74ee2e9cb8691eb0f425afa9e2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 11:21:32 +0200 Subject: [PATCH 080/168] test.python.compiler.test_sequencer --- test/python/compiler/test_sequencer.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/test/python/compiler/test_sequencer.py b/test/python/compiler/test_sequencer.py index 771e854effab..4f5389a930f9 100644 --- a/test/python/compiler/test_sequencer.py +++ b/test/python/compiler/test_sequencer.py @@ -27,7 +27,8 @@ class TestSequence(QiskitTestCase): def setUp(self): super().setUp() - self.backend = Fake127QPulseV1() + with self.assertWarns(DeprecationWarning): + self.backend = Fake127QPulseV1() self.backend.configuration().timing_constraints = {} def test_sequence_empty(self): From 3db79f99bfec13489dd3bbfc177ed5898dedbe7d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 12 Jul 2024 11:42:34 +0200 Subject: [PATCH 081/168] test.python.compiler.test_transpiler --- qiskit/providers/fake_provider/fake_backend.py | 4 +++- test/python/compiler/test_transpiler.py | 6 ++++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 055b6d7d6fb6..c38935f2245a 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -42,7 +42,9 @@ class FakeBackend(BackendV1): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="Fake backends using BackendV1 are deprecated in favor of GenericBackendV2", + additional_msg="Fake backends using BackendV1 are deprecated in favor of " + ":class:`.GenericBackendV2`. You can convert BackendV1 to " + ":class:`.BackendV2` with :class:`.BackendV2Converter`.", ) def __init__(self, configuration, time_alive=10): """FakeBackend initializer. diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 116ffff6d43a..176b3006e9b2 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1574,7 +1574,8 @@ def test_scheduling_dt_constraints(self): """Test that scheduling-related loose transpile constraints work with both BackendV1 and BackendV2.""" - backend_v1 = Fake27QPulseV1() + with self.assertWarns(DeprecationWarning): + backend_v1 = Fake27QPulseV1() backend_v2 = BackendV2Converter(backend_v1) qc = QuantumCircuit(1, 1) qc.x(0) @@ -1594,7 +1595,8 @@ def test_backend_props_constraints(self): """Test that loose transpile constraints work with both BackendV1 and BackendV2.""" - backend_v1 = Fake20QV1() + with self.assertWarns(DeprecationWarning): + backend_v1 = Fake20QV1() backend_v2 = BackendV2Converter(backend_v1) qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(2, "qr2") From f1a64904eca939181f727f97d570a29a3b3c1acf Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 17 Jul 2024 23:55:14 +0200 Subject: [PATCH 082/168] test.python.primitives.test_primitive --- test/python/primitives/test_primitive.py | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/test/python/primitives/test_primitive.py b/test/python/primitives/test_primitive.py index f0401e771448..94b0daddd53f 100644 --- a/test/python/primitives/test_primitive.py +++ b/test/python/primitives/test_primitive.py @@ -21,7 +21,7 @@ from qiskit.circuit.random import random_circuit from qiskit.primitives.base import validation from qiskit.primitives.utils import _circuit_key -from qiskit.providers.fake_provider import Fake20QV1 +from qiskit.providers.fake_provider import GenericBackendV2 from test import QiskitTestCase # pylint: disable=wrong-import-order @@ -142,7 +142,11 @@ def test_with_scheduling(n): qc = QuantumCircuit(1) qc.x(0) qc.add_calibration("x", qubits=(0,), schedule=custom_gate) - return transpile(qc, Fake20QV1(), scheduling_method="alap") + backend = GenericBackendV2( + num_qubits=20, + basis_gates=["id", "u1", "u2", "u3", "cx"], + ) + return transpile(qc, backend, scheduling_method="alap") keys = [_circuit_key(test_with_scheduling(i)) for i in range(1, 5)] self.assertEqual(len(keys), len(set(keys))) From fcc7db423997c491a28ec7d924564de6dcd0535b Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 00:33:33 +0200 Subject: [PATCH 083/168] better depreaction handleling from Aer --- qiskit/primitives/backend_estimator.py | 20 ++++----- .../providers/fake_provider/fake_backend.py | 5 +-- .../fake_provider/generic_backend_v2.py | 16 +++---- qiskit/visualization/circuit/_utils.py | 2 +- test/python/compiler/test_transpiler.py | 6 +-- .../fake_provider/test_fake_backends.py | 22 +++------- .../fake_provider/test_generic_backend_v2.py | 7 +-- test/python/providers/test_fake_backends.py | 43 ++++++++----------- test/python/transpiler/test_sabre_swap.py | 10 ++--- .../python/transpiler/test_star_prerouting.py | 16 ++----- .../visualization/test_circuit_drawer.py | 2 +- test/utils/base.py | 18 ++++++++ 12 files changed, 67 insertions(+), 100 deletions(-) diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index 4f237396d2b2..8446c870b1fd 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -15,7 +15,6 @@ from __future__ import annotations -import warnings from collections.abc import Sequence from itertools import accumulate @@ -68,17 +67,14 @@ def _run_circuits( max_circuits = backend.max_circuits else: raise RuntimeError("Backend version not supported") - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - if max_circuits: - jobs = [ - backend.run(circuits[pos : pos + max_circuits], **run_options) - for pos in range(0, len(circuits), max_circuits) - ] - result = [x.result() for x in jobs] - else: - result = [backend.run(circuits, **run_options).result()] + if max_circuits: + jobs = [ + backend.run(circuits[pos : pos + max_circuits], **run_options) + for pos in range(0, len(circuits), max_circuits) + ] + result = [x.result() for x in jobs] + else: + result = [backend.run(circuits, **run_options).result()] return result, metadata diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index c38935f2245a..13c199d77106 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -65,10 +65,7 @@ def _setup_sim(self): self.sim = AerSimulator() if self.properties(): - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops Treating CircuitInstruction as an iterable - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - noise_model = NoiseModel.from_backend(self) + noise_model = NoiseModel.from_backend(self) self.sim.set_options(noise_model=noise_model) # Update fake backend default options too to avoid overwriting # it when run() is called diff --git a/qiskit/providers/fake_provider/generic_backend_v2.py b/qiskit/providers/fake_provider/generic_backend_v2.py index 09827eba48b7..48c676d72bfb 100644 --- a/qiskit/providers/fake_provider/generic_backend_v2.py +++ b/qiskit/providers/fake_provider/generic_backend_v2.py @@ -565,18 +565,12 @@ def _setup_sim(self) -> None: @classmethod def _default_options(cls) -> Options: - with warnings.catch_warnings(): # TODO remove catch once aer release without Provider ABC - warnings.filterwarnings( - "ignore", - category=DeprecationWarning, - message=".+abstract Provider and ProviderV1.+", - ) - if _optionals.HAS_AER: - from qiskit_aer import AerSimulator + if _optionals.HAS_AER: + from qiskit_aer import AerSimulator - return AerSimulator._default_options() - else: - return BasicSimulator._default_options() + return AerSimulator._default_options() + else: + return BasicSimulator._default_options() def drive_channel(self, qubit: int): drive_channels_map = getattr(self, "channels_map", {}).get("drive", {}) diff --git a/qiskit/visualization/circuit/_utils.py b/qiskit/visualization/circuit/_utils.py index 2077a3891542..e6ee03905d27 100644 --- a/qiskit/visualization/circuit/_utils.py +++ b/qiskit/visualization/circuit/_utils.py @@ -387,7 +387,7 @@ def _get_valid_justify_arg(justify): warn( f"Setting QuantumCircuit.draw()’s or circuit_drawer()'s justify argument: {justify}, to a " "value other than 'left', 'right', 'none' or None (='left'). Default 'left' will be used. " - "Support for invalid justify arguments is deprecated as of qiskit 1.2.0. Starting no " + "Support for invalid justify arguments is deprecated as of Qiskit 1.2.0. Starting no " "earlier than 3 months after the release date, invalid arguments will error.", DeprecationWarning, 2, diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 176b3006e9b2..cbe51c33e552 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -17,7 +17,6 @@ import math import os import sys -import warnings from logging import StreamHandler, getLogger from unittest.mock import patch import numpy as np @@ -2713,10 +2712,7 @@ def test_parallel_dispatch(self, opt_level): tqc = transpile( qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242 ) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() + result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: self.assertTrue(math.isclose(count["00000"], 500, rel_tol=0.1)) diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index bd1abe8d090e..03e9ff9a13e0 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -13,10 +13,9 @@ """Test of generated fake backends.""" import math import unittest -import warnings from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile -from qiskit.providers.fake_provider import Fake5QV1, GenericBackendV2 +from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.utils import optionals from test import QiskitTestCase # pylint: disable=wrong-import-order @@ -38,16 +37,15 @@ class FakeBackendsTest(QiskitTestCase): @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backends_get_kwargs_v1(self): - """Fake backends honor kwargs passed. - To remove once Fake5QV1 gets removed""" - with self.assertWarns(DeprecationWarning): - backend = Fake5QV1() + """Fake backends honor kwargs passed.""" + backend = GenericBackendV2(num_qubits=5) qc = QuantumCircuit(2) qc.x(range(0, 2)) qc.measure_all() trans_qc = transpile(qc, backend) + raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @@ -78,10 +76,7 @@ def test_fake_backends_get_kwargs(self): qc.measure_all() trans_qc = transpile(qc, backend) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() + raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) @@ -93,10 +88,7 @@ def test_fake_backend_v2_noise_model_always_present(self): qc = QuantumCircuit(1) qc.x(0) qc.measure_all() - with warnings.catch_warnings(): - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - res = backend.run(qc, shots=1000).result().get_counts() + + res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000}) diff --git a/test/python/providers/fake_provider/test_generic_backend_v2.py b/test/python/providers/fake_provider/test_generic_backend_v2.py index 51df49e73456..33bf57cf3903 100644 --- a/test/python/providers/fake_provider/test_generic_backend_v2.py +++ b/test/python/providers/fake_provider/test_generic_backend_v2.py @@ -13,7 +13,6 @@ """ Test of GenericBackendV2 backend""" import math -import warnings from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, transpile from qiskit.providers.fake_provider import GenericBackendV2 @@ -137,11 +136,7 @@ def test_run(self): backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"]) tqc = transpile(qc, backend=backend, optimization_level=3, seed_transpiler=42) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using Provider ABC - # https://github.com/Qiskit/qiskit-aer/pull/2184 - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - result = backend.run(tqc, seed_simulator=42, shots=1000).result() + result = backend.run(tqc, seed_simulator=42, shots=1000).result() counts = result.get_counts() self.assertTrue(math.isclose(counts["00000"], 500, rel_tol=0.1)) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 8f7ccb855488..5826ad228fad 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -106,18 +106,15 @@ def setUpClass(cls): optimization_level=[0, 1, 2, 3], ) def test_circuit_on_fake_backend_v2(self, backend, optimization_level): - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - if not optionals.HAS_AER and backend.num_qubits > 20: - self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") - job = backend.run( - transpile( - self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level - ), - seed_simulator=42, - ) - result = job.result() + if not optionals.HAS_AER and backend.num_qubits > 20: + self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") + job = backend.run( + transpile( + self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level + ), + seed_simulator=42, + ) + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") @@ -133,16 +130,13 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): self.skipTest( f"Unable to run fake_backend {backend.configuration().backend_name} without qiskit-aer" ) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - job = backend.run( - transpile( - self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level - ), - seed_simulator=42, - ) - result = job.result() + job = backend.run( + transpile( + self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level + ), + seed_simulator=42, + ) + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") @@ -237,10 +231,7 @@ def test_converter(self, opt_level): self.assertIsInstance(backend_v2, BackendV2) res = transpile(self.circuit, backend_v2, optimization_level=opt_level) job = backend_v2.run(res) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - result = job.result() + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index 0ab954fd3412..2b4fd8671b61 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -283,13 +283,9 @@ def test_no_infinite_loop(self, method): from qiskit_aer import Aer - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField and Provider ABC - # https://github.com/Qiskit/qiskit-aer/pull/2184 - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - sim = Aer.get_backend("aer_simulator") - in_results = sim.run(qc, shots=4096).result().get_counts() - out_results = sim.run(routed, shots=4096).result().get_counts() + sim = Aer.get_backend("aer_simulator") + in_results = sim.run(qc, shots=4096).result().get_counts() + out_results = sim.run(routed, shots=4096).result().get_counts() self.assertEqual(set(in_results), set(out_results)) def test_classical_condition(self): diff --git a/test/python/transpiler/test_star_prerouting.py b/test/python/transpiler/test_star_prerouting.py index aeac559e2b9c..ddc8096eefd7 100644 --- a/test/python/transpiler/test_star_prerouting.py +++ b/test/python/transpiler/test_star_prerouting.py @@ -15,8 +15,6 @@ """Test the StarPreRouting pass""" import unittest -import warnings - from test import QiskitTestCase import ddt @@ -260,11 +258,8 @@ def test_100q_grid_full_path(self, opt_level): ) pm.init += StarPreRouting() result = pm.run(qc) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - counts_before = AerSimulator().run(qc).result().get_counts() - counts_after = AerSimulator().run(result).result().get_counts() + counts_before = AerSimulator().run(qc).result().get_counts() + counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) def test_10q_bv_no_barrier(self): @@ -303,11 +298,8 @@ def test_100q_grid_full_path_no_barrier(self, opt_level): ) pm.init += StarPreRouting() result = pm.run(qc) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - counts_before = AerSimulator().run(qc).result().get_counts() - counts_after = AerSimulator().run(result).result().get_counts() + counts_before = AerSimulator().run(qc).result().get_counts() + counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) def test_hadamard_ordering(self): diff --git a/test/python/visualization/test_circuit_drawer.py b/test/python/visualization/test_circuit_drawer.py index d459bd945046..dd69faac02cb 100644 --- a/test/python/visualization/test_circuit_drawer.py +++ b/test/python/visualization/test_circuit_drawer.py @@ -249,7 +249,7 @@ def test_warning_for_bad_justify_argument(self): error_message = re.escape( f"Setting QuantumCircuit.draw()’s or circuit_drawer()'s justify argument: {bad_arg}, to a " "value other than 'left', 'right', 'none' or None (='left'). Default 'left' will be used. " - "Support for invalid justify arguments is deprecated as of qiskit 1.2.0. Starting no " + "Support for invalid justify arguments is deprecated as of Qiskit 1.2.0. Starting no " "earlier than 3 months after the release date, invalid arguments will error.", ) diff --git a/test/utils/base.py b/test/utils/base.py index 0b02f3e58488..de4afbb79446 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -129,6 +129,24 @@ def setUpClass(cls): module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", ) + # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2065 is in a release version + # of Aer. + warnings.filterwarnings( + "default", + category=DeprecationWarning, + message=r".* If user still need Qobj,.*", + module=r"qiskit_aer", + ) + + # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2184 is in a release version + # of Aer. + warnings.filterwarnings( + "default", + category=DeprecationWarning, + message=r".*The abstract Provider and ProviderV1 classes are deprecated.*", + module="qiskit_aer", + ) + allow_DeprecationWarning_message = [ r"The property ``qiskit\.circuit\.bit\.Bit\.(register|index)`` is deprecated.*", ] From 56a401afebd52d90a5a090b84fa918cb9a2b655b Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 00:39:54 +0200 Subject: [PATCH 084/168] test.python.primitives.test_backend_estimator_v2 --- test/python/primitives/test_backend_estimator_v2.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/python/primitives/test_backend_estimator_v2.py b/test/python/primitives/test_backend_estimator_v2.py index 6728d57e3fdd..319fd846ee95 100644 --- a/test/python/primitives/test_backend_estimator_v2.py +++ b/test/python/primitives/test_backend_estimator_v2.py @@ -446,8 +446,9 @@ def max_circuits(self): self.assertEqual(run_mock.call_count, 10) def test_job_size_limit_backend_v1(self): - """Test BackendEstimatorV2 respects job size limit""" - backend = Fake7QPulseV1() + """Test BackendEstimatorV2 respects job size limit from BackendV1""" + with self.assertWarns(DeprecationWarning): + backend = Fake7QPulseV1() config = backend.configuration() config.max_experiments = 1 backend._configuration = config From 4d08cea61d1f9a814690fb7214ec4dfe9aa5721d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 00:40:54 +0200 Subject: [PATCH 085/168] test.python.compiler.test_compiler --- test/python/compiler/test_compiler.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/python/compiler/test_compiler.py b/test/python/compiler/test_compiler.py index 1479fde88cec..32d33ba3e56c 100644 --- a/test/python/compiler/test_compiler.py +++ b/test/python/compiler/test_compiler.py @@ -188,7 +188,6 @@ def test_example_swap_bits(self): def test_parallel_compile(self): """Trigger parallel routines in compile.""" - backend = Fake20QV1() qr = QuantumRegister(16) cr = ClassicalRegister(2) qc = QuantumCircuit(qr, cr) @@ -198,6 +197,7 @@ def test_parallel_compile(self): qc.measure(qr[5], cr[0]) qlist = [qc for k in range(10)] with self.assertWarns(DeprecationWarning): + backend = Fake20QV1() qobj = assemble(transpile(qlist, backend=backend)) self.assertEqual(len(qobj.experiments), 10) @@ -500,7 +500,8 @@ def test_yzy_zyz_cases(self): See: https://github.com/Qiskit/qiskit-terra/issues/607 """ - backend = Fake5QV1() + with self.assertWarns(DeprecationWarning): + backend = Fake5QV1() qr = QuantumRegister(2) circ1 = QuantumCircuit(qr) circ1.cx(qr[0], qr[1]) From 1fbb30f309bbb3e5f261856b091e8b855d0169ee Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 01:21:07 +0200 Subject: [PATCH 086/168] ignore warnings, because the output is otherwise very verbose --- test/utils/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/utils/base.py b/test/utils/base.py index de4afbb79446..03d7d41c53ab 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -132,7 +132,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2065 is in a release version # of Aer. warnings.filterwarnings( - "default", + "ignore", category=DeprecationWarning, message=r".* If user still need Qobj,.*", module=r"qiskit_aer", From 674399278d6d603cd9416b3bedfd98ca35154a3b Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 07:37:43 +0200 Subject: [PATCH 087/168] ignore to avoid fludding the CI log --- test/utils/base.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/utils/base.py b/test/utils/base.py index 03d7d41c53ab..059263ec15e4 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -123,7 +123,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2179 is in a release version # of Aer. warnings.filterwarnings( - "default", + "ignore", category=DeprecationWarning, message="Treating CircuitInstruction as an iterable is deprecated", module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", @@ -141,7 +141,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2184 is in a release version # of Aer. warnings.filterwarnings( - "default", + "ignore", category=DeprecationWarning, message=r".*The abstract Provider and ProviderV1 classes are deprecated.*", module="qiskit_aer", From 4492c623daf61a5bb7f19c9ec9fffd2877e0b545 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 10:10:24 +0200 Subject: [PATCH 088/168] seeding all GenericBackendV2 --- test/python/circuit/test_parameters.py | 1 + test/python/circuit/test_scheduled_circuit.py | 2 +- test/python/compiler/test_transpiler.py | 26 +++++++++---------- .../primitives/test_backend_estimator.py | 2 +- .../python/primitives/test_backend_sampler.py | 2 +- test/python/primitives/test_primitive.py | 3 +-- .../fake_provider/test_fake_backends.py | 3 ++- .../fake_provider/test_generic_backend_v2.py | 24 +++++++++-------- test/python/providers/test_backend_v2.py | 14 +++++----- test/python/providers/test_fake_backends.py | 8 +++--- test/python/pulse/test_builder_v2.py | 4 +-- test/python/pulse/test_macros.py | 2 ++ test/python/qpy/test_circuit_load_from_qpy.py | 10 +++---- test/python/scheduler/test_basic_scheduler.py | 2 +- .../transpiler/test_passmanager_config.py | 5 ++-- 15 files changed, 57 insertions(+), 51 deletions(-) diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index 4cf7b711967b..d192f10fdddc 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -1129,6 +1129,7 @@ def test_transpile_across_optimization_levels(self, opt_level): [2, 4], [4, 2], ], + seed=42, ), optimization_level=opt_level, ) diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index 7dd92864285b..3e992db0963d 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -305,7 +305,7 @@ def test_convert_duration_to_dt(self): """Test that circuit duration unit conversion is applied only when necessary. Tests fix for bug reported in PR #11782.""" - backend = GenericBackendV2(num_qubits=3, calibrate_instructions=True, seed=10) + backend = GenericBackendV2(num_qubits=3, calibrate_instructions=True, seed=42) schedule_config = ScheduleConfig( inst_map=backend.target.instruction_schedule_map(), meas_map=backend.meas_map, diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index cbe51c33e552..6d97b8717867 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -170,7 +170,7 @@ def test_num_processes_kwarg_concurrent_default(self, num_processes): qc.h(0) qc.cx(0, 1) qc.measure_all() - target = GenericBackendV2(num_qubits=27).target + target = GenericBackendV2(num_qubits=27, seed=42).target res = transpile([qc] * 3, target=target, num_processes=num_processes) self.assertIsInstance(res, list) for circ in res: @@ -269,7 +269,7 @@ def test_transpile_non_adjacent_layout(self): circuit.cx(qr[2], qr[3]) backend = GenericBackendV2( - num_qubits=15, basis_gates=["ecr", "id", "rz", "sx", "x"], coupling_map=cmap + num_qubits=15, basis_gates=["ecr", "id", "rz", "sx", "x"], coupling_map=cmap, seed=42 ) initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] @@ -313,7 +313,7 @@ def test_already_mapped_1(self): See: https://github.com/Qiskit/qiskit-terra/issues/342 """ - backend = GenericBackendV2(num_qubits=16, coupling_map=RUESCHLIKON_CMAP) + backend = GenericBackendV2(num_qubits=16, coupling_map=RUESCHLIKON_CMAP, seed=42) coupling_map = backend.coupling_map basis_gates = backend.operation_names @@ -588,7 +588,7 @@ def test_transpile_singleton(self): def test_mapping_correction(self): """Test mapping works in previous failed case.""" - backend = GenericBackendV2(num_qubits=12) + backend = GenericBackendV2(num_qubits=12, seed=42) qr = QuantumRegister(name="qr", size=11) cr = ClassicalRegister(name="qc", size=11) circuit = QuantumCircuit(qr, cr) @@ -708,7 +708,7 @@ def test_transpiler_layout_from_intlist(self): def test_mapping_multi_qreg(self): """Test mapping works for multiple qregs.""" - backend = GenericBackendV2(num_qubits=8) + backend = GenericBackendV2(num_qubits=8, seed=42) qr = QuantumRegister(3, name="qr") qr2 = QuantumRegister(1, name="qr2") qr3 = QuantumRegister(4, name="qr3") @@ -725,7 +725,7 @@ def test_mapping_multi_qreg(self): def test_transpile_circuits_diff_registers(self): """Transpile list of circuits with different qreg names.""" - backend = GenericBackendV2(num_qubits=4) + backend = GenericBackendV2(num_qubits=4, seed=42) circuits = [] for _ in range(2): qr = QuantumRegister(2) @@ -741,7 +741,7 @@ def test_transpile_circuits_diff_registers(self): def test_wrong_initial_layout(self): """Test transpile with a bad initial layout.""" - backend = GenericBackendV2(num_qubits=4) + backend = GenericBackendV2(num_qubits=4, seed=42) qubit_reg = QuantumRegister(2, name="q") clbit_reg = ClassicalRegister(2, name="c") @@ -780,7 +780,7 @@ def test_parameterized_circuit_for_device(self): theta = Parameter("theta") qc.p(theta, qr[0]) - backend = GenericBackendV2(num_qubits=4) + backend = GenericBackendV2(num_qubits=4, seed=42) transpiled_qc = transpile( qc, @@ -820,7 +820,7 @@ def test_parameter_expression_circuit_for_device(self): square = theta * theta qc.rz(square, qr[0]) - backend = GenericBackendV2(num_qubits=4) + backend = GenericBackendV2(num_qubits=4, seed=42) transpiled_qc = transpile( qc, backend=backend, @@ -853,7 +853,7 @@ def test_do_not_run_gatedirection_with_symmetric_cm(self): circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "example.qasm")) layout = Layout.generate_trivial_layout(*circ.qregs) coupling_map = [] - for node1, node2 in GenericBackendV2(num_qubits=16).coupling_map: + for node1, node2 in GenericBackendV2(num_qubits=16, seed=42).coupling_map: coupling_map.append([node1, node2]) coupling_map.append([node2, node1]) @@ -912,7 +912,7 @@ def test_pass_manager_empty(self): def test_move_measurements(self): """Measurements applied AFTER swap mapping.""" - cmap = GenericBackendV2(num_qubits=16).coupling_map + cmap = GenericBackendV2(num_qubits=16, seed=42).coupling_map qasm_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "qasm") circ = QuantumCircuit.from_qasm_file(os.path.join(qasm_dir, "move_measurements.qasm")) @@ -956,7 +956,7 @@ def test_initialize_FakeMelbourne(self): qc = QuantumCircuit(qr) qc.initialize(desired_vector, [qr[0], qr[1], qr[2]]) - out = transpile(qc, backend=GenericBackendV2(num_qubits=4)) + out = transpile(qc, backend=GenericBackendV2(num_qubits=4, seed=42)) out_dag = circuit_to_dag(out) reset_nodes = out_dag.named_nodes("reset") @@ -1275,7 +1275,7 @@ def test_transpiled_custom_gates_calibration(self): transpiled_circuit = transpile( circ, - backend=GenericBackendV2(num_qubits=4), + backend=GenericBackendV2(num_qubits=4, seed=42), layout_method="trivial", seed_transpiler=42, ) diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index ce9adada0f3b..5d4ec3da2504 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -284,7 +284,7 @@ class FakeBackendLimitedCircuits(GenericBackendV2): def max_circuits(self): return 1 - backend = FakeBackendLimitedCircuits(num_qubits=5) + backend = FakeBackendLimitedCircuits(num_qubits=5, seed=42) backend.set_options(seed_simulator=123) qc = RealAmplitudes(num_qubits=2, reps=2) op = SparsePauliOp.from_list([("IZ", 1), ("XI", 2), ("ZY", -1)]) diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index c8e644f2be3b..cd97dd90332d 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -312,7 +312,7 @@ def max_circuits(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=FakeBackendLimitedCircuits(num_qubits=5)) + sampler = BackendSampler(backend=FakeBackendLimitedCircuits(num_qubits=5, seed=42)) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) diff --git a/test/python/primitives/test_primitive.py b/test/python/primitives/test_primitive.py index 94b0daddd53f..1c0074fdf91f 100644 --- a/test/python/primitives/test_primitive.py +++ b/test/python/primitives/test_primitive.py @@ -143,8 +143,7 @@ def test_with_scheduling(n): qc.x(0) qc.add_calibration("x", qubits=(0,), schedule=custom_gate) backend = GenericBackendV2( - num_qubits=20, - basis_gates=["id", "u1", "u2", "u3", "cx"], + num_qubits=20, basis_gates=["id", "u1", "u2", "u3", "cx"], seed=42 ) return transpile(qc, backend, scheduling_method="alap") diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index 03e9ff9a13e0..f297cc5b53bf 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -38,7 +38,7 @@ class FakeBackendsTest(QiskitTestCase): @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") def test_fake_backends_get_kwargs_v1(self): """Fake backends honor kwargs passed.""" - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) qc = QuantumCircuit(2) qc.x(range(0, 2)) @@ -69,6 +69,7 @@ def test_fake_backends_get_kwargs(self): [2, 4], [4, 2], ], + seed=42, ) qc = QuantumCircuit(2) diff --git a/test/python/providers/fake_provider/test_generic_backend_v2.py b/test/python/providers/fake_provider/test_generic_backend_v2.py index 33bf57cf3903..21abe6674b5f 100644 --- a/test/python/providers/fake_provider/test_generic_backend_v2.py +++ b/test/python/providers/fake_provider/test_generic_backend_v2.py @@ -33,17 +33,17 @@ def setUp(self): def test_supported_basis_gates(self): """Test that target raises error if basis_gate not in ``supported_names``.""" with self.assertRaises(QiskitError): - GenericBackendV2(num_qubits=8, basis_gates=["cx", "id", "rz", "sx", "zz"]) + GenericBackendV2(num_qubits=8, basis_gates=["cx", "id", "rz", "sx", "zz"], seed=42) def test_cx_1Q(self): """Test failing with a backend with single qubit but with a two-qubit basis gate""" with self.assertRaises(QiskitError): - GenericBackendV2(num_qubits=1, basis_gates=["cx", "id"]) + GenericBackendV2(num_qubits=1, basis_gates=["cx", "id"], seed=42) def test_ccx_2Q(self): """Test failing with a backend with two qubits but with a three-qubit basis gate""" with self.assertRaises(QiskitError): - GenericBackendV2(num_qubits=2, basis_gates=["ccx", "id"]) + GenericBackendV2(num_qubits=2, basis_gates=["ccx", "id"], seed=42) def test_calibration_no_noise_info(self): """Test failing with a backend with calibration and no noise info""" @@ -53,27 +53,28 @@ def test_calibration_no_noise_info(self): basis_gates=["ccx", "id"], calibrate_instructions=True, noise_info=False, + seed=42, ) def test_no_noise(self): """Test no noise info when parameter is false""" - backend = GenericBackendV2(num_qubits=2, noise_info=False) + backend = GenericBackendV2(num_qubits=2, noise_info=False, seed=42) self.assertEqual(backend.target.qubit_properties, None) def test_no_pulse_channels(self): """Test no/empty pulse channels when parameter is false""" - backend = GenericBackendV2(num_qubits=2, pulse_channels=False) + backend = GenericBackendV2(num_qubits=2, pulse_channels=False, seed=42) self.assertTrue(len(backend.channels_map) == 0) def test_operation_names(self): """Test that target basis gates include "delay", "measure" and "reset" even if not provided by user.""" - target = GenericBackendV2(num_qubits=8) + target = GenericBackendV2(num_qubits=8, seed=42) op_names = list(target.operation_names) op_names.sort() self.assertEqual(op_names, ["cx", "delay", "id", "measure", "reset", "rz", "sx", "x"]) - target = GenericBackendV2(num_qubits=8, basis_gates=["ecr", "id", "rz", "sx", "x"]) + target = GenericBackendV2(num_qubits=8, basis_gates=["ecr", "id", "rz", "sx", "x"], seed=42) op_names = list(target.operation_names) op_names.sort() self.assertEqual(op_names, ["delay", "ecr", "id", "measure", "reset", "rz", "sx", "x"]) @@ -81,7 +82,7 @@ def test_operation_names(self): def test_incompatible_coupling_map(self): """Test that the size of the coupling map must match num_qubits.""" with self.assertRaises(QiskitError): - GenericBackendV2(num_qubits=5, coupling_map=self.cmap) + GenericBackendV2(num_qubits=5, coupling_map=self.cmap, seed=42) def test_control_flow_operation_names(self): """Test that control flow instructions are added to the target if control_flow is True.""" @@ -90,6 +91,7 @@ def test_control_flow_operation_names(self): basis_gates=["ecr", "id", "rz", "sx", "x"], coupling_map=self.cmap, control_flow=True, + seed=42, ).target op_names = list(target.operation_names) op_names.sort() @@ -119,7 +121,7 @@ def test_default_coupling_map(self): (1, 3), (3, 1), (1, 4), (4, 1), (2, 3), (3, 2), (2, 4), (4, 2), (3, 4), (4, 3)] # fmt: on self.assertEqual( - list(GenericBackendV2(num_qubits=5).coupling_map.get_edges()), + list(GenericBackendV2(num_qubits=5, seed=42).coupling_map.get_edges()), reference_cmap, ) @@ -134,7 +136,7 @@ def test_run(self): qc.cx(qr[0], qr[k]) qc.measure(qr, cr) - backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"]) + backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"], seed=42) tqc = transpile(qc, backend=backend, optimization_level=3, seed_transpiler=42) result = backend.run(tqc, seed_simulator=42, shots=1000).result() counts = result.get_counts() @@ -157,7 +159,7 @@ def test_duration_defaults(self): "rxx": (7.992e-08, 8.99988e-07), } for _ in range(20): - target = GenericBackendV2(num_qubits=2, basis_gates=basis_gates).target + target = GenericBackendV2(num_qubits=2, basis_gates=basis_gates, seed=42).target for inst in target: for qargs in target.qargs_for_operation_name(inst): duration = target[inst][qargs].duration diff --git a/test/python/providers/test_backend_v2.py b/test/python/providers/test_backend_v2.py index 70330085b1ab..05b7172f9cb9 100644 --- a/test/python/providers/test_backend_v2.py +++ b/test/python/providers/test_backend_v2.py @@ -41,7 +41,7 @@ class TestBackendV2(QiskitTestCase): def setUp(self): super().setUp() - self.backend = GenericBackendV2(num_qubits=2, seed=42, basis_gates=["rx", "u"]) + self.backend = GenericBackendV2(num_qubits=2, basis_gates=["rx", "u"], seed=42) cx_props = { (0, 1): InstructionProperties(duration=5.23e-7, error=0.00098115), } @@ -127,9 +127,9 @@ def test_transpile(self, opt_level): ) def test_5q_ghz(self, opt_level, gate, bidirectional): if bidirectional: - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) else: - backend = GenericBackendV2(num_qubits=5, coupling_map=TENERIFE_CMAP) + backend = GenericBackendV2(num_qubits=5, coupling_map=TENERIFE_CMAP, seed=42) qc = QuantumCircuit(5) qc.h(0) getattr(qc, gate)(0, 1) @@ -207,7 +207,7 @@ def test_transpile_mumbai_target(self): @data(0, 1, 2, 3, 4) def test_drive_channel(self, qubit): """Test getting drive channel with qubit index.""" - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) chan = backend.drive_channel(qubit) ref = channels.DriveChannel(qubit) self.assertEqual(chan, ref) @@ -215,7 +215,7 @@ def test_drive_channel(self, qubit): @data(0, 1, 2, 3, 4) def test_measure_channel(self, qubit): """Test getting measure channel with qubit index.""" - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) chan = backend.measure_channel(qubit) ref = channels.MeasureChannel(qubit) self.assertEqual(chan, ref) @@ -223,7 +223,7 @@ def test_measure_channel(self, qubit): @data(0, 1, 2, 3, 4) def test_acquire_channel(self, qubit): """Test getting acquire channel with qubit index.""" - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) chan = backend.acquire_channel(qubit) ref = channels.AcquireChannel(qubit) self.assertEqual(chan, ref) @@ -241,7 +241,7 @@ def test_control_channel(self, qubits): (1, 0): 1, (0, 1): 0, } - backend = GenericBackendV2(num_qubits=5, coupling_map=BOGOTA_CMAP) + backend = GenericBackendV2(num_qubits=5, coupling_map=BOGOTA_CMAP, seed=42) chan = backend.control_channel(qubits)[0] ref = channels.ControlChannel(bogota_cr_channels_map[qubits]) self.assertEqual(chan, ref) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 5826ad228fad..0eede200681f 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -84,7 +84,7 @@ BACKENDS_V2 = [] for n in [5, 7, 16, 20, 27, 65, 127]: cmap = CouplingMap.from_ring(n) - BACKENDS_V2.append(GenericBackendV2(num_qubits=n, coupling_map=cmap)) + BACKENDS_V2.append(GenericBackendV2(num_qubits=n, coupling_map=cmap, seed=42)) @ddt @@ -269,9 +269,11 @@ def test_converter_with_missing_gate_property(self): self.assertDictEqual(backend_v2.target["u2"], {None: None}) def test_non_cx_tests(self): - backend = GenericBackendV2(num_qubits=5, basis_gates=["cz", "x", "sx", "id", "rz"]) + backend = GenericBackendV2(num_qubits=5, basis_gates=["cz", "x", "sx", "id", "rz"], seed=42) self.assertIsInstance(backend.target.operation_from_name("cz"), CZGate) - backend = GenericBackendV2(num_qubits=5, basis_gates=["ecr", "x", "sx", "id", "rz"]) + backend = GenericBackendV2( + num_qubits=5, basis_gates=["ecr", "x", "sx", "id", "rz"], seed=42 + ) self.assertIsInstance(backend.target.operation_from_name("ecr"), ECRGate) @unittest.skipUnless(optionals.HAS_AER, "Aer required for this test") diff --git a/test/python/pulse/test_builder_v2.py b/test/python/pulse/test_builder_v2.py index 843c8a8447fe..79d3ac5b6020 100644 --- a/test/python/pulse/test_builder_v2.py +++ b/test/python/pulse/test_builder_v2.py @@ -32,9 +32,7 @@ class TestBuilderV2(QiskitTestCase): def setUp(self): super().setUp() self.backend = GenericBackendV2( - num_qubits=27, - coupling_map=MUMBAI_CMAP, - calibrate_instructions=True, + num_qubits=27, coupling_map=MUMBAI_CMAP, calibrate_instructions=True, seed=42 ) def assertScheduleEqual(self, program, target): diff --git a/test/python/pulse/test_macros.py b/test/python/pulse/test_macros.py index ee83038c7ed0..6d87320cf480 100644 --- a/test/python/pulse/test_macros.py +++ b/test/python/pulse/test_macros.py @@ -41,6 +41,7 @@ def setUp(self): self.backend_v2 = GenericBackendV2( num_qubits=27, calibrate_instructions=self.backend_v1.defaults().instruction_schedule_map, + seed=42, ) def test_measure(self): @@ -220,6 +221,7 @@ def setUp(self): self.backend_v2 = GenericBackendV2( num_qubits=2, calibrate_instructions=self.backend_v1.defaults().instruction_schedule_map, + seed=42, ) def test_measure_all(self): diff --git a/test/python/qpy/test_circuit_load_from_qpy.py b/test/python/qpy/test_circuit_load_from_qpy.py index 774920699e1e..8f0cffb36a5f 100644 --- a/test/python/qpy/test_circuit_load_from_qpy.py +++ b/test/python/qpy/test_circuit_load_from_qpy.py @@ -114,7 +114,7 @@ def test_transpile_layout(self, opt_level): qc.h(0) qc.cx(0, 1) qc.measure_all() - backend = GenericBackendV2(num_qubits=127) + backend = GenericBackendV2(num_qubits=127, seed=42) tqc = transpile(qc, backend, optimization_level=opt_level) self.assert_roundtrip_equal(tqc) @@ -128,7 +128,7 @@ def test_transpile_with_routing(self, opt_level): qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() - backend = GenericBackendV2(num_qubits=127) + backend = GenericBackendV2(num_qubits=127, seed=42) tqc = transpile(qc, backend, optimization_level=opt_level) self.assert_roundtrip_equal(tqc) @@ -139,7 +139,7 @@ def test_transpile_layout_explicit_None_final_layout(self, opt_level): qc.h(0) qc.cx(0, 1) qc.measure_all() - backend = GenericBackendV2(num_qubits=127) + backend = GenericBackendV2(num_qubits=127, seed=42) tqc = transpile(qc, backend, optimization_level=opt_level) tqc.layout.final_layout = None self.assert_roundtrip_equal(tqc) @@ -203,7 +203,7 @@ def test_custom_register_name(self, opt_level): qc.cx(0, 3) qc.cx(0, 4) qc.measure_all() - backend = GenericBackendV2(num_qubits=127) + backend = GenericBackendV2(num_qubits=127, seed=42) tqc = transpile(qc, backend, optimization_level=opt_level) self.assert_roundtrip_equal(tqc) @@ -215,7 +215,7 @@ def test_no_register(self, opt_level): qc.h(0) qc.cx(0, 1) qc.measure_all() - backend = GenericBackendV2(num_qubits=127) + backend = GenericBackendV2(num_qubits=127, seed=42) tqc = transpile(qc, backend, optimization_level=opt_level) # Manually validate to deal with qubit equality needing exact objects qpy_file = io.BytesIO() diff --git a/test/python/scheduler/test_basic_scheduler.py b/test/python/scheduler/test_basic_scheduler.py index 98363880b14b..947a255ddf21 100644 --- a/test/python/scheduler/test_basic_scheduler.py +++ b/test/python/scheduler/test_basic_scheduler.py @@ -516,7 +516,7 @@ class TestBasicScheduleV2(QiskitTestCase): def setUp(self): super().setUp() - self.backend = GenericBackendV2(num_qubits=3, calibrate_instructions=True) + self.backend = GenericBackendV2(num_qubits=3, calibrate_instructions=True, seed=42) self.inst_map = self.backend.instruction_schedule_map # self.pulse_2_samples is the pulse sequence used to calibrate "measure" in # GenericBackendV2. See class construction for more details. diff --git a/test/python/transpiler/test_passmanager_config.py b/test/python/transpiler/test_passmanager_config.py index 344428158dc3..f9ee28e0ac60 100644 --- a/test/python/transpiler/test_passmanager_config.py +++ b/test/python/transpiler/test_passmanager_config.py @@ -41,7 +41,7 @@ def test_config_from_backend(self): def test_config_from_backend_v2(self): """Test from_backend() with a BackendV2 instance.""" - backend = GenericBackendV2(num_qubits=27) + backend = GenericBackendV2(num_qubits=27, seed=42) config = PassManagerConfig.from_backend(backend) self.assertEqual(config.basis_gates, backend.operation_names) self.assertEqual(config.inst_map, backend.instruction_schedule_map) @@ -137,6 +137,7 @@ def test_from_backend_and_user(self): ], basis_gates=["id", "u1", "u2", "u3", "cx"], calibrate_instructions=None, + seed=42, ) config = PassManagerConfig.from_backend( backend, basis_gates=["user_gate"], initial_layout=initial_layout @@ -158,7 +159,7 @@ def test_from_backendv1_inst_map_is_none(self): def test_invalid_user_option(self): """Test from_backend() with an invalid user option.""" - backend = GenericBackendV2(num_qubits=20) + backend = GenericBackendV2(num_qubits=20, seed=42) with self.assertRaises(TypeError): PassManagerConfig.from_backend(backend, invalid_option=None) From 6cbf167ee50f99951de5fbe793730c94bb5e0ff4 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 12:07:12 +0200 Subject: [PATCH 089/168] test.python.visualization.test_gate_map --- test/python/visualization/test_gate_map.py | 706 ++++++++++++++++++++- 1 file changed, 699 insertions(+), 7 deletions(-) diff --git a/test/python/visualization/test_gate_map.py b/test/python/visualization/test_gate_map.py index bf9b1ca80d79..8e87dcb085e4 100644 --- a/test/python/visualization/test_gate_map.py +++ b/test/python/visualization/test_gate_map.py @@ -19,8 +19,6 @@ Fake5QV1, Fake20QV1, Fake7QPulseV1, - Fake27QPulseV1, - Fake127QPulseV1, GenericBackendV2, ) from qiskit.visualization import ( @@ -108,7 +106,69 @@ def test_plot_gate_map_no_backend(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_backend_v1(self): """Test plotting error map with fake backend v1.""" - backend = Fake27QPulseV1() + coupling_map = [ + [0, 1], + [1, 0], + [1, 2], + [1, 4], + [2, 1], + [2, 3], + [3, 2], + [3, 5], + [4, 1], + [4, 7], + [5, 3], + [5, 8], + [6, 7], + [7, 4], + [7, 6], + [7, 10], + [8, 5], + [8, 9], + [8, 11], + [9, 8], + [10, 7], + [10, 12], + [11, 8], + [11, 14], + [12, 10], + [12, 13], + [12, 15], + [13, 12], + [13, 14], + [14, 11], + [14, 13], + [14, 16], + [15, 12], + [15, 18], + [16, 14], + [16, 19], + [17, 18], + [18, 15], + [18, 17], + [18, 21], + [19, 16], + [19, 20], + [19, 22], + [20, 19], + [21, 18], + [21, 23], + [22, 19], + [22, 25], + [23, 21], + [23, 24], + [24, 23], + [24, 25], + [25, 22], + [25, 24], + [25, 26], + [26, 25], + ] + backend = GenericBackendV2( + num_qubits=27, + pulse_channels=True, + coupling_map=coupling_map, + ) img_ref = path_to_diagram_reference("fake_27_q_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: @@ -122,9 +182,68 @@ def test_plot_error_map_backend_v1(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_backend_v2(self): """Test plotting error map with fake backend v2.""" + coupling_map = [ + [0, 1], + [1, 0], + [1, 2], + [1, 4], + [2, 1], + [2, 3], + [3, 2], + [3, 5], + [4, 1], + [4, 7], + [5, 3], + [5, 8], + [6, 7], + [7, 4], + [7, 6], + [7, 10], + [8, 5], + [8, 9], + [8, 11], + [9, 8], + [10, 7], + [10, 12], + [11, 8], + [11, 14], + [12, 10], + [12, 13], + [12, 15], + [13, 12], + [13, 14], + [14, 11], + [14, 13], + [14, 16], + [15, 12], + [15, 18], + [16, 14], + [16, 19], + [17, 18], + [18, 15], + [18, 17], + [18, 21], + [19, 16], + [19, 20], + [19, 22], + [20, 19], + [21, 18], + [21, 23], + [22, 19], + [22, 25], + [23, 21], + [23, 24], + [24, 23], + [24, 25], + [25, 22], + [25, 24], + [25, 26], + [26, 25], + ] backend = GenericBackendV2( num_qubits=27, - coupling_map=Fake27QPulseV1().configuration().coupling_map, + pulse_channels=True, + coupling_map=coupling_map, ) img_ref = path_to_diagram_reference("fake_27_q_v2_error.png") fig = plot_error_map(backend) @@ -139,7 +258,295 @@ def test_plot_error_map_backend_v2(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_over_100_qubit(self): """Test plotting error map with large fake backend.""" - backend = Fake127QPulseV1() + coupling_map = [ + [0, 1], + [0, 14], + [1, 0], + [1, 2], + [2, 1], + [2, 3], + [3, 2], + [3, 4], + [4, 3], + [4, 5], + [4, 15], + [5, 4], + [5, 6], + [6, 5], + [6, 7], + [7, 6], + [7, 8], + [8, 7], + [8, 16], + [9, 10], + [10, 9], + [10, 11], + [11, 10], + [11, 12], + [12, 11], + [12, 13], + [12, 17], + [13, 12], + [14, 0], + [14, 18], + [15, 4], + [15, 22], + [16, 8], + [16, 26], + [17, 12], + [17, 30], + [18, 14], + [18, 19], + [19, 18], + [19, 20], + [20, 19], + [20, 21], + [20, 33], + [21, 20], + [21, 22], + [22, 15], + [22, 21], + [22, 23], + [23, 22], + [23, 24], + [24, 23], + [24, 25], + [24, 34], + [25, 24], + [25, 26], + [26, 16], + [26, 25], + [26, 27], + [27, 26], + [27, 28], + [28, 27], + [28, 29], + [28, 35], + [29, 28], + [29, 30], + [30, 17], + [30, 29], + [30, 31], + [31, 30], + [31, 32], + [32, 31], + [32, 36], + [33, 20], + [33, 39], + [34, 24], + [34, 43], + [35, 28], + [35, 47], + [36, 32], + [36, 51], + [37, 38], + [37, 52], + [38, 37], + [38, 39], + [39, 33], + [39, 38], + [39, 40], + [40, 39], + [40, 41], + [41, 40], + [41, 42], + [41, 53], + [42, 41], + [42, 43], + [43, 34], + [43, 42], + [43, 44], + [44, 43], + [44, 45], + [45, 44], + [45, 46], + [45, 54], + [46, 45], + [46, 47], + [47, 35], + [47, 46], + [47, 48], + [48, 47], + [48, 49], + [49, 48], + [49, 50], + [49, 55], + [50, 49], + [50, 51], + [51, 36], + [51, 50], + [52, 37], + [52, 56], + [53, 41], + [53, 60], + [54, 45], + [54, 64], + [55, 49], + [55, 68], + [56, 52], + [56, 57], + [57, 56], + [57, 58], + [58, 57], + [58, 59], + [58, 71], + [59, 58], + [59, 60], + [60, 53], + [60, 59], + [60, 61], + [61, 60], + [61, 62], + [62, 61], + [62, 63], + [62, 72], + [63, 62], + [63, 64], + [64, 54], + [64, 63], + [64, 65], + [65, 64], + [65, 66], + [66, 65], + [66, 67], + [66, 73], + [67, 66], + [67, 68], + [68, 55], + [68, 67], + [68, 69], + [69, 68], + [69, 70], + [70, 69], + [70, 74], + [71, 58], + [71, 77], + [72, 62], + [72, 81], + [73, 66], + [73, 85], + [74, 70], + [74, 89], + [75, 76], + [75, 90], + [76, 75], + [76, 77], + [77, 71], + [77, 76], + [77, 78], + [78, 77], + [78, 79], + [79, 78], + [79, 80], + [79, 91], + [80, 79], + [80, 81], + [81, 72], + [81, 80], + [81, 82], + [82, 81], + [82, 83], + [83, 82], + [83, 84], + [83, 92], + [84, 83], + [84, 85], + [85, 73], + [85, 84], + [85, 86], + [86, 85], + [86, 87], + [87, 86], + [87, 88], + [87, 93], + [88, 87], + [88, 89], + [89, 74], + [89, 88], + [90, 75], + [90, 94], + [91, 79], + [91, 98], + [92, 83], + [92, 102], + [93, 87], + [93, 106], + [94, 90], + [94, 95], + [95, 94], + [95, 96], + [96, 95], + [96, 97], + [96, 109], + [97, 96], + [97, 98], + [98, 91], + [98, 97], + [98, 99], + [99, 98], + [99, 100], + [100, 99], + [100, 101], + [100, 110], + [101, 100], + [101, 102], + [102, 92], + [102, 101], + [102, 103], + [103, 102], + [103, 104], + [104, 103], + [104, 105], + [104, 111], + [105, 104], + [105, 106], + [106, 93], + [106, 105], + [106, 107], + [107, 106], + [107, 108], + [108, 107], + [108, 112], + [109, 96], + [110, 100], + [110, 118], + [111, 104], + [111, 122], + [112, 108], + [112, 126], + [113, 114], + [114, 113], + [114, 115], + [115, 114], + [115, 116], + [116, 115], + [116, 117], + [117, 116], + [117, 118], + [118, 110], + [118, 117], + [118, 119], + [119, 118], + [119, 120], + [120, 119], + [120, 121], + [121, 120], + [121, 122], + [122, 111], + [122, 121], + [122, 123], + [123, 122], + [123, 124], + [124, 123], + [124, 125], + [125, 124], + [125, 126], + [126, 112], + [126, 125], + ] + backend = GenericBackendV2( + num_qubits=127, coupling_map=coupling_map, pulse_channels=True, seed=42 + ) img_ref = path_to_diagram_reference("fake_127_q_error.png") fig = plot_error_map(backend) with BytesIO() as img_buffer: @@ -153,9 +560,294 @@ def test_plot_error_map_over_100_qubit(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_over_100_qubit_backend_v2(self): """Test plotting error map with large fake backendv2.""" + coupling_map = [ + [0, 1], + [0, 14], + [1, 0], + [1, 2], + [2, 1], + [2, 3], + [3, 2], + [3, 4], + [4, 3], + [4, 5], + [4, 15], + [5, 4], + [5, 6], + [6, 5], + [6, 7], + [7, 6], + [7, 8], + [8, 7], + [8, 16], + [9, 10], + [10, 9], + [10, 11], + [11, 10], + [11, 12], + [12, 11], + [12, 13], + [12, 17], + [13, 12], + [14, 0], + [14, 18], + [15, 4], + [15, 22], + [16, 8], + [16, 26], + [17, 12], + [17, 30], + [18, 14], + [18, 19], + [19, 18], + [19, 20], + [20, 19], + [20, 21], + [20, 33], + [21, 20], + [21, 22], + [22, 15], + [22, 21], + [22, 23], + [23, 22], + [23, 24], + [24, 23], + [24, 25], + [24, 34], + [25, 24], + [25, 26], + [26, 16], + [26, 25], + [26, 27], + [27, 26], + [27, 28], + [28, 27], + [28, 29], + [28, 35], + [29, 28], + [29, 30], + [30, 17], + [30, 29], + [30, 31], + [31, 30], + [31, 32], + [32, 31], + [32, 36], + [33, 20], + [33, 39], + [34, 24], + [34, 43], + [35, 28], + [35, 47], + [36, 32], + [36, 51], + [37, 38], + [37, 52], + [38, 37], + [38, 39], + [39, 33], + [39, 38], + [39, 40], + [40, 39], + [40, 41], + [41, 40], + [41, 42], + [41, 53], + [42, 41], + [42, 43], + [43, 34], + [43, 42], + [43, 44], + [44, 43], + [44, 45], + [45, 44], + [45, 46], + [45, 54], + [46, 45], + [46, 47], + [47, 35], + [47, 46], + [47, 48], + [48, 47], + [48, 49], + [49, 48], + [49, 50], + [49, 55], + [50, 49], + [50, 51], + [51, 36], + [51, 50], + [52, 37], + [52, 56], + [53, 41], + [53, 60], + [54, 45], + [54, 64], + [55, 49], + [55, 68], + [56, 52], + [56, 57], + [57, 56], + [57, 58], + [58, 57], + [58, 59], + [58, 71], + [59, 58], + [59, 60], + [60, 53], + [60, 59], + [60, 61], + [61, 60], + [61, 62], + [62, 61], + [62, 63], + [62, 72], + [63, 62], + [63, 64], + [64, 54], + [64, 63], + [64, 65], + [65, 64], + [65, 66], + [66, 65], + [66, 67], + [66, 73], + [67, 66], + [67, 68], + [68, 55], + [68, 67], + [68, 69], + [69, 68], + [69, 70], + [70, 69], + [70, 74], + [71, 58], + [71, 77], + [72, 62], + [72, 81], + [73, 66], + [73, 85], + [74, 70], + [74, 89], + [75, 76], + [75, 90], + [76, 75], + [76, 77], + [77, 71], + [77, 76], + [77, 78], + [78, 77], + [78, 79], + [79, 78], + [79, 80], + [79, 91], + [80, 79], + [80, 81], + [81, 72], + [81, 80], + [81, 82], + [82, 81], + [82, 83], + [83, 82], + [83, 84], + [83, 92], + [84, 83], + [84, 85], + [85, 73], + [85, 84], + [85, 86], + [86, 85], + [86, 87], + [87, 86], + [87, 88], + [87, 93], + [88, 87], + [88, 89], + [89, 74], + [89, 88], + [90, 75], + [90, 94], + [91, 79], + [91, 98], + [92, 83], + [92, 102], + [93, 87], + [93, 106], + [94, 90], + [94, 95], + [95, 94], + [95, 96], + [96, 95], + [96, 97], + [96, 109], + [97, 96], + [97, 98], + [98, 91], + [98, 97], + [98, 99], + [99, 98], + [99, 100], + [100, 99], + [100, 101], + [100, 110], + [101, 100], + [101, 102], + [102, 92], + [102, 101], + [102, 103], + [103, 102], + [103, 104], + [104, 103], + [104, 105], + [104, 111], + [105, 104], + [105, 106], + [106, 93], + [106, 105], + [106, 107], + [107, 106], + [107, 108], + [108, 107], + [108, 112], + [109, 96], + [110, 100], + [110, 118], + [111, 104], + [111, 122], + [112, 108], + [112, 126], + [113, 114], + [114, 113], + [114, 115], + [115, 114], + [115, 116], + [116, 115], + [116, 117], + [117, 116], + [117, 118], + [118, 110], + [118, 117], + [118, 119], + [119, 118], + [119, 120], + [120, 119], + [120, 121], + [121, 120], + [121, 122], + [122, 111], + [122, 121], + [122, 123], + [123, 122], + [123, 124], + [124, 123], + [124, 125], + [125, 124], + [125, 126], + [126, 112], + [126, 125], + ] backend = GenericBackendV2( - num_qubits=127, - coupling_map=Fake127QPulseV1().configuration().coupling_map, + num_qubits=127, coupling_map=coupling_map, pulse_channels=True, seed=42 ) img_ref = path_to_diagram_reference("fake_127_q_v2_error.png") fig = plot_error_map(backend) From 2c88395a50c4638ff07868a0c682a944c57838f2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 12:10:50 +0200 Subject: [PATCH 090/168] deprecation warnings: once --- test/utils/base.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/utils/base.py b/test/utils/base.py index 059263ec15e4..5250347fc10d 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -123,7 +123,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2179 is in a release version # of Aer. warnings.filterwarnings( - "ignore", + "default", category=DeprecationWarning, message="Treating CircuitInstruction as an iterable is deprecated", module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", @@ -132,7 +132,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2065 is in a release version # of Aer. warnings.filterwarnings( - "ignore", + "once", # If "default", it floods the CI output category=DeprecationWarning, message=r".* If user still need Qobj,.*", module=r"qiskit_aer", @@ -141,7 +141,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2184 is in a release version # of Aer. warnings.filterwarnings( - "ignore", + "once", # If "default", it floods the CI output category=DeprecationWarning, message=r".*The abstract Provider and ProviderV1 classes are deprecated.*", module="qiskit_aer", From ce72692e482182c6bf2d76c2d171aea7e61a2336 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 12:48:16 +0200 Subject: [PATCH 091/168] default --- test/utils/base.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/utils/base.py b/test/utils/base.py index 5250347fc10d..a96f2e0413c2 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -132,7 +132,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2065 is in a release version # of Aer. warnings.filterwarnings( - "once", # If "default", it floods the CI output + "ignore", # If "default", it floods the CI output category=DeprecationWarning, message=r".* If user still need Qobj,.*", module=r"qiskit_aer", @@ -141,7 +141,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2184 is in a release version # of Aer. warnings.filterwarnings( - "once", # If "default", it floods the CI output + "ignore", # If "default", it floods the CI output category=DeprecationWarning, message=r".*The abstract Provider and ProviderV1 classes are deprecated.*", module="qiskit_aer", From 365da09717f36665f828af63e71492ef2633fb48 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 15:17:57 +0200 Subject: [PATCH 092/168] default --- test/utils/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/utils/base.py b/test/utils/base.py index a96f2e0413c2..80b43c5c1190 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -123,7 +123,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2179 is in a release version # of Aer. warnings.filterwarnings( - "default", + "ignore", # If "default", it floods the CI output category=DeprecationWarning, message="Treating CircuitInstruction as an iterable is deprecated", module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", From 330b1807e6cdf6b66af28e35b4b6fab4a6c343a2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 20:55:07 +0200 Subject: [PATCH 093/168] BackendConfiguration --- qiskit/providers/models/__init__.py | 11 +++++++++++ qiskit/providers/models/backendconfiguration.py | 11 ++++++++++- 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/qiskit/providers/models/__init__.py b/qiskit/providers/models/__init__.py index bf90a9d16c0e..facd7b7c2201 100644 --- a/qiskit/providers/models/__init__.py +++ b/qiskit/providers/models/__init__.py @@ -38,6 +38,7 @@ GateProperties Nduv """ +import warnings from .backendconfiguration import ( BackendConfiguration, @@ -50,3 +51,13 @@ from .backendstatus import BackendStatus from .jobstatus import JobStatus from .pulsedefaults import PulseDefaults, Command + + +warnings.warn( + "qiskit.providers.models is deprecated since Qiskit 1.2 and will be removed in Qiskit 2.0." + "With the removal of Qobj, there is no need for these schema-conformant objects. If you still need" + "to use them, it could be because you are using a BackendV1, which it is also deprecated in favor" + "of BackendV2", + DeprecationWarning, + 2, +) diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index ebd0a6d9bbb6..ddee16c5a974 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -26,6 +26,7 @@ DriveChannel, MeasureChannel, ) +from qiskit.utils import deprecate_func class GateConfig: @@ -493,7 +494,15 @@ def __contains__(self, item): class BackendConfiguration(QasmBackendConfiguration): """Backwards compat shim representing an abstract backend configuration.""" - pass + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The class `BackendConfiguration` is being deprecated " + "as they are not necessary for BackendV2. If user still need Qobj, that probably " + "means that they are using a backend based on the deprecated BackendV1 class.", + ) + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) class PulseBackendConfiguration(QasmBackendConfiguration): From 5da8083ed22c77d9ba78161231b23c998fd21b16 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 20:55:51 +0200 Subject: [PATCH 094/168] PulseBackendConfiguration --- qiskit/providers/models/backendconfiguration.py | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index ddee16c5a974..bef0f4b32976 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -510,6 +510,14 @@ class PulseBackendConfiguration(QasmBackendConfiguration): about the set up of the device which can be useful for building Pulse programs. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The class `PulseBackendConfiguration` is being deprecated " + "as they are not necessary for BackendV2. If user still need Qobj, " + "that probably means that they are using a backend based on the " + "deprecated BackendV1 class.", + ) def __init__( self, backend_name: str, From 19e86e0c1cd86da8f5e9dbc55ff5a77991ed87af Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 20:59:38 +0200 Subject: [PATCH 095/168] QasmBackendConfiguration --- qiskit/providers/models/backendconfiguration.py | 8 ++++++++ test/utils/base.py | 2 +- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index bef0f4b32976..9b8fe616dd5c 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -212,6 +212,14 @@ class QasmBackendConfiguration: _data = {} + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="The class `QasmBackendConfiguration` is being deprecated " + "as they are not necessary for BackendV2. If user still need Qobj, " + "that probably means that they are using a backend based on the " + "deprecated BackendV1 class.", + ) def __init__( self, backend_name, diff --git a/test/utils/base.py b/test/utils/base.py index 80b43c5c1190..4136728578dd 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -135,7 +135,7 @@ def setUpClass(cls): "ignore", # If "default", it floods the CI output category=DeprecationWarning, message=r".* If user still need Qobj,.*", - module=r"qiskit_aer", + module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", ) # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2184 is in a release version From 9d77fe17d8b369b7480f25cacc8ded828c111cd1 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 22:25:02 +0200 Subject: [PATCH 096/168] QasmBackendConfiguration and adjust stacklevel --- qiskit/providers/models/backendconfiguration.py | 4 ++-- qiskit/utils/deprecation.py | 5 +++-- test/utils/base.py | 2 +- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index 9b8fe616dd5c..2d60fe2718d0 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -215,10 +215,10 @@ class QasmBackendConfiguration: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The class `QasmBackendConfiguration` is being deprecated " - "as they are not necessary for BackendV2. If user still need Qobj, " + additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " "that probably means that they are using a backend based on the " "deprecated BackendV1 class.", + stacklevel=3, ) def __init__( self, diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 294ea9414924..9240de32b07d 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -29,6 +29,7 @@ def deprecate_func( package_name: str = "qiskit", removal_timeline: str = "no earlier than 3 months after the release date", is_property: bool = False, + stacklevel: int = 2, ): """Decorator to indicate a function has been deprecated. @@ -50,7 +51,7 @@ def deprecate_func( is_property: If the deprecated function is a `@property`, set this to True so that the generated message correctly describes it as such. (This isn't necessary for property setters, as their docstring is ignored by Python.) - + stacklevel: It will be pass to :func:`warnings.warn`. Returns: Callable: The decorated callable. """ @@ -92,7 +93,7 @@ def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): - warnings.warn(msg, category=category, stacklevel=2) + warnings.warn(msg, category=category, stacklevel=stacklevel) return func(*args, **kwargs) add_deprecation_to_docstring(wrapper, msg, since=since, pending=pending) diff --git a/test/utils/base.py b/test/utils/base.py index 4136728578dd..80b43c5c1190 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -135,7 +135,7 @@ def setUpClass(cls): "ignore", # If "default", it floods the CI output category=DeprecationWarning, message=r".* If user still need Qobj,.*", - module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", + module=r"qiskit_aer", ) # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2184 is in a release version From 35ef95f955a2cfe3c43eb2d7f95db683843439e7 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 22:26:58 +0200 Subject: [PATCH 097/168] UchannelLO --- qiskit/providers/models/backendconfiguration.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index 2d60fe2718d0..3f36b7ca6559 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -142,6 +142,13 @@ class UchannelLO: scale: Scale factor for qubit frequency. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " + "that probably means that they are using a backend based on the " + "deprecated BackendV1 class.", + ) def __init__(self, q, scale): """Initialize a UchannelLOSchema object From 1ef62b4b628df48b9d5d2f9d7fbf04a144ee1b02 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 22:30:45 +0200 Subject: [PATCH 098/168] GateConfig --- .../providers/models/backendconfiguration.py | 8 +++++++ .../python/transpiler/test_pulse_gate_pass.py | 22 ++++++++++++++----- 2 files changed, 24 insertions(+), 6 deletions(-) diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index 3f36b7ca6559..c6e40757a63b 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -39,6 +39,14 @@ class GateConfig: and CX. """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " + "that probably means that they are using a backend based on the " + "deprecated BackendV1 class.", + stacklevel=3, + ) def __init__( self, name, diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index ebd42f82bada..8d6528d875c3 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -197,9 +197,10 @@ def test_transpile_with_custom_gate(self): ) # Add gate to backend configuration backend.configuration().basis_gates.append("my_gate") - dummy_config = GateConfig( - name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,), (1,)] - ) + with self.assertWarns(DeprecationWarning): + dummy_config = GateConfig( + name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,), (1,)] + ) backend.configuration().gates.append(dummy_config) # Remove timing constraints to avoid triggering # scheduling passes. @@ -231,7 +232,10 @@ def test_transpile_with_parameterized_custom_gate(self): ) # Add gate to backend configuration backend.configuration().basis_gates.append("my_gate") - dummy_config = GateConfig(name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,)]) + with self.assertWarns(DeprecationWarning): + dummy_config = GateConfig( + name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,)] + ) backend.configuration().gates.append(dummy_config) # Remove timing constraints to avoid triggering # scheduling passes. @@ -261,7 +265,10 @@ def test_transpile_with_multiple_circuits(self): ) # Add gate to backend configuration backend.configuration().basis_gates.append("my_gate") - dummy_config = GateConfig(name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,)]) + with self.assertWarns(DeprecationWarning): + dummy_config = GateConfig( + name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,)] + ) backend.configuration().gates.append(dummy_config) # Remove timing constraints to avoid triggering # scheduling passes. @@ -292,7 +299,10 @@ def test_multiple_instructions_with_different_parameters(self): ) # Add gate to backend configuration backend.configuration().basis_gates.append("my_gate") - dummy_config = GateConfig(name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,)]) + with self.assertWarns(DeprecationWarning): + dummy_config = GateConfig( + name="my_gate", parameters=[], qasm_def="", coupling_map=[(0,)] + ) backend.configuration().gates.append(dummy_config) # Remove timing constraints to avoid triggering # scheduling passes. From 9097bc97569e0cbc81273647fcb0c9757722cf02 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 18 Jul 2024 22:58:58 +0200 Subject: [PATCH 099/168] test.python.providers.test_fake_backends.TestFakeBackends --- qiskit/providers/models/backendproperties.py | 9 +++++ test/python/providers/test_fake_backends.py | 42 +++++++++++--------- 2 files changed, 33 insertions(+), 18 deletions(-) diff --git a/qiskit/providers/models/backendproperties.py b/qiskit/providers/models/backendproperties.py index 332aac7c5edd..12cf60fc0fbd 100644 --- a/qiskit/providers/models/backendproperties.py +++ b/qiskit/providers/models/backendproperties.py @@ -18,6 +18,7 @@ import dateutil.parser from qiskit.providers.exceptions import BackendPropertyError +from qiskit.utils import deprecate_func from qiskit.utils.units import apply_prefix PropertyT = Tuple[Any, datetime.datetime] @@ -172,6 +173,14 @@ class BackendProperties: _data = {} + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " + "that probably means that they are using a backend based on the " + "deprecated BackendV1 class.", + stacklevel=3, + ) def __init__( self, backend_name, backend_version, last_update_date, qubits, gates, general, **kwargs ): diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 0eede200681f..10587c6da066 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -143,15 +143,18 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): def test_qobj_failure(self): backend = BACKENDS[-1] - tqc = transpile(self.circuit, backend) with self.assertWarns(DeprecationWarning): + tqc = transpile(self.circuit, backend) qobj = assemble(tqc, backend) with self.assertRaises(QiskitError): backend.run(qobj) @data(*BACKENDS) def test_to_dict_properties(self, backend): - properties = backend.properties() + with warnings.catch_warnings(): + # The class QobjExperimentHeader is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + properties = backend.properties() if properties: self.assertIsInstance(backend.properties().to_dict(), dict) else: @@ -526,10 +529,10 @@ def test_filter_faulty_qubits_backend_v2_converter(self): """Test faulty qubits in v2 conversion.""" with self.assertWarns(DeprecationWarning): backend = Fake127QPulseV1() - # Get properties dict to make it easier to work with the properties API - # is difficult to edit because of the multiple layers of nesting and - # different object types - props_dict = backend.properties().to_dict() + # Get properties dict to make it easier to work with the properties API + # is difficult to edit because of the multiple layers of nesting and + # different object types + props_dict = backend.properties().to_dict() for i in range(62, 67): non_operational = { "date": datetime.datetime.now(datetime.timezone.utc), @@ -538,7 +541,8 @@ def test_filter_faulty_qubits_backend_v2_converter(self): "value": 0, } props_dict["qubits"][i].append(non_operational) - backend._properties = BackendProperties.from_dict(props_dict) + with self.assertWarns(DeprecationWarning): + backend._properties = BackendProperties.from_dict(props_dict) v2_backend = BackendV2Converter(backend, filter_faulty=True) for i in range(62, 67): for qarg in v2_backend.target.qargs: @@ -548,10 +552,10 @@ def test_filter_faulty_qubits_backend_v2_converter_with_delay(self): """Test faulty qubits in v2 conversion.""" with self.assertWarns(DeprecationWarning): backend = Fake127QPulseV1() - # Get properties dict to make it easier to work with the properties API - # is difficult to edit because of the multiple layers of nesting and - # different object types - props_dict = backend.properties().to_dict() + # Get properties dict to make it easier to work with the properties API + # is difficult to edit because of the multiple layers of nesting and + # different object types + props_dict = backend.properties().to_dict() for i in range(62, 67): non_operational = { "date": datetime.datetime.now(datetime.timezone.utc), @@ -560,7 +564,8 @@ def test_filter_faulty_qubits_backend_v2_converter_with_delay(self): "value": 0, } props_dict["qubits"][i].append(non_operational) - backend._properties = BackendProperties.from_dict(props_dict) + with self.assertWarns(DeprecationWarning): + backend._properties = BackendProperties.from_dict(props_dict) v2_backend = BackendV2Converter(backend, filter_faulty=True, add_delay=True) for i in range(62, 67): for qarg in v2_backend.target.qargs: @@ -617,10 +622,10 @@ def test_filter_faulty_qubits_and_gates_backend_v2_converter(self): """Test faulty gates and qubits.""" with self.assertWarns(DeprecationWarning): backend = Fake127QPulseV1() - # Get properties dict to make it easier to work with the properties API - # is difficult to edit because of the multiple layers of nesting and - # different object types - props_dict = backend.properties().to_dict() + # Get properties dict to make it easier to work with the properties API + # is difficult to edit because of the multiple layers of nesting and + # different object types + props_dict = backend.properties().to_dict() for i in range(62, 67): non_operational = { "date": datetime.datetime.now(datetime.timezone.utc), @@ -649,7 +654,8 @@ def test_filter_faulty_qubits_and_gates_backend_v2_converter(self): if tuple(gate["qubits"]) in invalid_cx_edges: gate["parameters"].append(non_operational_gate) - backend._properties = BackendProperties.from_dict(props_dict) + with self.assertWarns(DeprecationWarning): + backend._properties = BackendProperties.from_dict(props_dict) v2_backend = BackendV2Converter(backend, filter_faulty=True) for i in range(62, 67): for qarg in v2_backend.target.qargs: @@ -696,7 +702,7 @@ def test_filter_faulty_no_faults_v2_converter(self): """Test that faulty qubit filtering does nothing with all operational qubits and gates.""" with self.assertWarns(DeprecationWarning): backend = Fake127QPulseV1() - v2_backend = BackendV2Converter(backend, filter_faulty=True) + v2_backend = BackendV2Converter(backend, filter_faulty=True) for i in range(v2_backend.num_qubits): self.assertIn((i,), v2_backend.target.qargs) From 03f8574f034b5a5eec1466e141383d222b2efe63 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 19 Jul 2024 17:50:23 +0200 Subject: [PATCH 100/168] test.python.providers.test_fake_backends --- qiskit/providers/backend_compat.py | 18 ++++++++++++++---- .../fake_provider/fake_qasm_backend.py | 6 +++++- qiskit/providers/models/backendproperties.py | 1 + .../transpiler/preset_passmanagers/__init__.py | 6 +++++- qiskit/transpiler/target.py | 15 +++++++++++++-- test/python/providers/test_fake_backends.py | 15 +++++++++------ 6 files changed, 47 insertions(+), 14 deletions(-) diff --git a/qiskit/providers/backend_compat.py b/qiskit/providers/backend_compat.py index e567c330a958..83cde6b4112f 100644 --- a/qiskit/providers/backend_compat.py +++ b/qiskit/providers/backend_compat.py @@ -25,6 +25,7 @@ from qiskit.providers.models.pulsedefaults import PulseDefaults from qiskit.providers.options import Options from qiskit.providers.exceptions import BackendPropertyError +from qiskit.utils import deprecate_func logger = logging.getLogger(__name__) @@ -352,6 +353,12 @@ class should only be used if you need a :class:`~.BackendV2` and still need ) """ + @deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="Since ``BackendV1`` is deprecated, this conversion tool from BackendV1 to " + "BackendV2 is going to be removed with BackendV1.", + ) def __init__( self, backend: BackendV1, @@ -390,10 +397,13 @@ def __init__( self._properties = None self._defaults = None - if hasattr(self._backend, "properties"): - self._properties = self._backend.properties() - if hasattr(self._backend, "defaults"): - self._defaults = self._backend.defaults() + with warnings.catch_warnings(): + # The class QobjExperimentHeader is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + if hasattr(self._backend, "properties"): + self._properties = self._backend.properties() + if hasattr(self._backend, "defaults"): + self._defaults = self._backend.defaults() self._target = None self._name_mapping = name_mapping diff --git a/qiskit/providers/fake_provider/fake_qasm_backend.py b/qiskit/providers/fake_provider/fake_qasm_backend.py index 55dad4aff601..aec595fb86bb 100644 --- a/qiskit/providers/fake_provider/fake_qasm_backend.py +++ b/qiskit/providers/fake_provider/fake_qasm_backend.py @@ -16,6 +16,7 @@ import json import os +import warnings from qiskit.exceptions import QiskitError from qiskit.providers.models import BackendProperties, QasmBackendConfiguration @@ -61,7 +62,10 @@ def _set_props_from_json(self): raise QiskitError("No properties file has been defined") props = self._load_json(self.props_filename) decode_backend_properties(props) - self._properties = BackendProperties.from_dict(props) + with warnings.catch_warnings(): + # This raises BackendProperties internally + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + self._properties = BackendProperties.from_dict(props) def _load_json(self, filename): with open(os.path.join(self.dirname, filename)) as f_json: diff --git a/qiskit/providers/models/backendproperties.py b/qiskit/providers/models/backendproperties.py index 12cf60fc0fbd..865d44ee0db9 100644 --- a/qiskit/providers/models/backendproperties.py +++ b/qiskit/providers/models/backendproperties.py @@ -257,6 +257,7 @@ def from_dict(cls, data): qubits.append(nduvs) gates = [GateProperties.from_dict(x) for x in in_data.pop("gates")] general = [Nduv.from_dict(x) for x in in_data.pop("general")] + return cls( backend_name, backend_version, last_update_date, qubits, gates, general, **in_data ) diff --git a/qiskit/transpiler/preset_passmanagers/__init__.py b/qiskit/transpiler/preset_passmanagers/__init__.py index f2f011e486c4..07bffa12943e 100644 --- a/qiskit/transpiler/preset_passmanagers/__init__.py +++ b/qiskit/transpiler/preset_passmanagers/__init__.py @@ -58,6 +58,7 @@ .. currentmodule:: qiskit.transpiler.preset_passmanagers """ import copy +import warnings from qiskit.circuit.controlflow import CONTROL_FLOW_OP_NAMES from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping @@ -363,7 +364,10 @@ def generate_preset_pass_manager( if timing_constraints is None: timing_constraints = target.timing_constraints() if backend_properties is None: - backend_properties = target_to_backend_properties(target) + with warnings.catch_warnings(): + # The function target_to_backend_properties is deprecated + warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") + _properties = target_to_backend_properties(target) pm_options = { "target": target, diff --git a/qiskit/transpiler/target.py b/qiskit/transpiler/target.py index 8805deece50e..9efec540ac5d 100644 --- a/qiskit/transpiler/target.py +++ b/qiskit/transpiler/target.py @@ -20,6 +20,7 @@ from __future__ import annotations import itertools +import warnings from typing import Optional, List, Any from collections.abc import Mapping @@ -50,7 +51,7 @@ # full target from qiskit.providers.backend import QubitProperties # pylint: disable=unused-import from qiskit.providers.models.backendproperties import BackendProperties - +from qiskit.utils import deprecate_func logger = logging.getLogger(__name__) @@ -1442,6 +1443,13 @@ def from_configuration( return target +@deprecate_func( + since="1.2", + removal_timeline="in the 2.0 release", + additional_msg="This function is not necessary for BackendV2. If user still need Qobj, that " + "probably means that they are using a backend based on the deprecated BackendV1 " + "class.", +) def target_to_backend_properties(target: Target): """Convert a :class:`~.Target` object into a legacy :class:`~.BackendProperties`""" @@ -1520,6 +1528,9 @@ def target_to_backend_properties(target: Target): if gates or qubits: properties_dict["gates"] = gates properties_dict["qubits"] = qubits - return BackendProperties.from_dict(properties_dict) + with warnings.catch_warnings(): + # This raises BackendProperties internally + warnings.filterwarnings("ignore", category=DeprecationWarning) + return BackendProperties.from_dict(properties_dict) else: return None diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 10587c6da066..4a629ce0d6de 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -604,9 +604,9 @@ def test_backend_v2_converter_with_meaningless_gate_config(self): """Test backend with broken gate config can be converted only with properties data.""" with self.assertWarns(DeprecationWarning): backend_v1 = Fake5QV1() - backend_v1.configuration().gates = [ - GateConfig(name="NotValidGate", parameters=[], qasm_def="not_valid_gate") - ] + backend_v1.configuration().gates = [ + GateConfig(name="NotValidGate", parameters=[], qasm_def="not_valid_gate") + ] backend_v2 = BackendV2Converter( backend=backend_v1, filter_faulty=True, @@ -691,7 +691,8 @@ def test_filter_faulty_gates_v2_converter(self): if tuple(gate["qubits"]) in invalid_cx_edges: gate["parameters"].append(non_operational_gate) - backend._properties = BackendProperties.from_dict(props_dict) + with self.assertWarns(DeprecationWarning): + backend._properties = BackendProperties.from_dict(props_dict) v2_backend = BackendV2Converter(backend, filter_faulty=True) for i in range(62, 67): self.assertIn((i,), v2_backend.target.qargs) @@ -710,17 +711,19 @@ def test_filter_faulty_no_faults_v2_converter(self): def test_faulty_full_path_transpile_connected_cmap(self, opt_level): with self.assertWarns(DeprecationWarning): backend = Fake5QV1() + props = backend.properties().to_dict() + non_operational_gate = { "date": datetime.datetime.now(datetime.timezone.utc), "name": "operational", "unit": "", "value": 0, } - props = backend.properties().to_dict() for gate in props["gates"]: if tuple(sorted(gate["qubits"])) == (0, 1): gate["parameters"].append(non_operational_gate) - backend._properties = BackendProperties.from_dict(props) + with self.assertWarns(DeprecationWarning): + backend._properties = BackendProperties.from_dict(props) v2_backend = BackendV2Converter(backend, filter_faulty=True) qc = QuantumCircuit(5) for x, y in itertools.product(range(5), range(5)): From deb7380f7510458527d3f80f0dd9d1558e95b9ae Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 21 Jul 2024 22:04:36 +0200 Subject: [PATCH 101/168] test.python.compiler.test_transpiler --- test/python/compiler/test_transpiler.py | 113 ++++++++++++++---------- 1 file changed, 67 insertions(+), 46 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 6d97b8717867..f0e504b35373 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1513,7 +1513,7 @@ def test_scheduling_timing_constraints(self): with self.assertWarns(DeprecationWarning): backend_v1 = Fake27QPulseV1() - backend_v2 = BackendV2Converter(backend_v1) + backend_v2 = BackendV2Converter(backend_v1) # the original timing constraints are granularity = min_length = 16 timing_constraints = TimingConstraints(granularity=32, min_length=64) error_msgs = { @@ -1537,11 +1537,12 @@ def test_scheduling_timing_constraints(self): [0, 0], ) with self.assertRaisesRegex(TranspilerError, error_msgs[duration]): - _ = transpile( - qc, - backend=backend, - timing_constraints=timing_constraints, - ) + with self.assertWarns(DeprecationWarning): + _ = transpile( + qc, + backend=backend, + timing_constraints=timing_constraints, + ) def test_scheduling_instruction_constraints(self): """Test that scheduling-related loose transpile constraints @@ -1549,7 +1550,7 @@ def test_scheduling_instruction_constraints(self): with self.assertWarns(DeprecationWarning): backend_v1 = Fake27QPulseV1() - backend_v2 = BackendV2Converter(backend_v1) + backend_v2 = BackendV2Converter(backend_v1) qc = QuantumCircuit(2) qc.h(0) qc.delay(500, 1, "dt") @@ -1558,16 +1559,24 @@ def test_scheduling_instruction_constraints(self): durations = InstructionDurations.from_backend(backend_v1) durations.update([("cx", [0, 1], 1000, "dt")]) - for backend in [backend_v1, backend_v2]: - with self.subTest(backend=backend): - scheduled = transpile( - qc, - backend=backend, - scheduling_method="alap", - instruction_durations=durations, - layout_method="trivial", - ) - self.assertEqual(scheduled.duration, 1500) + with self.assertWarns(DeprecationWarning): + scheduled = transpile( + qc, + backend=backend_v1, + scheduling_method="alap", + instruction_durations=durations, + layout_method="trivial", + ) + self.assertEqual(scheduled.duration, 1500) + + scheduled = transpile( + qc, + backend=backend_v2, + scheduling_method="alap", + instruction_durations=durations, + layout_method="trivial", + ) + self.assertEqual(scheduled.duration, 1500) def test_scheduling_dt_constraints(self): """Test that scheduling-related loose transpile constraints @@ -1575,20 +1584,23 @@ def test_scheduling_dt_constraints(self): with self.assertWarns(DeprecationWarning): backend_v1 = Fake27QPulseV1() - backend_v2 = BackendV2Converter(backend_v1) + backend_v2 = BackendV2Converter(backend_v1) qc = QuantumCircuit(1, 1) qc.x(0) qc.measure(0, 0) original_dt = 2.2222222222222221e-10 original_duration = 3504 - for backend in [backend_v1, backend_v2]: - with self.subTest(backend=backend): - # halve dt in sec = double duration in dt - scheduled = transpile( - qc, backend=backend, scheduling_method="asap", dt=original_dt / 2 - ) - self.assertEqual(scheduled.duration, original_duration * 2) + with self.assertWarns(DeprecationWarning): + # halve dt in sec = double duration in dt + scheduled = transpile( + qc, backend=backend_v1, scheduling_method="asap", dt=original_dt / 2 + ) + self.assertEqual(scheduled.duration, original_duration * 2) + + # halve dt in sec = double duration in dt + scheduled = transpile(qc, backend=backend_v2, scheduling_method="asap", dt=original_dt / 2) + self.assertEqual(scheduled.duration, original_duration * 2) def test_backend_props_constraints(self): """Test that loose transpile constraints @@ -1596,7 +1608,7 @@ def test_backend_props_constraints(self): with self.assertWarns(DeprecationWarning): backend_v1 = Fake20QV1() - backend_v2 = BackendV2Converter(backend_v1) + backend_v2 = BackendV2Converter(backend_v1) qr1 = QuantumRegister(3, "qr1") qr2 = QuantumRegister(2, "qr2") qc = QuantumCircuit(qr1, qr2) @@ -1608,7 +1620,8 @@ def test_backend_props_constraints(self): # generate a fake backend with same number of qubits # but different backend properties fake_backend = GenericBackendV2(num_qubits=20, seed=42) - custom_backend_properties = target_to_backend_properties(fake_backend.target) + with self.assertWarns(DeprecationWarning): + custom_backend_properties = target_to_backend_properties(fake_backend.target) # expected layout for custom_backend_properties # (different from expected layout for Fake20QV1) @@ -1635,17 +1648,25 @@ def test_backend_props_constraints(self): 17: Qubit(QuantumRegister(15, "ancilla"), 14), } - for backend in [backend_v1, backend_v2]: - with self.subTest(backend=backend): - result = transpile( - qc, - backend=backend, - backend_properties=custom_backend_properties, - optimization_level=2, - seed_transpiler=42, - ) + with self.assertWarns(DeprecationWarning): + result = transpile( + qc, + backend=backend_v1, + backend_properties=custom_backend_properties, + optimization_level=2, + seed_transpiler=42, + ) + + self.assertEqual(result._layout.initial_layout._p2v, vf2_layout) + result = transpile( + qc, + backend=backend_v2, + backend_properties=custom_backend_properties, + optimization_level=2, + seed_transpiler=42, + ) - self.assertEqual(result._layout.initial_layout._p2v, vf2_layout) + self.assertEqual(result._layout.initial_layout._p2v, vf2_layout) @data(1, 2, 3) def test_no_infinite_loop(self, optimization_level): @@ -2082,9 +2103,9 @@ def test_transpile_annotated_ops_with_backend_v1(self, opt_level): qc.append(AnnotatedOperation(HGate(), PowerModifier(3)), [2]) with self.assertWarns(DeprecationWarning): backend = Fake20QV1() - transpiled = transpile( - qc, optimization_level=opt_level, backend=backend, seed_transpiler=42 - ) + transpiled = transpile( + qc, optimization_level=opt_level, backend=backend, seed_transpiler=42 + ) self.assertLessEqual(set(transpiled.count_ops().keys()), {"u1", "u2", "u3", "cx"}) @combine(opt_level=[0, 1, 2, 3]) @@ -2457,12 +2478,12 @@ def test_qasm3_output(self, optimization_level): with self.assertWarns(DeprecationWarning): backend = Fake20QV1() - transpiled = transpile( - self._regular_circuit(), - backend=backend, - optimization_level=optimization_level, - seed_transpiler=2022_10_17, - ) + transpiled = transpile( + self._regular_circuit(), + backend=backend, + optimization_level=optimization_level, + seed_transpiler=2022_10_17, + ) # TODO: There's not a huge amount we can sensibly test for the output here until we can # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump # itself doesn't throw an error, though. From 0fe2e02f7caf279f72eb92f64f0f5279d65320a7 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 21 Jul 2024 22:16:26 +0200 Subject: [PATCH 102/168] remove catch --- qiskit/assembler/assemble_circuits.py | 3 +-- qiskit/compiler/assembler.py | 16 ++++++---------- 2 files changed, 7 insertions(+), 12 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index a8d7a78cfc4c..ac54a0563368 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -404,8 +404,7 @@ def _assemble_circuits( @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The function assemble_circuits is being deprecated " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " + additional_msg="The function is not necessary for BackendV2. If user still need Qobj, that probably " "means that they are using a backend based on the deprecated BackendV1 class.", ) def assemble_circuits( diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 11195a851ab0..01f7978ed653 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -265,16 +265,12 @@ def _assemble( ) end_time = time() _log_assembly_time(start_time, end_time) - with warnings.catch_warnings(): - # The Qobj is deprecated - # warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - warnings.filterwarnings("ignore", category=DeprecationWarning) - return _assemble_circuits( - circuits=bound_experiments, - qobj_id=qobj_id, - qobj_header=qobj_header, - run_config=run_config, - ) + return _assemble_circuits( + circuits=bound_experiments, + qobj_id=qobj_id, + qobj_header=qobj_header, + run_config=run_config, + ) elif all(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments): run_config = _parse_pulse_args( From d185d7e618b9eb7bc7810a2ff33b8215e2bbb7cf Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 21 Jul 2024 22:19:55 +0200 Subject: [PATCH 103/168] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- qiskit/assembler/assemble_circuits.py | 6 +++--- .../notes/deprecate_assemble-67486b4d0a8d4f96.yaml | 7 ++----- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index a8d7a78cfc4c..b6f8c4038574 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -404,9 +404,9 @@ def _assemble_circuits( @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The function assemble_circuits is being deprecated " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated `BackendV1` " + "workflow, and no longer necessary for `BackendV2`. If a user workflow requires `Qobj` it likely relies " + "on deprecated functionality and should be updated to use `BackendV2`.", ) def assemble_circuits( circuits: List[QuantumCircuit], run_config: RunConfig, qobj_id: int, qobj_header: QobjHeader diff --git a/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml b/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml index 94044a361bb9..b7b50d2eb2b2 100644 --- a/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml +++ b/releasenotes/notes/deprecate_assemble-67486b4d0a8d4f96.yaml @@ -1,10 +1,7 @@ --- deprecations_providers: - | - The structures related to Qobj are now deprecated. Interacting with remote backends should be done via QPY or - OpenQASM instead. + The `Qobj` structure and related classes are now deprecated, they were introduced as part of the `BackendV1` workflow and are no longer necessary for interacting with :class:`.BackendV2` backends. Remote backend interaction should be done via `QPY` or `OpenQASM` instead. deprecations_transpiler: - | - The function `assemble` is now deprecated as the Qobj structure is not needed any more. The function was used, - among other things, to create a Qobj. It was also used for binding parameter and that functionality is now - fully covered by :meth:`~.QuantumCircuit.assign_parameters`. + The `assemble` function is now deprecated and will be removed in the 2.0 release. The function was primarily used to create a `Qobj`, which is no longer necessary in :class:`.BackendV2`-based workflows. It was also used for binding parameters, a functionality fully covered by :meth:`~.QuantumCircuit.assign_parameters`. From ac54cd8b364cfb5b9a2171897c40077044a2b508 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 21 Jul 2024 22:31:07 +0200 Subject: [PATCH 104/168] remove catch --- qiskit/compiler/assembler.py | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index eb1697fd4e07..0446735a5089 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -265,16 +265,12 @@ def _assemble( ) end_time = time() _log_assembly_time(start_time, end_time) - with warnings.catch_warnings(): - # The Qobj is deprecated - # warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - warnings.filterwarnings("ignore", category=DeprecationWarning) - return _assemble_circuits( - circuits=bound_experiments, - qobj_id=qobj_id, - qobj_header=qobj_header, - run_config=run_config, - ) + return _assemble_circuits( + circuits=bound_experiments, + qobj_id=qobj_id, + qobj_header=qobj_header, + run_config=run_config, + ) elif all(isinstance(exp, (ScheduleBlock, Schedule, Instruction)) for exp in experiments): run_config = _parse_pulse_args( From 9cd165b48f912f49750747cbe944293a6629f4f5 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 21 Jul 2024 22:52:52 +0200 Subject: [PATCH 105/168] new deprecate warning message --- qiskit/assembler/disassemble.py | 7 +-- qiskit/circuit/instruction.py | 7 +-- qiskit/compiler/assembler.py | 7 +-- qiskit/qobj/common.py | 7 +-- qiskit/qobj/converters/lo_config.py | 7 +-- qiskit/qobj/converters/pulse_instruction.py | 8 ++-- qiskit/qobj/pulse_qobj.py | 51 +++++++++++---------- qiskit/qobj/qasm_qobj.py | 51 +++++++++++---------- qiskit/qobj/utils.py | 6 +-- 9 files changed, 83 insertions(+), 68 deletions(-) diff --git a/qiskit/assembler/disassemble.py b/qiskit/assembler/disassemble.py index 8f296a42d9bf..74905a9a6d20 100644 --- a/qiskit/assembler/disassemble.py +++ b/qiskit/assembler/disassemble.py @@ -41,9 +41,10 @@ @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The function disassemble is being deprecated " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def disassemble(qobj) -> Union[CircuitModule, PulseModule]: """Disassemble a qobj and return the circuits or pulse schedules, run_config, and user header. diff --git a/qiskit/circuit/instruction.py b/qiskit/circuit/instruction.py index 30796fa08ad2..7963d0c1e096 100644 --- a/qiskit/circuit/instruction.py +++ b/qiskit/circuit/instruction.py @@ -362,9 +362,10 @@ def unit(self, unit): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The method assemble is being deprecated " - "as it is not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def assemble(self): """Assemble a QasmQobjInstruction""" diff --git a/qiskit/compiler/assembler.py b/qiskit/compiler/assembler.py index 0446735a5089..2802169b4afb 100644 --- a/qiskit/compiler/assembler.py +++ b/qiskit/compiler/assembler.py @@ -44,9 +44,10 @@ def _log_assembly_time(start_time, end_time): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The function assemble is being deprecated " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def assemble( experiments: Union[ diff --git a/qiskit/qobj/common.py b/qiskit/qobj/common.py index 9a3fdd4e20e2..0f1e2372fd9a 100644 --- a/qiskit/qobj/common.py +++ b/qiskit/qobj/common.py @@ -26,9 +26,10 @@ class QobjDictField(SimpleNamespace): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QobjDictField's subclasses, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, **kwargs): """Instantiate a new Qobj dict field object. diff --git a/qiskit/qobj/converters/lo_config.py b/qiskit/qobj/converters/lo_config.py index a76df3991f05..a5b5beb80df2 100644 --- a/qiskit/qobj/converters/lo_config.py +++ b/qiskit/qobj/converters/lo_config.py @@ -27,9 +27,10 @@ class LoConfigConverter: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including LoConfigConverter class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__( self, diff --git a/qiskit/qobj/converters/pulse_instruction.py b/qiskit/qobj/converters/pulse_instruction.py index 45f82a9c7d50..e17036210d57 100644 --- a/qiskit/qobj/converters/pulse_instruction.py +++ b/qiskit/qobj/converters/pulse_instruction.py @@ -111,10 +111,10 @@ def _convert_NewInstruction(self, instruction, time_offset): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including InstructionToQobjConverter " - "class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__( self, diff --git a/qiskit/qobj/pulse_qobj.py b/qiskit/qobj/pulse_qobj.py index 0de59f894dc6..7a5ce06c8f3f 100644 --- a/qiskit/qobj/pulse_qobj.py +++ b/qiskit/qobj/pulse_qobj.py @@ -32,10 +32,10 @@ class QobjMeasurementOption: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QobjMeasurementOption " - "class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, name, params=None): """Instantiate a new QobjMeasurementOption object. @@ -101,9 +101,10 @@ class PulseQobjInstruction: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including PulseQobjInstruction class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__( self, @@ -301,9 +302,10 @@ class PulseQobjConfig(QobjDictField): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including PulseQobjConfig class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__( self, @@ -409,9 +411,10 @@ class PulseQobjExperiment: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including PulseQobjExperiment class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, instructions, config=None, header=None): """Instantiate a PulseQobjExperiment. @@ -506,10 +509,10 @@ class PulseQobjExperimentConfig(QobjDictField): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including PulseQobjExperimentConfig " - "class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, qubit_lo_freq=None, meas_lo_freq=None, **kwargs): """Instantiate a PulseQobjExperimentConfig object. @@ -533,9 +536,10 @@ class PulseLibraryItem: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including PulseLibraryItem class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, name, samples): """Instantiate a pulse library item. @@ -590,9 +594,10 @@ class PulseQobj: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including PulseQobj class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, qobj_id, config, experiments, header=None): """Instantiate a new Pulse Qobj Object. diff --git a/qiskit/qobj/qasm_qobj.py b/qiskit/qobj/qasm_qobj.py index b9b78bcb4ec1..8858913fb47c 100644 --- a/qiskit/qobj/qasm_qobj.py +++ b/qiskit/qobj/qasm_qobj.py @@ -27,9 +27,10 @@ class QasmQobjInstruction: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including PulseQobj class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__( self, @@ -211,9 +212,10 @@ class QasmQobjExperiment: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QasmQobjExperiment class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, config=None, header=None, instructions=None): """Instantiate a QasmQobjExperiment. @@ -294,9 +296,10 @@ class QasmQobjConfig(SimpleNamespace): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QasmQobjConfig class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__( self, @@ -435,10 +438,10 @@ class QasmQobjExperimentConfig(QobjDictField): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QasmQobjExperimentConfig " - "class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, calibrations=None, qubit_lo_freq=None, meas_lo_freq=None, **kwargs): """ @@ -479,10 +482,10 @@ class QasmExperimentCalibrations: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QasmExperimentCalibrations " - "class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, gates): """ @@ -527,9 +530,10 @@ class GateCalibration: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including GateCalibration class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, name, qubits, params, instructions): """ @@ -589,9 +593,10 @@ class QasmQobj: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QasmQobj class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated " + "`BackendV1` workflow, and no longer necessary for `BackendV2`. If a user " + "workflow requires `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", ) def __init__(self, qobj_id=None, config=None, experiments=None, header=None): """Instantiate a new OpenQASM 2 Qobj Object. diff --git a/qiskit/qobj/utils.py b/qiskit/qobj/utils.py index 1d3b6bd84300..1e691d6324bf 100644 --- a/qiskit/qobj/utils.py +++ b/qiskit/qobj/utils.py @@ -20,9 +20,9 @@ @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The full Qobj module is being deprecated, including QobjType class, " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + additional_msg="The `Qobj` class and related functionality are part of the deprecated `BackendV1` " + "workflow, and no longer necessary for `BackendV2`. If a user workflow requires `Qobj` it likely " + "relies on deprecated functionality and should be updated to use `BackendV2`.", ) class QobjType(str, Enum): """Qobj.type allowed values.""" From a45431ac7a3af661c4b30fa6312adf04fd764830 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 22 Jul 2024 10:44:25 +0200 Subject: [PATCH 106/168] lint qiskit/assembler/assemble_circuits.py --- qiskit/assembler/assemble_circuits.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index b6f8c4038574..5fd3eced62cc 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -405,8 +405,9 @@ def _assemble_circuits( since="1.2", removal_timeline="in the 2.0 release", additional_msg="The `Qobj` class and related functionality are part of the deprecated `BackendV1` " - "workflow, and no longer necessary for `BackendV2`. If a user workflow requires `Qobj` it likely relies " - "on deprecated functionality and should be updated to use `BackendV2`.", + "workflow, and no longer necessary for `BackendV2`. If a user workflow requires " + "`Qobj` it likely relies on deprecated functionality and should be updated to " + "use `BackendV2`.", ) def assemble_circuits( circuits: List[QuantumCircuit], run_config: RunConfig, qobj_id: int, qobj_header: QobjHeader From fa7f32d58596df49e4726b29e8946851f5c44e90 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 22 Jul 2024 13:56:49 +0200 Subject: [PATCH 107/168] concurrency warnings --- qiskit/assembler/assemble_circuits.py | 6 +++++- test/python/compiler/test_transpiler.py | 6 +----- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/qiskit/assembler/assemble_circuits.py b/qiskit/assembler/assemble_circuits.py index 5fd3eced62cc..62f3df180718 100644 --- a/qiskit/assembler/assemble_circuits.py +++ b/qiskit/assembler/assemble_circuits.py @@ -316,7 +316,11 @@ def _configure_experiment_los( def _assemble_circuits( circuits: List[QuantumCircuit], run_config: RunConfig, qobj_id: int, qobj_header: QobjHeader ) -> QasmQobj: - experiments_and_pulse_libs = parallel_map(_assemble_circuit, circuits, [run_config]) + with warnings.catch_warnings(): + # Still constructs Qobj, that is deprecated. The message is hard to trace to a module, + # because concurrency is hard. + warnings.filterwarnings("ignore", category=DeprecationWarning) + experiments_and_pulse_libs = parallel_map(_assemble_circuit, circuits, [run_config]) experiments = [] pulse_library = {} for exp, lib in experiments_and_pulse_libs: diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index a1bfae10ee47..77b63a3098bc 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -17,7 +17,6 @@ import math import os import sys -import warnings from logging import StreamHandler, getLogger from unittest.mock import patch import numpy as np @@ -2639,10 +2638,7 @@ def test_parallel_dispatch(self, opt_level): tqc = transpile( qlist, backend=backend, optimization_level=opt_level, seed_transpiler=424242 ) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() + result = backend.run(tqc, seed_simulator=4242424242, shots=1000).result() counts = result.get_counts() for count in counts: self.assertTrue(math.isclose(count["00000"], 500, rel_tol=0.1)) From 2a085b5356f693184c5b7ff8cfa5aaeedba4bf25 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 22 Jul 2024 14:25:29 +0200 Subject: [PATCH 108/168] ignore aer warnings --- test/utils/base.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/test/utils/base.py b/test/utils/base.py index 0b02f3e58488..8bb76777f56d 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -129,6 +129,24 @@ def setUpClass(cls): module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", ) + # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2065 is in a release version + # of Aer. + warnings.filterwarnings( + "ignore", # If "default", it floods the CI output + category=DeprecationWarning, + message=r".*The `Qobj` class and related functionality.*", + module=r"qiskit_aer", + ) + + # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2184 is in a release version + # of Aer. + warnings.filterwarnings( + "ignore", # If "default", it floods the CI output + category=DeprecationWarning, + message=r".*The abstract Provider and ProviderV1 classes are deprecated.*", + module="qiskit_aer", + ) + allow_DeprecationWarning_message = [ r"The property ``qiskit\.circuit\.bit\.Bit\.(register|index)`` is deprecated.*", ] From 5e63bef6cc2aa15b5dadfcf0b39c5e8761757f93 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 11:39:11 +0200 Subject: [PATCH 109/168] Update test/python/providers/fake_provider/test_fake_backends.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- test/python/providers/fake_provider/test_fake_backends.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index 7318fc2bc05a..3d22c2de7e72 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -61,10 +61,6 @@ def test_fake_backend_v2_noise_model_always_present(self): qc = QuantumCircuit(1) qc.x(0) qc.measure_all() - with warnings.catch_warnings(): - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - res = backend.run(qc, shots=1000).result().get_counts() + res = backend.run(qc, shots=1000).result().get_counts() # Assert noise was present and result wasn't ideal self.assertNotEqual(res, {"1": 1000}) From 83332e52f2ca12a78f0ecc04cac6f163df796835 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 11:40:02 +0200 Subject: [PATCH 110/168] Update test/python/circuit/test_parameters.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- test/python/circuit/test_parameters.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index d977aa30089f..4f989767164f 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -1022,8 +1022,7 @@ def test_binding_parameterized_circuits_built_in_multiproc_(self): ) def test_binding_parameterized_circuits_built_in_multiproc(self): - """Verify subcircuits built in a subprocess can still be bound. - REMOVE this test once assemble is REMOVED""" + """Verify subcircuits built in a subprocess can still be bound.""" # ref: https://github.com/Qiskit/qiskit-terra/issues/2429 num_processes = 4 From 60cc9c54159af92ab05bf158d24dbfc3dda0df4c Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 11:40:21 +0200 Subject: [PATCH 111/168] Update qiskit/providers/models/pulsedefaults.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- qiskit/providers/models/pulsedefaults.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/providers/models/pulsedefaults.py b/qiskit/providers/models/pulsedefaults.py index fcd11c26ec29..494d31c7a60d 100644 --- a/qiskit/providers/models/pulsedefaults.py +++ b/qiskit/providers/models/pulsedefaults.py @@ -272,7 +272,7 @@ def from_dict(cls, data): PulseDefaults: The PulseDefaults from the input dictionary. """ schema = { - "pulse_library": PulseLibraryItem, # The class PulseLibraryItem` is deprecated + "pulse_library": PulseLibraryItem, # The class PulseLibraryItem is deprecated "cmd_def": Command, "meas_kernel": MeasurementKernel, "discriminator": Discriminator, From 1362b1b0cd882555750446b5ca681043e456d8e4 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 14:31:30 +0200 Subject: [PATCH 112/168] Update test/python/providers/fake_provider/test_fake_backends.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- test/python/providers/fake_provider/test_fake_backends.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index 3d22c2de7e72..ba9909d95abc 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -46,10 +46,7 @@ def test_fake_backends_get_kwargs(self): qc.measure_all() trans_qc = transpile(qc, backend) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() + raw_counts = backend.run(trans_qc, shots=1000).result().get_counts() self.assertEqual(sum(raw_counts.values()), 1000) From 787090f4216271478d8ebcc2d95ecb00db7a44b6 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 14:31:37 +0200 Subject: [PATCH 113/168] Update test/python/providers/fake_provider/test_generic_backend_v2.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- .../providers/fake_provider/test_generic_backend_v2.py | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/test/python/providers/fake_provider/test_generic_backend_v2.py b/test/python/providers/fake_provider/test_generic_backend_v2.py index 51df49e73456..e0dc3e986c8a 100644 --- a/test/python/providers/fake_provider/test_generic_backend_v2.py +++ b/test/python/providers/fake_provider/test_generic_backend_v2.py @@ -137,11 +137,7 @@ def test_run(self): backend = GenericBackendV2(num_qubits=5, basis_gates=["cx", "id", "rz", "sx", "x"]) tqc = transpile(qc, backend=backend, optimization_level=3, seed_transpiler=42) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using Provider ABC - # https://github.com/Qiskit/qiskit-aer/pull/2184 - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - result = backend.run(tqc, seed_simulator=42, shots=1000).result() + result = backend.run(tqc, seed_simulator=42, shots=1000).result() counts = result.get_counts() self.assertTrue(math.isclose(counts["00000"], 500, rel_tol=0.1)) From 20a0c5cab953be84e3a680f88b9a9d33760a2396 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 16:49:45 +0200 Subject: [PATCH 114/168] lint --- test/python/providers/fake_provider/test_fake_backends.py | 1 - test/python/providers/fake_provider/test_generic_backend_v2.py | 1 - 2 files changed, 2 deletions(-) diff --git a/test/python/providers/fake_provider/test_fake_backends.py b/test/python/providers/fake_provider/test_fake_backends.py index ba9909d95abc..c12be3584fc2 100644 --- a/test/python/providers/fake_provider/test_fake_backends.py +++ b/test/python/providers/fake_provider/test_fake_backends.py @@ -13,7 +13,6 @@ """Test of generated fake backends.""" import math import unittest -import warnings from qiskit import QuantumRegister, ClassicalRegister, QuantumCircuit, transpile from qiskit.providers.fake_provider import Fake5QV1, GenericBackendV2 diff --git a/test/python/providers/fake_provider/test_generic_backend_v2.py b/test/python/providers/fake_provider/test_generic_backend_v2.py index e0dc3e986c8a..33bf57cf3903 100644 --- a/test/python/providers/fake_provider/test_generic_backend_v2.py +++ b/test/python/providers/fake_provider/test_generic_backend_v2.py @@ -13,7 +13,6 @@ """ Test of GenericBackendV2 backend""" import math -import warnings from qiskit import ClassicalRegister, QuantumCircuit, QuantumRegister, transpile from qiskit.providers.fake_provider import GenericBackendV2 From bd216a17e8e0f3f20b6b5862c0b7c4f20d45ff56 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 16:53:01 +0200 Subject: [PATCH 115/168] https://github.com/Qiskit/qiskit/pull/12649#discussion_r1686717954 --- test/python/providers/test_fake_backends.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 49771deef568..f857d32c210c 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -132,16 +132,13 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): self.skipTest( f"Unable to run fake_backend {backend.configuration().backend_name} without qiskit-aer" ) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - job = backend.run( - transpile( - self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level - ), - seed_simulator=42, - ) - result = job.result() + job = backend.run( + transpile( + self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level + ), + seed_simulator=42, + ) + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") From c1c3b32caf4d040b756e3f05b08d743cefb76d5a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 16:55:01 +0200 Subject: [PATCH 116/168] https://github.com/Qiskit/qiskit/pull/12649#discussion_r1686717732 --- test/python/providers/test_fake_backends.py | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index f857d32c210c..1a1c55d1ee2d 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -105,18 +105,15 @@ def setUpClass(cls): optimization_level=[0, 1, 2, 3], ) def test_circuit_on_fake_backend_v2(self, backend, optimization_level): - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - if not optionals.HAS_AER and backend.num_qubits > 20: - self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") - job = backend.run( - transpile( - self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level - ), - seed_simulator=42, - ) - result = job.result() + if not optionals.HAS_AER and backend.num_qubits > 20: + self.skipTest(f"Unable to run fake_backend {backend.name} without qiskit-aer") + job = backend.run( + transpile( + self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level + ), + seed_simulator=42, + ) + result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] self.assertEqual(max_count, "11") From 7a2b3f79ec0a607eb4ed67a05f3b561f728aee17 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 16:56:09 +0200 Subject: [PATCH 117/168] Update test/python/transpiler/test_sabre_swap.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- test/python/transpiler/test_sabre_swap.py | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index 5273e2a17089..ae3199a7ff27 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -275,11 +275,8 @@ def test_no_infinite_loop(self, method): # Assert that the same keys are produced by a simulation - this is a test that the inserted # swaps route the qubits correctly. - with warnings.catch_warnings(): - # TODO remove Aer stops using Provider Qiskit class - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - if not optionals.HAS_AER: - return + if not optionals.HAS_AER: + return from qiskit_aer import Aer From 5f19ae93c93d9a0ba9ddeb7aae32426b92f14b88 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 16:56:45 +0200 Subject: [PATCH 118/168] Update qiskit/providers/models/pulsedefaults.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- qiskit/providers/models/pulsedefaults.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/providers/models/pulsedefaults.py b/qiskit/providers/models/pulsedefaults.py index 494d31c7a60d..1302994d40e6 100644 --- a/qiskit/providers/models/pulsedefaults.py +++ b/qiskit/providers/models/pulsedefaults.py @@ -284,7 +284,7 @@ def from_dict(cls, data): for key, value in data.items(): if key in schema: with warnings.catch_warnings(): - # The class PulseLibraryItem` is deprecated + # The class PulseLibraryItem is deprecated warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") if isinstance(value, list): in_data[key] = list(map(schema[key].from_dict, value)) From a761b2d758780b72c7fec119aa3f242f5a15ebf5 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 23 Jul 2024 17:58:00 +0200 Subject: [PATCH 119/168] ignore Treating CircuitInstruction... --- test/utils/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/utils/base.py b/test/utils/base.py index 8bb76777f56d..6d0c917ace30 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -123,7 +123,7 @@ def setUpClass(cls): # Safe to remove once https://github.com/Qiskit/qiskit-aer/pull/2179 is in a release version # of Aer. warnings.filterwarnings( - "default", + "ignore", # If "default", it floods the CI output category=DeprecationWarning, message="Treating CircuitInstruction as an iterable is deprecated", module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", From 264f2af3d294991ecd8fa525f1d62a5021ba9e15 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 24 Jul 2024 09:27:26 +0200 Subject: [PATCH 120/168] another unnecessary catch from aer --- qiskit/primitives/backend_estimator.py | 20 ++++++++------------ 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/qiskit/primitives/backend_estimator.py b/qiskit/primitives/backend_estimator.py index 4f237396d2b2..8446c870b1fd 100644 --- a/qiskit/primitives/backend_estimator.py +++ b/qiskit/primitives/backend_estimator.py @@ -15,7 +15,6 @@ from __future__ import annotations -import warnings from collections.abc import Sequence from itertools import accumulate @@ -68,17 +67,14 @@ def _run_circuits( max_circuits = backend.max_circuits else: raise RuntimeError("Backend version not supported") - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - if max_circuits: - jobs = [ - backend.run(circuits[pos : pos + max_circuits], **run_options) - for pos in range(0, len(circuits), max_circuits) - ] - result = [x.result() for x in jobs] - else: - result = [backend.run(circuits, **run_options).result()] + if max_circuits: + jobs = [ + backend.run(circuits[pos : pos + max_circuits], **run_options) + for pos in range(0, len(circuits), max_circuits) + ] + result = [x.result() for x in jobs] + else: + result = [backend.run(circuits, **run_options).result()] return result, metadata From 4c76ad0ce05412ea1399b681ce0268460a0f929a Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Wed, 24 Jul 2024 09:29:53 +0200 Subject: [PATCH 121/168] another unnecessary catch from aer, again --- .../providers/fake_provider/fake_backend.py | 23 +++++-------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/qiskit/providers/fake_provider/fake_backend.py b/qiskit/providers/fake_provider/fake_backend.py index 0256cbc9e17c..4a638f315574 100644 --- a/qiskit/providers/fake_provider/fake_backend.py +++ b/qiskit/providers/fake_provider/fake_backend.py @@ -58,10 +58,7 @@ def _setup_sim(self): self.sim = AerSimulator() if self.properties(): - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops Treating CircuitInstruction as an iterable - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - noise_model = NoiseModel.from_backend(self) + noise_model = NoiseModel.from_backend(self) self.sim.set_options(noise_model=noise_model) # Update fake backend default options too to avoid overwriting # it when run() is called @@ -123,20 +120,12 @@ def properties(self): @classmethod def _default_options(cls): - with warnings.catch_warnings(): - # Remove once https://github.com/Qiskit/qiskit-aer/issues/2178 gets closed. - warnings.filterwarnings( - "ignore", - category=DeprecationWarning, - module="qiskit", - message=".+abstract Provider and ProviderV1.+", - ) - if _optionals.HAS_AER: - from qiskit_aer import QasmSimulator + if _optionals.HAS_AER: + from qiskit_aer import QasmSimulator - return QasmSimulator._default_options() - else: - return basic_provider.BasicSimulator._default_options() + return QasmSimulator._default_options() + else: + return basic_provider.BasicSimulator._default_options() def run(self, run_input, **kwargs): """Main job in simulator""" From b69bdf96b5663ddb6bb8ffb367398701df515cef Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 11:03:57 +0200 Subject: [PATCH 122/168] removing more unnecesary catches --- test/python/transpiler/test_sabre_swap.py | 11 +++-------- test/python/transpiler/test_star_prerouting.py | 15 ++++----------- 2 files changed, 7 insertions(+), 19 deletions(-) diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index ae3199a7ff27..bf2ef5b1f9c4 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -15,7 +15,6 @@ import unittest import itertools -import warnings import ddt import numpy.random @@ -280,13 +279,9 @@ def test_no_infinite_loop(self, method): from qiskit_aer import Aer - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using QobjDictField and Provider ABC - # https://github.com/Qiskit/qiskit-aer/pull/2184 - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - sim = Aer.get_backend("aer_simulator") - in_results = sim.run(qc, shots=4096).result().get_counts() - out_results = sim.run(routed, shots=4096).result().get_counts() + sim = Aer.get_backend("aer_simulator") + in_results = sim.run(qc, shots=4096).result().get_counts() + out_results = sim.run(routed, shots=4096).result().get_counts() self.assertEqual(set(in_results), set(out_results)) def test_classical_condition(self): diff --git a/test/python/transpiler/test_star_prerouting.py b/test/python/transpiler/test_star_prerouting.py index aeac559e2b9c..e244d97a45aa 100644 --- a/test/python/transpiler/test_star_prerouting.py +++ b/test/python/transpiler/test_star_prerouting.py @@ -15,7 +15,6 @@ """Test the StarPreRouting pass""" import unittest -import warnings from test import QiskitTestCase import ddt @@ -260,11 +259,8 @@ def test_100q_grid_full_path(self, opt_level): ) pm.init += StarPreRouting() result = pm.run(qc) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - counts_before = AerSimulator().run(qc).result().get_counts() - counts_after = AerSimulator().run(result).result().get_counts() + counts_before = AerSimulator().run(qc).result().get_counts() + counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) def test_10q_bv_no_barrier(self): @@ -303,11 +299,8 @@ def test_100q_grid_full_path_no_barrier(self, opt_level): ) pm.init += StarPreRouting() result = pm.run(qc) - with warnings.catch_warnings(): - # TODO remove this catch once Aer stops using qiskit.qobj.common.QobjDictField` - warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") - counts_before = AerSimulator().run(qc).result().get_counts() - counts_after = AerSimulator().run(result).result().get_counts() + counts_before = AerSimulator().run(qc).result().get_counts() + counts_after = AerSimulator().run(result).result().get_counts() self.assertEqual(counts_before, counts_after) def test_hadamard_ordering(self): From 8c7f685d2dcb7b7f952c4ed284c4843a2765ddbb Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 13:44:47 +0200 Subject: [PATCH 123/168] less lines --- test/python/transpiler/test_star_prerouting.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/test/python/transpiler/test_star_prerouting.py b/test/python/transpiler/test_star_prerouting.py index ddc8096eefd7..738af45cea7e 100644 --- a/test/python/transpiler/test_star_prerouting.py +++ b/test/python/transpiler/test_star_prerouting.py @@ -20,10 +20,7 @@ from qiskit.circuit.library import QFT from qiskit.circuit.quantumcircuit import QuantumCircuit -from qiskit.converters import ( - circuit_to_dag, - dag_to_circuit, -) +from qiskit.converters import circuit_to_dag, dag_to_circuit from qiskit.quantum_info import Operator from qiskit.transpiler.passes import VF2Layout, ApplyLayout, SabreSwap, SabreLayout from qiskit.transpiler.passes.routing.star_prerouting import StarPreRouting From cd21d3067946fd3c09737dcac1aa6961a6e7a3f4 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 14:57:26 +0200 Subject: [PATCH 124/168] seeding --- test/python/compiler/test_scheduler.py | 1 - test/python/transpiler/test_pulse_gate_pass.py | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/test/python/compiler/test_scheduler.py b/test/python/compiler/test_scheduler.py index ae7957c90010..ad9b14b24c4a 100644 --- a/test/python/compiler/test_scheduler.py +++ b/test/python/compiler/test_scheduler.py @@ -51,7 +51,6 @@ def test_instruction_map_and_backend_not_supplied(self): def test_instruction_map_and_backend_defaults_unavailable(self): """Test backend defaults unavailable when backend is provided, but instruction map is not.""" - # TODO remove the test once BackendV1 is removed, since BackendV2 does not have defaults with self.assertWarns(DeprecationWarning): self.backend = FakeOpenPulse3Q() self.backend._defaults = None diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index ebd42f82bada..539674609c26 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -130,6 +130,7 @@ def test_transpile_with_custom_basis_gate_in_target(self): num_qubits=5, coupling_map=BOGOTA_CMAP, calibrate_instructions=backend_pulse.defaults().instruction_schedule_map, + seed=42, ).target target["sx"][(0,)].calibration = self.custom_sx_q0 @@ -156,7 +157,6 @@ def test_transpile_with_instmap(self): """Test providing instruction schedule map.""" with self.assertWarns(DeprecationWarning): backend = Fake27QPulseV1() - instmap = backend.defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) instmap.add("sx", (1,), self.custom_sx_q1) From f34620cebab81a486fb4b6646a228b81c7a233a1 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 16:15:30 +0200 Subject: [PATCH 125/168] remove those comments --- test/python/compiler/test_assembler.py | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/test/python/compiler/test_assembler.py b/test/python/compiler/test_assembler.py index fdd23edd53f3..c333ce9ace22 100644 --- a/test/python/compiler/test_assembler.py +++ b/test/python/compiler/test_assembler.py @@ -64,7 +64,6 @@ def setUp(self): self.circ.measure(qr, cr) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated self.backend = Fake5QV1() self.backend_config = self.backend.configuration() self.num_qubits = self.backend_config.n_qubits @@ -553,7 +552,6 @@ def test_pulse_gates_single_circ(self): circ.add_calibration(RxGate(3.14), [1], x180) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble(circ, FakeOpenPulse2Q()) # Only one circuit, so everything is stored at the job level cals = qobj.config.calibrations @@ -576,7 +574,6 @@ def test_custom_pulse_gates_single_circ(self): circ.add_calibration("h", [0], custom_h_schedule) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble(circ, FakeOpenPulse2Q()) lib = qobj.config.pulse_library self.assertEqual(len(lib), 1) @@ -596,7 +593,6 @@ def test_pulse_gates_with_parameteric_pulses(self): circ.add_calibration("h", [0], custom_h_schedule) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = FakeOpenPulse2Q() backend.configuration().parametric_pulses = ["drag"] with self.assertWarns(DeprecationWarning): @@ -641,7 +637,6 @@ def test_pulse_gates_common_cals(self): circ2.add_calibration(RxGate(3.14), [1], dummy_sched) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble([circ, circ2], FakeOpenPulse2Q()) # Identical pulses are only added once self.assertEqual(len(qobj.config.pulse_library), 1) @@ -669,7 +664,6 @@ def test_pulse_gates_delay_only(self): test_sched = pulse.Delay(64, DriveChannel(0)) + pulse.Delay(160, DriveChannel(0)) circ.add_calibration("test", [0], test_sched) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated qobj = assemble(circ, FakeOpenPulse2Q()) self.assertEqual(len(qobj.config.calibrations.gates[0].instructions), 2) self.assertEqual( @@ -983,7 +977,6 @@ class TestPulseAssembler(QiskitTestCase): def setUp(self): super().setUp() with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated self.backend = FakeOpenPulse2Q() self.backend_config = self.backend.configuration() @@ -1293,7 +1286,6 @@ def test_pulse_name_conflicts(self): def test_pulse_name_conflicts_in_other_schedule(self): """Test two pulses with the same name in different schedule can be resolved.""" with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = Fake27QPulseV1() defaults = backend.defaults() @@ -1403,7 +1395,6 @@ def test_assemble_parametric(self): << sched.duration ) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = [ "gaussian", @@ -1452,7 +1443,6 @@ def test_assemble_parametric_unsupported(self): sched += Play(pulse.Constant(duration=25, amp=1), DriveChannel(2)) with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = FakeOpenPulse3Q() backend.configuration().parametric_pulses = ["something_extra"] @@ -1466,7 +1456,6 @@ def test_assemble_parametric_unsupported(self): def test_assemble_parametric_pulse_kwarg_with_backend_setting(self): """Test that parametric pulses respect the kwarg over backend""" with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = Fake27QPulseV1() qc = QuantumCircuit(1, 1) @@ -1484,7 +1473,6 @@ def test_assemble_parametric_pulse_kwarg_with_backend_setting(self): def test_assemble_parametric_pulse_kwarg_empty_list_with_backend_setting(self): """Test that parametric pulses respect the kwarg as empty list over backend""" with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = Fake27QPulseV1() qc = QuantumCircuit(1, 1) @@ -1843,7 +1831,6 @@ def setUp(self): self.schedule = pulse.Schedule(name="fake_experiment") with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated self.backend = FakeOpenPulse2Q() self.config = self.backend.configuration() self.defaults = self.backend.defaults() @@ -1986,7 +1973,6 @@ def test_missing_lo_ranges(self): def test_unsupported_meas_level(self): """Test that assembly raises an error if meas_level is not supported""" with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = FakeOpenPulse2Q() backend.configuration().meas_levels = [1, 2] with self.assertRaises(QiskitError), self.assertWarns(DeprecationWarning): @@ -2008,7 +1994,6 @@ def test_unsupported_meas_level(self): def test_single_and_deprecated_acquire_styles(self): """Test that acquires are identically combined with Acquires that take a single channel.""" with self.assertWarns(DeprecationWarning): - # Ignorable, because assemble and BackendV1 are deprecated backend = FakeOpenPulse2Q() new_style_schedule = Schedule() acq_dur = 1200 From 6013044499e0a8949d0aa2a44d9f34f8f38c1468 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 16:24:15 +0200 Subject: [PATCH 126/168] test.python.compiler.test_transpiler.TestTranspile.test_scheduling_timing_constraints --- test/python/compiler/test_transpiler.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 6d97b8717867..7ef005e19638 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -96,7 +96,7 @@ from test import QiskitTestCase, combine, slow_test # pylint: disable=wrong-import-order -from ..legacy_cmaps import MELBOURNE_CMAP, RUESCHLIKON_CMAP +from ..legacy_cmaps import MELBOURNE_CMAP, RUESCHLIKON_CMAP, MUMBAI_CMAP class CustomCX(Gate): @@ -1513,7 +1513,13 @@ def test_scheduling_timing_constraints(self): with self.assertWarns(DeprecationWarning): backend_v1 = Fake27QPulseV1() - backend_v2 = BackendV2Converter(backend_v1) + backend_v2 = GenericBackendV2( + num_qubits=27, + calibrate_instructions=True, + control_flow=True, + coupling_map=MUMBAI_CMAP, + seed=42, + ) # the original timing constraints are granularity = min_length = 16 timing_constraints = TimingConstraints(granularity=32, min_length=64) error_msgs = { From ff36f48eff71a2d47852d24778a4e0f5264a7e16 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 16:59:57 +0200 Subject: [PATCH 127/168] tokyo cmap --- test/python/compiler/test_transpiler.py | 51 +------------------------ 1 file changed, 2 insertions(+), 49 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 7ef005e19638..7ad1950f2633 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -96,7 +96,7 @@ from test import QiskitTestCase, combine, slow_test # pylint: disable=wrong-import-order -from ..legacy_cmaps import MELBOURNE_CMAP, RUESCHLIKON_CMAP, MUMBAI_CMAP +from ..legacy_cmaps import MELBOURNE_CMAP, RUESCHLIKON_CMAP, MUMBAI_CMAP, TOKYO_CMAP class CustomCX(Gate): @@ -2103,54 +2103,7 @@ def test_transpile_annotated_ops_with_backend(self, opt_level): backend = GenericBackendV2( num_qubits=20, - coupling_map=[ - [0, 1], - [1, 0], - [1, 2], - [1, 6], - [2, 1], - [2, 3], - [3, 2], - [3, 4], - [3, 8], - [4, 3], - [5, 6], - [5, 10], - [6, 1], - [6, 5], - [6, 7], - [7, 6], - [7, 8], - [7, 12], - [8, 3], - [8, 7], - [8, 9], - [9, 8], - [9, 14], - [10, 5], - [10, 11], - [11, 10], - [11, 12], - [11, 16], - [12, 7], - [12, 11], - [12, 13], - [13, 12], - [13, 14], - [13, 18], - [14, 9], - [14, 13], - [15, 16], - [16, 11], - [16, 15], - [16, 17], - [17, 16], - [17, 18], - [18, 13], - [18, 17], - [18, 19], - [19, 18], - ], + coupling_map=TOKYO_CMAP, basis_gates=["id", "u1", "u2", "u3", "cx"], ) transpiled = transpile( From 5eb561e94b07e53119e1c5e75bce69236f387afd Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 18:39:31 +0200 Subject: [PATCH 128/168] test.python.circuit.test_scheduled_circuit.TestScheduledCircuit.test_schedule_circuit_when_backend_tells_dt --- test/python/circuit/test_scheduled_circuit.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index 3e992db0963d..c934b5b5e04c 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -56,10 +56,10 @@ def test_schedule_circuit_when_backend_tells_dt(self): qc.h(0) # 195[dt] qc.h(1) # 210[dt] - backend = GenericBackendV2(27, calibrate_instructions=True, seed=42) + backend = GenericBackendV2(2, calibrate_instructions=True, seed=42) sc = transpile(qc, backend, scheduling_method="alap", layout_method="trivial") - self.assertEqual(sc.duration, 451096) + self.assertEqual(sc.duration, 451095) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 450900) @@ -68,7 +68,7 @@ def test_schedule_circuit_when_backend_tells_dt(self): self.assertEqual(sc.data[1].operation.duration, 0) self.assertEqual(sc.data[1].operation.unit, "dt") self.assertEqual(sc.data[4].operation.name, "delay") - self.assertEqual(sc.data[4].operation.duration, 450928) + self.assertEqual(sc.data[4].operation.duration, 450885) self.assertEqual(sc.data[4].operation.unit, "dt") def test_schedule_circuit_when_transpile_option_tells_dt(self): From 469189c7a77f59016954836791a41e1c4f564462 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 18:53:45 +0200 Subject: [PATCH 129/168] comment in test_sequencer.py --- test/python/compiler/test_sequencer.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/python/compiler/test_sequencer.py b/test/python/compiler/test_sequencer.py index 4f5389a930f9..e32d6370367b 100644 --- a/test/python/compiler/test_sequencer.py +++ b/test/python/compiler/test_sequencer.py @@ -13,6 +13,8 @@ # pylint: disable=missing-function-docstring """Tests basic functionality of the sequence function""" +# TODO with the removal of pulses, this file can be removed too. + import unittest from qiskit import QuantumCircuit, pulse From 11a82d43a9fd62f6777b00e45b3edf2cfb889197 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 19:03:53 +0200 Subject: [PATCH 130/168] test.python.compiler.test_transpiler.TestPostTranspileIntegration.test_qasm3_output --- test/python/compiler/test_transpiler.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 7ad1950f2633..661df86f02c3 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -2413,6 +2413,26 @@ def test_qpy_roundtrip_standalone_var_target(self, optimization_level): @data(0, 1, 2, 3) def test_qasm3_output(self, optimization_level): """Test that the output of a transpiled circuit can be dumped into OpenQASM 3.""" + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + ) + + transpiled = transpile( + self._regular_circuit(), + backend=backend, + optimization_level=optimization_level, + seed_transpiler=2022_10_17, + ) + # TODO: There's not a huge amount we can sensibly test for the output here until we can + # round-trip the OpenQASM 3 back into a Terra circuit. Mostly we're concerned that the dump + # itself doesn't throw an error, though. + self.assertIsInstance(qasm3.dumps(transpiled).strip(), str) + + @data(0, 1, 2, 3) + def test_qasm3_output_v1(self, optimization_level): + """Test that the output of a transpiled circuit can be dumped into OpenQASM 3 (backend V1).""" with self.assertWarns(DeprecationWarning): backend = Fake20QV1() From 353592514f44f301e1dbba83fecf75adeaf109a8 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 19:05:16 +0200 Subject: [PATCH 131/168] Update test/python/primitives/test_primitive.py MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- test/python/primitives/test_primitive.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/python/primitives/test_primitive.py b/test/python/primitives/test_primitive.py index 1c0074fdf91f..8b8ef4be03c5 100644 --- a/test/python/primitives/test_primitive.py +++ b/test/python/primitives/test_primitive.py @@ -143,7 +143,7 @@ def test_with_scheduling(n): qc.x(0) qc.add_calibration("x", qubits=(0,), schedule=custom_gate) backend = GenericBackendV2( - num_qubits=20, basis_gates=["id", "u1", "u2", "u3", "cx"], seed=42 + num_qubits=2, basis_gates=["id", "u1", "u2", "u3", "cx"], seed=42 ) return transpile(qc, backend, scheduling_method="alap") From e005b48671e171d81ec5a2940c8183d757a35356 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 19:06:29 +0200 Subject: [PATCH 132/168] test/python/providers/test_backendconfiguration.py:30 --- test/python/providers/test_backendconfiguration.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/python/providers/test_backendconfiguration.py b/test/python/providers/test_backendconfiguration.py index 1fc5a6bb3e12..82bbd1c6847f 100644 --- a/test/python/providers/test_backendconfiguration.py +++ b/test/python/providers/test_backendconfiguration.py @@ -12,6 +12,9 @@ """ Test that the PulseBackendConfiguration methods work as expected with a mocked Pulse backend. """ +# TODO the full file can be removed once BackendV1 is removed, since it is the +# only one with backend.configuration() + import collections import copy From 10b0de4aaf41e37647a99fca6a06e7bfe8f30ea0 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Thu, 25 Jul 2024 22:39:39 +0200 Subject: [PATCH 133/168] test.python.primitives.test_backend_sampler --- test/python/primitives/test_backend_sampler.py | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index 8c3288aee318..f0fdb4f07f8c 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -322,7 +322,8 @@ def max_circuits(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=FakeBackendLimitedCircuits(num_qubits=5, seed=42)) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=FakeBackendLimitedCircuits(num_qubits=5, seed=42)) result = sampler.run([qc, qc2]).result() self.assertIsInstance(result, SamplerResult) self.assertEqual(len(result.quasi_dists), 2) @@ -380,7 +381,8 @@ def test_sequential_run(self): qc2 = QuantumCircuit(1) qc2.x(0) qc2.measure_all() - sampler = BackendSampler(backend=backend) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) result = sampler.run([qc]).result() self.assertDictAlmostEqual(result.quasi_dists[0], {0: 1}, 0.1) result2 = sampler.run([qc2]).result() @@ -424,7 +426,8 @@ def callback(msg): backend = GenericBackendV2( 7, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 ) - sampler = BackendSampler(backend=backend, bound_pass_manager=bound_pass) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend, bound_pass_manager=bound_pass) _ = sampler.run([self._circuit[0]]).result() expected = [ "bound_pass_manager", @@ -447,7 +450,8 @@ def callback(msg): # pylint: disable=function-redefined backend = GenericBackendV2( 7, calibrate_instructions=True, basis_gates=["cx", "u1", "u2", "u3"], seed=42 ) - sampler = BackendSampler(backend=backend, bound_pass_manager=bound_pass) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend, bound_pass_manager=bound_pass) _ = sampler.run([self._circuit[0], self._circuit[0]]).result() expected = [ "bound_pass_manager", From 589e6f2bd93dde84e03400e04ebfa5d8603ed87e Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 26 Jul 2024 10:24:13 +0200 Subject: [PATCH 134/168] restore the assertWarns, waiting for #12818 --- .../primitives/test_backend_estimator.py | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/test/python/primitives/test_backend_estimator.py b/test/python/primitives/test_backend_estimator.py index fed1c8c72c7d..3263c149d8ae 100644 --- a/test/python/primitives/test_backend_estimator.py +++ b/test/python/primitives/test_backend_estimator.py @@ -390,10 +390,11 @@ def callback(msg): bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator( - backend=GenericBackendV2(num_qubits=5, seed=42), bound_pass_manager=bound_pass - ) - _ = estimator.run(qc, op).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator( + backend=GenericBackendV2(num_qubits=5, seed=42), bound_pass_manager=bound_pass + ) + _ = estimator.run(qc, op).result() expected = [ "bound_pass_manager", ] @@ -412,10 +413,12 @@ def callback(msg): # pylint: disable=function-redefined bound_counter = CallbackPass("bound_pass_manager", callback) bound_pass = PassManager(bound_counter) - estimator = BackendEstimator( - backend=GenericBackendV2(num_qubits=5, seed=42), bound_pass_manager=bound_pass - ) - _ = estimator.run([qc, qc], [op, op]).result() + with self.assertWarns(DeprecationWarning): + estimator = BackendEstimator( + backend=GenericBackendV2(num_qubits=5, seed=42), + bound_pass_manager=bound_pass, + ) + _ = estimator.run([qc, qc], [op, op]).result() expected = [ "bound_pass_manager", "bound_pass_manager", From bd2e363ea5694261a2a42e60e791eeeb8634fcf2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 26 Jul 2024 22:39:34 +0200 Subject: [PATCH 135/168] use legacy_cmaps instead of explict coupling maps --- test/python/circuit/test_parameters.py | 16 +----- .../transpiler/test_passmanager_config.py | 50 +------------------ 2 files changed, 4 insertions(+), 62 deletions(-) diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index 8ac22be3c91f..c2df1a423ec4 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -35,6 +35,7 @@ from qiskit.providers.basic_provider import BasicSimulator from qiskit.utils import parallel_map from test import QiskitTestCase, combine # pylint: disable=wrong-import-order +from ..legacy_cmaps import BOGOTA_CMAP def raise_if_parameter_table_invalid(circuit): @@ -1114,20 +1115,7 @@ def test_transpile_across_optimization_levels(self, opt_level): qc, GenericBackendV2( num_qubits=5, - coupling_map=[ - [0, 1], - [1, 0], - [1, 2], - [2, 1], - [0, 2], - [2, 0], - [2, 3], - [3, 2], - [3, 4], - [4, 3], - [2, 4], - [4, 2], - ], + coupling_map=BOGOTA_CMAP, seed=42, ), optimization_level=opt_level, diff --git a/test/python/transpiler/test_passmanager_config.py b/test/python/transpiler/test_passmanager_config.py index f9ee28e0ac60..ebac6a410b7f 100644 --- a/test/python/transpiler/test_passmanager_config.py +++ b/test/python/transpiler/test_passmanager_config.py @@ -19,6 +19,7 @@ from qiskit.transpiler.coupling import CouplingMap from qiskit.transpiler.passmanager_config import PassManagerConfig from test import QiskitTestCase # pylint: disable=wrong-import-order +from ..legacy_cmaps import ALMADEN_CMAP class TestPassManagerConfig(QiskitTestCase): @@ -87,54 +88,7 @@ def test_from_backend_and_user(self): backend = GenericBackendV2( num_qubits=20, - coupling_map=[ - [0, 1], - [1, 0], - [1, 2], - [1, 6], - [2, 1], - [2, 3], - [3, 2], - [3, 4], - [3, 8], - [4, 3], - [5, 6], - [5, 10], - [6, 1], - [6, 5], - [6, 7], - [7, 6], - [7, 8], - [7, 12], - [8, 3], - [8, 7], - [8, 9], - [9, 8], - [9, 14], - [10, 5], - [10, 11], - [11, 10], - [11, 12], - [11, 16], - [12, 7], - [12, 11], - [12, 13], - [13, 12], - [13, 14], - [13, 18], - [14, 9], - [14, 13], - [15, 16], - [16, 11], - [16, 15], - [16, 17], - [17, 16], - [17, 18], - [18, 13], - [18, 17], - [18, 19], - [19, 18], - ], + coupling_map=ALMADEN_CMAP, basis_gates=["id", "u1", "u2", "u3", "cx"], calibrate_instructions=None, seed=42, From 982e274d80572cef4c207eafb6dda7a49250c1b6 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 26 Jul 2024 22:48:17 +0200 Subject: [PATCH 136/168] use more legacy_map --- .../python/transpiler/test_passmanager_run.py | 54 ++----------------- 1 file changed, 3 insertions(+), 51 deletions(-) diff --git a/test/python/transpiler/test_passmanager_run.py b/test/python/transpiler/test_passmanager_run.py index 969dbc6bd951..3da6a042564c 100644 --- a/test/python/transpiler/test_passmanager_run.py +++ b/test/python/transpiler/test_passmanager_run.py @@ -18,6 +18,7 @@ from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler import Layout, PassManager from qiskit.transpiler.passmanager_config import PassManagerConfig +from ..legacy_cmaps import ALMADEN_CMAP from test import QiskitTestCase # pylint: disable=wrong-import-order @@ -83,57 +84,8 @@ def test_default_pass_manager_single(self): circuit.cx(qr[1], qr[2]) circuit.cx(qr[2], qr[3]) - coupling_map = [ - [0, 1], - [1, 0], - [1, 2], - [1, 6], - [2, 1], - [2, 3], - [3, 2], - [3, 4], - [3, 8], - [4, 3], - [5, 6], - [5, 10], - [6, 1], - [6, 5], - [6, 7], - [7, 6], - [7, 8], - [7, 12], - [8, 3], - [8, 7], - [8, 9], - [9, 8], - [9, 14], - [10, 5], - [10, 11], - [11, 10], - [11, 12], - [11, 16], - [12, 7], - [12, 11], - [12, 13], - [13, 12], - [13, 14], - [13, 18], - [14, 9], - [14, 13], - [15, 16], - [16, 11], - [16, 15], - [16, 17], - [17, 16], - [17, 18], - [18, 13], - [18, 17], - [18, 19], - [19, 18], - ] - backend = GenericBackendV2( - num_qubits=20, coupling_map=coupling_map, basis_gates=["id", "u1", "u2", "u3", "cx"] + num_qubits=20, coupling_map=ALMADEN_CMAP, basis_gates=["id", "u1", "u2", "u3", "cx"] ) initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] @@ -151,7 +103,7 @@ def test_default_pass_manager_single(self): for instruction in new_circuit.data: if isinstance(instruction.operation, CXGate): - self.assertIn([bit_indices[x] for x in instruction.qubits], coupling_map) + self.assertIn([bit_indices[x] for x in instruction.qubits], ALMADEN_CMAP) def test_default_pass_manager_two(self): """Test default_pass_manager.run(circuitS). From 36633d17c5db1e8718ac069e35fe4c3fe22b8125 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Fri, 26 Jul 2024 23:04:04 +0200 Subject: [PATCH 137/168] KYOTO_CMAP --- test/python/legacy_cmaps.py | 148 +++++++++++++++++++++ test/python/visualization/test_gate_map.py | 60 +-------- 2 files changed, 150 insertions(+), 58 deletions(-) diff --git a/test/python/legacy_cmaps.py b/test/python/legacy_cmaps.py index 08d2f043ca4e..84f4be45128b 100644 --- a/test/python/legacy_cmaps.py +++ b/test/python/legacy_cmaps.py @@ -426,3 +426,151 @@ [64, 54], [64, 63], ] + +# 127 qubits +KYOTO_CMAP = [ + [0, 14], + [1, 0], + [1, 2], + [3, 2], + [4, 3], + [4, 5], + [6, 5], + [7, 6], + [8, 7], + [8, 9], + [8, 16], + [9, 10], + [11, 10], + [11, 12], + [12, 13], + [15, 4], + [16, 26], + [17, 12], + [17, 30], + [18, 14], + [18, 19], + [19, 20], + [21, 20], + [22, 15], + [22, 21], + [22, 23], + [23, 24], + [25, 24], + [25, 26], + [27, 26], + [27, 28], + [28, 29], + [28, 35], + [30, 29], + [30, 31], + [31, 32], + [32, 36], + [33, 20], + [33, 39], + [34, 24], + [34, 43], + [37, 38], + [38, 39], + [39, 40], + [40, 41], + [42, 41], + [43, 42], + [44, 43], + [44, 45], + [46, 45], + [47, 35], + [47, 46], + [48, 47], + [49, 48], + [49, 55], + [50, 49], + [50, 51], + [51, 36], + [52, 37], + [53, 41], + [53, 60], + [54, 45], + [54, 64], + [55, 68], + [56, 52], + [57, 56], + [57, 58], + [59, 58], + [59, 60], + [61, 60], + [62, 61], + [62, 63], + [63, 64], + [64, 65], + [65, 66], + [67, 66], + [67, 68], + [68, 69], + [70, 69], + [71, 58], + [72, 62], + [73, 66], + [73, 85], + [74, 70], + [75, 90], + [76, 75], + [76, 77], + [77, 71], + [77, 78], + [79, 78], + [79, 91], + [80, 79], + [81, 72], + [81, 80], + [82, 81], + [82, 83], + [83, 92], + [84, 83], + [84, 85], + [86, 85], + [87, 86], + [87, 93], + [88, 87], + [89, 74], + [89, 88], + [93, 106], + [94, 90], + [94, 95], + [96, 95], + [96, 97], + [96, 109], + [97, 98], + [98, 91], + [98, 99], + [99, 100], + [101, 100], + [101, 102], + [102, 92], + [102, 103], + [104, 103], + [104, 111], + [105, 104], + [105, 106], + [106, 107], + [107, 108], + [109, 114], + [110, 100], + [112, 108], + [113, 114], + [115, 114], + [116, 115], + [117, 116], + [118, 110], + [118, 117], + [119, 118], + [120, 119], + [121, 120], + [122, 111], + [122, 121], + [122, 123], + [124, 123], + [125, 124], + [125, 126], + [126, 112], +] diff --git a/test/python/visualization/test_gate_map.py b/test/python/visualization/test_gate_map.py index 8e87dcb085e4..9bbccedb0c30 100644 --- a/test/python/visualization/test_gate_map.py +++ b/test/python/visualization/test_gate_map.py @@ -31,6 +31,7 @@ from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.layout import Layout, TranspileLayout from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase +from ..legacy_cmaps import KYOTO_CMAP if optionals.HAS_MATPLOTLIB: import matplotlib.pyplot as plt @@ -106,64 +107,7 @@ def test_plot_gate_map_no_backend(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_backend_v1(self): """Test plotting error map with fake backend v1.""" - coupling_map = [ - [0, 1], - [1, 0], - [1, 2], - [1, 4], - [2, 1], - [2, 3], - [3, 2], - [3, 5], - [4, 1], - [4, 7], - [5, 3], - [5, 8], - [6, 7], - [7, 4], - [7, 6], - [7, 10], - [8, 5], - [8, 9], - [8, 11], - [9, 8], - [10, 7], - [10, 12], - [11, 8], - [11, 14], - [12, 10], - [12, 13], - [12, 15], - [13, 12], - [13, 14], - [14, 11], - [14, 13], - [14, 16], - [15, 12], - [15, 18], - [16, 14], - [16, 19], - [17, 18], - [18, 15], - [18, 17], - [18, 21], - [19, 16], - [19, 20], - [19, 22], - [20, 19], - [21, 18], - [21, 23], - [22, 19], - [22, 25], - [23, 21], - [23, 24], - [24, 23], - [24, 25], - [25, 22], - [25, 24], - [25, 26], - [26, 25], - ] + coupling_map = KYOTO_CMAP backend = GenericBackendV2( num_qubits=27, pulse_channels=True, From 6b521db1141002c55b23d46d2d3d7acb7ffe2abf Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sat, 27 Jul 2024 12:22:36 +0200 Subject: [PATCH 138/168] more legacy_cmap --- test/python/visualization/test_gate_map.py | 351 +-------------------- 1 file changed, 4 insertions(+), 347 deletions(-) diff --git a/test/python/visualization/test_gate_map.py b/test/python/visualization/test_gate_map.py index 9bbccedb0c30..fcac1e71c400 100644 --- a/test/python/visualization/test_gate_map.py +++ b/test/python/visualization/test_gate_map.py @@ -31,7 +31,7 @@ from qiskit import QuantumRegister, QuantumCircuit from qiskit.transpiler.layout import Layout, TranspileLayout from .visualization import path_to_diagram_reference, QiskitVisualizationTestCase -from ..legacy_cmaps import KYOTO_CMAP +from ..legacy_cmaps import KYOTO_CMAP, MUMBAI_CMAP if optionals.HAS_MATPLOTLIB: import matplotlib.pyplot as plt @@ -107,11 +107,10 @@ def test_plot_gate_map_no_backend(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_backend_v1(self): """Test plotting error map with fake backend v1.""" - coupling_map = KYOTO_CMAP backend = GenericBackendV2( num_qubits=27, pulse_channels=True, - coupling_map=coupling_map, + coupling_map=MUMBAI_CMAP, ) img_ref = path_to_diagram_reference("fake_27_q_error.png") fig = plot_error_map(backend) @@ -126,64 +125,7 @@ def test_plot_error_map_backend_v1(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_backend_v2(self): """Test plotting error map with fake backend v2.""" - coupling_map = [ - [0, 1], - [1, 0], - [1, 2], - [1, 4], - [2, 1], - [2, 3], - [3, 2], - [3, 5], - [4, 1], - [4, 7], - [5, 3], - [5, 8], - [6, 7], - [7, 4], - [7, 6], - [7, 10], - [8, 5], - [8, 9], - [8, 11], - [9, 8], - [10, 7], - [10, 12], - [11, 8], - [11, 14], - [12, 10], - [12, 13], - [12, 15], - [13, 12], - [13, 14], - [14, 11], - [14, 13], - [14, 16], - [15, 12], - [15, 18], - [16, 14], - [16, 19], - [17, 18], - [18, 15], - [18, 17], - [18, 21], - [19, 16], - [19, 20], - [19, 22], - [20, 19], - [21, 18], - [21, 23], - [22, 19], - [22, 25], - [23, 21], - [23, 24], - [24, 23], - [24, 25], - [25, 22], - [25, 24], - [25, 26], - [26, 25], - ] + coupling_map = MUMBAI_CMAP backend = GenericBackendV2( num_qubits=27, pulse_channels=True, @@ -202,292 +144,7 @@ def test_plot_error_map_backend_v2(self): @unittest.skipUnless(optionals.HAS_SEABORN, "Seaborn not installed") def test_plot_error_map_over_100_qubit(self): """Test plotting error map with large fake backend.""" - coupling_map = [ - [0, 1], - [0, 14], - [1, 0], - [1, 2], - [2, 1], - [2, 3], - [3, 2], - [3, 4], - [4, 3], - [4, 5], - [4, 15], - [5, 4], - [5, 6], - [6, 5], - [6, 7], - [7, 6], - [7, 8], - [8, 7], - [8, 16], - [9, 10], - [10, 9], - [10, 11], - [11, 10], - [11, 12], - [12, 11], - [12, 13], - [12, 17], - [13, 12], - [14, 0], - [14, 18], - [15, 4], - [15, 22], - [16, 8], - [16, 26], - [17, 12], - [17, 30], - [18, 14], - [18, 19], - [19, 18], - [19, 20], - [20, 19], - [20, 21], - [20, 33], - [21, 20], - [21, 22], - [22, 15], - [22, 21], - [22, 23], - [23, 22], - [23, 24], - [24, 23], - [24, 25], - [24, 34], - [25, 24], - [25, 26], - [26, 16], - [26, 25], - [26, 27], - [27, 26], - [27, 28], - [28, 27], - [28, 29], - [28, 35], - [29, 28], - [29, 30], - [30, 17], - [30, 29], - [30, 31], - [31, 30], - [31, 32], - [32, 31], - [32, 36], - [33, 20], - [33, 39], - [34, 24], - [34, 43], - [35, 28], - [35, 47], - [36, 32], - [36, 51], - [37, 38], - [37, 52], - [38, 37], - [38, 39], - [39, 33], - [39, 38], - [39, 40], - [40, 39], - [40, 41], - [41, 40], - [41, 42], - [41, 53], - [42, 41], - [42, 43], - [43, 34], - [43, 42], - [43, 44], - [44, 43], - [44, 45], - [45, 44], - [45, 46], - [45, 54], - [46, 45], - [46, 47], - [47, 35], - [47, 46], - [47, 48], - [48, 47], - [48, 49], - [49, 48], - [49, 50], - [49, 55], - [50, 49], - [50, 51], - [51, 36], - [51, 50], - [52, 37], - [52, 56], - [53, 41], - [53, 60], - [54, 45], - [54, 64], - [55, 49], - [55, 68], - [56, 52], - [56, 57], - [57, 56], - [57, 58], - [58, 57], - [58, 59], - [58, 71], - [59, 58], - [59, 60], - [60, 53], - [60, 59], - [60, 61], - [61, 60], - [61, 62], - [62, 61], - [62, 63], - [62, 72], - [63, 62], - [63, 64], - [64, 54], - [64, 63], - [64, 65], - [65, 64], - [65, 66], - [66, 65], - [66, 67], - [66, 73], - [67, 66], - [67, 68], - [68, 55], - [68, 67], - [68, 69], - [69, 68], - [69, 70], - [70, 69], - [70, 74], - [71, 58], - [71, 77], - [72, 62], - [72, 81], - [73, 66], - [73, 85], - [74, 70], - [74, 89], - [75, 76], - [75, 90], - [76, 75], - [76, 77], - [77, 71], - [77, 76], - [77, 78], - [78, 77], - [78, 79], - [79, 78], - [79, 80], - [79, 91], - [80, 79], - [80, 81], - [81, 72], - [81, 80], - [81, 82], - [82, 81], - [82, 83], - [83, 82], - [83, 84], - [83, 92], - [84, 83], - [84, 85], - [85, 73], - [85, 84], - [85, 86], - [86, 85], - [86, 87], - [87, 86], - [87, 88], - [87, 93], - [88, 87], - [88, 89], - [89, 74], - [89, 88], - [90, 75], - [90, 94], - [91, 79], - [91, 98], - [92, 83], - [92, 102], - [93, 87], - [93, 106], - [94, 90], - [94, 95], - [95, 94], - [95, 96], - [96, 95], - [96, 97], - [96, 109], - [97, 96], - [97, 98], - [98, 91], - [98, 97], - [98, 99], - [99, 98], - [99, 100], - [100, 99], - [100, 101], - [100, 110], - [101, 100], - [101, 102], - [102, 92], - [102, 101], - [102, 103], - [103, 102], - [103, 104], - [104, 103], - [104, 105], - [104, 111], - [105, 104], - [105, 106], - [106, 93], - [106, 105], - [106, 107], - [107, 106], - [107, 108], - [108, 107], - [108, 112], - [109, 96], - [110, 100], - [110, 118], - [111, 104], - [111, 122], - [112, 108], - [112, 126], - [113, 114], - [114, 113], - [114, 115], - [115, 114], - [115, 116], - [116, 115], - [116, 117], - [117, 116], - [117, 118], - [118, 110], - [118, 117], - [118, 119], - [119, 118], - [119, 120], - [120, 119], - [120, 121], - [121, 120], - [121, 122], - [122, 111], - [122, 121], - [122, 123], - [123, 122], - [123, 124], - [124, 123], - [124, 125], - [125, 124], - [125, 126], - [126, 112], - [126, 125], - ] + coupling_map = KYOTO_CMAP backend = GenericBackendV2( num_qubits=127, coupling_map=coupling_map, pulse_channels=True, seed=42 ) From 889173bc154b5fe79594694a2fadd8da59986753 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sat, 27 Jul 2024 21:40:23 +0200 Subject: [PATCH 139/168] https://github.com/Qiskit/qiskit/issues/12832 --- test/python/result/test_mitigators.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/python/result/test_mitigators.py b/test/python/result/test_mitigators.py index 8112089b6ad6..8dcdedc433fe 100644 --- a/test/python/result/test_mitigators.py +++ b/test/python/result/test_mitigators.py @@ -120,6 +120,9 @@ def test_mitigation_improvement(self): """Test whether readout mitigation led to more accurate results""" shots = 1024 with self.assertWarns(DeprecationWarning): + # TODO self.assignment_matrices calls LocalReadoutMitigator, + # which only supports BackendV1 at the moment: + # https://github.com/Qiskit/qiskit/issues/12832 assignment_matrices = self.assignment_matrices() mitigators = self.mitigators(assignment_matrices) circuit, circuit_name, num_qubits = self.ghz_3_circuit() From 6febe720db74676b6def3f5a82ee80ff0c085135 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Sun, 28 Jul 2024 22:07:40 +0200 Subject: [PATCH 140/168] test.python.transpiler.test_vf2_post_layout --- qiskit/compiler/transpiler.py | 16 ++++++++++++---- .../generate_preset_pass_manager.py | 12 +++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py index adf60ca91e56..2b6f476d00ad 100644 --- a/qiskit/compiler/transpiler.py +++ b/qiskit/compiler/transpiler.py @@ -315,10 +315,18 @@ def callback_func(**kwargs): optimization_level = config.get("transpile_optimization_level", 2) if backend is not None and getattr(backend, "version", 0) <= 1: - # This is a temporary conversion step to allow for a smoother transition - # to a fully target-based transpiler pipeline while maintaining the behavior - # of `transpile` with BackendV1 inputs. - backend = BackendV2Converter(backend) + with warnings.catch_warnings(): + # This is a temporary conversion step to allow for a smoother transition + # to a fully target-based transpiler pipeline while maintaining the behavior + # of `transpile` with BackendV1 inputs. + # TODO BackendV1 is deprecated and this path can be removed once it gets removed. + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message=r".+qiskit\.providers\.backend_compat\.BackendV2Converter.+", + module="qiskit", + ) + backend = BackendV2Converter(backend) if ( scheduling_method is not None diff --git a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py index bdbac42c8055..140c46464e32 100644 --- a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +++ b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py @@ -15,6 +15,7 @@ """ import copy +import warnings from qiskit.circuit.controlflow import CONTROL_FLOW_OP_NAMES from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping @@ -331,7 +332,16 @@ def generate_preset_pass_manager( if timing_constraints is None: timing_constraints = target.timing_constraints() if backend_properties is None: - backend_properties = target_to_backend_properties(target) + with warnings.catch_warnings(): + # TODO this branch (targe-to-properties) is going to be removed soon (1.3) in favor + # of backend-to-target approach + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message=r".+qiskit\.transpiler\.target\.target_to_backend_properties.+", + module="qiskit", + ) + backend_properties = target_to_backend_properties(target) # Parse non-target dependent pm options initial_layout = _parse_initial_layout(initial_layout) From 52e99607508ade5a52a4896d5b4461257e76b858 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 29 Jul 2024 10:44:11 +0200 Subject: [PATCH 141/168] comma --- qiskit/circuit/add_control.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qiskit/circuit/add_control.py b/qiskit/circuit/add_control.py index 2b374d54c455..c0b73625f337 100644 --- a/qiskit/circuit/add_control.py +++ b/qiskit/circuit/add_control.py @@ -73,7 +73,7 @@ def control( ) -> ControlledGate: """Return controlled version of gate using controlled rotations. This function first checks the name of the operation to see if it knows of a method from which - to generate a controlled version. Currently these are `x`, `rx`, `ry`, and `rz`. + to generate a controlled version. Currently, these are `x`, `rx`, `ry`, and `rz`. If a method is not directly known, it calls the unroller to convert to `u1`, `u3`, and `cx` gates. From 0c2b6487ad7ea45300f297321bf04843ba2b9dab Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 29 Jul 2024 12:16:10 +0200 Subject: [PATCH 142/168] https://github.com/Qiskit/qiskit/pull/12660#discussion_r1694781920 --- test/python/transpiler/test_calibrationbuilder.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/test/python/transpiler/test_calibrationbuilder.py b/test/python/transpiler/test_calibrationbuilder.py index cb7293049ef5..ff2665b4896f 100644 --- a/test/python/transpiler/test_calibrationbuilder.py +++ b/test/python/transpiler/test_calibrationbuilder.py @@ -267,6 +267,8 @@ def build_reverse( def test_rzx_calibration_cr_pulse_stretch(self, theta: float): """Test that cross resonance pulse durations are computed correctly.""" with self.assertWarns(DeprecationWarning): + # TODO this tests does not work with BackendV2 + # https://github.com/Qiskit/qiskit/issues/12834 backend = Fake27QPulseV1() inst_map = backend.defaults().instruction_schedule_map cr_schedule = inst_map.get("cx", (0, 1)) From f80ce38bc1f806eb338ecebca26b4cdbc82fbe4d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 29 Jul 2024 15:21:30 +0200 Subject: [PATCH 143/168] do not deprecate BackendV2Converter yet --- qiskit/providers/backend_compat.py | 7 ----- .../providers/models/backendconfiguration.py | 26 +++++++++++-------- 2 files changed, 15 insertions(+), 18 deletions(-) diff --git a/qiskit/providers/backend_compat.py b/qiskit/providers/backend_compat.py index 83cde6b4112f..f554897d34c4 100644 --- a/qiskit/providers/backend_compat.py +++ b/qiskit/providers/backend_compat.py @@ -25,7 +25,6 @@ from qiskit.providers.models.pulsedefaults import PulseDefaults from qiskit.providers.options import Options from qiskit.providers.exceptions import BackendPropertyError -from qiskit.utils import deprecate_func logger = logging.getLogger(__name__) @@ -353,12 +352,6 @@ class should only be used if you need a :class:`~.BackendV2` and still need ) """ - @deprecate_func( - since="1.2", - removal_timeline="in the 2.0 release", - additional_msg="Since ``BackendV1`` is deprecated, this conversion tool from BackendV1 to " - "BackendV2 is going to be removed with BackendV1.", - ) def __init__( self, backend: BackendV1, diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index c6e40757a63b..5aed4ecd721d 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -230,9 +230,10 @@ class QasmBackendConfiguration: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " - "that probably means that they are using a backend based on the " - "deprecated BackendV1 class.", + 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 `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", stacklevel=3, ) def __init__( @@ -515,14 +516,16 @@ def __contains__(self, item): class BackendConfiguration(QasmBackendConfiguration): - """Backwards compat shim representing an abstract backend configuration.""" + """Backwards compatibility shim representing an abstract backend configuration.""" @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The class `BackendConfiguration` is being deprecated " - "as they are not necessary for BackendV2. If user still need Qobj, that probably " - "means that they are using a backend based on the deprecated BackendV1 class.", + 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 `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=3, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @@ -536,10 +539,11 @@ class PulseBackendConfiguration(QasmBackendConfiguration): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="The class `PulseBackendConfiguration` is being deprecated " - "as they are not necessary for BackendV2. If user still need Qobj, " - "that probably means that they are using a backend based on the " - "deprecated BackendV1 class.", + 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 `Qobj` it likely relies on deprecated functionality and " + "should be updated to use `BackendV2`.", + stacklevel=3, ) def __init__( self, From b28394b94ea4db489ee6296d756135ea9b701c63 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 29 Jul 2024 16:31:57 +0200 Subject: [PATCH 144/168] test.python.providers.test_faulty_backend --- test/python/providers/test_faulty_backend.py | 57 ++++++++++++++------ 1 file changed, 41 insertions(+), 16 deletions(-) diff --git a/test/python/providers/test_faulty_backend.py b/test/python/providers/test_faulty_backend.py index e1a3f9fa179e..bd8db856ec0b 100644 --- a/test/python/providers/test_faulty_backend.py +++ b/test/python/providers/test_faulty_backend.py @@ -26,15 +26,21 @@ class FaultyQubitBackendTestCase(QiskitTestCase): """Test operational-related methods of backend.properties() with Fake7QV1FaultyQ1, which is like Fake7QV1 but with a faulty 1Q""" + # These test can be removed with Fake7QV1FaultyQ1 + backend = Fake7QV1FaultyQ1() def test_operational_false(self): """Test operation status of the qubit. Q1 is non-operational""" - self.assertFalse(self.backend.properties().is_qubit_operational(1)) + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + self.assertFalse(properties.is_qubit_operational(1)) def test_faulty_qubits(self): """Test faulty_qubits method.""" - self.assertEqual(self.backend.properties().faulty_qubits(), [1]) + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + self.assertEqual(properties.faulty_qubits(), [1]) def test_convert_to_target_with_filter(self): """Test converting legacy data structure to V2 target model with faulty qubits. @@ -43,11 +49,13 @@ def test_convert_to_target_with_filter(self): even though instruction is not provided by the backend, since these are the necessary instructions that the transpiler may assume. """ + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() # Filter out faulty Q1 target = convert_to_target( configuration=self.backend.configuration(), - properties=self.backend.properties(), + properties=properties, add_delay=True, filter_faulty=True, ) @@ -57,10 +65,13 @@ def test_convert_to_target_with_filter(self): def test_convert_to_target_without_filter(self): """Test converting legacy data structure to V2 target model with faulty qubits.""" + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + # Include faulty Q1 even though data could be incomplete target = convert_to_target( configuration=self.backend.configuration(), - properties=self.backend.properties(), + properties=properties, add_delay=True, filter_faulty=False, ) @@ -68,17 +79,20 @@ def test_convert_to_target_without_filter(self): self.assertTrue(target.instruction_supported(operation_name="delay", qargs=(1,))) # Properties are preserved + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + self.assertEqual( target.qubit_properties[1].t1, - self.backend.properties().t1(1), + properties.t1(1), ) self.assertEqual( target.qubit_properties[1].t2, - self.backend.properties().t2(1), + properties.t2(1), ) self.assertEqual( target.qubit_properties[1].frequency, - self.backend.properties().frequency(1), + properties.frequency(1), ) @@ -90,12 +104,16 @@ class FaultyGate13BackendTestCase(QiskitTestCase): def test_operational_gate(self): """Test is_gate_operational method.""" - self.assertFalse(self.backend.properties().is_gate_operational("cx", [1, 3])) - self.assertFalse(self.backend.properties().is_gate_operational("cx", [3, 1])) + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + self.assertFalse(properties.is_gate_operational("cx", [1, 3])) + self.assertFalse(properties.is_gate_operational("cx", [3, 1])) def test_faulty_gates(self): """Test faulty_gates method.""" - gates = self.backend.properties().faulty_gates() + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + gates = properties.faulty_gates() self.assertEqual(len(gates), 2) self.assertEqual([gate.gate for gate in gates], ["cx", "cx"]) self.assertEqual(sorted(gate.qubits for gate in gates), [[1, 3], [3, 1]]) @@ -109,12 +127,16 @@ class FaultyGate01BackendTestCase(QiskitTestCase): def test_operational_gate(self): """Test is_gate_operational method.""" - self.assertFalse(self.backend.properties().is_gate_operational("cx", [0, 1])) - self.assertFalse(self.backend.properties().is_gate_operational("cx", [1, 0])) + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + self.assertFalse(properties.is_gate_operational("cx", [0, 1])) + self.assertFalse(properties.is_gate_operational("cx", [1, 0])) def test_faulty_gates(self): """Test faulty_gates method.""" - gates = self.backend.properties().faulty_gates() + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + gates = properties.faulty_gates() self.assertEqual(len(gates), 2) self.assertEqual([gate.gate for gate in gates], ["cx", "cx"]) self.assertEqual(sorted(gate.qubits for gate in gates), [[0, 1], [1, 0]]) @@ -129,9 +151,12 @@ class MissingPropertyQubitBackendTestCase(QiskitTestCase): def test_convert_to_target(self): """Test converting legacy data structure to V2 target model with missing qubit property.""" + with self.assertWarns(DeprecationWarning): + properties = self.backend.properties() + target = convert_to_target( configuration=self.backend.configuration(), - properties=self.backend.properties(), + properties=properties, add_delay=True, filter_faulty=True, ) @@ -139,9 +164,9 @@ def test_convert_to_target(self): self.assertIsNone(target.qubit_properties[1].t1) self.assertEqual( target.qubit_properties[1].t2, - self.backend.properties().t2(1), + properties.t2(1), ) self.assertEqual( target.qubit_properties[1].frequency, - self.backend.properties().frequency(1), + properties.frequency(1), ) From f16ad3a62e491889bc67f01f8ddaa6607e5dec8d Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 29 Jul 2024 16:35:16 +0200 Subject: [PATCH 145/168] test.python.compiler.test_transpiler.TestTranspile --- test/python/compiler/test_transpiler.py | 26 +++++++++++-------------- 1 file changed, 11 insertions(+), 15 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 52891d4398cb..f4680095fe62 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1576,15 +1576,14 @@ def test_scheduling_instruction_constraints(self): durations = InstructionDurations.from_backend(backend_v1) durations.update([("cx", [0, 1], 1000, "dt")]) - with self.assertWarns(DeprecationWarning): - scheduled = transpile( - qc, - backend=backend_v1, - scheduling_method="alap", - instruction_durations=durations, - layout_method="trivial", - ) - self.assertEqual(scheduled.duration, 1500) + scheduled = transpile( + qc, + backend=backend_v1, + scheduling_method="alap", + instruction_durations=durations, + layout_method="trivial", + ) + self.assertEqual(scheduled.duration, 1500) scheduled = transpile( qc, @@ -1608,12 +1607,9 @@ def test_scheduling_dt_constraints(self): original_dt = 2.2222222222222221e-10 original_duration = 3504 - with self.assertWarns(DeprecationWarning): - # halve dt in sec = double duration in dt - scheduled = transpile( - qc, backend=backend_v1, scheduling_method="asap", dt=original_dt / 2 - ) - self.assertEqual(scheduled.duration, original_duration * 2) + # halve dt in sec = double duration in dt + scheduled = transpile(qc, backend=backend_v1, scheduling_method="asap", dt=original_dt / 2) + self.assertEqual(scheduled.duration, original_duration * 2) # halve dt in sec = double duration in dt scheduled = transpile(qc, backend=backend_v2, scheduling_method="asap", dt=original_dt / 2) From 6bfcbbfe4d7a41fe74292eaaacdd66dda8027da6 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Mon, 29 Jul 2024 17:23:33 +0200 Subject: [PATCH 146/168] cleaning up warnings --- .../basic_provider/basic_simulator.py | 47 ++++++++++++------- test/utils/base.py | 9 ++++ 2 files changed, 38 insertions(+), 18 deletions(-) diff --git a/qiskit/providers/basic_provider/basic_simulator.py b/qiskit/providers/basic_provider/basic_simulator.py index 1d1205294677..31aea10af3e8 100644 --- a/qiskit/providers/basic_provider/basic_simulator.py +++ b/qiskit/providers/basic_provider/basic_simulator.py @@ -236,24 +236,35 @@ def configuration(self) -> BackendConfiguration: for name in self.target.operation_names ] - self._configuration = BackendConfiguration( - backend_name=self.name, - backend_version=self.backend_version, - n_qubits=self.num_qubits, - basis_gates=self.target.operation_names, - gates=gates, - local=True, - simulator=True, - conditional=True, - open_pulse=False, - memory=True, - # This max_shots is used by the assembler, setting it to 0 - # to maintain the behavior from the previous implementation. - # Not related to the actual shots set in the backend options - max_shots=0, - coupling_map=None, - description="A python simulator for quantum experiments", - ) + with warnings.catch_warnings(): + # This is a temporary conversion step to allow for a smoother transition + # to a fully target-based transpiler pipeline while maintaining the behavior + # of `transpile` with BackendV1 inputs. + # TODO Provider models are deprecated + # https://github.com/Qiskit/qiskit/issues/12843 + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message=r".+qiskit\.providers\.models\.backendconfiguration\..+", + ) + self._configuration = BackendConfiguration( + backend_name=self.name, + backend_version=self.backend_version, + n_qubits=self.num_qubits, + basis_gates=self.target.operation_names, + gates=gates, + local=True, + simulator=True, + conditional=True, + open_pulse=False, + memory=True, + # This max_shots is used by the assembler, setting it to 0 + # to maintain the behavior from the previous implementation. + # Not related to the actual shots set in the backend options + max_shots=0, + coupling_map=None, + description="A python simulator for quantum experiments", + ) return self._configuration @classmethod diff --git a/test/utils/base.py b/test/utils/base.py index 6d0c917ace30..78d5aceb58f2 100644 --- a/test/utils/base.py +++ b/test/utils/base.py @@ -129,6 +129,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"The class ``qiskit\.providers\.models\..*`", + module=r"qiskit_aer(\.[a-zA-Z0-9_]+)*", + ) + # Safe to remove once https://github.com/Qiskit/qiskit-aer/issues/2065 is in a release version # of Aer. warnings.filterwarnings( From ce993d734cb802c25768c7ef5a347fd2c6f630b6 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 09:33:15 +0200 Subject: [PATCH 147/168] no deprecation in test/python/compiler/test_transpiler.py --- test/python/compiler/test_transpiler.py | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index f4680095fe62..75e527683e1f 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1661,14 +1661,13 @@ def test_backend_props_constraints(self): 17: Qubit(QuantumRegister(15, "ancilla"), 14), } - with self.assertWarns(DeprecationWarning): - result = transpile( - qc, - backend=backend_v1, - backend_properties=custom_backend_properties, - optimization_level=2, - seed_transpiler=42, - ) + result = transpile( + qc, + backend=backend_v1, + backend_properties=custom_backend_properties, + optimization_level=2, + seed_transpiler=42, + ) self.assertEqual(result._layout.initial_layout._p2v, vf2_layout) result = transpile( From 5db7ec35aeed4b95cbf022a4a73cc22d3ae6ca0e Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 11:10:23 +0200 Subject: [PATCH 148/168] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- qiskit/circuit/add_control.py | 2 +- qiskit/providers/backend.py | 7 ++-- .../basic_provider/basic_simulator.py | 3 -- .../fake_provider/fake_qasm_backend.py | 2 +- qiskit/providers/models/__init__.py | 2 +- .../providers/models/backendconfiguration.py | 32 ++++++++++--------- qiskit/providers/models/backendproperties.py | 7 ++-- .../preset_passmanagers/__init__.py | 16 ---------- .../generate_preset_pass_manager.py | 2 +- qiskit/transpiler/target.py | 6 ++-- qiskit/utils/deprecation.py | 2 +- .../notes/backendv1-d0d0642ed38fed3c.yaml | 9 +++--- 12 files changed, 37 insertions(+), 53 deletions(-) diff --git a/qiskit/circuit/add_control.py b/qiskit/circuit/add_control.py index c0b73625f337..98c9b4d4e452 100644 --- a/qiskit/circuit/add_control.py +++ b/qiskit/circuit/add_control.py @@ -73,7 +73,7 @@ def control( ) -> ControlledGate: """Return controlled version of gate using controlled rotations. This function first checks the name of the operation to see if it knows of a method from which - to generate a controlled version. Currently, these are `x`, `rx`, `ry`, and `rz`. + to generate a controlled version. Currently, these are ``x``, ``rx``, ``ry``, and ``rz``. If a method is not directly known, it calls the unroller to convert to `u1`, `u3`, and `cx` gates. diff --git a/qiskit/providers/backend.py b/qiskit/providers/backend.py index 836b4453954f..a8c36e99da07 100644 --- a/qiskit/providers/backend.py +++ b/qiskit/providers/backend.py @@ -75,10 +75,9 @@ class BackendV1(Backend, ABC): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="If this backend is only a hardware description, consider constructing a " - "Target. If the provider also provides access for execution, it can construct " - "Primitives. Alternatebly, consider moving to BackendV2 " - "(see https://qisk.it/backendV1-to-V2).", + additional_msg="If the backend only encapsulates a hardware description, consider constructing a " + "Target directly. If it is part of a provider that gives access to execution, consider using Primitives instead. " + "Alternatively, consider moving to BackendV2 (see https://qisk.it/backendV1-to-V2).", ) def __init__(self, configuration, provider=None, **fields): """Initialize a backend class diff --git a/qiskit/providers/basic_provider/basic_simulator.py b/qiskit/providers/basic_provider/basic_simulator.py index 31aea10af3e8..32666c57f184 100644 --- a/qiskit/providers/basic_provider/basic_simulator.py +++ b/qiskit/providers/basic_provider/basic_simulator.py @@ -237,9 +237,6 @@ def configuration(self) -> BackendConfiguration: ] with warnings.catch_warnings(): - # This is a temporary conversion step to allow for a smoother transition - # to a fully target-based transpiler pipeline while maintaining the behavior - # of `transpile` with BackendV1 inputs. # TODO Provider models are deprecated # https://github.com/Qiskit/qiskit/issues/12843 warnings.filterwarnings( diff --git a/qiskit/providers/fake_provider/fake_qasm_backend.py b/qiskit/providers/fake_provider/fake_qasm_backend.py index aec595fb86bb..7ad7222f7907 100644 --- a/qiskit/providers/fake_provider/fake_qasm_backend.py +++ b/qiskit/providers/fake_provider/fake_qasm_backend.py @@ -63,7 +63,7 @@ def _set_props_from_json(self): props = self._load_json(self.props_filename) decode_backend_properties(props) with warnings.catch_warnings(): - # This raises BackendProperties internally + # This raises the BackendProperties deprecation warning internally warnings.filterwarnings("ignore", category=DeprecationWarning, module="qiskit") self._properties = BackendProperties.from_dict(props) diff --git a/qiskit/providers/models/__init__.py b/qiskit/providers/models/__init__.py index facd7b7c2201..58fafed92986 100644 --- a/qiskit/providers/models/__init__.py +++ b/qiskit/providers/models/__init__.py @@ -56,7 +56,7 @@ warnings.warn( "qiskit.providers.models is deprecated since Qiskit 1.2 and will be removed in Qiskit 2.0." "With the removal of Qobj, there is no need for these schema-conformant objects. If you still need" - "to use them, it could be because you are using a BackendV1, which it is also deprecated in favor" + "to use them, it could be because you are using a BackendV1, which is also deprecated in favor" "of BackendV2", DeprecationWarning, 2, diff --git a/qiskit/providers/models/backendconfiguration.py b/qiskit/providers/models/backendconfiguration.py index 5aed4ecd721d..a50745c9572c 100644 --- a/qiskit/providers/models/backendconfiguration.py +++ b/qiskit/providers/models/backendconfiguration.py @@ -42,9 +42,10 @@ class GateConfig: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " - "that probably means that they are using a backend based on the " - "deprecated BackendV1 class.", + additional_msg="The models in ``qiskit.providers.models`` 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=3, ) def __init__( @@ -153,9 +154,10 @@ class UchannelLO: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " - "that probably means that they are using a backend based on the " - "deprecated BackendV1 class.", + additional_msg="The models in ``qiskit.providers.models`` 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`.", ) def __init__(self, q, scale): """Initialize a UchannelLOSchema object @@ -230,9 +232,9 @@ class QasmBackendConfiguration: @deprecate_func( since="1.2", 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 `Qobj` it likely relies on deprecated functionality and " + additional_msg="The models in ``qiskit.providers.models`` 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=3, ) @@ -521,9 +523,9 @@ class BackendConfiguration(QasmBackendConfiguration): @deprecate_func( since="1.2", 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 `Qobj` it likely relies on deprecated functionality and " + additional_msg="The models in ``qiskit.providers.models`` 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=3, ) @@ -539,9 +541,9 @@ class PulseBackendConfiguration(QasmBackendConfiguration): @deprecate_func( since="1.2", 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 `Qobj` it likely relies on deprecated functionality and " + additional_msg="The models in ``qiskit.providers.models`` 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=3, ) diff --git a/qiskit/providers/models/backendproperties.py b/qiskit/providers/models/backendproperties.py index 865d44ee0db9..75e7cd18d03a 100644 --- a/qiskit/providers/models/backendproperties.py +++ b/qiskit/providers/models/backendproperties.py @@ -176,9 +176,10 @@ class BackendProperties: @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="This class is not necessary for BackendV2. If user still need Qobj, " - "that probably means that they are using a backend based on the " - "deprecated BackendV1 class.", + 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=3, ) def __init__( diff --git a/qiskit/transpiler/preset_passmanagers/__init__.py b/qiskit/transpiler/preset_passmanagers/__init__.py index a0ef93dbf938..cad512c07a52 100644 --- a/qiskit/transpiler/preset_passmanagers/__init__.py +++ b/qiskit/transpiler/preset_passmanagers/__init__.py @@ -57,22 +57,6 @@ .. autofunction:: generate_scheduling .. currentmodule:: qiskit.transpiler.preset_passmanagers """ -import copy -import warnings - -from qiskit.circuit.controlflow import CONTROL_FLOW_OP_NAMES -from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping -from qiskit.providers.backend_compat import BackendV2Converter - -from qiskit.transpiler.instruction_durations import InstructionDurations -from qiskit.transpiler.timing_constraints import TimingConstraints - -from qiskit.transpiler.passmanager_config import PassManagerConfig -from qiskit.transpiler.target import Target, target_to_backend_properties -from qiskit.transpiler import CouplingMap - -from qiskit.transpiler.exceptions import TranspilerError - from .generate_preset_pass_manager import generate_preset_pass_manager from .level0 import level_0_pass_manager from .level1 import level_1_pass_manager diff --git a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py index 140c46464e32..7e60a5b1875f 100644 --- a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +++ b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py @@ -333,7 +333,7 @@ def generate_preset_pass_manager( timing_constraints = target.timing_constraints() if backend_properties is None: with warnings.catch_warnings(): - # TODO this branch (targe-to-properties) is going to be removed soon (1.3) in favor + # TODO this approach (target-to-properties) is going to be removed soon (1.3) in favor # of backend-to-target approach warnings.filterwarnings( "ignore", diff --git a/qiskit/transpiler/target.py b/qiskit/transpiler/target.py index 91ad9bfca5f8..21598cba1712 100644 --- a/qiskit/transpiler/target.py +++ b/qiskit/transpiler/target.py @@ -1169,9 +1169,9 @@ def from_configuration( @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="This function is not necessary for BackendV2. If user still need Qobj, that " - "probably means that they are using a backend based on the deprecated BackendV1 " - "class.", + additional_msg="This method is used to build an element from the deprecated ``qiskit.providers.models`` module. " + "These models 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`.", ) def target_to_backend_properties(target: Target): """Convert a :class:`~.Target` object into a legacy :class:`~.BackendProperties`""" diff --git a/qiskit/utils/deprecation.py b/qiskit/utils/deprecation.py index 9240de32b07d..aebea233282e 100644 --- a/qiskit/utils/deprecation.py +++ b/qiskit/utils/deprecation.py @@ -51,7 +51,7 @@ def deprecate_func( is_property: If the deprecated function is a `@property`, set this to True so that the generated message correctly describes it as such. (This isn't necessary for property setters, as their docstring is ignored by Python.) - stacklevel: It will be pass to :func:`warnings.warn`. + stacklevel: Stack level passed to :func:`warnings.warn`. Returns: Callable: The decorated callable. """ diff --git a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml index d6d2fdca4c47..c2aa474a4999 100644 --- a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml +++ b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml @@ -1,7 +1,8 @@ --- deprecations_providers: - | - BackendV1 is deprecated and it will be removed not earlier than the next major release. - If providers want to explose a backend only as a hardware description, consider constructing a :class:`.Target`. - If the provider also provides access for execution, that can be done via the primitives interfaces. - Alternatebly, if the previous model is prefered, consider moving to :class:`.BackendV2` (see https://qisk.it/backendV1-to-V2). + The ``BackendV1`` class is deprecated and it will be removed not earlier than the next major release. + There are several migration paths available depending on the main purpose of the backend object: + - To expose backend information with no access to execution (just a hardware description), consider constructing a :class:`.Target` directly. + - To provides access to execution capabilities, consider relying on the primitives interfaces instead. + - Alternatively, to continue providing simultaneous :class:`.Target` (hardware information) and ``run`` (execution) capabilities, consider moving to :class:`.BackendV2` (see https://qisk.it/backendV1-to-V2). From d4f22cc12cd1e97ed59fb079660ba84d171f6795 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 11:44:37 +0200 Subject: [PATCH 149/168] reno lint --- releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml index c2aa474a4999..f1729eded389 100644 --- a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml +++ b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml @@ -3,6 +3,7 @@ deprecations_providers: - | The ``BackendV1`` class is deprecated and it will be removed not earlier than the next major release. There are several migration paths available depending on the main purpose of the backend object: - - To expose backend information with no access to execution (just a hardware description), consider constructing a :class:`.Target` directly. - - To provides access to execution capabilities, consider relying on the primitives interfaces instead. - - Alternatively, to continue providing simultaneous :class:`.Target` (hardware information) and ``run`` (execution) capabilities, consider moving to :class:`.BackendV2` (see https://qisk.it/backendV1-to-V2). + + - To expose backend information with no access to execution (just a hardware description), consider constructing a :class:`.Target` directly. + - To provides access to execution capabilities, consider relying on the primitives interfaces instead. + - Alternatively, to continue providing simultaneous :class:`.Target` (hardware information) and ``run`` (execution) capabilities, consider moving to :class:`.BackendV2` (see https://qisk.it/backendV1-to-V2). From baa16f14eea93d56b8eaf09b468a02309d2c0549 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 12:13:08 +0200 Subject: [PATCH 150/168] adding models in reno --- releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml index f1729eded389..3b19a7ab9a2c 100644 --- a/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml +++ b/releasenotes/notes/backendv1-d0d0642ed38fed3c.yaml @@ -1,9 +1,14 @@ --- deprecations_providers: - | - The ``BackendV1`` class is deprecated and it will be removed not earlier than the next major release. - There are several migration paths available depending on the main purpose of the backend object: + The :class:`.BackendV1` class is deprecated and it will be removed not earlier than the next major release. + There are several migration paths available depending on the main purpose of the backend object:: - To expose backend information with no access to execution (just a hardware description), consider constructing a :class:`.Target` directly. - To provides access to execution capabilities, consider relying on the primitives interfaces instead. - - Alternatively, to continue providing simultaneous :class:`.Target` (hardware information) and ``run`` (execution) capabilities, consider moving to :class:`.BackendV2` (see https://qisk.it/backendV1-to-V2). + - Alternatively, to continue providing simultaneous :class:`.Target` (hardware information) and ``run`` (execution) capabilities, consider moving to :class:`.BackendV2` (see ). + + - | + The models in :mod:`qiskit.providers.models` are part of the deprecated :class:`.BackendV1` workflow + and no longer necessary for :class:`.BackendV2`. If a user workflow requires these representations it + likely relies on deprecated functionality and should be updated to use :class:`.BackendV2`. From 0910b6a37da7e06d3c37ed024ec5b6190652fe89 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 12:56:53 +0200 Subject: [PATCH 151/168] black --- qiskit/transpiler/target.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/qiskit/transpiler/target.py b/qiskit/transpiler/target.py index 21598cba1712..da4a44a8ee02 100644 --- a/qiskit/transpiler/target.py +++ b/qiskit/transpiler/target.py @@ -1169,9 +1169,11 @@ def from_configuration( @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="This method is used to build an element from the deprecated ``qiskit.providers.models`` module. " - "These models 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`.", + additional_msg="This method is used to build an element from the deprecated " + "``qiskit.providers.models`` module. These models 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`.", ) def target_to_backend_properties(target: Target): """Convert a :class:`~.Target` object into a legacy :class:`~.BackendProperties`""" From 048fef553903b8c0097276125887d14ebb3a2788 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 14:05:03 +0200 Subject: [PATCH 152/168] test.python.transpiler.test_preset_passmanagers --- qiskit/compiler/transpiler.py | 11 +- .../generate_preset_pass_manager.py | 9 ++ test/python/providers/test_fake_backends.py | 18 ++- .../transpiler/test_preset_passmanagers.py | 108 ++++++++++++++---- 4 files changed, 118 insertions(+), 28 deletions(-) diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py index 2b6f476d00ad..84cf89542a9b 100644 --- a/qiskit/compiler/transpiler.py +++ b/qiskit/compiler/transpiler.py @@ -315,11 +315,20 @@ def callback_func(**kwargs): optimization_level = config.get("transpile_optimization_level", 2) if backend is not None and getattr(backend, "version", 0) <= 1: + warnings.warn( + f"The function transpile will stop supporting BackendV1 {backend} " + "in the backend parameter not earlier than the release of 2.0. " + "BackendV1 is deprecated and and providers should move to BackendV2.", + category=DeprecationWarning, + stacklevel=2, + ) with warnings.catch_warnings(): # This is a temporary conversion step to allow for a smoother transition # to a fully target-based transpiler pipeline while maintaining the behavior # of `transpile` with BackendV1 inputs. - # TODO BackendV1 is deprecated and this path can be removed once it gets removed. + # TODO BackendV1 is deprecated and this path can be + # removed once it gets removed: + # https://github.com/Qiskit/qiskit/pull/12850 warnings.filterwarnings( "ignore", category=DeprecationWarning, diff --git a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py index 7e60a5b1875f..f9d1f208ff46 100644 --- a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +++ b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py @@ -255,6 +255,14 @@ def generate_preset_pass_manager( # This is a temporary conversion step to allow for a smoother transition # to a fully target-based transpiler pipeline while maintaining the behavior # of `transpile` with BackendV1 inputs. + warnings.warn( + "The function generate_preset_pass_manager will stop supporting " + f"BackendV1 {backend} " + "in the backend parameter not earlier than the release of 2.0. " + "BackendV1 is deprecated and and providers should move to BackendV2.", + category=DeprecationWarning, + stacklevel=2, + ) backend = BackendV2Converter(backend) # Check if a custom inst_map was specified before overwriting inst_map @@ -335,6 +343,7 @@ def generate_preset_pass_manager( with warnings.catch_warnings(): # TODO this approach (target-to-properties) is going to be removed soon (1.3) in favor # of backend-to-target approach + # https://github.com/Qiskit/qiskit/pull/12850 warnings.filterwarnings( "ignore", category=DeprecationWarning, diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 6d1f9499b3f5..9591b8afb684 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -130,12 +130,14 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): self.skipTest( f"Unable to run fake_backend {backend.configuration().backend_name} without qiskit-aer" ) - job = backend.run( - transpile( + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled = transpile( self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level - ), - seed_simulator=42, - ) + ) + job = backend.run(transpiled, seed_simulator=42) result = job.result() counts = result.get_counts() max_count = max(counts.items(), key=operator.itemgetter(1))[0] @@ -223,7 +225,11 @@ def test_delay_circuit(self): qc.x(1) qc.delay(250, 1, unit="ns") qc.measure_all() - res = transpile(qc, backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + res = transpile(qc, backend) self.assertIn("delay", res.count_ops()) @data(0, 1, 2, 3) diff --git a/test/python/transpiler/test_preset_passmanagers.py b/test/python/transpiler/test_preset_passmanagers.py index 3d11a5d55e93..4901d117e4fa 100644 --- a/test/python/transpiler/test_preset_passmanagers.py +++ b/test/python/transpiler/test_preset_passmanagers.py @@ -39,7 +39,7 @@ from qiskit.transpiler.preset_passmanagers.builtin_plugins import OptimizationPassManager from test import QiskitTestCase # pylint: disable=wrong-import-order -from ..legacy_cmaps import MELBOURNE_CMAP, RUESCHLIKON_CMAP, LAGOS_CMAP, TOKYO_CMAP +from ..legacy_cmaps import MELBOURNE_CMAP, RUESCHLIKON_CMAP, LAGOS_CMAP, TOKYO_CMAP, BOGOTA_CMAP def mock_get_passmanager_stage( @@ -222,8 +222,12 @@ def test_alignment_constraints_called_with_by_default(self, level): circuit.h(q[0]) circuit.cz(q[0], q[1]) with unittest.mock.patch("qiskit.transpiler.passes.TimeUnitConversion.run") as mock: - with self.assertWarns(DeprecationWarning): - backend = Fake20QV1() + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) transpile(circuit, backend=backend, optimization_level=level) mock.assert_not_called() @@ -238,15 +242,23 @@ def test_alignment_constraints_called_with_delay_in_circuit(self, level): with unittest.mock.patch( "qiskit.transpiler.passes.TimeUnitConversion.run", return_value=circuit_to_dag(circuit) ) as mock: - with self.assertWarns(DeprecationWarning): - backend = Fake20QV1() + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) transpile(circuit, backend=backend, optimization_level=level) mock.assert_called_once() def test_unroll_only_if_not_gates_in_basis(self): """Test that the list of passes _unroll only runs if a gate is not in the basis.""" - with self.assertWarns(DeprecationWarning): - qcomp = Fake5QV1() + qcomp = GenericBackendV2( + num_qubits=5, + coupling_map=BOGOTA_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) qv_circuit = QuantumVolume(3) gates_in_basis_true_count = 0 collect_2q_blocks_count = 0 @@ -278,8 +290,18 @@ class TestTranspileLevels(QiskitTestCase): circuit=[emptycircuit, circuit_2532], level=[0, 1, 2, 3], backend=[ - Fake5QV1(), - Fake20QV1(), + GenericBackendV2( + num_qubits=5, + coupling_map=BOGOTA_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ), + GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ), None, ], dsc="Transpiler {circuit.__name__} on {backend} backend at level {level}", @@ -290,6 +312,27 @@ def test(self, circuit, level, backend): result = transpile(circuit(), backend=backend, optimization_level=level, seed_transpiler=42) self.assertIsInstance(result, QuantumCircuit) + @combine( + circuit=[emptycircuit, circuit_2532], + level=[0, 1, 2, 3], + backend=[ + Fake5QV1(), + Fake20QV1(), + ], + dsc="Transpiler {circuit.__name__} on {backend} backend V1 at level {level}", + name="{circuit.__name__}_{backend}_level{level}", + ) + def test_v1(self, circuit, level, backend): + """All the levels with all the backends""" + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + result = transpile( + circuit(), backend=backend, optimization_level=level, seed_transpiler=42 + ) + self.assertIsInstance(result, QuantumCircuit) + @ddt class TestPassesInspection(QiskitTestCase): @@ -787,8 +830,12 @@ def test_layout_2503(self, level): 19: ancilla[16], } - with self.assertWarns(DeprecationWarning): - backend = Fake20QV1() + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) qc_b = transpile(qc, backend, initial_layout=initial_layout, optimization_level=level) self.assertEqual(qc_b._layout.initial_layout._p2v, final_layout) @@ -1044,8 +1091,12 @@ def test_trivial_layout(self, level): expected_layouts = [trivial_layout, trivial_layout] - with self.assertWarns(DeprecationWarning): - backend = Fake20QV1() + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) result = transpile(qc, backend, optimization_level=level, seed_transpiler=42) self.assertEqual(result._layout.initial_layout._p2v, expected_layouts[level]) @@ -1078,8 +1129,12 @@ def test_initial_layout(self, level): 18: qr[9], } - with self.assertWarns(DeprecationWarning): - backend = Fake20QV1() + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) result = transpile( qc, backend, optimization_level=level, initial_layout=initial_layout, seed_transpiler=42 ) @@ -1159,8 +1214,12 @@ def test_optimization_condition(self, level): cr = ClassicalRegister(1) qc = QuantumCircuit(qr, cr) qc.cx(0, 1).c_if(cr, 1) - with self.assertWarns(DeprecationWarning): - backend = Fake20QV1() + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) circ = transpile(qc, backend, optimization_level=level) self.assertIsInstance(circ, QuantumCircuit) @@ -1226,7 +1285,11 @@ def test_with_backend(self, optimization_level): """Test a passmanager is constructed when only a backend and optimization level.""" with self.assertWarns(DeprecationWarning): backend = Fake20QV1() - pm = generate_preset_pass_manager(optimization_level, backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level, backend) self.assertIsInstance(pm, PassManager) def test_default_optimization_level(self): @@ -1597,9 +1660,12 @@ def test_invalid_methods_raise_on_control_flow(self, optimization_level): def test_unsupported_basis_gates_raise(self, optimization_level): """Test that trying to transpile a control-flow circuit for a backend that doesn't support the necessary operations in its `basis_gates` will raise a sensible error.""" - with self.assertWarns(DeprecationWarning): - backend = Fake20QV1() - + backend = GenericBackendV2( + num_qubits=20, + coupling_map=TOKYO_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) qc = QuantumCircuit(1, 1) with qc.for_loop((0,)): pass From 428450137dad88d4e577863657dfb0a32395adc1 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 14:17:58 +0200 Subject: [PATCH 153/168] seeding GenericBackendV2 --- test/python/compiler/test_transpiler.py | 8 ++++---- test/python/transpiler/test_calibrationbuilder.py | 6 +++--- test/python/transpiler/test_gates_in_basis_pass.py | 10 +++++----- test/python/transpiler/test_passmanager_run.py | 10 ++++++++-- test/python/transpiler/test_pulse_gate_pass.py | 14 +++----------- test/python/transpiler/test_sabre_swap.py | 2 +- test/python/transpiler/test_unitary_synthesis.py | 2 +- 7 files changed, 25 insertions(+), 27 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 75e527683e1f..023e7e63f403 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1305,7 +1305,7 @@ def test_transpiled_basis_gates_calibrations(self): circ.add_calibration("h", [0], q0_x180) transpiled_circuit = transpile( - circ, backend=GenericBackendV2(num_qubits=4), seed_transpiler=42 + circ, backend=GenericBackendV2(num_qubits=4, seed=42), seed_transpiler=42 ) self.assertEqual(transpiled_circuit.calibrations, circ.calibrations) @@ -1325,7 +1325,7 @@ def test_transpile_calibrated_custom_gate_on_diff_qubit(self): with self.assertRaises(QiskitError): transpile( circ, - backend=GenericBackendV2(num_qubits=4), + backend=GenericBackendV2(num_qubits=4, seed=42), layout_method="trivial", seed_transpiler=42, optimization_level=1, @@ -1368,7 +1368,7 @@ def test_transpile_subset_of_calibrated_gates(self): transpiled_circ = transpile( circ, - backend=GenericBackendV2(num_qubits=4), + backend=GenericBackendV2(num_qubits=4, seed=42), layout_method="trivial", seed_transpiler=42, ) @@ -1390,7 +1390,7 @@ def q0_rxt(tau): transpiled_circ = transpile( circ, - backend=GenericBackendV2(num_qubits=4), + backend=GenericBackendV2(num_qubits=4, seed=42), layout_method="trivial", seed_transpiler=42, ) diff --git a/test/python/transpiler/test_calibrationbuilder.py b/test/python/transpiler/test_calibrationbuilder.py index 5499538b95c4..90676a38a586 100644 --- a/test/python/transpiler/test_calibrationbuilder.py +++ b/test/python/transpiler/test_calibrationbuilder.py @@ -516,7 +516,7 @@ def test_raises_error_when_rotation_angle_not_assigned(self): an unassigned Parameter, not a number. The QiskitError occurs while trying to typecast the Parameter into a float. """ - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) tp = RXCalibrationBuilder(backend.target) qubits = (0,) rx = RXGate(Parameter("theta")) @@ -528,7 +528,7 @@ def test_raises_error_when_rotation_angle_not_assigned(self): @data(0, np.pi / 3, (2 / 3) * np.pi) def test_pulse_schedule(self, theta: float): """Test that get_calibration() returns a schedule with correct amplitude.""" - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) dummy_target = Target() sx_amp, sx_beta, sx_sigma, sx_duration, sx_angle = 0.6, 2, 40, 160, 0.5 with builder.build(backend=backend) as dummy_sx_cal: @@ -579,7 +579,7 @@ def test_with_normalizerxangles(self): ) ism = InstructionScheduleMap() ism.add("sx", (0,), sched) - backend = GenericBackendV2(num_qubits=5, calibrate_instructions=ism) + backend = GenericBackendV2(num_qubits=5, calibrate_instructions=ism, seed=42) # NormalizeRXAngle pass should also be included because it's a required pass. pm = PassManager(RXCalibrationBuilder(backend.target)) diff --git a/test/python/transpiler/test_gates_in_basis_pass.py b/test/python/transpiler/test_gates_in_basis_pass.py index 06ce5e0f6702..0dd5e880e0c0 100644 --- a/test/python/transpiler/test_gates_in_basis_pass.py +++ b/test/python/transpiler/test_gates_in_basis_pass.py @@ -99,7 +99,7 @@ def test_all_gates_in_basis_after_translation(self): def test_all_gates_in_basis_with_target(self): """Test circuit with all gates in basis with target.""" - target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"]).target + target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"], seed=42).target basis_gates = ["cx", "u"] # not used property_set = {} analysis_pass = GatesInBasis(basis_gates, target=target) @@ -112,7 +112,7 @@ def test_all_gates_in_basis_with_target(self): def test_all_gates_not_in_basis_with_target(self): """Test circuit with not all gates in basis with target.""" - target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"]).target + target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"], seed=42).target basis_gates = ["cx", "h"] property_set = {} analysis_pass = GatesInBasis(basis_gates, target=target) @@ -125,7 +125,7 @@ def test_all_gates_not_in_basis_with_target(self): def test_all_gates_in_basis_not_on_all_qubits_with_target(self): """Test circuit with gate in global basis but not local basis.""" - target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"]).target + target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"], seed=42).target basis_gates = ["ecr", "cx", "h"] property_set = {} analysis_pass = GatesInBasis(basis_gates, target=target) @@ -138,7 +138,7 @@ def test_all_gates_in_basis_not_on_all_qubits_with_target(self): def test_all_gates_in_basis_empty_circuit_with_target(self): """Test circuit with no gates with target.""" - target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"]).target + target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"], seed=42).target basis_gates = ["cx", "u"] property_set = {} analysis_pass = GatesInBasis(basis_gates, target=target) @@ -191,7 +191,7 @@ def test_all_gates_not_in_ideal_sim_target(self): def test_all_gates_in_basis_after_translation_with_target(self): """Test circuit with gates in basis after conditional translation.""" - target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"]).target + target = GenericBackendV2(num_qubits=5, basis_gates=["u", "cx"], seed=42).target basis_gates = ["cx", "u"] property_set = {} analysis_pass = GatesInBasis(basis_gates, target) diff --git a/test/python/transpiler/test_passmanager_run.py b/test/python/transpiler/test_passmanager_run.py index 3da6a042564c..96df928c6e21 100644 --- a/test/python/transpiler/test_passmanager_run.py +++ b/test/python/transpiler/test_passmanager_run.py @@ -85,7 +85,10 @@ def test_default_pass_manager_single(self): circuit.cx(qr[2], qr[3]) backend = GenericBackendV2( - num_qubits=20, coupling_map=ALMADEN_CMAP, basis_gates=["id", "u1", "u2", "u3", "cx"] + num_qubits=20, + coupling_map=ALMADEN_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, ) initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] @@ -187,7 +190,10 @@ def test_default_pass_manager_two(self): initial_layout = [None, qr[0], qr[1], qr[2], None, qr[3]] backend = GenericBackendV2( - num_qubits=20, coupling_map=coupling_map, basis_gates=["id", "u1", "u2", "u3", "cx"] + num_qubits=20, + coupling_map=coupling_map, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, ) pass_manager = level_1_pass_manager( diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index f9d73600ecb6..73598ad60d8f 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -78,9 +78,7 @@ def test_transpile_with_backend_target(self): """Test transpile without custom calibrations from target.""" target = GenericBackendV2( - num_qubits=5, - coupling_map=BOGOTA_CMAP, - calibrate_instructions=True, + num_qubits=5, coupling_map=BOGOTA_CMAP, calibrate_instructions=True, seed=42 ).target qc = circuit.QuantumCircuit(2) @@ -459,10 +457,7 @@ def test_transpile_with_instmap_with_v2backend_with_custom_gate(self, opt_level) qc.append(gate, [0]) qc.measure_all() - backend = GenericBackendV2( - num_qubits=5, - calibrate_instructions=True, - ) + backend = GenericBackendV2(num_qubits=5, calibrate_instructions=True, seed=42) transpiled_qc = transpile( qc, backend, @@ -485,10 +480,7 @@ def test_transpile_with_instmap_not_mutate_backend(self): This should not override the source object since the same backend may be used for future transpile without intention of instruction overriding. """ - backend = GenericBackendV2( - num_qubits=5, - calibrate_instructions=True, - ) + backend = GenericBackendV2(num_qubits=5, calibrate_instructions=True, seed=42) original_sx0 = backend.target["sx"][(0,)].calibration with self.assertWarns(DeprecationWarning): diff --git a/test/python/transpiler/test_sabre_swap.py b/test/python/transpiler/test_sabre_swap.py index 6650ca27c6f4..856b5ff09f5b 100644 --- a/test/python/transpiler/test_sabre_swap.py +++ b/test/python/transpiler/test_sabre_swap.py @@ -1393,7 +1393,7 @@ def test_random_circuit_no_control_flow_target(self, size): routing_method="sabre", layout_method="sabre", seed_transpiler=12342, - target=GenericBackendV2(num_qubits=27, coupling_map=MUMBAI_CMAP).target, + target=GenericBackendV2(num_qubits=27, coupling_map=MUMBAI_CMAP, seed=42).target, ) self.assert_valid_circuit(tqc) diff --git a/test/python/transpiler/test_unitary_synthesis.py b/test/python/transpiler/test_unitary_synthesis.py index 43acd4ef67af..153e119c5319 100644 --- a/test/python/transpiler/test_unitary_synthesis.py +++ b/test/python/transpiler/test_unitary_synthesis.py @@ -908,7 +908,7 @@ def test_single_qubit_with_target(self): qc = QuantumCircuit(1) qc.append(ZGate(), [qc.qubits[0]]) dag = circuit_to_dag(qc) - backend = GenericBackendV2(num_qubits=5) + backend = GenericBackendV2(num_qubits=5, seed=42) unitary_synth_pass = UnitarySynthesis(target=backend.target) result_dag = unitary_synth_pass.run(dag) result_qc = dag_to_circuit(result_dag) From 11c1e189d527d4e959311155be3605bfb7223504 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 16:15:33 +0200 Subject: [PATCH 154/168] less Fake5QV1 --- .../transpiler/test_unitary_synthesis.py | 13 +- .../python/transpiler/test_vf2_post_layout.py | 134 ++++++++++++++---- .../visualization/test_circuit_latex.py | 11 +- 3 files changed, 123 insertions(+), 35 deletions(-) diff --git a/test/python/transpiler/test_unitary_synthesis.py b/test/python/transpiler/test_unitary_synthesis.py index 153e119c5319..4abf6511d8d2 100644 --- a/test/python/transpiler/test_unitary_synthesis.py +++ b/test/python/transpiler/test_unitary_synthesis.py @@ -65,6 +65,7 @@ from test.python.providers.fake_mumbai_v2 import ( # pylint: disable=wrong-import-order FakeMumbaiFractionalCX, ) +from ..legacy_cmaps import YORKTOWN_CMAP class FakeBackend2QV2(GenericBackendV2): @@ -674,8 +675,14 @@ def test_coupling_map_unequal_durations(self, opt): qr = QuantumRegister(2) circ = QuantumCircuit(qr) circ.append(random_unitary(4, seed=1), [1, 0]) - with self.assertWarns(DeprecationWarning): - backend = Fake5QV1() + backend = GenericBackendV2( + num_qubits=5, + coupling_map=YORKTOWN_CMAP, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + calibrate_instructions=True, + pulse_channels=True, + seed=42, + ) tqc = transpile( circ, backend=backend, @@ -687,7 +694,7 @@ def test_coupling_map_unequal_durations(self, opt): self.assertTrue( all( ( - (0, 1) == (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]) + (1, 0) == (tqc_index[instr.qubits[0]], tqc_index[instr.qubits[1]]) for instr in tqc.get_instructions("cx") ) ) diff --git a/test/python/transpiler/test_vf2_post_layout.py b/test/python/transpiler/test_vf2_post_layout.py index e97ed279a8d8..5b78977a3c9b 100644 --- a/test/python/transpiler/test_vf2_post_layout.py +++ b/test/python/transpiler/test_vf2_post_layout.py @@ -26,7 +26,7 @@ from qiskit.transpiler.target import Target, InstructionProperties from test import QiskitTestCase # pylint: disable=wrong-import-order -from ..legacy_cmaps import LIMA_CMAP, YORKTOWN_CMAP +from ..legacy_cmaps import LIMA_CMAP, YORKTOWN_CMAP, BOGOTA_CMAP class TestVF2PostLayout(QiskitTestCase): @@ -183,29 +183,6 @@ def test_skip_3q_circuit_control_flow_v2(self): vf2_pass.property_set["VF2PostLayout_stop_reason"], VF2PostLayoutStopReason.MORE_THAN_2Q ) - def test_best_mapping_ghz_state_full_device_multiple_qregs(self): - """Test best mappings with multiple registers""" - with self.assertWarns(DeprecationWarning): - backend = Fake5QV1() - qr_a = QuantumRegister(2) - qr_b = QuantumRegister(3) - qc = QuantumCircuit(qr_a, qr_b) - qc.h(qr_a[0]) - qc.cx(qr_a[0], qr_a[1]) - qc.cx(qr_a[0], qr_b[0]) - qc.cx(qr_a[0], qr_b[1]) - qc.cx(qr_a[0], qr_b[2]) - qc.measure_all() - tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") - initial_layout = tqc._layout - dag = circuit_to_dag(tqc) - cmap = CouplingMap(backend.configuration().coupling_map) - props = backend.properties() - pass_ = VF2PostLayout(coupling_map=cmap, properties=props, seed=self.seed) - pass_.run(dag) - self.assertLayout(dag, cmap, pass_.property_set) - self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) - def test_2q_circuit_5q_backend(self): """A simple example, without considering the direction 0 - 1 @@ -217,7 +194,11 @@ def test_2q_circuit_5q_backend(self): qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 - tqc = transpile(circuit, backend, layout_method="dense") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) @@ -254,6 +235,40 @@ def test_2q_circuit_5q_backend_controlflow(self): self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend_max_trials(self): + """A simple example, without considering the direction + 0 - 1 + qr1 - qr0 + """ + max_trials = 11 + backend = GenericBackendV2( + num_qubits=5, + coupling_map=YORKTOWN_CMAP, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + seed=1, + ) + + qr = QuantumRegister(2, "qr") + circuit = QuantumCircuit(qr) + circuit.cx(qr[1], qr[0]) # qr1 -> qr0 + tqc = transpile(circuit, backend, layout_method="dense") + initial_layout = tqc._layout + dag = circuit_to_dag(tqc) + cmap = CouplingMap(backend.coupling_map) + pass_ = VF2PostLayout(target=backend.target, seed=self.seed, max_trials=max_trials) + with self.assertLogs( + "qiskit.transpiler.passes.layout.vf2_post_layout", level="DEBUG" + ) as cm: + pass_.run(dag) + self.assertIn( + f"DEBUG:qiskit.transpiler.passes.layout.vf2_post_layout:Trial {max_trials} " + f"is >= configured max trials {max_trials}", + cm.output, + ) + print(pass_.property_set["VF2PostLayout_stop_reason"]) + self.assertLayout(dag, cmap, pass_.property_set) + self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) + + def test_2q_circuit_5q_backend_max_trials_v1(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 @@ -265,7 +280,11 @@ def test_2q_circuit_5q_backend_max_trials(self): qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 - tqc = transpile(circuit, backend, layout_method="dense") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) @@ -287,7 +306,7 @@ def test_2q_circuit_5q_backend_max_trials(self): self.assertLayout(dag, cmap, pass_.property_set) self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) - def test_best_mapping_ghz_state_full_device_multiple_qregs_v2(self): + def test_best_mapping_ghz_state_full_device_multiple_qregs(self): """Test best mappings with multiple registers""" backend = GenericBackendV2( num_qubits=5, @@ -634,6 +653,32 @@ def test_skip_3q_circuit_v2(self): ) def test_best_mapping_ghz_state_full_device_multiple_qregs(self): + """Test best mappings with multiple registers""" + backend = GenericBackendV2( + num_qubits=5, + coupling_map=YORKTOWN_CMAP, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + seed=8, + ) + qr_a = QuantumRegister(2) + qr_b = QuantumRegister(3) + qc = QuantumCircuit(qr_a, qr_b) + qc.h(qr_a[0]) + qc.cx(qr_a[0], qr_a[1]) + qc.cx(qr_a[0], qr_b[0]) + qc.cx(qr_a[0], qr_b[1]) + qc.cx(qr_a[0], qr_b[2]) + qc.measure_all() + tqc = transpile(qc, seed_transpiler=self.seed, layout_method="trivial") + initial_layout = tqc._layout + dag = circuit_to_dag(tqc) + cmap = CouplingMap(backend.coupling_map) + pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False) + pass_.run(dag) + self.assertLayout(dag, cmap, pass_.property_set) + self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) + + def test_best_mapping_ghz_state_full_device_multiple_qregs_v1(self): """Test best mappings with multiple registers""" with self.assertWarns(DeprecationWarning): backend = Fake5QV1() @@ -646,7 +691,11 @@ def test_best_mapping_ghz_state_full_device_multiple_qregs(self): qc.cx(qr_a[0], qr_b[1]) qc.cx(qr_a[0], qr_b[2]) qc.measure_all() - tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) @@ -659,6 +708,29 @@ def test_best_mapping_ghz_state_full_device_multiple_qregs(self): self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) def test_2q_circuit_5q_backend(self): + """A simple example, without considering the direction + 0 - 1 + qr1 - qr0 + """ + backend = GenericBackendV2( + num_qubits=5, + coupling_map=BOGOTA_CMAP, + basis_gates=["id", "u1", "u2", "u3", "cx"], + seed=42, + ) + qr = QuantumRegister(2, "qr") + circuit = QuantumCircuit(qr) + circuit.cx(qr[1], qr[0]) # qr1 -> qr0 + tqc = transpile(circuit, backend, layout_method="dense") + initial_layout = tqc._layout + dag = circuit_to_dag(tqc) + cmap = CouplingMap(backend.coupling_map) + pass_ = VF2PostLayout(target=backend.target, seed=self.seed, strict_direction=False) + pass_.run(dag) + self.assertLayout(dag, cmap, pass_.property_set) + self.assertNotEqual(pass_.property_set["post_layout"], initial_layout) + + def test_2q_circuit_5q_backend_v1(self): """A simple example, without considering the direction 0 - 1 qr1 - qr0 @@ -669,7 +741,11 @@ def test_2q_circuit_5q_backend(self): qr = QuantumRegister(2, "qr") circuit = QuantumCircuit(qr) circuit.cx(qr[1], qr[0]) # qr1 -> qr0 - tqc = transpile(circuit, backend, layout_method="dense") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout dag = circuit_to_dag(tqc) cmap = CouplingMap(backend.configuration().coupling_map) diff --git a/test/python/visualization/test_circuit_latex.py b/test/python/visualization/test_circuit_latex.py index 1be7ad7ce051..bcf5b77d51bd 100644 --- a/test/python/visualization/test_circuit_latex.py +++ b/test/python/visualization/test_circuit_latex.py @@ -20,7 +20,7 @@ from qiskit.visualization import circuit_drawer from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister, transpile -from qiskit.providers.fake_provider import Fake5QV1 +from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.circuit.library import ( XGate, MCXGate, @@ -36,6 +36,7 @@ from qiskit.quantum_info.random import random_unitary from qiskit.utils import optionals from .visualization import QiskitVisualizationTestCase +from ..legacy_cmaps import YORKTOWN_CMAP pi = np.pi @@ -481,8 +482,12 @@ def test_partial_layout(self): See: https://github.com/Qiskit/qiskit-terra/issues/4757""" filename = self._get_resource_path("test_latex_partial_layout.tex") - with self.assertWarns(DeprecationWarning): - backend = Fake5QV1() + backend = GenericBackendV2( + num_qubits=5, + coupling_map=YORKTOWN_CMAP, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + seed=42, + ) circuit = QuantumCircuit(3) circuit.h(1) From b0c16ee5596e18196f9550f1bba98fa22fedf861 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 16:20:08 +0200 Subject: [PATCH 155/168] test.python.transpiler.test_sabre_layout --- test/python/transpiler/test_sabre_layout.py | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/test/python/transpiler/test_sabre_layout.py b/test/python/transpiler/test_sabre_layout.py index 42ae3691c3ca..5ab8fe5c10b2 100644 --- a/test/python/transpiler/test_sabre_layout.py +++ b/test/python/transpiler/test_sabre_layout.py @@ -24,12 +24,12 @@ from qiskit.transpiler.exceptions import TranspilerError from qiskit.converters import circuit_to_dag from qiskit.compiler.transpiler import transpile -from qiskit.providers.fake_provider import Fake27QPulseV1, GenericBackendV2 +from qiskit.providers.fake_provider import GenericBackendV2 from qiskit.transpiler.passes.layout.sabre_pre_layout import SabrePreLayout from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from test import QiskitTestCase # pylint: disable=wrong-import-order -from ..legacy_cmaps import ALMADEN_CMAP +from ..legacy_cmaps import ALMADEN_CMAP, MUMBAI_CMAP class TestSabreLayout(QiskitTestCase): @@ -195,8 +195,12 @@ def test_layout_with_classical_bits(self): rz(0) q4835[1]; """ ) - with self.assertWarns(DeprecationWarning): - backend = Fake27QPulseV1() + backend = GenericBackendV2( + num_qubits=27, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + coupling_map=MUMBAI_CMAP, + seed=42, + ) res = transpile( qc, backend, layout_method="sabre", seed_transpiler=1234, optimization_level=1 ) @@ -249,8 +253,12 @@ def test_layout_many_search_trials(self): barrier q18585[5],q18585[2],q18585[8],q18585[3],q18585[6]; """ ) - with self.assertWarns(DeprecationWarning): - backend = Fake27QPulseV1() + backend = GenericBackendV2( + num_qubits=27, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + coupling_map=MUMBAI_CMAP, + seed=42, + ) res = transpile( qc, backend, From 8681761dc74b6377247e45cb49101df8c2353b51 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 16:31:08 +0200 Subject: [PATCH 156/168] test.python.transpiler.test_pulse_gate_pass --- .../python/transpiler/test_pulse_gate_pass.py | 57 ++++++++++++++++--- 1 file changed, 49 insertions(+), 8 deletions(-) diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index 73598ad60d8f..226093640514 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -57,6 +57,7 @@ def setUp(self): def test_transpile_with_bare_backend(self): """Test transpile without custom calibrations.""" with self.assertWarns(DeprecationWarning): + # TODO Move this test to backendV2 backend = Fake27QPulseV1() # Remove timing constraints to avoid triggering # scheduling passes. @@ -69,7 +70,11 @@ def test_transpile_with_bare_backend(self): qc.sx(1) qc.measure_all() - transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) ref_calibration = {} self.assertDictEqual(transpiled_qc.calibrations, ref_calibration) @@ -96,6 +101,7 @@ def test_transpile_with_backend_target(self): def test_transpile_with_custom_basis_gate(self): """Test transpile with custom calibrations.""" with self.assertWarns(DeprecationWarning): + # TODO Move this test to backendV2 backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) backend.defaults().instruction_schedule_map.add("sx", (1,), self.custom_sx_q1) @@ -110,7 +116,11 @@ def test_transpile_with_custom_basis_gate(self): qc.sx(1) qc.measure_all() - transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) ref_calibration = { "sx": { @@ -154,6 +164,7 @@ def test_transpile_with_custom_basis_gate_in_target(self): def test_transpile_with_instmap(self): """Test providing instruction schedule map.""" with self.assertWarns(DeprecationWarning): + # TODO Move this test to backendV2 backend = Fake27QPulseV1() instmap = backend.defaults().instruction_schedule_map instmap.add("sx", (0,), self.custom_sx_q0) @@ -161,6 +172,7 @@ def test_transpile_with_instmap(self): # Inst map is renewed with self.assertWarns(DeprecationWarning): + # TODO Move this test to backendV2 backend = Fake27QPulseV1() # Remove timing constraints to avoid triggering # scheduling passes. @@ -173,7 +185,11 @@ def test_transpile_with_instmap(self): qc.sx(1) qc.measure_all() - transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1]) ref_calibration = { "sx": { @@ -186,6 +202,7 @@ def test_transpile_with_instmap(self): def test_transpile_with_custom_gate(self): """Test providing non-basis gate.""" with self.assertWarns(DeprecationWarning): + # TODO Move this test to backendV2 backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] @@ -208,7 +225,11 @@ def test_transpile_with_custom_gate(self): qc.append(circuit.Gate("my_gate", 1, [1.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [2.0]), [1]) - transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0, 1]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0, 1]) my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False) my_gate_q1_2_0 = self.my_gate_q1.assign_parameters({self.sched_param: 2.0}, inplace=False) @@ -224,6 +245,7 @@ def test_transpile_with_custom_gate(self): def test_transpile_with_parameterized_custom_gate(self): """Test providing non-basis gate, which is kept parameterized throughout transpile.""" with self.assertWarns(DeprecationWarning): + # TODO convert this to BackendV2/Target backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] @@ -243,7 +265,11 @@ def test_transpile_with_parameterized_custom_gate(self): qc = circuit.QuantumCircuit(1) qc.append(circuit.Gate("my_gate", 1, [param]), [0]) - transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) my_gate_q0_p = self.my_gate_q0.assign_parameters({self.sched_param: param}, inplace=False) @@ -257,6 +283,7 @@ def test_transpile_with_parameterized_custom_gate(self): def test_transpile_with_multiple_circuits(self): """Test transpile with multiple circuits with custom gate.""" with self.assertWarns(DeprecationWarning): + # TODO move this test to backendV2 backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] @@ -279,7 +306,11 @@ def test_transpile_with_multiple_circuits(self): qc.append(circuit.Gate("my_gate", 1, [param]), [0]) circs.append(qc) - transpiled_qcs = transpile(circs, backend, basis_gates=["my_gate"], initial_layout=[0]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qcs = transpile(circs, backend, basis_gates=["my_gate"], initial_layout=[0]) for param, transpiled_qc in zip(params, transpiled_qcs): my_gate_q0_x = self.my_gate_q0.assign_parameters( @@ -291,6 +322,7 @@ def test_transpile_with_multiple_circuits(self): def test_multiple_instructions_with_different_parameters(self): """Test adding many instruction with different parameter binding.""" with self.assertWarns(DeprecationWarning): + # TODO Move this test to backendV2 backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add( "my_gate", (0,), self.my_gate_q0, arguments=["P0"] @@ -311,7 +343,11 @@ def test_multiple_instructions_with_different_parameters(self): qc.append(circuit.Gate("my_gate", 1, [2.0]), [0]) qc.append(circuit.Gate("my_gate", 1, [3.0]), [0]) - transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) my_gate_q0_1_0 = self.my_gate_q0.assign_parameters({self.sched_param: 1.0}, inplace=False) my_gate_q0_2_0 = self.my_gate_q0.assign_parameters({self.sched_param: 2.0}, inplace=False) @@ -329,6 +365,7 @@ def test_multiple_instructions_with_different_parameters(self): def test_transpile_with_different_qubit(self): """Test transpile with qubit without custom gate.""" with self.assertWarns(DeprecationWarning): + # TODO Move this test to backendV2 backend = Fake27QPulseV1() backend.defaults().instruction_schedule_map.add("sx", (0,), self.custom_sx_q0) # Remove timing constraints to avoid triggering @@ -339,7 +376,11 @@ def test_transpile_with_different_qubit(self): qc.sx(0) qc.measure_all() - transpiled_qc = transpile(qc, backend, initial_layout=[3]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled_qc = transpile(qc, backend, initial_layout=[3]) self.assertDictEqual(transpiled_qc.calibrations, {}) From 10867061052ff1ae0c36470509c4fb02a5adfc09 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 16:35:26 +0200 Subject: [PATCH 157/168] test.python.pulse.test_builder --- test/python/pulse/test_builder.py | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/test/python/pulse/test_builder.py b/test/python/pulse/test_builder.py index 563b83345496..1374e73b3bfb 100644 --- a/test/python/pulse/test_builder.py +++ b/test/python/pulse/test_builder.py @@ -766,9 +766,12 @@ def get_sched(qubit_idx: [int], backend): qc = circuit.QuantumCircuit(2) for idx in qubit_idx: qc.append(circuit.library.U2Gate(0, pi / 2), [idx]) - return compiler.schedule( - compiler.transpile(qc, backend=backend, optimization_level=1), backend - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + transpiled = compiler.transpile(qc, backend=backend, optimization_level=1) + return compiler.schedule(transpiled, backend) with pulse.build(self.backend) as schedule: with pulse.align_sequential(): @@ -788,7 +791,11 @@ def get_sched(qubit_idx: [int], backend): # prepare and schedule circuits that will be used. single_u2_qc = circuit.QuantumCircuit(2) single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) - single_u2_qc = compiler.transpile(single_u2_qc, self.backend, optimization_level=1) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + single_u2_qc = compiler.transpile(single_u2_qc, self.backend, optimization_level=1) single_u2_sched = compiler.schedule(single_u2_qc, self.backend) # sequential context @@ -813,7 +820,11 @@ def get_sched(qubit_idx: [int], backend): triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) - triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend, optimization_level=1) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend, optimization_level=1) align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap") # measurement From 241f2dd9b70eb7d2ae664c3e18a3c00df6958842 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 17:13:10 +0200 Subject: [PATCH 158/168] test.python.primitives.test_backend_sampler_v2 --- .../primitives/test_backend_sampler_v2.py | 676 +++++++++++++++++- 1 file changed, 653 insertions(+), 23 deletions(-) diff --git a/test/python/primitives/test_backend_sampler_v2.py b/test/python/primitives/test_backend_sampler_v2.py index 632ed1984d2d..d0c4a3bfd414 100644 --- a/test/python/primitives/test_backend_sampler_v2.py +++ b/test/python/primitives/test_backend_sampler_v2.py @@ -35,7 +35,9 @@ from qiskit.providers.fake_provider import Fake7QPulseV1, GenericBackendV2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager -BACKENDS = [BasicSimulator(), Fake7QPulseV1(), BackendV2Converter(Fake7QPulseV1())] +BACKENDS_V1 = [Fake7QPulseV1()] +BACKENDS_V2 = [BasicSimulator(), BackendV2Converter(Fake7QPulseV1())] +BACKENDS = BACKENDS_V1 + BACKENDS_V2 @ddt @@ -85,7 +87,62 @@ def _assert_allclose(self, bitarray: BitArray, target: NDArray | BitArray, rtol= tgt = np.array([target_counts.get(i, 0) for i in range(max_key + 1)]) np.testing.assert_allclose(ary, tgt, rtol=rtol, atol=atol, err_msg=f"index: {idx}") - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_sampler_run_v1(self, backend): + """Test run().""" + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + + with self.subTest("single"): + bell, _, target = self._cases[1] + bell = pm.run(bell) + sampler = BackendSamplerV2(backend=backend, options=self._options) + job = sampler.run([bell], shots=self._shots) + result = job.result() + self.assertIsInstance(result, PrimitiveResult) + self.assertIsInstance(result.metadata, dict) + self.assertEqual(len(result), 1) + self.assertIsInstance(result[0], PubResult) + self.assertIsInstance(result[0].data, DataBin) + self.assertIsInstance(result[0].data.meas, BitArray) + self._assert_allclose(result[0].data.meas, np.array(target)) + + with self.subTest("single with param"): + pqc, param_vals, target = self._cases[2] + 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) + result = job.result() + self.assertIsInstance(result, PrimitiveResult) + self.assertIsInstance(result.metadata, dict) + self.assertEqual(len(result), 1) + self.assertIsInstance(result[0], PubResult) + self.assertIsInstance(result[0].data, DataBin) + self.assertIsInstance(result[0].data.meas, BitArray) + self._assert_allclose(result[0].data.meas, np.array(target)) + + with self.subTest("multiple"): + pqc, param_vals, target = self._cases[2] + 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, param_vals, param_vals]})], shots=self._shots + ) + result = job.result() + self.assertIsInstance(result, PrimitiveResult) + self.assertIsInstance(result.metadata, dict) + self.assertEqual(len(result), 1) + self.assertIsInstance(result[0], PubResult) + self.assertIsInstance(result[0].data, DataBin) + self.assertIsInstance(result[0].data.meas, BitArray) + self._assert_allclose(result[0].data.meas, np.array([target, target, target])) + + @combine(backend=BACKENDS_V2) def test_sampler_run(self, backend): """Test run().""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -136,7 +193,24 @@ def test_sampler_run(self, backend): self.assertIsInstance(result[0].data.meas, BitArray) self._assert_allclose(result[0].data.meas, np.array([target, target, target])) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + 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="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + bell = pm.run(bell) + result1 = sampler.run([bell], shots=self._shots).result() + meas1 = result1[0].data.meas + result2 = sampler.run([bell], shots=self._shots).result() + meas2 = result2[0].data.meas + self._assert_allclose(meas1, meas2, rtol=0) + + @combine(backend=BACKENDS_V2) def test_sampler_run_multiple_times(self, backend): """Test run() returns the same results if the same input is given.""" bell, _, _ = self._cases[1] @@ -149,7 +223,24 @@ def test_sampler_run_multiple_times(self, backend): meas2 = result2[0].data.meas self._assert_allclose(meas1, meas2, rtol=0) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + 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="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + bell = pm.run(bell) + result = sampler.run([bell, bell, bell], shots=self._shots).result() + self.assertEqual(len(result), 3) + self._assert_allclose(result[0].data.meas, np.array(target)) + self._assert_allclose(result[1].data.meas, np.array(target)) + self._assert_allclose(result[2].data.meas, np.array(target)) + + @combine(backend=BACKENDS_V2) def test_sample_run_multiple_circuits(self, backend): """Test run() with multiple circuits.""" bell, _, target = self._cases[1] @@ -162,13 +253,14 @@ def test_sample_run_multiple_circuits(self, backend): self._assert_allclose(result[1].data.meas, np.array(target)) self._assert_allclose(result[2].data.meas, np.array(target)) - @combine(backend=BACKENDS) - def test_sampler_run_with_parameterized_circuits(self, backend): + @combine(backend=BACKENDS_V1) + def test_sampler_run_with_parameterized_circuits_v1(self, backend): """Test run() with parameterized circuits.""" pqc1, param1, target1 = self._cases[4] pqc2, param2, target2 = self._cases[5] pqc3, param3, target3 = self._cases[6] - pm = generate_preset_pass_manager(optimization_level=0, backend=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) @@ -180,7 +272,7 @@ def test_sampler_run_with_parameterized_circuits(self, backend): self._assert_allclose(result[1].data.meas, np.array(target2)) self._assert_allclose(result[2].data.meas, np.array(target3)) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V2) def test_run_1qubit(self, backend): """test for 1-qubit cases""" qc = QuantumCircuit(1) @@ -197,7 +289,28 @@ def test_run_1qubit(self, backend): for i in range(2): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_run_1qubit_v1(self, backend): + """test for 1-qubit cases""" + qc = QuantumCircuit(1) + qc.measure_all() + qc2 = QuantumCircuit(1) + qc2.x(0) + qc2.measure_all() + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc, qc2 = pm.run([qc, qc2]) + + 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): + self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) + + @combine(backend=BACKENDS_V2) def test_run_2qubit(self, backend): """test for 2-qubit cases""" qc0 = QuantumCircuit(2) @@ -220,7 +333,34 @@ def test_run_2qubit(self, backend): for i in range(4): self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_run_2qubit_v1(self, backend): + """test for 2-qubit cases""" + qc0 = QuantumCircuit(2) + qc0.measure_all() + qc1 = QuantumCircuit(2) + qc1.x(0) + qc1.measure_all() + qc2 = QuantumCircuit(2) + qc2.x(1) + qc2.measure_all() + qc3 = QuantumCircuit(2) + qc3.x([0, 1]) + qc3.measure_all() + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + 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) + result = sampler.run([qc0, qc1, qc2, qc3], shots=self._shots).result() + self.assertEqual(len(result), 4) + for i in range(4): + self._assert_allclose(result[i].data.meas, np.array({i: self._shots})) + + @combine(backend=BACKENDS_V2) def test_run_single_circuit(self, backend): """Test for single circuit case.""" sampler = BackendSamplerV2(backend=backend, options=self._options) @@ -278,7 +418,69 @@ def test_run_single_circuit(self, backend): self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, target) - @combine(backend=BACKENDS) + @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="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + + with self.subTest("No parameter"): + circuit, _, target = self._cases[1] + circuit = pm.run(circuit) + param_target = [ + (None, np.array(target)), + ({}, np.array(target)), + ] + for param, target in param_target: + with self.subTest(f"{circuit.name} w/ {param}"): + result = sampler.run([(circuit, param)], shots=self._shots).result() + self.assertEqual(len(result), 1) + self._assert_allclose(result[0].data.meas, target) + + with self.subTest("One parameter"): + circuit = QuantumCircuit(1, 1, name="X gate") + param = Parameter("x") + circuit.ry(param, 0) + circuit.measure(0, 0) + circuit = pm.run(circuit) + param_target = [ + ({"x": np.pi}, np.array({1: self._shots})), + ({param: np.pi}, np.array({1: self._shots})), + ({"x": np.array(np.pi)}, np.array({1: self._shots})), + ({param: np.array(np.pi)}, np.array({1: self._shots})), + ({"x": [np.pi]}, np.array({1: self._shots})), + ({param: [np.pi]}, np.array({1: self._shots})), + ({"x": np.array([np.pi])}, np.array({1: self._shots})), + ({param: np.array([np.pi])}, np.array({1: self._shots})), + ] + for param, target in param_target: + with self.subTest(f"{circuit.name} w/ {param}"): + result = sampler.run([(circuit, param)], shots=self._shots).result() + self.assertEqual(len(result), 1) + self._assert_allclose(result[0].data.c, target) + + with self.subTest("More than one parameter"): + circuit, param, target = self._cases[3] + circuit = pm.run(circuit) + param_target = [ + (param, np.array(target)), + (tuple(param), np.array(target)), + (np.array(param), np.array(target)), + ((param,), np.array([target])), + ([param], np.array([target])), + (np.array([param]), np.array([target])), + ] + for param, target in param_target: + with self.subTest(f"{circuit.name} w/ {param}"): + result = sampler.run([(circuit, param)], shots=self._shots).result() + self.assertEqual(len(result), 1) + self._assert_allclose(result[0].data.meas, target) + + @combine(backend=BACKENDS_V2) def test_run_reverse_meas_order(self, backend): """test for sampler with reverse measurement order""" x = Parameter("x") @@ -305,7 +507,38 @@ def test_run_reverse_meas_order(self, backend): # qc({x: pi/2, y: 0}) self._assert_allclose(result[1].data.c, np.array({1: self._shots / 2, 5: self._shots / 2})) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_run_reverse_meas_order_v1(self, backend): + """test for sampler with reverse measurement order""" + x = Parameter("x") + y = Parameter("y") + + qc = QuantumCircuit(3, 3) + qc.rx(x, 0) + qc.rx(y, 1) + qc.x(2) + qc.measure(0, 2) + qc.measure(1, 1) + qc.measure(2, 0) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc = pm.run(qc) + + 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) + + # qc({x: 0, y: 0}) + self._assert_allclose(result[0].data.c, np.array({1: self._shots})) + + # qc({x: pi/2, y: 0}) + self._assert_allclose(result[1].data.c, np.array({1: self._shots / 2, 5: self._shots / 2})) + + @combine(backend=BACKENDS_V2) def test_run_errors(self, backend): """Test for errors with run method""" qc1 = QuantumCircuit(1) @@ -357,7 +590,63 @@ def test_run_errors(self, backend): with self.assertRaisesRegex(ValueError, "Note that if you want to run a single pub,"): _ = sampler.run((qc2, [0, 1])).result() - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_run_errors_v1(self, backend): + """Test for errors with run method""" + qc1 = QuantumCircuit(1) + qc1.measure_all() + qc2 = RealAmplitudes(num_qubits=1, reps=1) + qc2.measure_all() + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc1, qc2 = pm.run([qc1, qc2]) + + sampler = BackendSamplerV2(backend=backend) + with self.subTest("set parameter values to a non-parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([(qc1, [1e2])]).result() + with self.subTest("missing all parameter values for a parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([qc2]).result() + with self.assertRaises(ValueError): + _ = sampler.run([(qc2, [])]).result() + with self.assertRaises(ValueError): + _ = sampler.run([(qc2, None)]).result() + with self.subTest("missing some parameter values for a parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([(qc2, [1e2])]).result() + with self.subTest("too many parameter values for a parameterized circuit"): + with self.assertRaises(ValueError): + _ = sampler.run([(qc2, [1e2] * 100)]).result() + with self.subTest("negative shots, run arg"): + with self.assertRaises(ValueError): + _ = sampler.run([qc1], shots=-1).result() + with self.subTest("negative shots, pub-like"): + with self.assertRaises(ValueError): + _ = sampler.run([(qc1, None, -1)]).result() + with self.subTest("negative shots, pub"): + with self.assertRaises(ValueError): + _ = sampler.run([SamplerPub(qc1, shots=-1)]).result() + with self.subTest("zero shots, run arg"): + with self.assertRaises(ValueError): + _ = sampler.run([qc1], shots=0).result() + with self.subTest("zero shots, pub-like"): + with self.assertRaises(ValueError): + _ = sampler.run([(qc1, None, 0)]).result() + with self.subTest("zero shots, pub"): + with self.assertRaises(ValueError): + _ = sampler.run([SamplerPub(qc1, shots=0)]).result() + with self.subTest("missing []"): + with self.assertRaisesRegex(ValueError, "An invalid Sampler pub-like was given"): + _ = sampler.run(qc1).result() + with self.subTest("missing [] for pqc"): + with self.assertRaisesRegex(ValueError, "Note that if you want to run a single pub,"): + _ = sampler.run((qc2, [0, 1])).result() + + @combine(backend=BACKENDS_V2) def test_run_empty_parameter(self, backend): """Test for empty parameter""" n = 5 @@ -377,12 +666,70 @@ def test_run_empty_parameter(self, backend): for i in range(2): self._assert_allclose(result[i].data.c, np.array({0: self._shots})) - @combine(backend=BACKENDS) - def test_run_numpy_params(self, backend): + @combine(backend=BACKENDS_V1) + def test_run_empty_parameter_v1(self, backend): + """Test for empty parameter""" + n = 5 + qc = QuantumCircuit(n, n - 1) + qc.measure(range(n - 1), range(n - 1)) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc = pm.run(qc) + 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) + self._assert_allclose(result[0].data.c, np.array({0: self._shots})) + + with self.subTest("two circuits"): + result = sampler.run([qc, qc], shots=self._shots).result() + self.assertEqual(len(result), 2) + for i in range(2): + self._assert_allclose(result[i].data.c, np.array({0: self._shots})) + + @combine(backend=BACKENDS_V2) + def test_run_numpy_params(self, backend): + """Test for numpy array as parameter values""" + qc = RealAmplitudes(num_qubits=2, reps=2) + qc.measure_all() + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc = pm.run(qc) + k = 5 + params_array = np.linspace(0, 1, k * qc.num_parameters).reshape((k, qc.num_parameters)) + params_list = params_array.tolist() + sampler = StatevectorSampler(seed=self._seed) + target = sampler.run([(qc, params_list)], shots=self._shots).result() + + with self.subTest("ndarray"): + 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) + result = sampler.run( + [(qc, params) for params in params_list], shots=self._shots + ).result() + self.assertEqual(len(result), k) + for i in range(k): + self._assert_allclose( + result[i].data.meas, np.array(target[0].data.meas.get_int_counts(i)) + ) + + @combine(backend=BACKENDS_V1) + def test_run_numpy_params_v1(self, backend): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) qc.measure_all() - pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) k = 5 params_array = np.linspace(0, 1, k * qc.num_parameters).reshape((k, qc.num_parameters)) @@ -407,7 +754,7 @@ def test_run_numpy_params(self, backend): result[i].data.meas, np.array(target[0].data.meas.get_int_counts(i)) ) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V2) def test_run_with_shots_option(self, backend): """test with shots option.""" bell, _, _ = self._cases[1] @@ -471,7 +818,75 @@ def test_run_with_shots_option(self, backend): self.assertEqual(result[1].data.meas.num_shots, shots2) self.assertEqual(sum(result[1].data.meas.get_counts().values()), shots2) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_run_with_shots_option_v1(self, backend): + """test with shots option.""" + bell, _, _ = self._cases[1] + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + bell = pm.run(bell) + shots = 100 + + with self.subTest("run arg"): + 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) + default_shots = sampler.options.default_shots + result = sampler.run([bell]).result() + self.assertEqual(len(result), 1) + self.assertEqual(result[0].data.meas.num_shots, default_shots) + self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) + + with self.subTest("setting default shots"): + default_shots = 100 + 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() + self.assertEqual(len(result), 1) + self.assertEqual(result[0].data.meas.num_shots, default_shots) + self.assertEqual(sum(result[0].data.meas.get_counts().values()), default_shots) + + with self.subTest("pub-like"): + 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) + 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) + shots1 = 100 + shots2 = 200 + result = sampler.run( + [ + SamplerPub(bell, shots=shots1), + SamplerPub(bell, shots=shots2), + ], + shots=self._shots, + ).result() + self.assertEqual(len(result), 2) + self.assertEqual(result[0].data.meas.num_shots, shots1) + self.assertEqual(sum(result[0].data.meas.get_counts().values()), shots1) + self.assertEqual(result[1].data.meas.num_shots, shots2) + self.assertEqual(sum(result[1].data.meas.get_counts().values()), shots2) + + @combine(backend=BACKENDS_V2) def test_run_shots_result_size(self, backend): """test with shots option to validate the result size""" n = 7 # should be less than or equal to the number of qubits of backend @@ -486,7 +901,26 @@ def test_run_shots_result_size(self, backend): self.assertLessEqual(result[0].data.meas.num_shots, self._shots) self.assertEqual(sum(result[0].data.meas.get_counts().values()), self._shots) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_run_shots_result_size_v1(self, backend): + """test with shots option to validate the result size""" + n = 7 # should be less than or equal to the number of qubits of backend + qc = QuantumCircuit(n) + qc.h(range(n)) + qc.measure_all() + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc = pm.run(qc) + 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) + self.assertEqual(sum(result[0].data.meas.get_counts().values()), self._shots) + + @combine(backend=BACKENDS_V2) def test_primitive_job_status_done(self, backend): """test primitive job's status""" bell, _, _ = self._cases[1] @@ -497,7 +931,22 @@ def test_primitive_job_status_done(self, backend): _ = job.result() self.assertEqual(job.status(), JobStatus.DONE) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_primitive_job_status_done_v1(self, backend): + """test primitive job's status""" + bell, _, _ = self._cases[1] + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + bell = pm.run(bell) + sampler = BackendSamplerV2(backend=backend, options=self._options) + job = sampler.run([bell], shots=self._shots) + _ = job.result() + self.assertEqual(job.status(), JobStatus.DONE) + + @combine(backend=BACKENDS_V2) def test_circuit_with_unitary(self, backend): """Test for circuit with unitary gate.""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -528,7 +977,42 @@ def test_circuit_with_unitary(self, backend): self.assertEqual(len(result), 1) self._assert_allclose(result[0].data.meas, np.array({1: self._shots})) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_circuit_with_unitary_v1(self, backend): + """Test for circuit with unitary gate.""" + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + + with self.subTest("identity"): + gate = UnitaryGate(np.eye(2)) + + circuit = QuantumCircuit(1) + circuit.append(gate, [0]) + circuit.measure_all() + circuit = pm.run(circuit) + + 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})) + + with self.subTest("X"): + gate = UnitaryGate([[0, 1], [1, 0]]) + + circuit = QuantumCircuit(1) + circuit.append(gate, [0]) + circuit.measure_all() + circuit = pm.run(circuit) + + 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})) + + @combine(backend=BACKENDS_V2) def test_circuit_with_multiple_cregs(self, backend): """Test for circuit with multiple classical registers.""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -608,7 +1092,91 @@ def test_circuit_with_multiple_cregs(self, backend): self.assertTrue(hasattr(data, creg.name)) self._assert_allclose(getattr(data, creg.name), np.array(target[creg.name])) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V1) + def test_circuit_with_multiple_cregs_v1(self, backend): + """Test for circuit with multiple classical registers.""" + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + cases = [] + + # case 1 + a = ClassicalRegister(1, "a") + b = ClassicalRegister(2, "b") + c = ClassicalRegister(3, "c") + + qc = QuantumCircuit(QuantumRegister(3), a, b, c) + qc.h(range(3)) + qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) + qc = pm.run(qc) + target = {"a": {0: 5000, 1: 5000}, "b": {0: 5000, 2: 5000}, "c": {0: 5000, 6: 5000}} + cases.append(("use all cregs", qc, target)) + + # case 2 + a = ClassicalRegister(1, "a") + b = ClassicalRegister(5, "b") + c = ClassicalRegister(3, "c") + + qc = QuantumCircuit(QuantumRegister(3), a, b, c) + qc.h(range(3)) + qc.measure([0, 1, 2, 2], [0, 2, 4, 5]) + qc = pm.run(qc) + target = { + "a": {0: 5000, 1: 5000}, + "b": {0: 2500, 2: 2500, 24: 2500, 26: 2500}, + "c": {0: 10000}, + } + cases.append(("use only a and b", qc, target)) + + # case 3 + a = ClassicalRegister(1, "a") + b = ClassicalRegister(2, "b") + c = ClassicalRegister(3, "c") + + qc = QuantumCircuit(QuantumRegister(3), a, b, c) + qc.h(range(3)) + qc.measure(1, 5) + qc = pm.run(qc) + target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} + cases.append(("use only c", qc, target)) + + # case 4 + a = ClassicalRegister(1, "a") + b = ClassicalRegister(2, "b") + c = ClassicalRegister(3, "c") + + qc = QuantumCircuit(QuantumRegister(3), a, b, c) + qc.h(range(3)) + qc.measure([0, 1, 2], [5, 5, 5]) + qc = pm.run(qc) + target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 5000, 4: 5000}} + cases.append(("use only c multiple qubits", qc, target)) + + # case 5 + a = ClassicalRegister(1, "a") + b = ClassicalRegister(2, "b") + c = ClassicalRegister(3, "c") + + qc = QuantumCircuit(QuantumRegister(3), a, b, c) + qc.h(range(3)) + qc = pm.run(qc) + target = {"a": {0: 10000}, "b": {0: 10000}, "c": {0: 10000}} + cases.append(("no measure", qc, target)) + + for title, qc, target in cases: + with self.subTest(title): + sampler = BackendSamplerV2(backend=backend, options=self._options) + result = sampler.run([qc], shots=self._shots).result() + self.assertEqual(len(result), 1) + data = result[0].data + self.assertEqual(len(data), 3) + for creg in qc.cregs: + self.assertTrue(hasattr(data, creg.name)) + self._assert_allclose(getattr(data, creg.name), np.array(target[creg.name])) + + @combine(backend=BACKENDS_V2) def test_circuit_with_aliased_cregs(self, backend): """Test for circuit with aliased classical registers.""" q = QuantumRegister(3, "q") @@ -644,6 +1212,46 @@ def test_circuit_with_aliased_cregs(self, backend): self.assertTrue(hasattr(data, creg_name)) self._assert_allclose(getattr(data, creg_name), np.array(creg)) + @combine(backend=BACKENDS_V1) + def test_circuit_with_aliased_cregs_v1(self, backend): + """Test for circuit with aliased classical registers.""" + q = QuantumRegister(3, "q") + c1 = ClassicalRegister(1, "c1") + c2 = ClassicalRegister(1, "c2") + + qc = QuantumCircuit(q, c1, c2) + qc.ry(np.pi / 4, 2) + qc.cx(2, 1) + qc.cx(0, 1) + qc.h(0) + qc.measure(0, c1) + qc.measure(1, c2) + qc.z(2).c_if(c1, 1) + qc.x(2).c_if(c2, 1) + qc2 = QuantumCircuit(5, 5) + qc2.compose(qc, [0, 2, 3], [2, 4], inplace=True) + cregs = [creg.name for creg in qc2.cregs] + target = { + cregs[0]: {0: 4255, 4: 4297, 16: 720, 20: 726}, + 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="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc2 = pm.run(qc2) + result = sampler.run([qc2], shots=self._shots).result() + self.assertEqual(len(result), 1) + data = result[0].data + self.assertEqual(len(data), 3) + for creg_name, creg in target.items(): + self.assertTrue(hasattr(data, creg_name)) + self._assert_allclose(getattr(data, creg_name), np.array(creg)) + @combine(backend=BACKENDS) def test_no_cregs(self, backend): """Test that the sampler works when there are no classical register in the circuit.""" @@ -670,7 +1278,7 @@ def test_empty_creg(self, backend): result = sampler.run([qc], shots=self._shots).result() self.assertEqual(result[0].data.c1.array.shape, (self._shots, 0)) - @combine(backend=BACKENDS) + @combine(backend=BACKENDS_V2) def test_diff_shots(self, backend): """Test of pubs with different shots""" pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -688,6 +1296,28 @@ def test_diff_shots(self, backend): self.assertEqual(result[1].data.meas.num_shots, shots2) self._assert_allclose(result[1].data.meas, np.array(target2)) + @combine(backend=BACKENDS_V1) + def test_diff_shots_v1(self, backend): + """Test of pubs with different shots""" + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + + bell, _, target = self._cases[1] + bell = pm.run(bell) + 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)]) + result = job.result() + self.assertEqual(len(result), 2) + self.assertEqual(result[0].data.meas.num_shots, self._shots) + self._assert_allclose(result[0].data.meas, np.array(target)) + self.assertEqual(result[1].data.meas.num_shots, shots2) + self._assert_allclose(result[1].data.meas, np.array(target2)) + def test_job_size_limit_backend_v2(self): """Test BackendSamplerV2 respects backend's job size limit.""" From 2991bc82565409d0d05329d6cb6ac951f32467f0 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 17:23:33 +0200 Subject: [PATCH 159/168] test.python.primitives.test_backend_sampler_v2 --- test/python/primitives/test_backend_sampler_v2.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/test/python/primitives/test_backend_sampler_v2.py b/test/python/primitives/test_backend_sampler_v2.py index d0c4a3bfd414..abb06eed8cb3 100644 --- a/test/python/primitives/test_backend_sampler_v2.py +++ b/test/python/primitives/test_backend_sampler_v2.py @@ -34,9 +34,19 @@ from qiskit.providers.basic_provider import BasicSimulator from qiskit.providers.fake_provider import Fake7QPulseV1, GenericBackendV2 from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager +from ..legacy_cmaps import LAGOS_CMAP BACKENDS_V1 = [Fake7QPulseV1()] -BACKENDS_V2 = [BasicSimulator(), BackendV2Converter(Fake7QPulseV1())] +BACKENDS_V2 = [ + BasicSimulator(), + BackendV2Converter(Fake7QPulseV1()), + GenericBackendV2( + num_qubits=7, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + coupling_map=LAGOS_CMAP, + seed=42, + ), +] BACKENDS = BACKENDS_V1 + BACKENDS_V2 From dc210de9fbf4292f6fcca755ebdaed58adb604db Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 17:37:12 +0200 Subject: [PATCH 160/168] test.python.primitives.test_backend_estimator_v2 --- .../primitives/test_backend_estimator_v2.py | 348 +++++++++++++++++- 1 file changed, 337 insertions(+), 11 deletions(-) diff --git a/test/python/primitives/test_backend_estimator_v2.py b/test/python/primitives/test_backend_estimator_v2.py index 319fd846ee95..6bde5f964f4a 100644 --- a/test/python/primitives/test_backend_estimator_v2.py +++ b/test/python/primitives/test_backend_estimator_v2.py @@ -33,8 +33,20 @@ from qiskit.quantum_info import SparsePauliOp from qiskit.transpiler.preset_passmanagers import generate_preset_pass_manager from qiskit.utils import optionals - -BACKENDS = [BasicSimulator(), Fake7QPulseV1(), BackendV2Converter(Fake7QPulseV1())] +from ..legacy_cmaps import LAGOS_CMAP + +BACKENDS_V1 = [Fake7QPulseV1()] +BACKENDS_V2 = [ + BasicSimulator(), + BackendV2Converter(Fake7QPulseV1()), + GenericBackendV2( + num_qubits=7, + basis_gates=["id", "rz", "sx", "x", "cx", "reset"], + coupling_map=LAGOS_CMAP, + seed=42, + ), +] +BACKENDS = BACKENDS_V1 + BACKENDS_V2 @ddt @@ -73,7 +85,7 @@ def setUp(self): [1, 2, 3, 4, 5, 6], ) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_estimator_run(self, backend, abelian_grouping): """Test Estimator.run()""" psi1, psi2 = self.psi @@ -120,7 +132,58 @@ def test_estimator_run(self, backend, abelian_grouping): np.testing.assert_allclose(result4[0].data.evs, [1.55555728, -1.08766318], rtol=self._rtol) np.testing.assert_allclose(result4[1].data.evs, [0.17849238], rtol=self._rtol) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_estimator_run_v1(self, backend, abelian_grouping): + """Test Estimator.run()""" + psi1, psi2 = self.psi + hamiltonian1, hamiltonian2, hamiltonian3 = self.hamiltonian + theta1, theta2, theta3 = self.theta + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + psi1, psi2 = pm.run([psi1, psi2]) + estimator = BackendEstimatorV2(backend=backend, options=self._options) + estimator.options.abelian_grouping = abelian_grouping + # Specify the circuit and observable by indices. + # calculate [ ] + ham1 = hamiltonian1.apply_layout(psi1.layout) + job = estimator.run([(psi1, ham1, [theta1])]) + result = job.result() + np.testing.assert_allclose(result[0].data.evs, [1.5555572817900956], rtol=self._rtol) + + # Objects can be passed instead of indices. + # Note that passing objects has an overhead + # since the corresponding indices need to be searched. + # User can append a circuit and observable. + # calculate [ ] + ham1 = hamiltonian1.apply_layout(psi2.layout) + result2 = estimator.run([(psi2, ham1, theta2)]).result() + np.testing.assert_allclose(result2[0].data.evs, [2.97797666], rtol=self._rtol) + + # calculate [ , ] + ham2 = hamiltonian2.apply_layout(psi1.layout) + ham3 = hamiltonian3.apply_layout(psi1.layout) + result3 = estimator.run([(psi1, [ham2, ham3], theta1)]).result() + np.testing.assert_allclose(result3[0].data.evs, [-0.551653, 0.07535239], rtol=self._rtol) + + # calculate [ [, + # ], + # [] ] + ham1 = hamiltonian1.apply_layout(psi1.layout) + ham3 = hamiltonian3.apply_layout(psi1.layout) + ham2 = hamiltonian2.apply_layout(psi2.layout) + result4 = estimator.run( + [ + (psi1, [ham1, ham3], [theta1, theta3]), + (psi2, ham2, theta2), + ] + ).result() + np.testing.assert_allclose(result4[0].data.evs, [1.55555728, -1.08766318], rtol=self._rtol) + np.testing.assert_allclose(result4[1].data.evs, [0.17849238], rtol=self._rtol) + + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_estimator_with_pub(self, backend, abelian_grouping): """Test estimator with explicit EstimatorPubs.""" psi1, psi2 = self.psi @@ -146,7 +209,37 @@ def test_estimator_with_pub(self, backend, abelian_grouping): np.testing.assert_allclose(result4[0].data.evs, [1.55555728, -1.08766318], rtol=self._rtol) np.testing.assert_allclose(result4[1].data.evs, [0.17849238], rtol=self._rtol) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_estimator_with_pub_v1(self, backend, abelian_grouping): + """Test estimator with explicit EstimatorPubs.""" + psi1, psi2 = self.psi + hamiltonian1, hamiltonian2, hamiltonian3 = self.hamiltonian + theta1, theta2, theta3 = self.theta + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + psi1, psi2 = pm.run([psi1, psi2]) + + ham1 = hamiltonian1.apply_layout(psi1.layout) + ham3 = hamiltonian3.apply_layout(psi1.layout) + obs1 = ObservablesArray.coerce([ham1, ham3]) + bind1 = BindingsArray.coerce({tuple(psi1.parameters): [theta1, theta3]}) + pub1 = EstimatorPub(psi1, obs1, bind1) + + ham2 = hamiltonian2.apply_layout(psi2.layout) + obs2 = ObservablesArray.coerce(ham2) + bind2 = BindingsArray.coerce({tuple(psi2.parameters): theta2}) + pub2 = EstimatorPub(psi2, obs2, bind2) + + estimator = BackendEstimatorV2(backend=backend, options=self._options) + estimator.options.abelian_grouping = abelian_grouping + result4 = estimator.run([pub1, pub2]).result() + np.testing.assert_allclose(result4[0].data.evs, [1.55555728, -1.08766318], rtol=self._rtol) + np.testing.assert_allclose(result4[1].data.evs, [0.17849238], rtol=self._rtol) + + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_estimator_run_no_params(self, backend, abelian_grouping): """test for estimator without parameters""" circuit = self.ansatz.assign_parameters([0, 1, 1, 2, 3, 5]) @@ -158,7 +251,23 @@ def test_estimator_run_no_params(self, backend, abelian_grouping): result = est.run([(circuit, observable)]).result() np.testing.assert_allclose(result[0].data.evs, [-1.284366511861733], rtol=self._rtol) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_estimator_run_no_params_v1(self, backend, abelian_grouping): + """test for estimator without parameters""" + circuit = self.ansatz.assign_parameters([0, 1, 1, 2, 3, 5]) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + circuit = pm.run(circuit) + est = BackendEstimatorV2(backend=backend, options=self._options) + est.options.abelian_grouping = abelian_grouping + observable = self.observable.apply_layout(circuit.layout) + result = est.run([(circuit, observable)]).result() + np.testing.assert_allclose(result[0].data.evs, [-1.284366511861733], rtol=self._rtol) + + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_run_single_circuit_observable(self, backend, abelian_grouping): """Test for single circuit and single observable case.""" est = BackendEstimatorV2(backend=backend, options=self._options) @@ -216,7 +325,69 @@ def test_run_single_circuit_observable(self, backend, abelian_grouping): np.testing.assert_allclose(result[0].data.evs, target, rtol=self._rtol) self.assertEqual(result[0].metadata["target_precision"], self._precision) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_run_single_circuit_observable_v1(self, backend, abelian_grouping): + """Test for single circuit and single observable case.""" + est = BackendEstimatorV2(backend=backend, options=self._options) + est.options.abelian_grouping = abelian_grouping + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + + with self.subTest("No parameter"): + qc = QuantumCircuit(1) + qc.x(0) + qc = pm.run(qc) + op = SparsePauliOp("Z") + op = op.apply_layout(qc.layout) + param_vals = [None, [], [[]], np.array([]), np.array([[]]), [np.array([])]] + target = [-1] + for val in param_vals: + self.subTest(f"{val}") + result = est.run([(qc, op, val)]).result() + np.testing.assert_allclose(result[0].data.evs, target, rtol=self._rtol) + self.assertEqual(result[0].metadata["target_precision"], self._precision) + + with self.subTest("One parameter"): + param = Parameter("x") + qc = QuantumCircuit(1) + qc.ry(param, 0) + qc = pm.run(qc) + op = SparsePauliOp("Z") + op = op.apply_layout(qc.layout) + param_vals = [ + [np.pi], + np.array([np.pi]), + ] + target = [-1] + for val in param_vals: + self.subTest(f"{val}") + result = est.run([(qc, op, val)]).result() + np.testing.assert_allclose(result[0].data.evs, target, rtol=self._rtol) + self.assertEqual(result[0].metadata["target_precision"], self._precision) + + with self.subTest("More than one parameter"): + qc = self.psi[0] + qc = pm.run(qc) + op = self.hamiltonian[0] + op = op.apply_layout(qc.layout) + param_vals = [ + self.theta[0], + [self.theta[0]], + np.array(self.theta[0]), + np.array([self.theta[0]]), + [np.array(self.theta[0])], + ] + target = [1.5555572817900956] + for val in param_vals: + self.subTest(f"{val}") + result = est.run([(qc, op, val)]).result() + np.testing.assert_allclose(result[0].data.evs, target, rtol=self._rtol) + self.assertEqual(result[0].metadata["target_precision"], self._precision) + + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_run_1qubit(self, backend, abelian_grouping): """Test for 1-qubit cases""" qc = QuantumCircuit(1) @@ -246,7 +417,41 @@ def test_run_1qubit(self, backend, abelian_grouping): result = est.run([(qc2, op_4)]).result() np.testing.assert_allclose(result[0].data.evs, [-1], rtol=self._rtol) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_run_1qubit_v1(self, backend, abelian_grouping): + """Test for 1-qubit cases""" + qc = QuantumCircuit(1) + qc2 = QuantumCircuit(1) + qc2.x(0) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc, qc2 = pm.run([qc, qc2]) + + op = SparsePauliOp.from_list([("I", 1)]) + op2 = SparsePauliOp.from_list([("Z", 1)]) + + est = BackendEstimatorV2(backend=backend, options=self._options) + est.options.abelian_grouping = abelian_grouping + op_1 = op.apply_layout(qc.layout) + result = est.run([(qc, op_1)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_2 = op2.apply_layout(qc.layout) + result = est.run([(qc, op_2)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_3 = op.apply_layout(qc2.layout) + result = est.run([(qc2, op_3)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_4 = op2.apply_layout(qc2.layout) + result = est.run([(qc2, op_4)]).result() + np.testing.assert_allclose(result[0].data.evs, [-1], rtol=self._rtol) + + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_run_2qubits(self, backend, abelian_grouping): """Test for 2-qubit cases (to check endian)""" qc = QuantumCircuit(2) @@ -285,6 +490,49 @@ def test_run_2qubits(self, backend, abelian_grouping): result = est.run([(qc2, op_6)]).result() np.testing.assert_allclose(result[0].data.evs, [-1], rtol=self._rtol) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_run_2qubits_v1(self, backend, abelian_grouping): + """Test for 2-qubit cases (to check endian)""" + qc = QuantumCircuit(2) + qc2 = QuantumCircuit(2) + qc2.x(0) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc, qc2 = pm.run([qc, qc2]) + + op = SparsePauliOp.from_list([("II", 1)]) + op2 = SparsePauliOp.from_list([("ZI", 1)]) + op3 = SparsePauliOp.from_list([("IZ", 1)]) + + est = BackendEstimatorV2(backend=backend, options=self._options) + est.options.abelian_grouping = abelian_grouping + op_1 = op.apply_layout(qc.layout) + result = est.run([(qc, op_1)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_2 = op.apply_layout(qc2.layout) + result = est.run([(qc2, op_2)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_3 = op2.apply_layout(qc.layout) + result = est.run([(qc, op_3)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_4 = op2.apply_layout(qc2.layout) + result = est.run([(qc2, op_4)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_5 = op3.apply_layout(qc.layout) + result = est.run([(qc, op_5)]).result() + np.testing.assert_allclose(result[0].data.evs, [1], rtol=self._rtol) + + op_6 = op3.apply_layout(qc2.layout) + result = est.run([(qc2, op_6)]).result() + np.testing.assert_allclose(result[0].data.evs, [-1], rtol=self._rtol) + @combine(backend=BACKENDS, abelian_grouping=[True, False]) def test_run_errors(self, backend, abelian_grouping): """Test for errors""" @@ -322,7 +570,7 @@ def test_run_errors(self, backend, abelian_grouping): with self.assertRaisesRegex(ValueError, "An invalid Estimator pub-like was given"): _ = est.run((qc, op)).result() - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_run_numpy_params(self, backend, abelian_grouping): """Test for numpy array as parameter values""" qc = RealAmplitudes(num_qubits=2, reps=2) @@ -350,7 +598,39 @@ def test_run_numpy_params(self, backend, abelian_grouping): self.assertEqual(result[0].data.evs.shape, (k,)) np.testing.assert_allclose(result[0].data.evs, target[0].data.evs, rtol=self._rtol) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_run_numpy_params_v1(self, backend, abelian_grouping): + """Test for numpy array as parameter values""" + qc = RealAmplitudes(num_qubits=2, reps=2) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + qc = pm.run(qc) + op = SparsePauliOp.from_list([("IZ", 1), ("XI", 2), ("ZY", -1)]) + op = op.apply_layout(qc.layout) + k = 5 + params_array = self._rng.random((k, qc.num_parameters)) + params_list = params_array.tolist() + params_list_array = list(params_array) + statevector_estimator = StatevectorEstimator(seed=123) + target = statevector_estimator.run([(qc, op, params_list)]).result() + + backend_estimator = BackendEstimatorV2(backend=backend, options=self._options) + backend_estimator.options.abelian_grouping = abelian_grouping + + with self.subTest("ndarrary"): + result = backend_estimator.run([(qc, op, params_array)]).result() + self.assertEqual(result[0].data.evs.shape, (k,)) + np.testing.assert_allclose(result[0].data.evs, target[0].data.evs, rtol=self._rtol) + + with self.subTest("list of ndarray"): + result = backend_estimator.run([(qc, op, params_list_array)]).result() + self.assertEqual(result[0].data.evs.shape, (k,)) + np.testing.assert_allclose(result[0].data.evs, target[0].data.evs, rtol=self._rtol) + + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_precision(self, backend, abelian_grouping): """Test for precision""" estimator = BackendEstimatorV2(backend=backend, options=self._options) @@ -372,7 +652,33 @@ def test_precision(self, backend, abelian_grouping): result = job.result() np.testing.assert_allclose(result[0].data.evs, [1.5555572817900956], rtol=self._rtol) - @combine(backend=BACKENDS, abelian_grouping=[True, False]) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_precision_v1(self, backend, abelian_grouping): + """Test for precision""" + estimator = BackendEstimatorV2(backend=backend, options=self._options) + estimator.options.abelian_grouping = abelian_grouping + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + psi1 = pm.run(self.psi[0]) + hamiltonian1 = self.hamiltonian[0].apply_layout(psi1.layout) + theta1 = self.theta[0] + job = estimator.run([(psi1, hamiltonian1, [theta1])]) + result = job.result() + np.testing.assert_allclose(result[0].data.evs, [1.901141473854881], rtol=self._rtol) + # The result of the second run is the same + job = estimator.run([(psi1, hamiltonian1, [theta1]), (psi1, hamiltonian1, [theta1])]) + result = job.result() + np.testing.assert_allclose(result[0].data.evs, [1.901141473854881], rtol=self._rtol) + np.testing.assert_allclose(result[1].data.evs, [1.901141473854881], rtol=self._rtol) + # apply smaller precision value + job = estimator.run([(psi1, hamiltonian1, [theta1])], precision=self._precision * 0.5) + result = job.result() + np.testing.assert_allclose(result[0].data.evs, [1.5555572817900956], rtol=self._rtol) + + @combine(backend=BACKENDS_V2, abelian_grouping=[True, False]) def test_diff_precision(self, backend, abelian_grouping): """Test for running different precisions at once""" estimator = BackendEstimatorV2(backend=backend, options=self._options) @@ -388,6 +694,26 @@ def test_diff_precision(self, backend, abelian_grouping): np.testing.assert_allclose(result[0].data.evs, [1.901141473854881], rtol=self._rtol) np.testing.assert_allclose(result[1].data.evs, [1.901141473854881], rtol=self._rtol) + @combine(backend=BACKENDS_V1, abelian_grouping=[True, False]) + def test_diff_precision_v1(self, backend, abelian_grouping): + """Test for running different precisions at once""" + estimator = BackendEstimatorV2(backend=backend, options=self._options) + estimator.options.abelian_grouping = abelian_grouping + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + ): + pm = generate_preset_pass_manager(optimization_level=0, backend=backend) + psi1 = pm.run(self.psi[0]) + hamiltonian1 = self.hamiltonian[0].apply_layout(psi1.layout) + theta1 = self.theta[0] + job = estimator.run( + [(psi1, hamiltonian1, [theta1]), (psi1, hamiltonian1, [theta1], self._precision * 0.8)] + ) + result = job.result() + np.testing.assert_allclose(result[0].data.evs, [1.901141473854881], rtol=self._rtol) + np.testing.assert_allclose(result[1].data.evs, [1.901141473854881], rtol=self._rtol) + @unittest.skipUnless(optionals.HAS_AER, "qiskit-aer is required to run this test") @combine(abelian_grouping=[True, False]) def test_aer(self, abelian_grouping): From ac542e5b3f9269000837db015aaf5803bd9a4fd5 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 17:48:19 +0200 Subject: [PATCH 161/168] test.python.compiler.test_transpiler --- test/python/compiler/test_transpiler.py | 46 ++++++++++++++++--------- 1 file changed, 30 insertions(+), 16 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 023e7e63f403..01f89a1e4d66 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1576,13 +1576,17 @@ def test_scheduling_instruction_constraints(self): durations = InstructionDurations.from_backend(backend_v1) durations.update([("cx", [0, 1], 1000, "dt")]) - scheduled = transpile( - qc, - backend=backend_v1, - scheduling_method="alap", - instruction_durations=durations, - layout_method="trivial", - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + scheduled = transpile( + qc, + backend=backend_v1, + scheduling_method="alap", + instruction_durations=durations, + layout_method="trivial", + ) self.assertEqual(scheduled.duration, 1500) scheduled = transpile( @@ -1607,8 +1611,14 @@ def test_scheduling_dt_constraints(self): original_dt = 2.2222222222222221e-10 original_duration = 3504 - # halve dt in sec = double duration in dt - scheduled = transpile(qc, backend=backend_v1, scheduling_method="asap", dt=original_dt / 2) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + # halve dt in sec = double duration in dt + scheduled = transpile( + qc, backend=backend_v1, scheduling_method="asap", dt=original_dt / 2 + ) self.assertEqual(scheduled.duration, original_duration * 2) # halve dt in sec = double duration in dt @@ -1661,13 +1671,17 @@ def test_backend_props_constraints(self): 17: Qubit(QuantumRegister(15, "ancilla"), 14), } - result = transpile( - qc, - backend=backend_v1, - backend_properties=custom_backend_properties, - optimization_level=2, - seed_transpiler=42, - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The function transpile will stop supporting BackendV1", + ): + result = transpile( + qc, + backend=backend_v1, + backend_properties=custom_backend_properties, + optimization_level=2, + seed_transpiler=42, + ) self.assertEqual(result._layout.initial_layout._p2v, vf2_layout) result = transpile( From ae46bcc119959a26650fc9e7b0600b1bb85da1f8 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 18:26:17 +0200 Subject: [PATCH 162/168] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- qiskit/compiler/transpiler.py | 6 +++--- .../generate_preset_pass_manager.py | 7 +++---- .../primitives/test_backend_estimator_v2.py | 16 ++++++++-------- 3 files changed, 14 insertions(+), 15 deletions(-) diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py index 84cf89542a9b..6b03ad6ea95e 100644 --- a/qiskit/compiler/transpiler.py +++ b/qiskit/compiler/transpiler.py @@ -316,9 +316,9 @@ def callback_func(**kwargs): if backend is not None and getattr(backend, "version", 0) <= 1: warnings.warn( - f"The function transpile will stop supporting BackendV1 {backend} " - "in the backend parameter not earlier than the release of 2.0. " - "BackendV1 is deprecated and and providers should move to BackendV2.", + f"The `transpile` function will stop supporting inputs of type `BackendV1` ( {backend} ) " + "in the `backend` parameter in a future release not earlier than 2.0. " + "`BackendV1` is deprecated and implementations should move to `BackendV2`.", category=DeprecationWarning, stacklevel=2, ) diff --git a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py index f9d1f208ff46..4bf4bc0875aa 100644 --- a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +++ b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py @@ -256,10 +256,9 @@ def generate_preset_pass_manager( # to a fully target-based transpiler pipeline while maintaining the behavior # of `transpile` with BackendV1 inputs. warnings.warn( - "The function generate_preset_pass_manager will stop supporting " - f"BackendV1 {backend} " - "in the backend parameter not earlier than the release of 2.0. " - "BackendV1 is deprecated and and providers should move to BackendV2.", + f"The `generate_preset_pass_manager` function will stop supporting inputs of type `BackendV1` ( {backend} ) " + "in the `backend` parameter in a future release not earlier than 2.0. " + "`BackendV1` is deprecated and implementations should move to `BackendV2`.", category=DeprecationWarning, stacklevel=2, ) diff --git a/test/python/primitives/test_backend_estimator_v2.py b/test/python/primitives/test_backend_estimator_v2.py index 6bde5f964f4a..1ba0ab8e5765 100644 --- a/test/python/primitives/test_backend_estimator_v2.py +++ b/test/python/primitives/test_backend_estimator_v2.py @@ -140,7 +140,7 @@ def test_estimator_run_v1(self, backend, abelian_grouping): theta1, theta2, theta3 = self.theta with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1, psi2 = pm.run([psi1, psi2]) @@ -217,7 +217,7 @@ def test_estimator_with_pub_v1(self, backend, abelian_grouping): theta1, theta2, theta3 = self.theta with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1, psi2 = pm.run([psi1, psi2]) @@ -332,7 +332,7 @@ def test_run_single_circuit_observable_v1(self, backend, abelian_grouping): est.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -425,7 +425,7 @@ def test_run_1qubit_v1(self, backend, abelian_grouping): qc2.x(0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) @@ -498,7 +498,7 @@ def test_run_2qubits_v1(self, backend, abelian_grouping): qc2.x(0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) @@ -604,7 +604,7 @@ def test_run_numpy_params_v1(self, backend, abelian_grouping): qc = RealAmplitudes(num_qubits=2, reps=2) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) @@ -659,7 +659,7 @@ def test_precision_v1(self, backend, abelian_grouping): estimator.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1 = pm.run(self.psi[0]) @@ -701,7 +701,7 @@ def test_diff_precision_v1(self, backend, abelian_grouping): estimator.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1 = pm.run(self.psi[0]) From b672edd912273a45c1b43b330eb9815e325bc4a1 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 18:28:54 +0200 Subject: [PATCH 163/168] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Elena Peña Tapia <57907331+ElePT@users.noreply.github.com> --- test/python/providers/test_fake_backends.py | 4 ++-- test/python/transpiler/test_preset_passmanagers.py | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 9591b8afb684..8d5634a8e235 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -132,7 +132,7 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): ) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled = transpile( self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level @@ -227,7 +227,7 @@ def test_delay_circuit(self): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): res = transpile(qc, backend) self.assertIn("delay", res.count_ops()) diff --git a/test/python/transpiler/test_preset_passmanagers.py b/test/python/transpiler/test_preset_passmanagers.py index 4901d117e4fa..272729c147bf 100644 --- a/test/python/transpiler/test_preset_passmanagers.py +++ b/test/python/transpiler/test_preset_passmanagers.py @@ -326,7 +326,7 @@ def test_v1(self, circuit, level, backend): """All the levels with all the backends""" with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): result = transpile( circuit(), backend=backend, optimization_level=level, seed_transpiler=42 @@ -1287,7 +1287,7 @@ def test_with_backend(self, optimization_level): backend = Fake20QV1() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level, backend) self.assertIsInstance(pm, PassManager) From 433768f825baa374485defeee9bead05ee3c3ee2 Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 18:36:00 +0200 Subject: [PATCH 164/168] test.python.primitives.test_backend_estimator_v2.TestBackendEstimatorV2 --- test/python/compiler/test_transpiler.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/python/compiler/test_transpiler.py b/test/python/compiler/test_transpiler.py index 01f89a1e4d66..90dda73c0739 100644 --- a/test/python/compiler/test_transpiler.py +++ b/test/python/compiler/test_transpiler.py @@ -1578,7 +1578,7 @@ def test_scheduling_instruction_constraints(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1` ", ): scheduled = transpile( qc, @@ -1613,7 +1613,7 @@ def test_scheduling_dt_constraints(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1` ", ): # halve dt in sec = double duration in dt scheduled = transpile( @@ -1673,7 +1673,7 @@ def test_backend_props_constraints(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1` ", ): result = transpile( qc, From 8ba5437e46f575903d68bc41e3d98759fd966efb Mon Sep 17 00:00:00 2001 From: Luciano Bello Date: Tue, 30 Jul 2024 18:39:52 +0200 Subject: [PATCH 165/168] test.python.primitives.test_backend_estimator_v2 --- .../primitives/test_backend_estimator_v2.py | 27 ++++++++++++------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/test/python/primitives/test_backend_estimator_v2.py b/test/python/primitives/test_backend_estimator_v2.py index 1ba0ab8e5765..afef4261f7e5 100644 --- a/test/python/primitives/test_backend_estimator_v2.py +++ b/test/python/primitives/test_backend_estimator_v2.py @@ -140,7 +140,8 @@ def test_estimator_run_v1(self, backend, abelian_grouping): theta1, theta2, theta3 = self.theta with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1, psi2 = pm.run([psi1, psi2]) @@ -217,7 +218,8 @@ def test_estimator_with_pub_v1(self, backend, abelian_grouping): theta1, theta2, theta3 = self.theta with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1, psi2 = pm.run([psi1, psi2]) @@ -257,7 +259,8 @@ def test_estimator_run_no_params_v1(self, backend, abelian_grouping): circuit = self.ansatz.assign_parameters([0, 1, 1, 2, 3, 5]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) circuit = pm.run(circuit) @@ -332,7 +335,8 @@ def test_run_single_circuit_observable_v1(self, backend, abelian_grouping): est.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -425,7 +429,8 @@ def test_run_1qubit_v1(self, backend, abelian_grouping): qc2.x(0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) @@ -498,7 +503,8 @@ def test_run_2qubits_v1(self, backend, abelian_grouping): qc2.x(0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) @@ -604,7 +610,8 @@ def test_run_numpy_params_v1(self, backend, abelian_grouping): qc = RealAmplitudes(num_qubits=2, reps=2) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) @@ -659,7 +666,8 @@ def test_precision_v1(self, backend, abelian_grouping): estimator.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1 = pm.run(self.psi[0]) @@ -701,7 +709,8 @@ def test_diff_precision_v1(self, backend, abelian_grouping): estimator.options.abelian_grouping = abelian_grouping with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will stop supporting " + "inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) psi1 = pm.run(self.psi[0]) From cd5d8ef57bdf0fdc3dd36f46bd100007e3a72c69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elena=20Pe=C3=B1a=20Tapia?= <57907331+ElePT@users.noreply.github.com> Date: Wed, 31 Jul 2024 09:44:42 +0200 Subject: [PATCH 166/168] Fix expected_regex in transpile tests --- test/python/pulse/test_builder.py | 6 +++--- test/python/transpiler/test_pulse_gate_pass.py | 16 ++++++++-------- test/python/transpiler/test_vf2_post_layout.py | 8 ++++---- 3 files changed, 15 insertions(+), 15 deletions(-) diff --git a/test/python/pulse/test_builder.py b/test/python/pulse/test_builder.py index 1374e73b3bfb..2b1c54377fbb 100644 --- a/test/python/pulse/test_builder.py +++ b/test/python/pulse/test_builder.py @@ -768,7 +768,7 @@ def get_sched(qubit_idx: [int], backend): qc.append(circuit.library.U2Gate(0, pi / 2), [idx]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled = compiler.transpile(qc, backend=backend, optimization_level=1) return compiler.schedule(transpiled, backend) @@ -793,7 +793,7 @@ def get_sched(qubit_idx: [int], backend): single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): single_u2_qc = compiler.transpile(single_u2_qc, self.backend, optimization_level=1) single_u2_sched = compiler.schedule(single_u2_qc, self.backend) @@ -822,7 +822,7 @@ def get_sched(qubit_idx: [int], backend): triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend, optimization_level=1) align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap") diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index 226093640514..88ebe59ad95e 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -72,7 +72,7 @@ def test_transpile_with_bare_backend(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) @@ -118,7 +118,7 @@ def test_transpile_with_custom_basis_gate(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) @@ -187,7 +187,7 @@ def test_transpile_with_instmap(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1]) @@ -227,7 +227,7 @@ def test_transpile_with_custom_gate(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0, 1]) @@ -267,7 +267,7 @@ def test_transpile_with_parameterized_custom_gate(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) @@ -308,7 +308,7 @@ def test_transpile_with_multiple_circuits(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qcs = transpile(circs, backend, basis_gates=["my_gate"], initial_layout=[0]) @@ -345,7 +345,7 @@ def test_multiple_instructions_with_different_parameters(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) @@ -378,7 +378,7 @@ def test_transpile_with_different_qubit(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, initial_layout=[3]) diff --git a/test/python/transpiler/test_vf2_post_layout.py b/test/python/transpiler/test_vf2_post_layout.py index 5b78977a3c9b..b8d6888a53d1 100644 --- a/test/python/transpiler/test_vf2_post_layout.py +++ b/test/python/transpiler/test_vf2_post_layout.py @@ -196,7 +196,7 @@ def test_2q_circuit_5q_backend(self): circuit.cx(qr[1], qr[0]) # qr1 -> qr0 with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout @@ -282,7 +282,7 @@ def test_2q_circuit_5q_backend_max_trials_v1(self): circuit.cx(qr[1], qr[0]) # qr1 -> qr0 with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout @@ -693,7 +693,7 @@ def test_best_mapping_ghz_state_full_device_multiple_qregs_v1(self): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout @@ -743,7 +743,7 @@ def test_2q_circuit_5q_backend_v1(self): circuit.cx(qr[1], qr[0]) # qr1 -> qr0 with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function transpile will stop supporting BackendV1", + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", ): tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout From 2d57de833f2a23dbdf07477f9001713605257dd0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elena=20Pe=C3=B1a=20Tapia?= Date: Wed, 31 Jul 2024 10:22:42 +0200 Subject: [PATCH 167/168] Fix missing assertions in: * test.python.circuit.test_scheduled_circuit * test.python.compiler.test_sequencer * test.python.circuit.test_parameters * test.python.primitives.test_backend_sampler_v2 * test.python.primitives.test_backend_sampler --- test/python/circuit/test_parameters.py | 6 +- test/python/circuit/test_scheduled_circuit.py | 161 +++++++++++++----- test/python/compiler/test_sequencer.py | 36 +++- .../python/primitives/test_backend_sampler.py | 39 ++++- .../primitives/test_backend_sampler_v2.py | 51 ++++-- 5 files changed, 225 insertions(+), 68 deletions(-) diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index c2df1a423ec4..3b7f962af982 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -1093,7 +1093,11 @@ def test_transpile_across_optimization_levelsV1(self, opt_level): qc.measure(range(5 - 1), range(5 - 1)) with self.assertWarns(DeprecationWarning): backend = Fake5QV1() - transpile(qc, backend, optimization_level=opt_level) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + transpile(qc, backend, optimization_level=opt_level) @data(0, 1, 2, 3) def test_transpile_across_optimization_levels(self, opt_level): diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index c934b5b5e04c..50920dc517ec 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -78,13 +78,17 @@ def test_schedule_circuit_when_transpile_option_tells_dt(self): qc.delay(100, 0, unit="ns") # 450[dt] qc.h(0) qc.h(1) - sc = transpile( - qc, - self.backend_without_dt, - scheduling_method="alap", - dt=self.dt, - layout_method="trivial", - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + sc = transpile( + qc, + self.backend_without_dt, + scheduling_method="alap", + dt=self.dt, + layout_method="trivial", + ) self.assertEqual(sc.duration, 450546) self.assertEqual(sc.unit, "dt") self.assertEqual(sc.data[0].operation.name, "delay") @@ -104,9 +108,13 @@ def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): qc.delay(100, 0, unit="ns") qc.h(0) qc.h(1) - sc = transpile( - qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial" - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + sc = transpile( + qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial" + ) self.assertAlmostEqual(sc.duration, 450610 * self.dt) self.assertEqual(sc.unit, "s") self.assertEqual(sc.data[0].operation.name, "delay") @@ -128,13 +136,21 @@ def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self) qc.delay(30, 0, unit="dt") qc.h(0) qc.h(1) - with self.assertRaises(QiskitError): - transpile(qc, self.backend_without_dt, scheduling_method="alap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + with self.assertRaises(QiskitError): + transpile(qc, self.backend_without_dt, scheduling_method="alap") def test_transpile_single_delay_circuit(self): qc = QuantumCircuit(1) qc.delay(1234, 0) - sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(sc.duration, 1234) self.assertEqual(sc.data[0].operation.name, "delay") self.assertEqual(sc.data[0].operation.duration, 1234) @@ -145,7 +161,11 @@ def test_transpile_t1_circuit(self): qc.x(0) # 320 [dt] qc.delay(1000, 0, unit="ns") # 4500 [dt] qc.measure_all() - scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(scheduled.duration, 8004) def test_transpile_delay_circuit_with_backend(self): @@ -153,9 +173,13 @@ def test_transpile_delay_circuit_with_backend(self): qc.h(0) qc.delay(100, 1, unit="ns") # 450 [dt] qc.cx(0, 1) # 1760 [dt] - scheduled = transpile( - qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + scheduled = transpile( + qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" + ) self.assertEqual(scheduled.duration, 1826) def test_transpile_delay_circuit_without_backend(self): @@ -187,7 +211,11 @@ def test_transpile_circuit_with_custom_instruction(self): def test_transpile_delay_circuit_with_dt_but_without_scheduling_method(self): qc = QuantumCircuit(1) qc.delay(100, 0, unit="ns") - transpiled = transpile(qc, backend=self.backend_with_dt) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + transpiled = transpile(qc, backend=self.backend_with_dt) self.assertEqual(transpiled.duration, None) # not scheduled self.assertEqual(transpiled.data[0].operation.duration, 450) # unit is converted ns -> dt @@ -212,7 +240,11 @@ def test_invalidate_schedule_circuit_if_new_instruction_is_appended(self): qc.h(0) qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) - scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") # append a gate to a scheduled circuit scheduled.h(0) self.assertEqual(scheduled.duration, None) @@ -245,21 +277,29 @@ def test_unit_seconds_when_using_backend_durations(self): qc.delay(500 * self.dt, 1, "s") qc.cx(0, 1) # usual case - scheduled = transpile( - qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + scheduled = transpile( + qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" + ) self.assertEqual(scheduled.duration, 1876) # update durations durations = InstructionDurations.from_backend(self.backend_with_dt) durations.update([("cx", [0, 1], 1000 * self.dt, "s")]) - scheduled = transpile( - qc, - backend=self.backend_with_dt, - scheduling_method="alap", - instruction_durations=durations, - layout_method="trivial", - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + scheduled = transpile( + qc, + backend=self.backend_with_dt, + scheduling_method="alap", + instruction_durations=durations, + layout_method="trivial", + ) self.assertEqual(scheduled.duration, 1500) def test_per_qubit_durations(self): @@ -348,13 +388,21 @@ def test_change_dt_in_transpile(self): qc.x(0) qc.measure(0, 0) # default case - scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap") org_duration = scheduled.duration # halve dt in sec = double duration in dt - scheduled = transpile( - qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2 - ) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + scheduled = transpile( + qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2 + ) self.assertEqual(scheduled.duration, org_duration * 2) @data("asap", "alap") @@ -366,7 +414,11 @@ def test_duration_on_same_instruction_instance(self, scheduling_method): qc = QuantumCircuit(3) qc.cz(0, 1) qc.cz(1, 2) - sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method) cxs = [inst.operation for inst in sc.data if inst.operation.name == "cx"] self.assertNotEqual(cxs[0].duration, cxs[1].duration) @@ -404,7 +456,11 @@ def test_can_transpile_circuits_after_assigning_parameters(self): qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) - circ = transpile(qc, self.backend_with_dt) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.duration, 450) # converted in dt @@ -414,7 +470,11 @@ def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) - circ = transpile(qc, self.backend_with_dt) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) with self.assertWarns(DeprecationWarning): qobj = assemble(circ, self.backend_with_dt) @@ -428,7 +488,11 @@ def test_can_transpile_circuits_with_unbounded_parameters(self): qc.delay(idle_dur, 0, "us") qc.measure(0, 0) # not assign parameter - circ = transpile(qc, self.backend_with_dt) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled self.assertEqual(circ.data[1].operation.unit, "dt") # converted in dt self.assertEqual( @@ -441,7 +505,11 @@ def test_fail_to_assemble_circuits_with_unbounded_parameters(self): qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) - qc = transpile(qc, self.backend_with_dt) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + qc = transpile(qc, self.backend_with_dt) with self.assertRaises(DeprecationWarning): assemble(qc, self.backend_with_dt) @@ -453,7 +521,11 @@ def test_can_schedule_circuits_with_bounded_parameters(self, scheduling_method): qc.delay(idle_dur, 0, "us") qc.measure(0, 0) qc = qc.assign_parameters({idle_dur: 0.1}) - circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) self.assertIsNotNone(circ.duration) # scheduled @data("asap", "alap") @@ -463,6 +535,11 @@ def test_fail_to_schedule_circuits_with_unbounded_parameters(self, scheduling_me qc.x(0) qc.delay(idle_dur, 0, "us") qc.measure(0, 0) - # not assign parameter - with self.assertRaises(TranspilerError): - transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) + + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + # unassigned parameter + with self.assertRaises(TranspilerError): + transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) diff --git a/test/python/compiler/test_sequencer.py b/test/python/compiler/test_sequencer.py index e32d6370367b..d3e0448df613 100644 --- a/test/python/compiler/test_sequencer.py +++ b/test/python/compiler/test_sequencer.py @@ -41,9 +41,17 @@ def test_transpile_and_sequence_agree_with_schedule(self): qc.h(0) qc.cx(0, 1) qc.measure_all() - sc = transpile(qc, self.backend, scheduling_method="alap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) - expected = schedule(transpile(qc, self.backend), self.backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual(actual, pad(expected)) def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(self): @@ -52,9 +60,17 @@ def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(self) qc.delay(500, 0, unit="ns") qc.h(0) qc.measure(0, 0) - sc = transpile(qc, self.backend, scheduling_method="alap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) - expected = schedule(transpile(qc, self.backend), self.backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual( actual.exclude(instruction_types=[pulse.Delay]), expected.exclude(instruction_types=[pulse.Delay]), @@ -65,7 +81,15 @@ def test_transpile_and_sequence_agree_with_schedule_for_circuits_without_measure qc = QuantumCircuit(2, name="bell_without_measurement") qc.h(0) qc.cx(0, 1) - sc = transpile(qc, self.backend, scheduling_method="alap") + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) - expected = schedule(transpile(qc, self.backend), self.backend) + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + ): + expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual(actual, pad(expected)) diff --git a/test/python/primitives/test_backend_sampler.py b/test/python/primitives/test_backend_sampler.py index f0fdb4f07f8c..27e438d30874 100644 --- a/test/python/primitives/test_backend_sampler.py +++ b/test/python/primitives/test_backend_sampler.py @@ -34,6 +34,12 @@ BACKENDS = [Fake7QPulseV1(), BackendV2Converter(Fake7QPulseV1())] +BACKENDS_V1 = [Fake7QPulseV1()] +BACKENDS_V2 = [ + BackendV2Converter(Fake7QPulseV1()), +] +BACKENDS = BACKENDS_V1 + BACKENDS_V2 + class CallbackPass(DummyAP): """A dummy analysis pass that calls a callback when executed""" @@ -236,8 +242,37 @@ def test_run_errors(self, backend): with self.assertRaises(ValueError): sampler.run([qc2], [[1e2]]).result() - @combine(backend=BACKENDS) - def test_run_empty_parameter(self, backend): + @combine(backend=BACKENDS_V1) + def test_run_empty_parameter_v1(self, backend): + """Test for empty parameter""" + n = 5 + qc = QuantumCircuit(n, n - 1) + qc.measure(range(n - 1), range(n - 1)) + with self.assertWarns(DeprecationWarning): + sampler = BackendSampler(backend=backend) + with self.subTest("one circuit"): + with self.assertWarnsRegex( + DeprecationWarning, + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", + ): + result = sampler.run([qc], shots=1000).result() + self.assertEqual(len(result.quasi_dists), 1) + for q_d in result.quasi_dists: + quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} + self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1) + self.assertEqual(len(result.metadata), 1) + + with self.subTest("two circuits"): + result = sampler.run([qc, qc], shots=1000).result() + self.assertEqual(len(result.quasi_dists), 2) + for q_d in result.quasi_dists: + quasi_dist = {k: v for k, v in q_d.items() if v != 0.0} + self.assertDictAlmostEqual(quasi_dist, {0: 1.0}, delta=0.1) + self.assertEqual(len(result.metadata), 2) + + @combine(backend=BACKENDS_V2) + def test_run_empty_parameter_v2(self, backend): """Test for empty parameter""" n = 5 qc = QuantumCircuit(n, n - 1) diff --git a/test/python/primitives/test_backend_sampler_v2.py b/test/python/primitives/test_backend_sampler_v2.py index abb06eed8cb3..0ff0460a069c 100644 --- a/test/python/primitives/test_backend_sampler_v2.py +++ b/test/python/primitives/test_backend_sampler_v2.py @@ -102,7 +102,8 @@ def test_sampler_run_v1(self, backend): """Test run().""" with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -210,7 +211,8 @@ def test_sampler_run_multiple_times_v1(self, backend): sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) @@ -240,7 +242,8 @@ def test_sample_run_multiple_circuits_v1(self, backend): sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) @@ -309,7 +312,8 @@ def test_run_1qubit_v1(self, backend): qc2.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc, qc2 = pm.run([qc, qc2]) @@ -359,7 +363,8 @@ def test_run_2qubit_v1(self, backend): qc3.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc0, qc1, qc2, qc3 = pm.run([qc0, qc1, qc2, qc3]) @@ -434,7 +439,8 @@ def test_run_single_circuit_v1(self, backend): sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -532,7 +538,8 @@ def test_run_reverse_meas_order_v1(self, backend): qc.measure(2, 0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) @@ -609,7 +616,8 @@ def test_run_errors_v1(self, backend): qc2.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc1, qc2 = pm.run([qc1, qc2]) @@ -684,7 +692,8 @@ def test_run_empty_parameter_v1(self, backend): qc.measure(range(n - 1), range(n - 1)) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) @@ -737,7 +746,8 @@ def test_run_numpy_params_v1(self, backend): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) @@ -834,7 +844,8 @@ def test_run_with_shots_option_v1(self, backend): bell, _, _ = self._cases[1] with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) @@ -920,7 +931,8 @@ def test_run_shots_result_size_v1(self, backend): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc = pm.run(qc) @@ -947,7 +959,8 @@ def test_primitive_job_status_done_v1(self, backend): bell, _, _ = self._cases[1] with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) bell = pm.run(bell) @@ -992,7 +1005,8 @@ def test_circuit_with_unitary_v1(self, backend): """Test for circuit with unitary gate.""" with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) @@ -1107,7 +1121,8 @@ def test_circuit_with_multiple_cregs_v1(self, backend): """Test for circuit with multiple classical registers.""" with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) cases = [] @@ -1250,7 +1265,8 @@ def test_circuit_with_aliased_cregs_v1(self, backend): sampler = BackendSamplerV2(backend=backend, options=self._options) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) qc2 = pm.run(qc2) @@ -1311,7 +1327,8 @@ def test_diff_shots_v1(self, backend): """Test of pubs with different shots""" with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The function generate_preset_pass_manager will stop supporting BackendV1", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level=0, backend=backend) From cf3c12d09fb3c54d69c138767cd4399b3fe12f52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Elena=20Pe=C3=B1a=20Tapia?= Date: Wed, 31 Jul 2024 10:49:10 +0200 Subject: [PATCH 168/168] Fix line-too-long lint complaints --- qiskit/compiler/transpiler.py | 7 ++- qiskit/providers/backend.py | 5 +- .../generate_preset_pass_manager.py | 7 ++- test/python/circuit/test_parameters.py | 3 +- test/python/circuit/test_scheduled_circuit.py | 57 ++++++++++++------- test/python/compiler/test_sequencer.py | 18 ++++-- test/python/providers/test_fake_backends.py | 6 +- test/python/pulse/test_builder.py | 9 ++- .../transpiler/test_preset_passmanagers.py | 6 +- .../python/transpiler/test_pulse_gate_pass.py | 24 +++++--- .../python/transpiler/test_vf2_post_layout.py | 12 ++-- 11 files changed, 101 insertions(+), 53 deletions(-) diff --git a/qiskit/compiler/transpiler.py b/qiskit/compiler/transpiler.py index 6b03ad6ea95e..fd93fde5989f 100644 --- a/qiskit/compiler/transpiler.py +++ b/qiskit/compiler/transpiler.py @@ -316,9 +316,10 @@ def callback_func(**kwargs): if backend is not None and getattr(backend, "version", 0) <= 1: warnings.warn( - f"The `transpile` function will stop supporting inputs of type `BackendV1` ( {backend} ) " - "in the `backend` parameter in a future release not earlier than 2.0. " - "`BackendV1` is deprecated and implementations should move to `BackendV2`.", + "The `transpile` function 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, ) diff --git a/qiskit/providers/backend.py b/qiskit/providers/backend.py index a8c36e99da07..6d9ed51043ec 100644 --- a/qiskit/providers/backend.py +++ b/qiskit/providers/backend.py @@ -75,8 +75,9 @@ class BackendV1(Backend, ABC): @deprecate_func( since="1.2", removal_timeline="in the 2.0 release", - additional_msg="If the backend only encapsulates a hardware description, consider constructing a " - "Target directly. If it is part of a provider that gives access to execution, consider using Primitives instead. " + additional_msg="If the backend only encapsulates a hardware description, " + "consider constructing a Target directly. If it is part of a provider " + "that gives access to execution, consider using Primitives instead. " "Alternatively, consider moving to BackendV2 (see https://qisk.it/backendV1-to-V2).", ) def __init__(self, configuration, provider=None, **fields): diff --git a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py index 4bf4bc0875aa..a9a9a5e2f029 100644 --- a/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py +++ b/qiskit/transpiler/preset_passmanagers/generate_preset_pass_manager.py @@ -256,9 +256,10 @@ def generate_preset_pass_manager( # to a fully target-based transpiler pipeline while maintaining the behavior # of `transpile` with BackendV1 inputs. warnings.warn( - f"The `generate_preset_pass_manager` function will stop supporting inputs of type `BackendV1` ( {backend} ) " - "in the `backend` parameter in a future release not earlier than 2.0. " - "`BackendV1` is deprecated and implementations should move to `BackendV2`.", + "The `generate_preset_pass_manager` function 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, ) diff --git a/test/python/circuit/test_parameters.py b/test/python/circuit/test_parameters.py index 3b7f962af982..ad336a0ad6bb 100644 --- a/test/python/circuit/test_parameters.py +++ b/test/python/circuit/test_parameters.py @@ -1095,7 +1095,8 @@ def test_transpile_across_optimization_levelsV1(self, opt_level): backend = Fake5QV1() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpile(qc, backend, optimization_level=opt_level) diff --git a/test/python/circuit/test_scheduled_circuit.py b/test/python/circuit/test_scheduled_circuit.py index 50920dc517ec..ce5cd8213105 100644 --- a/test/python/circuit/test_scheduled_circuit.py +++ b/test/python/circuit/test_scheduled_circuit.py @@ -80,7 +80,8 @@ def test_schedule_circuit_when_transpile_option_tells_dt(self): qc.h(1) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): sc = transpile( qc, @@ -110,7 +111,8 @@ def test_schedule_circuit_in_sec_when_no_one_tells_dt(self): qc.h(1) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): sc = transpile( qc, self.backend_without_dt, scheduling_method="alap", layout_method="trivial" @@ -138,7 +140,8 @@ def test_cannot_schedule_circuit_with_mixed_SI_and_dt_when_no_one_tells_dt(self) qc.h(1) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): with self.assertRaises(QiskitError): transpile(qc, self.backend_without_dt, scheduling_method="alap") @@ -148,7 +151,8 @@ def test_transpile_single_delay_circuit(self): qc.delay(1234, 0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): sc = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(sc.duration, 1234) @@ -163,7 +167,8 @@ def test_transpile_t1_circuit(self): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") self.assertEqual(scheduled.duration, 8004) @@ -175,7 +180,8 @@ def test_transpile_delay_circuit_with_backend(self): qc.cx(0, 1) # 1760 [dt] with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" @@ -213,7 +219,8 @@ def test_transpile_delay_circuit_with_dt_but_without_scheduling_method(self): qc.delay(100, 0, unit="ns") with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled = transpile(qc, backend=self.backend_with_dt) self.assertEqual(transpiled.duration, None) # not scheduled @@ -242,7 +249,8 @@ def test_invalidate_schedule_circuit_if_new_instruction_is_appended(self): qc.cx(0, 1) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="alap") # append a gate to a scheduled circuit @@ -279,7 +287,8 @@ def test_unit_seconds_when_using_backend_durations(self): # usual case with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="alap", layout_method="trivial" @@ -291,7 +300,8 @@ def test_unit_seconds_when_using_backend_durations(self): durations.update([("cx", [0, 1], 1000 * self.dt, "s")]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): scheduled = transpile( qc, @@ -390,7 +400,8 @@ def test_change_dt_in_transpile(self): # default case with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): scheduled = transpile(qc, backend=self.backend_with_dt, scheduling_method="asap") org_duration = scheduled.duration @@ -398,7 +409,8 @@ def test_change_dt_in_transpile(self): # halve dt in sec = double duration in dt with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): scheduled = transpile( qc, backend=self.backend_with_dt, scheduling_method="asap", dt=self.dt / 2 @@ -416,7 +428,8 @@ def test_duration_on_same_instruction_instance(self, scheduling_method): qc.cz(1, 2) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): sc = transpile(qc, backend=self.backend_with_dt, scheduling_method=scheduling_method) cxs = [inst.operation for inst in sc.data if inst.operation.name == "cx"] @@ -458,7 +471,8 @@ def test_can_transpile_circuits_after_assigning_parameters(self): qc = qc.assign_parameters({idle_dur: 0.1}) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled @@ -472,7 +486,8 @@ def test_can_transpile_and_assemble_circuits_with_assigning_parameters_inbetween qc.measure(0, 0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): circ = transpile(qc, self.backend_with_dt) circ = circ.assign_parameters({idle_dur: 0.1}) @@ -490,7 +505,8 @@ def test_can_transpile_circuits_with_unbounded_parameters(self): # not assign parameter with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): circ = transpile(qc, self.backend_with_dt) self.assertEqual(circ.duration, None) # not scheduled @@ -507,7 +523,8 @@ def test_fail_to_assemble_circuits_with_unbounded_parameters(self): qc.measure(0, 0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): qc = transpile(qc, self.backend_with_dt) with self.assertRaises(DeprecationWarning): @@ -523,7 +540,8 @@ def test_can_schedule_circuits_with_bounded_parameters(self, scheduling_method): qc = qc.assign_parameters({idle_dur: 0.1}) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): circ = transpile(qc, self.backend_with_dt, scheduling_method=scheduling_method) self.assertIsNotNone(circ.duration) # scheduled @@ -538,7 +556,8 @@ def test_fail_to_schedule_circuits_with_unbounded_parameters(self, scheduling_me with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): # unassigned parameter with self.assertRaises(TranspilerError): diff --git a/test/python/compiler/test_sequencer.py b/test/python/compiler/test_sequencer.py index d3e0448df613..ae75348a5cdf 100644 --- a/test/python/compiler/test_sequencer.py +++ b/test/python/compiler/test_sequencer.py @@ -43,13 +43,15 @@ def test_transpile_and_sequence_agree_with_schedule(self): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual(actual, pad(expected)) @@ -62,13 +64,15 @@ def test_transpile_and_sequence_agree_with_schedule_for_circuit_with_delay(self) qc.measure(0, 0) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual( @@ -83,13 +87,15 @@ def test_transpile_and_sequence_agree_with_schedule_for_circuits_without_measure qc.cx(0, 1) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): sc = transpile(qc, self.backend, scheduling_method="alap") actual = sequence(sc, self.backend) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): expected = schedule(transpile(qc, self.backend), self.backend) self.assertEqual(actual, pad(expected)) diff --git a/test/python/providers/test_fake_backends.py b/test/python/providers/test_fake_backends.py index 8d5634a8e235..6d8716359bcc 100644 --- a/test/python/providers/test_fake_backends.py +++ b/test/python/providers/test_fake_backends.py @@ -132,7 +132,8 @@ def test_circuit_on_fake_backend(self, backend, optimization_level): ) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled = transpile( self.circuit, backend, seed_transpiler=42, optimization_level=optimization_level @@ -227,7 +228,8 @@ def test_delay_circuit(self): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): res = transpile(qc, backend) self.assertIn("delay", res.count_ops()) diff --git a/test/python/pulse/test_builder.py b/test/python/pulse/test_builder.py index 2b1c54377fbb..72a6de11ae08 100644 --- a/test/python/pulse/test_builder.py +++ b/test/python/pulse/test_builder.py @@ -768,7 +768,8 @@ def get_sched(qubit_idx: [int], backend): qc.append(circuit.library.U2Gate(0, pi / 2), [idx]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled = compiler.transpile(qc, backend=backend, optimization_level=1) return compiler.schedule(transpiled, backend) @@ -793,7 +794,8 @@ def get_sched(qubit_idx: [int], backend): single_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [1]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): single_u2_qc = compiler.transpile(single_u2_qc, self.backend, optimization_level=1) single_u2_sched = compiler.schedule(single_u2_qc, self.backend) @@ -822,7 +824,8 @@ def get_sched(qubit_idx: [int], backend): triple_u2_qc.append(circuit.library.U2Gate(0, pi / 2), [0]) with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): triple_u2_qc = compiler.transpile(triple_u2_qc, self.backend, optimization_level=1) align_left_reference = compiler.schedule(triple_u2_qc, self.backend, method="alap") diff --git a/test/python/transpiler/test_preset_passmanagers.py b/test/python/transpiler/test_preset_passmanagers.py index 272729c147bf..58f6d35a20d5 100644 --- a/test/python/transpiler/test_preset_passmanagers.py +++ b/test/python/transpiler/test_preset_passmanagers.py @@ -326,7 +326,8 @@ def test_v1(self, circuit, level, backend): """All the levels with all the backends""" with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): result = transpile( circuit(), backend=backend, optimization_level=level, seed_transpiler=42 @@ -1287,7 +1288,8 @@ def test_with_backend(self, optimization_level): backend = Fake20QV1() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `generate_preset_pass_manager` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `generate_preset_pass_manager` function will " + "stop supporting inputs of type `BackendV1`", ): pm = generate_preset_pass_manager(optimization_level, backend) self.assertIsInstance(pm, PassManager) diff --git a/test/python/transpiler/test_pulse_gate_pass.py b/test/python/transpiler/test_pulse_gate_pass.py index 88ebe59ad95e..07d6172264d4 100644 --- a/test/python/transpiler/test_pulse_gate_pass.py +++ b/test/python/transpiler/test_pulse_gate_pass.py @@ -72,7 +72,8 @@ def test_transpile_with_bare_backend(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) @@ -118,7 +119,8 @@ def test_transpile_with_custom_basis_gate(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, initial_layout=[0, 1]) @@ -187,7 +189,8 @@ def test_transpile_with_instmap(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, inst_map=instmap, initial_layout=[0, 1]) @@ -227,7 +230,8 @@ def test_transpile_with_custom_gate(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0, 1]) @@ -267,7 +271,8 @@ def test_transpile_with_parameterized_custom_gate(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) @@ -308,7 +313,8 @@ def test_transpile_with_multiple_circuits(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qcs = transpile(circs, backend, basis_gates=["my_gate"], initial_layout=[0]) @@ -345,7 +351,8 @@ def test_multiple_instructions_with_different_parameters(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, basis_gates=["my_gate"], initial_layout=[0]) @@ -378,7 +385,8 @@ def test_transpile_with_different_qubit(self): with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): transpiled_qc = transpile(qc, backend, initial_layout=[3]) diff --git a/test/python/transpiler/test_vf2_post_layout.py b/test/python/transpiler/test_vf2_post_layout.py index b8d6888a53d1..5acdd3ba6ebc 100644 --- a/test/python/transpiler/test_vf2_post_layout.py +++ b/test/python/transpiler/test_vf2_post_layout.py @@ -196,7 +196,8 @@ def test_2q_circuit_5q_backend(self): circuit.cx(qr[1], qr[0]) # qr1 -> qr0 with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout @@ -282,7 +283,8 @@ def test_2q_circuit_5q_backend_max_trials_v1(self): circuit.cx(qr[1], qr[0]) # qr1 -> qr0 with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout @@ -693,7 +695,8 @@ def test_best_mapping_ghz_state_full_device_multiple_qregs_v1(self): qc.measure_all() with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): tqc = transpile(qc, backend, seed_transpiler=self.seed, layout_method="trivial") initial_layout = tqc._layout @@ -743,7 +746,8 @@ def test_2q_circuit_5q_backend_v1(self): circuit.cx(qr[1], qr[0]) # qr1 -> qr0 with self.assertWarnsRegex( DeprecationWarning, - expected_regex="The `transpile` function will stop supporting inputs of type `BackendV1`", + expected_regex="The `transpile` function will " + "stop supporting inputs of type `BackendV1`", ): tqc = transpile(circuit, backend, layout_method="dense") initial_layout = tqc._layout